1use std::cell::{Cell, RefCell};
13use std::collections::{HashMap, HashSet};
14use std::hash::Hash;
15use std::path::PathBuf;
16use std::rc::Rc;
17use std::time::Duration;
18
19use mitsuami_reactive::{IntoValue, Signal, Value, signal};
20
21use crate::element::{Element, ElementBuilder};
22use crate::list::{FileFn, KeyFn, ListHandle, Mount, MoveFn, RowParts, RowRender, Shape, TreeParts, build_rows};
23use crate::services::Shortcut;
24use crate::tweak::Tweak;
25use crate::ui::Ui;
26use crate::units::Length;
27use crate::view::{AnyView, View};
28use crate::widget::{ListStyle, NodeId, Prop, RowDrop, RowMoves, SelectionMode, WidgetKind};
29
30type ChildrenFn<T> = Rc<dyn Fn(&T) -> Option<Vec<T>>>;
33
34type LoadingFn<T> = Rc<dyn Fn(&T) -> bool>;
36
37pub struct Tree<T: 'static = (), K: 'static = (), R = RowRender<T>> {
60 element: Element,
61 roots: Value<Vec<T>>,
62 key: KeyFn<T, K>,
63 children: ChildrenFn<T>,
64 render: R,
65 expanded: Option<Signal<Vec<K>>>,
66 mode: Option<Value<SelectionMode>>,
67 style: Option<ListStyle>,
68 selected: Option<Signal<Vec<K>>>,
69 on_activate: Option<Rc<dyn Fn(K)>>,
70 estimate: Option<f32>,
71 handle: Option<ListHandle<K>>,
72 files: Option<FileFn<T>>,
73 moves: Option<(RowMoves, MoveFn<K>)>,
74 loading: Option<LoadingFn<T>>,
75}
76
77impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> Tree<T, K> {
78 pub fn new<V: View>(
79 roots: impl IntoValue<Vec<T>>,
80 key: impl Fn(&T) -> K + 'static,
81 children: impl Fn(&T) -> Option<Vec<T>> + 'static,
82 render: impl Fn(T) -> V + 'static,
83 ) -> Tree<T, K> {
84 Tree::with_element(
85 Element::new(WidgetKind::Tree),
86 roots.into_value(),
87 Rc::new(key),
88 Rc::new(children),
89 RowRender::new(move |item| AnyView::new(render(item))),
90 )
91 }
92}
93
94impl<T: 'static, K: 'static, R> Tree<T, K, R> {
95 fn with_element(
96 element: Element,
97 roots: Value<Vec<T>>,
98 key: KeyFn<T, K>,
99 children: ChildrenFn<T>,
100 render: R,
101 ) -> Tree<T, K, R> {
102 Tree {
103 element,
104 roots,
105 key,
106 children,
107 render,
108 expanded: None,
109 mode: None,
110 style: None,
111 selected: None,
112 on_activate: None,
113 estimate: None,
114 handle: None,
115 files: None,
116 moves: None,
117 loading: None,
118 }
119 }
120
121 pub fn on_move(mut self, moves: RowMoves, handler: impl Fn(Vec<K>, RowDrop<K>) + 'static) -> Self {
131 self.moves = Some((moves, Rc::new(handler)));
132 self
133 }
134
135 pub fn loading(mut self, loading: impl Fn(&T) -> bool + 'static) -> Self {
143 self.loading = Some(Rc::new(loading));
144 self
145 }
146
147 pub fn expanded(mut self, expanded: Signal<Vec<K>>) -> Self {
153 self.expanded = Some(expanded);
154 self
155 }
156
157 pub fn drag_files(mut self, file: impl Fn(&T) -> Option<PathBuf> + 'static) -> Self {
160 self.files = Some(Rc::new(file));
161 self
162 }
163
164 pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
169 self.selected = Some(selected);
170 self
171 }
172
173 pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
176 self.mode = Some(mode.into_value());
177 self
178 }
179
180 pub fn list_style(mut self, style: ListStyle) -> Self {
183 self.style = Some(style);
184 self
185 }
186
187 pub fn on_activate(mut self, handler: impl Fn(K) + 'static) -> Self {
191 self.on_activate = Some(Rc::new(handler));
192 self
193 }
194
195 pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Self {
201 self.element.on_key(key.into(), handler);
202 self
203 }
204
205 pub fn estimated_row_height(mut self, height: impl Into<Length>) -> Self {
208 self.estimate = match height.into() {
209 Length::Px(px) => Some(px),
210 _ => None,
211 };
212 self
213 }
214
215 pub fn handle(mut self, handle: ListHandle<K>) -> Self {
219 self.handle = Some(handle);
220 self
221 }
222
223 pub fn native(mut self, tweak: Tweak<Tree>) -> Self {
226 tweak.apply(&mut self.element);
227 self
228 }
229}
230
231impl<T: 'static, K: 'static, R> ElementBuilder for Tree<T, K, R> {
232 fn element(&mut self) -> &mut Element {
233 &mut self.element
234 }
235}
236
237const SPINNER_DELAY: Duration = Duration::from_millis(500);
240
241struct Delayed<T: 'static, K: 'static> {
246 ui: Ui,
247 key: KeyFn<T, K>,
248 loading: LoadingFn<T>,
249 since: RefCell<HashMap<K, (Duration, u64)>>,
250 walk: Cell<u64>,
251 due: Signal<u64>,
252}
253
254impl<T, K: Eq + Hash + Clone> Delayed<T, K> {
255 fn shows(&self, item: &T) -> bool {
257 if !(self.loading)(item) {
258 return false;
259 }
260 self.due.get();
262 let now = self.ui.executor().now();
263 let mut since = self.since.borrow_mut();
264 let walk = self.walk.get();
265 let entry = since.entry((self.key)(item)).or_insert_with(|| {
266 let (ui, due) = (self.ui.clone(), self.due);
267 self.ui.spawn_local(async move {
268 ui.sleep(SPINNER_DELAY).await;
269 if due.is_alive() {
270 due.update(|n| *n += 1);
271 }
272 });
273 (now, walk)
274 });
275 entry.1 = walk;
276 now.saturating_sub(entry.0) >= SPINNER_DELAY
277 }
278
279 fn walk<R>(&self, f: impl FnOnce() -> R) -> R {
281 let walk = self.walk.get() + 1;
282 self.walk.set(walk);
283 let out = f();
284 self.since.borrow_mut().retain(|_, (_, seen)| *seen == walk);
285 out
286 }
287}
288
289#[derive(Clone)]
291struct Flat<T> {
292 item: T,
293 shape: Shape,
294}
295
296fn flatten<T: Clone, K: Eq + Hash>(
300 roots: Vec<T>,
301 key: &dyn Fn(&T) -> K,
302 children: &dyn Fn(&T) -> Option<Vec<T>>,
303 loading: Option<&dyn Fn(&T) -> bool>,
304 open: &HashSet<K>,
305) -> Vec<Flat<T>> {
306 struct Walk<'a, T, K> {
307 key: &'a dyn Fn(&T) -> K,
308 children: &'a dyn Fn(&T) -> Option<Vec<T>>,
309 loading: Option<&'a dyn Fn(&T) -> bool>,
310 open: &'a HashSet<K>,
311 folders: Vec<K>,
313 out: Vec<Flat<T>>,
314 }
315
316 impl<T: Clone, K: Eq + Hash> Walk<'_, T, K> {
317 fn visit(&mut self, items: Vec<T>, parent: Option<usize>, depth: u32) {
318 for item in items {
319 let k = (self.key)(&item);
320 let kids = (self.children)(&item);
321 let expandable = kids.is_some();
322 let expanded = expandable && self.open.contains(&k) && !self.folders.contains(&k);
323 let loading = self.loading.is_some_and(|loading| loading(&item));
324 let index = self.out.len();
325 self.out.push(Flat { item, shape: Shape { parent, depth, expandable, expanded, loading } });
326 if let (true, Some(kids)) = (expanded, kids) {
327 self.folders.push(k);
328 self.visit(kids, Some(index), depth + 1);
329 self.folders.pop();
330 }
331 }
332 }
333 }
334
335 let mut walk = Walk { key, children, loading, open, folders: Vec::new(), out: Vec::new() };
336 walk.visit(roots, None, 0);
337 walk.out
338}
339
340impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> View for Tree<T, K> {
341 fn build(self, ui: &Ui) -> NodeId {
342 let Tree {
343 element,
344 roots,
345 key,
346 children,
347 render,
348 expanded,
349 mode,
350 style,
351 selected,
352 on_activate,
353 estimate,
354 handle,
355 files,
356 moves,
357 loading,
358 } = self;
359 let expanded = expanded.unwrap_or_else(|| signal(Vec::new()));
360 let loads = loading.is_some();
361 let delayed = loading.map(|loading| Delayed {
362 ui: ui.clone(),
363 key: key.clone(),
364 loading,
365 since: RefCell::default(),
366 walk: Cell::new(0),
367 due: signal(0),
368 });
369 let each = {
370 let (key, children) = (key.clone(), children.clone());
371 Value::Dynamic(Rc::new(move || {
372 let open: HashSet<K> = expanded.get().into_iter().collect();
373 match &delayed {
374 Some(delayed) => {
375 let shows = |item: &T| delayed.shows(item);
376 delayed.walk(|| flatten(roots.get(), &*key, &*children, Some(&shows), &open))
377 }
378 None => flatten(roots.get(), &*key, &*children, None, &open),
379 }
380 }))
381 };
382 let mount: Mount<Flat<T>> = Rc::new(move |ui: &Ui, row, flat: Flat<T>| {
383 let host = ui.create(WidgetKind::Container, vec![Prop::Row(row)]);
384 let content = render.render(flat.item).build(ui);
385 ui.append_child(host, content);
386 vec![host]
387 });
388 let tree = TreeParts {
389 shape: Rc::new(|flat: &Flat<T>| flat.shape),
390 on_expand: Rc::new(move |k: K, open: bool| {
391 let has = expanded.with_untracked(|keys| keys.contains(&k));
392 match (open, has) {
393 (true, false) => expanded.update(|keys| keys.push(k)),
394 (false, true) => expanded.update(|keys| keys.retain(|o| *o != k)),
395 _ => {}
396 }
397 }),
398 loading: loads,
399 };
400 let item_key = key.clone();
401 let parts = RowParts {
402 each,
403 key: Rc::new(move |flat: &Flat<T>| item_key(&flat.item)),
404 mount,
405 mode,
406 style,
407 selected,
408 on_activate,
409 estimate,
410 handle,
411 files: files.map(|file| Rc::new(move |flat: &Flat<T>| file(&flat.item)) as FileFn<Flat<T>>),
412 moves,
413 tree: Some(tree),
414 };
415 build_rows(ui, element, parts)
416 }
417}
418
419impl Tree<(), (), ()> {
425 #[doc(hidden)]
426 pub fn __tag() -> TreeWithoutRoots {
427 TreeWithoutRoots(Element::new(WidgetKind::Tree))
428 }
429}
430
431#[doc(hidden)]
432pub struct TreeWithoutRoots(Element);
433
434impl TreeWithoutRoots {
435 pub fn roots<T: Clone + 'static>(self, roots: impl IntoValue<Vec<T>>) -> TreeWithoutKey<T> {
436 TreeWithoutKey { element: self.0, roots: roots.into_value() }
437 }
438}
439
440impl ElementBuilder for TreeWithoutRoots {
441 fn element(&mut self) -> &mut Element {
442 &mut self.0
443 }
444}
445
446#[doc(hidden)]
447pub struct TreeWithoutKey<T: 'static> {
448 element: Element,
449 roots: Value<Vec<T>>,
450}
451
452impl<T: Clone + 'static> TreeWithoutKey<T> {
453 pub fn key<K: Eq + Hash + Clone + 'static>(self, key: impl Fn(&T) -> K + 'static) -> TreeWithoutChildren<T, K> {
454 TreeWithoutChildren { element: self.element, roots: self.roots, key: Rc::new(key) }
455 }
456}
457
458impl<T: 'static> ElementBuilder for TreeWithoutKey<T> {
459 fn element(&mut self) -> &mut Element {
460 &mut self.element
461 }
462}
463
464#[doc(hidden)]
465pub struct TreeWithoutChildren<T: 'static, K: 'static> {
466 element: Element,
467 roots: Value<Vec<T>>,
468 key: KeyFn<T, K>,
469}
470
471impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> TreeWithoutChildren<T, K> {
472 pub fn children(self, children: impl Fn(&T) -> Option<Vec<T>> + 'static) -> Tree<T, K, ()> {
473 Tree::with_element(self.element, self.roots, self.key, Rc::new(children), ())
474 }
475}
476
477impl<T: 'static, K: 'static> ElementBuilder for TreeWithoutChildren<T, K> {
478 fn element(&mut self) -> &mut Element {
479 &mut self.element
480 }
481}
482
483impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> Tree<T, K, ()> {
484 #[doc(hidden)]
485 pub fn __children<V: View>(self, render: impl Fn(T) -> V + 'static) -> Tree<T, K> {
486 let Tree {
487 element,
488 roots,
489 key,
490 children,
491 expanded,
492 mode,
493 style,
494 selected,
495 on_activate,
496 estimate,
497 handle,
498 files,
499 moves,
500 loading,
501 ..
502 } = self;
503 Tree {
504 element,
505 roots,
506 key,
507 children,
508 render: RowRender::new(move |item| AnyView::new(render(item))),
509 expanded,
510 mode,
511 style,
512 selected,
513 on_activate,
514 estimate,
515 handle,
516 files,
517 moves,
518 loading,
519 }
520 }
521}