ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
FlatTreeModel.hpp
Go to the documentation of this file.
1#pragma once
2
11
12#include "Common.hpp"
13
14#include <functional>
15#include <optional>
16#include <type_traits>
17#include <unordered_set>
18#include <utility>
19#include <vector>
20
21namespace ZenitUI::UI
22{
26
27 namespace detail
28 {
29 template <typename NodeT, typename ElemT>
30 const NodeT *unwrapNodePtr(const ElemT &elem) noexcept
31 {
32 using Decayed = std::decay_t<ElemT>;
33 if constexpr (std::is_same_v<Decayed, NodeT>)
34 return &elem;
35 else if constexpr (std::is_pointer_v<Decayed>)
36 return elem;
37 else
38 return elem.get();
39 }
40 } // namespace detail
41
43 template <typename NodeT, typename KeyT>
45 {
46 KeyT key{};
47 const NodeT *node{nullptr};
48 int depth{0};
50 bool hasChildren{false};
51 bool expanded{false};
52 };
53
62 template <typename NodeT, typename KeyT>
64 {
65 public:
66 using Row = FlatTreeRow<NodeT, KeyT>;
67 using KeyFn = std::function<KeyT(const NodeT &)>;
68 using ChildVisitor = std::function<bool(const NodeT &)>;
69 using ChildrenInvoker = std::function<void(const NodeT &, const ChildVisitor &)>;
70
77 template <typename KeyFnT, typename ChildrenFnT>
78 FlatTreeModel(KeyFnT &&keyFn, ChildrenFnT &&childrenFn)
79 : keyFn_(std::forward<KeyFnT>(keyFn)),
80 visitChildren_([fn = std::forward<ChildrenFnT>(childrenFn)](
81 const NodeT &node,
82 const ChildVisitor &visitor)
83 {
84 for (const auto &ch : fn(node))
85 {
86 if (const NodeT *ptr = detail::unwrapNodePtr<NodeT>(ch))
87 {
88 if (!visitor(*ptr))
89 break;
90 }
91 }
92 })
93 {
94 }
95
101 template <typename Range>
102 void setRoots(const Range &roots, bool notify = true)
103 {
104 roots_.clear();
105 for (const auto &r : roots)
106 {
107 if (const NodeT *ptr = detail::unwrapNodePtr<NodeT>(r))
108 roots_.push_back(ptr);
109 }
110 rebuild(notify);
111 }
112
114 void rebuild(bool notify = true)
115 {
116 rows_.clear();
117 for (const NodeT *root : roots_)
118 {
119 if (root)
120 appendSubtree(*root, 0, -1);
121 }
122 if (notify && onChanged)
123 onChanged();
124 }
125
126 size_t count() const noexcept { return rows_.size(); }
127 bool empty() const noexcept { return rows_.empty(); }
128 const Row &at(size_t index) const { return rows_.at(index); }
129 const std::vector<Row> &rows() const noexcept { return rows_; }
130
132 int findRowByKey(const KeyT &key) const
133 {
134 for (size_t i = 0; i < rows_.size(); ++i)
135 if (rows_[i].key == key)
136 return static_cast<int>(i);
137 return -1;
138 }
139
140 bool isExpanded(const KeyT &key) const { return expanded_.count(key) > 0; }
141
143 bool setExpanded(const KeyT &key, bool expanded, bool notify = true)
144 {
145 const bool changed = expanded ? expanded_.insert(key).second : (expanded_.erase(key) > 0);
146 if (!changed)
147 return false;
148 rebuild(notify);
149 if (notify && onItemToggled)
150 onItemToggled(key, expanded);
151 return true;
152 }
153
155 bool toggle(const KeyT &key, bool notify = true)
156 {
157 return setExpanded(key, !isExpanded(key), notify);
158 }
159
161 void expandAll(bool notify = true)
162 {
163 for (const NodeT *root : roots_)
164 {
165 if (root)
166 expandAllRecursive(*root);
167 }
168 rebuild(notify);
169 }
170
172 void collapseAll(bool notify = true)
173 {
174 if (expanded_.empty())
175 return;
176 expanded_.clear();
177 rebuild(notify);
178 }
179
180 void select(const KeyT &key, bool notify = true)
181 {
182 if (selected_.has_value() && *selected_ == key)
183 return;
184 selected_ = key;
185 if (notify && onSelectionChanged)
186 onSelectionChanged(selected_);
187 }
188
189 void clearSelection(bool notify = true)
190 {
191 if (!selected_.has_value())
192 return;
193 selected_.reset();
194 if (notify && onSelectionChanged)
195 onSelectionChanged(selected_);
196 }
197
198 bool isSelected(const KeyT &key) const
199 {
200 return selected_.has_value() && *selected_ == key;
201 }
202
203 const std::optional<KeyT> &selectedKey() const noexcept { return selected_; }
204
207 {
208 return selected_.has_value() ? findRowByKey(*selected_) : -1;
209 }
210
215 bool handleKey(int key)
216 {
217 if (rows_.empty())
218 return false;
219
220 const int curIdx = selectedRowIndex();
221 const int n = static_cast<int>(rows_.size());
222
223 switch (key)
224 {
225 case Key::Down:
226 if (curIdx < 0)
227 select(rows_.front().key, true);
228 else if (curIdx + 1 < n)
229 select(rows_[static_cast<size_t>(curIdx + 1)].key, true);
230 return true;
231
232 case Key::Up:
233 if (curIdx < 0)
234 select(rows_.back().key, true);
235 else if (curIdx > 0)
236 select(rows_[static_cast<size_t>(curIdx - 1)].key, true);
237 return true;
238
239 case Key::Home:
240 select(rows_.front().key, true);
241 return true;
242
243 case Key::End:
244 select(rows_.back().key, true);
245 return true;
246
247 case Key::Right:
248 if (curIdx >= 0)
249 {
250 const Row cur = rows_[static_cast<size_t>(curIdx)];
251 if (cur.hasChildren)
252 {
253 if (!cur.expanded)
254 setExpanded(cur.key, true, true);
255 else if (curIdx + 1 < n && rows_[static_cast<size_t>(curIdx + 1)].parentRowIndex == curIdx)
256 select(rows_[static_cast<size_t>(curIdx + 1)].key, true);
257 }
258 }
259 return true;
260
261 case Key::Left:
262 if (curIdx >= 0)
263 {
264 const Row cur = rows_[static_cast<size_t>(curIdx)];
265 if (cur.hasChildren && cur.expanded)
266 setExpanded(cur.key, false, true);
267 else if (cur.parentRowIndex >= 0)
268 select(rows_[static_cast<size_t>(cur.parentRowIndex)].key, true);
269 }
270 return true;
271
272 case Key::Enter:
273 if (curIdx >= 0 && onItemActivated)
274 onItemActivated(rows_[static_cast<size_t>(curIdx)]);
275 return true;
276
277 default:
278 return false;
279 }
280 }
281
282 std::function<void()> onChanged;
283 std::function<void(const std::optional<KeyT> &)> onSelectionChanged;
284 std::function<void(const Row &)> onItemActivated;
285 std::function<void(const KeyT &, bool)> onItemToggled;
286
287 private:
288 bool nodeHasChildren(const NodeT &node) const
289 {
290 bool found = false;
291 visitChildren_(node, [&](const NodeT &) -> bool
292 {
293 found = true;
294 return false; // O(1) stop after first child
295 });
296 return found;
297 }
298
299 void appendSubtree(const NodeT &node, int depth, int parentRowIndex)
300 {
301 KeyT key = keyFn_(node);
302 const bool hasKids = nodeHasChildren(node);
303 const bool exp = hasKids && isExpanded(key);
304
305 const int myIndex = static_cast<int>(rows_.size());
306 rows_.push_back(Row{std::move(key), &node, depth, parentRowIndex, hasKids, exp});
307
308 if (exp)
309 {
310 visitChildren_(node, [&](const NodeT &child) -> bool
311 {
312 appendSubtree(child, depth + 1, myIndex);
313 return true;
314 });
315 }
316 }
317
318 void expandAllRecursive(const NodeT &node)
319 {
320 bool hasKids = false;
321 visitChildren_(node, [&](const NodeT &child) -> bool
322 {
323 hasKids = true;
324 expandAllRecursive(child);
325 return true;
326 });
327 if (hasKids)
328 expanded_.insert(keyFn_(node));
329 }
330
331 KeyFn keyFn_;
332 ChildrenInvoker visitChildren_;
333 std::vector<const NodeT *> roots_;
334 std::vector<Row> rows_;
335 std::unordered_set<KeyT> expanded_;
336 std::optional<KeyT> selected_;
337 };
338
340} // namespace ZenitUI::UI
Centralized standard library includes used throughout ZenitUI.
void expandAll(bool notify=true)
Expand every branch reachable from the current roots.
Definition FlatTreeModel.hpp:161
int findRowByKey(const KeyT &key) const
Index of key in the current flat projection, or -1 if hidden/absent.
Definition FlatTreeModel.hpp:132
bool toggle(const KeyT &key, bool notify=true)
Toggle the expanded state of key.
Definition FlatTreeModel.hpp:155
bool handleKey(int key)
Handle standard tree navigation keys (Up, Down, Left, Right, Home, End, Enter).
Definition FlatTreeModel.hpp:215
FlatTreeModel(KeyFnT &&keyFn, ChildrenFnT &&childrenFn)
Construct a model from a key extractor and a children range accessor.
Definition FlatTreeModel.hpp:78
void setRoots(const Range &roots, bool notify=true)
Set root nodes from any iterable range of NodeT or pointers to NodeT.
Definition FlatTreeModel.hpp:102
bool setExpanded(const KeyT &key, bool expanded, bool notify=true)
Expand or collapse key.
Definition FlatTreeModel.hpp:143
void rebuild(bool notify=true)
Re-project the flat row list from the current roots and expanded set.
Definition FlatTreeModel.hpp:114
void collapseAll(bool notify=true)
Collapse every branch.
Definition FlatTreeModel.hpp:172
int selectedRowIndex() const
Flat index of the selected row, or -1 if nothing is selected or it is collapsed.
Definition FlatTreeModel.hpp:206
One visible row produced by FlatTreeModel.
Definition FlatTreeModel.hpp:45
bool hasChildren
true if the node has at least one child.
Definition FlatTreeModel.hpp:50
int parentRowIndex
Index of the parent row in rows(), or -1 for roots.
Definition FlatTreeModel.hpp:49
int depth
Nesting level (0 for roots).
Definition FlatTreeModel.hpp:48
bool expanded
true if the branch is currently expanded.
Definition FlatTreeModel.hpp:51
const NodeT * node
Non-owning pointer to the user's C++ tree node.
Definition FlatTreeModel.hpp:47