sandbox
Loading...
Searching...
No Matches
vertical_layout.hpp
1// SPDX-License-Identifier: MIT
2#ifndef LIBSBX_UI_VERTICAL_LAYOUT_HPP_
3#define LIBSBX_UI_VERTICAL_LAYOUT_HPP_
4
5#include <algorithm>
6
7#include <libsbx/ui/layout.hpp>
8#include <libsbx/ui/element.hpp>
9
10namespace sbx::ui {
11
12class vertical_layout : public layout {
13
14public:
15
16 std::float_t spacing{0.0f};
17
18 vertical_layout() = default;
19
20 vertical_layout(std::float_t spacing)
21 : spacing{spacing} { }
22
23 ~vertical_layout() override = default;
24
25 auto arrange(const rectangle& bounds, std::vector<std::unique_ptr<element>>& children) -> void override {
26 const auto content = content_rectangle(bounds);
27
28 if (children.empty()) {
29 return;
30 }
31
32 auto total_fixed = 0.0f;
33 auto total_flex = 0.0f;
34
35 for (auto& child : children) {
36 if (child->sizing.flex > 0.0f) {
37 total_flex += child->sizing.flex;
38 } else {
39 total_fixed += child->sizing.preferred.y();
40 }
41 }
42
43 const auto total_spacing = spacing * static_cast<std::float_t>(children.size() - 1u);
44 const auto remaining = std::max(0.0f, content.height - total_fixed - total_spacing);
45
46 auto cursor_y = content.y + content.height;
47
48 for (auto& child : children) {
49 auto child_height = 0.0f;
50
51 if (child->sizing.flex > 0.0f) {
52 child_height = total_flex > 0.0f ? (child->sizing.flex / total_flex) * remaining : 0.0f;
53 } else {
54 child_height = child->sizing.preferred.y();
55 }
56
57 child_height = std::clamp(child_height, child->sizing.min.y(), child->sizing.max.y());
58
59 auto child_width = child->sizing.preferred.x() > 0.0f ? std::clamp(child->sizing.preferred.x(), child->sizing.min.x(), child->sizing.max.x()) : content.width;
60
61 cursor_y -= child_height;
62
63 child->resolve_as_arranged(rectangle{content.x, cursor_y, child_width, child_height});
64
65 cursor_y -= spacing;
66 }
67 }
68
69}; // class vertical_layout
70
71} // namespace sbx::ui
72
73#endif // LIBSBX_UI_VERTICAL_LAYOUT_HPP_
Definition: layout.hpp:39
Definition: vertical_layout.hpp:12
Definition: layout.hpp:15