1use std::cell::RefCell;
11use std::collections::{HashMap, HashSet};
12use std::hash::Hash;
13use std::path::PathBuf;
14use std::rc::Rc;
15
16use mitsuami_reactive::{IntoValue, Owner, Signal, Value, effect, untrack};
17
18use crate::command::{EventValue, UiEvent};
19use crate::element::{Element, ElementBuilder};
20use crate::services::Shortcut;
21use crate::tweak::Tweak;
22use crate::ui::{Ui, WeakUi};
23use crate::units::Length;
24use crate::view::{AnyView, View};
25use crate::widget::{ListStyle, NodeId, Prop, RowDrop, RowKey, RowMoves, SelectionMode, TreeRow, WidgetKind};
26
27pub(crate) type KeyFn<T, K> = Rc<dyn Fn(&T) -> K>;
28pub(crate) type FileFn<T> = Rc<dyn Fn(&T) -> Option<PathBuf>>;
30type RowOf<K> = Rc<dyn Fn(&K) -> Option<RowKey>>;
31pub(crate) type MoveFn<K> = Rc<dyn Fn(Vec<K>, RowDrop<K>)>;
33
34pub struct RowRender<T>(Rc<dyn Fn(T) -> AnyView>);
36
37impl<T> RowRender<T> {
38 pub(crate) fn new(render: impl Fn(T) -> AnyView + 'static) -> RowRender<T> {
39 RowRender(Rc::new(render))
40 }
41
42 pub(crate) fn render(&self, item: T) -> AnyView {
43 (self.0)(item)
44 }
45}
46
47pub struct List<T: 'static = (), K: 'static = (), R = RowRender<T>> {
67 element: Element,
68 each: Value<Vec<T>>,
69 key: KeyFn<T, K>,
70 render: R,
71 mode: Option<Value<SelectionMode>>,
72 style: Option<ListStyle>,
73 selected: Option<Signal<Vec<K>>>,
74 on_activate: Option<Rc<dyn Fn(K)>>,
75 estimate: Option<f32>,
76 handle: Option<ListHandle<K>>,
77 files: Option<FileFn<T>>,
78 moves: Option<(RowMoves, MoveFn<K>)>,
79}
80
81impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> List<T, K> {
82 pub fn new<V: View>(
83 each: impl IntoValue<Vec<T>>,
84 key: impl Fn(&T) -> K + 'static,
85 render: impl Fn(T) -> V + 'static,
86 ) -> List<T, K> {
87 List::keyed(each.into_value(), Rc::new(key), RowRender(Rc::new(move |item| AnyView::new(render(item)))))
88 }
89}
90
91impl<T: 'static, K: 'static, R> List<T, K, R> {
92 fn keyed(each: Value<Vec<T>>, key: KeyFn<T, K>, render: R) -> List<T, K, R> {
93 List::with_element(Element::new(WidgetKind::List), each, key, render)
94 }
95
96 fn with_element(element: Element, each: Value<Vec<T>>, key: KeyFn<T, K>, render: R) -> List<T, K, R> {
97 List {
98 element,
99 each,
100 key,
101 render,
102 mode: None,
103 style: None,
104 selected: None,
105 on_activate: None,
106 estimate: None,
107 handle: None,
108 files: None,
109 moves: None,
110 }
111 }
112
113 pub fn on_move(mut self, moves: RowMoves, handler: impl Fn(Vec<K>, RowDrop<K>) + 'static) -> Self {
126 self.moves = Some((moves, Rc::new(handler)));
127 self
128 }
129
130 pub fn drag_files(mut self, file: impl Fn(&T) -> Option<PathBuf> + 'static) -> Self {
142 self.files = Some(Rc::new(file));
143 self
144 }
145
146 pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
150 self.selected = Some(selected);
151 self
152 }
153
154 pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
158 self.mode = Some(mode.into_value());
159 self
160 }
161
162 pub fn list_style(mut self, style: ListStyle) -> Self {
169 self.style = Some(style);
170 self
171 }
172
173 pub fn on_activate(mut self, handler: impl Fn(K) + 'static) -> Self {
176 self.on_activate = Some(Rc::new(handler));
177 self
178 }
179
180 pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Self {
193 self.element.on_key(key.into(), handler);
194 self
195 }
196
197 pub fn estimated_row_height(mut self, height: impl Into<Length>) -> Self {
200 self.estimate = match height.into() {
201 Length::Px(px) => Some(px),
202 _ => None,
203 };
204 self
205 }
206
207 pub fn handle(mut self, handle: ListHandle<K>) -> Self {
209 self.handle = Some(handle);
210 self
211 }
212
213 pub fn native(mut self, tweak: Tweak<List>) -> Self {
219 tweak.apply(&mut self.element);
220 self
221 }
222}
223
224impl<T: 'static, K: 'static, R> ElementBuilder for List<T, K, R> {
225 fn element(&mut self) -> &mut Element {
226 &mut self.element
227 }
228}
229
230pub struct ListHandle<K: 'static>(Rc<RefCell<HandleState<K>>>);
233
234struct HandleState<K> {
235 connection: Option<Connection<K>>,
236 pending: Option<K>,
240}
241
242struct Connection<K> {
243 ui: WeakUi,
244 id: NodeId,
245 row_of: RowOf<K>,
246}
247
248impl<K: 'static> ListHandle<K> {
249 pub fn new() -> ListHandle<K> {
250 ListHandle(Rc::new(RefCell::new(HandleState { connection: None, pending: None })))
251 }
252
253 pub fn id(&self) -> Option<NodeId> {
255 self.0.borrow().connection.as_ref().map(|c| c.id)
256 }
257
258 pub fn scroll_to(&self, key: &K)
262 where
263 K: Clone,
264 {
265 let mut state = self.0.borrow_mut();
266 let found = state
267 .connection
268 .as_ref()
269 .and_then(|Connection { ui, id, row_of }| Some((ui.upgrade()?, *id, row_of(key)?)));
270 match found {
271 Some((ui, id, row)) => {
272 state.pending = None;
273 drop(state);
274 ui.scroll_to_row(id, row);
275 }
276 None => state.pending = Some(key.clone()),
277 }
278 }
279}
280
281impl<K: 'static> Clone for ListHandle<K> {
282 fn clone(&self) -> Self {
283 ListHandle(self.0.clone())
284 }
285}
286
287impl<K: 'static> Default for ListHandle<K> {
288 fn default() -> Self {
289 ListHandle::new()
290 }
291}
292
293struct Rows<T, K> {
295 order: Vec<RowKey>,
297 items: HashMap<RowKey, T>,
298 position: HashMap<RowKey, usize>,
299 row_keys: HashMap<K, RowKey>,
300 keys: HashMap<RowKey, K>,
301 next_key: u64,
302 mounted: HashMap<RowKey, (Vec<NodeId>, Owner)>,
305}
306
307pub(crate) type Mount<T> = Rc<dyn Fn(&Ui, RowKey, T) -> Vec<NodeId>>;
309
310pub(crate) struct RowParts<T: 'static, K: 'static> {
313 pub each: Value<Vec<T>>,
314 pub key: KeyFn<T, K>,
315 pub mount: Mount<T>,
316 pub mode: Option<Value<SelectionMode>>,
317 pub style: Option<ListStyle>,
318 pub selected: Option<Signal<Vec<K>>>,
319 pub on_activate: Option<Rc<dyn Fn(K)>>,
320 pub estimate: Option<f32>,
321 pub handle: Option<ListHandle<K>>,
322 pub files: Option<FileFn<T>>,
323 pub moves: Option<(RowMoves, MoveFn<K>)>,
324 pub tree: Option<TreeParts<T, K>>,
327}
328
329#[derive(Clone, Copy, Debug)]
331pub(crate) struct Shape {
332 pub parent: Option<usize>,
334 pub depth: u32,
335 pub expandable: bool,
336 pub expanded: bool,
337 pub loading: bool,
339}
340
341pub(crate) struct TreeParts<T: 'static, K: 'static> {
343 pub shape: Rc<dyn Fn(&T) -> Shape>,
344 pub on_expand: Rc<dyn Fn(K, bool)>,
346 pub loading: bool,
348}
349
350impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> View for List<T, K> {
351 fn build(self, ui: &Ui) -> NodeId {
352 let List { element, each, key, render, mode, style, selected, on_activate, estimate, handle, files, moves } =
353 self;
354 let mount: Mount<T> = Rc::new(move |ui: &Ui, row, item| {
355 let host = ui.create(WidgetKind::Container, vec![Prop::Row(row)]);
356 let content = (render.0)(item).build(ui);
357 ui.append_child(host, content);
358 vec![host]
359 });
360 let parts = RowParts {
361 each,
362 key,
363 mount,
364 mode,
365 style,
366 selected,
367 on_activate,
368 estimate,
369 handle,
370 files,
371 moves,
372 tree: None,
373 };
374 build_rows(ui, element, parts)
375 }
376}
377
378pub(crate) fn build_rows<T: Clone + 'static, K: Eq + Hash + Clone + 'static>(
381 ui: &Ui,
382 mut element: Element,
383 parts: RowParts<T, K>,
384) -> NodeId {
385 let RowParts { each, key, mount, mode, style, selected, on_activate, estimate, handle, files, moves, tree } = parts;
386 let mode = mode.unwrap_or(Value::Static(match selected {
387 Some(_) => SelectionMode::Single,
388 None => SelectionMode::None,
389 }));
390 element.prop(mode, Prop::SelectionMode);
391 match tree {
392 Some(_) => element.prop(Value::Static(Vec::new()), Prop::TreeRows),
393 None => element.prop(Value::Static(Vec::new()), Prop::Rows),
394 }
395 element.prop(Value::Static(Vec::new()), Prop::Selected);
396 if let Some(style) = style {
397 element.prop(Value::Static(style), Prop::ListStyle);
398 }
399 if let Some(estimate) = estimate {
400 element.prop(Value::Static(estimate), Prop::EstimatedRowHeight);
401 }
402 if let Some((moves, _)) = &moves {
403 element.prop(Value::Static(*moves), Prop::RowMoves);
404 }
405 let id = element.build(ui);
406
407 let rows: Rc<RefCell<Rows<T, K>>> = Rc::new(RefCell::new(Rows {
408 order: Vec::new(),
409 items: HashMap::new(),
410 position: HashMap::new(),
411 row_keys: HashMap::new(),
412 keys: HashMap::new(),
413 next_key: 1,
414 mounted: HashMap::new(),
415 }));
416 let scope = ui.owner_or_node_scope(id);
420 let rows_scope = scope.child();
421
422 let arrange = {
425 let rows = rows.clone();
426 move |ui: &Ui| {
427 let rows = rows.borrow();
428 let mut mounted: Vec<(usize, &Vec<NodeId>)> =
429 rows.mounted.iter().map(|(row, (hosts, _))| (rows.position[row], hosts)).collect();
430 mounted.sort_by_key(|(position, _)| *position);
431 ui.set_children(id, mounted.into_iter().flat_map(|(_, hosts)| hosts.iter().copied()).collect());
432 }
433 };
434 let unmount = move |ui: &Ui, rows: &mut Rows<T, K>, row: RowKey| {
435 if let Some((hosts, owner)) = rows.mounted.remove(&row) {
436 owner.dispose();
437 for host in hosts {
438 ui.destroy(host);
439 }
440 }
441 };
442 {
444 let (weak, rows, arrange, unmount) = (ui.downgrade(), rows.clone(), arrange.clone(), unmount);
445 ui.on_event(id, move |event| {
446 let Some(ui) = weak.upgrade() else { return };
447 match event {
448 UiEvent::RowShown(row) => {
449 let item = {
450 let rows = rows.borrow();
451 if rows.mounted.contains_key(row) {
452 return;
453 }
454 let Some(item) = rows.items.get(row).cloned() else { return };
455 item
456 };
457 let owner = rows_scope.child();
458 let hosts = owner.with(|| mount(&ui, *row, item));
459 let gone = {
463 let mut rows = rows.borrow_mut();
464 match rows.items.contains_key(row) {
465 true => {
466 rows.mounted.insert(*row, (hosts, owner));
467 None
468 }
469 false => Some(hosts),
470 }
471 };
472 if let Some(hosts) = gone {
473 owner.dispose();
474 for host in hosts {
475 ui.destroy(host);
476 }
477 }
478 }
479 UiEvent::RowHidden(row) => unmount(&ui, &mut rows.borrow_mut(), *row),
480 _ => return,
481 }
482 arrange(&ui);
483 });
484 }
485
486 {
489 let (ui, rows) = (ui.clone(), rows.clone());
490 let pending = handle.as_ref().map(|h| h.0.clone());
491 let shape = tree.as_ref().map(|t| t.shape.clone());
492 let loading = tree.as_ref().is_some_and(|t| t.loading);
493 let update = move || {
494 let items = each.get();
495 untrack(|| {
496 let mut row_files = Vec::new();
497 let mut shapes = Vec::new();
498 let (order, was) = {
499 let mut rows = rows.borrow_mut();
500 let rows = &mut *rows;
501 let was: HashSet<RowKey> = rows.order.iter().copied().collect();
502 let mut row_keys = HashMap::with_capacity(items.len());
503 let mut keys = HashMap::with_capacity(items.len());
504 let mut by_key = HashMap::with_capacity(items.len());
505 let mut order = Vec::with_capacity(items.len());
506 for item in items {
507 let k = key(&item);
508 let row = match rows.row_keys.get(&k) {
512 Some(row) if !row_keys.contains_key(&k) => *row,
513 _ => {
514 rows.next_key += 1;
515 RowKey(rows.next_key - 1)
516 }
517 };
518 if let Some(shape) = &shape {
519 shapes.push(shape(&item));
520 }
521 if let Some(path) = files.as_ref().and_then(|file| file(&item)) {
522 row_files.push((row, path));
523 }
524 row_keys.entry(k.clone()).or_insert(row);
525 keys.insert(row, k);
526 by_key.insert(row, item);
527 order.push(row);
528 }
529 rows.position = order.iter().enumerate().map(|(i, row)| (*row, i)).collect();
530 rows.items = by_key;
531 rows.row_keys = row_keys;
532 rows.keys = keys;
533 rows.order = order.clone();
534 let gone: Vec<RowKey> =
535 rows.mounted.keys().filter(|row| !rows.items.contains_key(row)).copied().collect();
536 for row in gone {
537 unmount(&ui, rows, row);
538 }
539 (order, was)
540 };
541 if files.is_some() {
543 ui.set_prop(id, Prop::RowFiles(row_files));
544 }
545 let rows_prop = |order: Vec<RowKey>| match shape {
548 Some(_) => Prop::TreeRows(
549 order
550 .iter()
551 .zip(&shapes)
552 .map(|(row, s)| TreeRow {
553 row: *row,
554 parent: s.parent.map(|i| order[i]),
555 depth: s.depth,
556 expandable: s.expandable,
557 expanded: s.expanded,
558 })
559 .collect(),
560 ),
561 None => Prop::Rows(order),
562 };
563 let set_rows = |order: Vec<RowKey>| {
564 if loading {
565 let rows = order.iter().zip(&shapes).filter(|(_, s)| s.loading).map(|(row, _)| *row);
566 let loading = Prop::TreeLoading(rows.collect());
567 ui.set_prop(id, rows_prop(order));
568 ui.set_prop(id, loading);
569 } else {
570 ui.set_prop(id, rows_prop(order));
571 }
572 };
573 let pending = pending.as_ref().and_then(|state| state.borrow_mut().pending.take());
575 let scroll = pending.and_then(|k| rows.borrow().row_keys.get(&k).copied());
576 let Some(selected) = selected else {
577 set_rows(order);
578 if let Some(row) = scroll {
579 ui.scroll_to_row(id, row);
580 }
581 return arrange(&ui);
582 };
583 let keys = selected.get_untracked();
587 let (kept, shown) = {
588 let rows = rows.borrow();
589 let kept: Vec<K> = keys.iter().filter(|k| rows.row_keys.contains_key(k)).cloned().collect();
590 let mut shown: Vec<RowKey> = kept.iter().map(|k| rows.row_keys[k]).collect();
591 shown.sort_by_key(|row| rows.position[row]);
592 (kept, shown)
593 };
594 let staying = shown.iter().filter(|row| was.contains(row)).copied().collect();
595 ui.set_prop(id, Prop::Selected(staying));
596 set_rows(order);
597 ui.set_prop(id, Prop::Selected(shown));
599 if let Some(row) = scroll {
600 ui.scroll_to_row(id, row);
601 }
602 if kept.len() != keys.len() {
603 selected.set(kept);
604 }
605 arrange(&ui);
606 });
607 };
608 scope.with(|| effect(update));
609 }
610
611 if let Some(selected) = selected {
613 let (ui_, rows_) = (ui.clone(), rows.clone());
614 let update = move || {
615 let keys = selected.get();
616 let rows = rows_.borrow();
617 let mut selection: Vec<RowKey> = keys.iter().filter_map(|k| rows.row_keys.get(k).copied()).collect();
619 selection.sort_by_key(|row| rows.position[row]);
620 drop(rows);
621 untrack(|| ui_.set_prop(id, Prop::Selected(selection)));
622 };
623 scope.with(|| effect(update));
624 let rows = rows.clone();
625 ui.on_event(id, move |event| {
626 if let UiEvent::Changed(EventValue::Rows(selection)) = event {
627 let keys: Vec<K> = {
628 let rows = rows.borrow();
629 selection.iter().filter_map(|row| rows.keys.get(row).cloned()).collect()
630 };
631 selected.set(keys);
632 }
633 });
634 }
635 if let Some(on_activate) = on_activate {
636 let rows = rows.clone();
637 ui.on_event(id, move |event| {
638 if let UiEvent::RowActivated(row) = event {
639 let key = rows.borrow().keys.get(row).cloned();
640 if let Some(key) = key {
641 on_activate(key);
642 }
643 }
644 });
645 }
646 if let Some((_, on_move)) = moves {
647 let rows = rows.clone();
648 ui.on_event(id, move |event| {
649 if let UiEvent::RowsMoved { rows: moved, to } = event {
650 let (keys, to) = {
651 let rows = rows.borrow();
652 let keys: Vec<K> = moved.iter().filter_map(|row| rows.keys.get(row).cloned()).collect();
653 let to = match to.map(|row| rows.keys.get(&row).cloned()) {
654 RowDrop::On(Some(k)) => RowDrop::On(k),
655 RowDrop::Before(Some(k)) => RowDrop::Before(k),
656 RowDrop::End => RowDrop::End,
657 _ => return,
659 };
660 (keys, to)
661 };
662 if !keys.is_empty() {
663 on_move(keys, to);
664 }
665 }
666 });
667 }
668 if let Some(TreeParts { on_expand, .. }) = tree {
669 let rows = rows.clone();
670 ui.on_event(id, move |event| {
671 if let UiEvent::RowExpanded(row, open) = event {
672 let key = rows.borrow().keys.get(row).cloned();
673 if let Some(key) = key {
674 on_expand(key, *open);
675 }
676 }
677 });
678 }
679 if let Some(handle) = handle {
680 let rows = rows.clone();
681 handle.0.borrow_mut().connection = Some(Connection {
682 ui: ui.downgrade(),
683 id,
684 row_of: Rc::new(move |k| rows.borrow().row_keys.get(k).copied()),
685 });
686 }
687 id
688}
689
690impl List<(), (), ()> {
695 #[doc(hidden)]
696 pub fn __tag() -> ListWithoutEach {
697 ListWithoutEach(Element::new(WidgetKind::List))
698 }
699}
700
701#[doc(hidden)]
702pub struct ListWithoutEach(Element);
703
704impl ListWithoutEach {
705 pub fn each<T: Clone + 'static>(self, each: impl IntoValue<Vec<T>>) -> ListWithoutKey<T> {
706 ListWithoutKey { element: self.0, each: each.into_value() }
707 }
708}
709
710impl ElementBuilder for ListWithoutEach {
711 fn element(&mut self) -> &mut Element {
712 &mut self.0
713 }
714}
715
716#[doc(hidden)]
717pub struct ListWithoutKey<T: 'static> {
718 element: Element,
719 each: Value<Vec<T>>,
720}
721
722impl<T: Clone + 'static> ListWithoutKey<T> {
723 pub fn key<K: Eq + Hash + Clone + 'static>(self, key: impl Fn(&T) -> K + 'static) -> List<T, K, ()> {
724 List::with_element(self.element, self.each, Rc::new(key), ())
725 }
726}
727
728impl<T: 'static> ElementBuilder for ListWithoutKey<T> {
729 fn element(&mut self) -> &mut Element {
730 &mut self.element
731 }
732}
733
734impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> List<T, K, ()> {
735 #[doc(hidden)]
736 pub fn __children<V: View>(self, render: impl Fn(T) -> V + 'static) -> List<T, K> {
737 let List { element, each, key, mode, style, selected, on_activate, estimate, handle, files, moves, .. } = self;
738 let render = RowRender(Rc::new(move |item| AnyView::new(render(item))) as Rc<dyn Fn(T) -> AnyView>);
739 List { element, each, key, render, mode, style, selected, on_activate, estimate, handle, files, moves }
740 }
741}