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, RowKey, SelectionMode, 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>>;
31
32pub struct RowRender<T>(Rc<dyn Fn(T) -> AnyView>);
34
35pub struct List<T: 'static = (), K: 'static = (), R = RowRender<T>> {
55 element: Element,
56 each: Value<Vec<T>>,
57 key: KeyFn<T, K>,
58 render: R,
59 mode: Option<Value<SelectionMode>>,
60 style: Option<ListStyle>,
61 selected: Option<Signal<Vec<K>>>,
62 on_activate: Option<Rc<dyn Fn(K)>>,
63 estimate: Option<f32>,
64 handle: Option<ListHandle<K>>,
65 files: Option<FileFn<T>>,
66}
67
68impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> List<T, K> {
69 pub fn new<V: View>(
70 each: impl IntoValue<Vec<T>>,
71 key: impl Fn(&T) -> K + 'static,
72 render: impl Fn(T) -> V + 'static,
73 ) -> List<T, K> {
74 List::keyed(each.into_value(), Rc::new(key), RowRender(Rc::new(move |item| AnyView::new(render(item)))))
75 }
76}
77
78impl<T: 'static, K: 'static, R> List<T, K, R> {
79 fn keyed(each: Value<Vec<T>>, key: KeyFn<T, K>, render: R) -> List<T, K, R> {
80 List::with_element(Element::new(WidgetKind::List), each, key, render)
81 }
82
83 fn with_element(element: Element, each: Value<Vec<T>>, key: KeyFn<T, K>, render: R) -> List<T, K, R> {
84 List {
85 element,
86 each,
87 key,
88 render,
89 mode: None,
90 style: None,
91 selected: None,
92 on_activate: None,
93 estimate: None,
94 handle: None,
95 files: None,
96 }
97 }
98
99 pub fn drag_files(mut self, file: impl Fn(&T) -> Option<PathBuf> + 'static) -> Self {
111 self.files = Some(Rc::new(file));
112 self
113 }
114
115 pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
119 self.selected = Some(selected);
120 self
121 }
122
123 pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
127 self.mode = Some(mode.into_value());
128 self
129 }
130
131 pub fn list_style(mut self, style: ListStyle) -> Self {
138 self.style = Some(style);
139 self
140 }
141
142 pub fn on_activate(mut self, handler: impl Fn(K) + 'static) -> Self {
145 self.on_activate = Some(Rc::new(handler));
146 self
147 }
148
149 pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Self {
162 self.element.on_key(key.into(), handler);
163 self
164 }
165
166 pub fn estimated_row_height(mut self, height: impl Into<Length>) -> Self {
169 self.estimate = match height.into() {
170 Length::Px(px) => Some(px),
171 _ => None,
172 };
173 self
174 }
175
176 pub fn handle(mut self, handle: ListHandle<K>) -> Self {
178 self.handle = Some(handle);
179 self
180 }
181
182 pub fn native(mut self, tweak: Tweak<List>) -> Self {
188 tweak.apply(&mut self.element);
189 self
190 }
191}
192
193impl<T: 'static, K: 'static, R> ElementBuilder for List<T, K, R> {
194 fn element(&mut self) -> &mut Element {
195 &mut self.element
196 }
197}
198
199pub struct ListHandle<K: 'static>(Rc<RefCell<HandleState<K>>>);
202
203struct HandleState<K> {
204 connection: Option<Connection<K>>,
205 pending: Option<K>,
209}
210
211struct Connection<K> {
212 ui: WeakUi,
213 id: NodeId,
214 row_of: RowOf<K>,
215}
216
217impl<K: 'static> ListHandle<K> {
218 pub fn new() -> ListHandle<K> {
219 ListHandle(Rc::new(RefCell::new(HandleState { connection: None, pending: None })))
220 }
221
222 pub fn id(&self) -> Option<NodeId> {
224 self.0.borrow().connection.as_ref().map(|c| c.id)
225 }
226
227 pub fn scroll_to(&self, key: &K)
231 where
232 K: Clone,
233 {
234 let mut state = self.0.borrow_mut();
235 let found = state
236 .connection
237 .as_ref()
238 .and_then(|Connection { ui, id, row_of }| Some((ui.upgrade()?, *id, row_of(key)?)));
239 match found {
240 Some((ui, id, row)) => {
241 state.pending = None;
242 drop(state);
243 ui.scroll_to_row(id, row);
244 }
245 None => state.pending = Some(key.clone()),
246 }
247 }
248}
249
250impl<K: 'static> Clone for ListHandle<K> {
251 fn clone(&self) -> Self {
252 ListHandle(self.0.clone())
253 }
254}
255
256impl<K: 'static> Default for ListHandle<K> {
257 fn default() -> Self {
258 ListHandle::new()
259 }
260}
261
262struct Rows<T, K> {
264 order: Vec<RowKey>,
266 items: HashMap<RowKey, T>,
267 position: HashMap<RowKey, usize>,
268 row_keys: HashMap<K, RowKey>,
269 keys: HashMap<RowKey, K>,
270 next_key: u64,
271 mounted: HashMap<RowKey, (Vec<NodeId>, Owner)>,
274}
275
276pub(crate) type Mount<T> = Rc<dyn Fn(&Ui, RowKey, T) -> Vec<NodeId>>;
278
279pub(crate) struct RowParts<T: 'static, K: 'static> {
282 pub each: Value<Vec<T>>,
283 pub key: KeyFn<T, K>,
284 pub mount: Mount<T>,
285 pub mode: Option<Value<SelectionMode>>,
286 pub style: Option<ListStyle>,
287 pub selected: Option<Signal<Vec<K>>>,
288 pub on_activate: Option<Rc<dyn Fn(K)>>,
289 pub estimate: Option<f32>,
290 pub handle: Option<ListHandle<K>>,
291 pub files: Option<FileFn<T>>,
292}
293
294impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> View for List<T, K> {
295 fn build(self, ui: &Ui) -> NodeId {
296 let List { element, each, key, render, mode, style, selected, on_activate, estimate, handle, files } = self;
297 let mount: Mount<T> = Rc::new(move |ui: &Ui, row, item| {
298 let host = ui.create(WidgetKind::Container, vec![Prop::Row(row)]);
299 let content = (render.0)(item).build(ui);
300 ui.append_child(host, content);
301 vec![host]
302 });
303 let parts = RowParts { each, key, mount, mode, style, selected, on_activate, estimate, handle, files };
304 build_rows(ui, element, parts)
305 }
306}
307
308pub(crate) fn build_rows<T: Clone + 'static, K: Eq + Hash + Clone + 'static>(
311 ui: &Ui,
312 mut element: Element,
313 parts: RowParts<T, K>,
314) -> NodeId {
315 let RowParts { each, key, mount, mode, style, selected, on_activate, estimate, handle, files } = parts;
316 let mode = mode.unwrap_or(Value::Static(match selected {
317 Some(_) => SelectionMode::Single,
318 None => SelectionMode::None,
319 }));
320 element.prop(mode, Prop::SelectionMode);
321 element.prop(Value::Static(Vec::new()), Prop::Rows);
322 element.prop(Value::Static(Vec::new()), Prop::Selected);
323 if let Some(style) = style {
324 element.prop(Value::Static(style), Prop::ListStyle);
325 }
326 if let Some(estimate) = estimate {
327 element.prop(Value::Static(estimate), Prop::EstimatedRowHeight);
328 }
329 let id = element.build(ui);
330
331 let rows: Rc<RefCell<Rows<T, K>>> = Rc::new(RefCell::new(Rows {
332 order: Vec::new(),
333 items: HashMap::new(),
334 position: HashMap::new(),
335 row_keys: HashMap::new(),
336 keys: HashMap::new(),
337 next_key: 1,
338 mounted: HashMap::new(),
339 }));
340 let scope = ui.owner_or_node_scope(id);
344 let rows_scope = scope.child();
345
346 let arrange = {
349 let rows = rows.clone();
350 move |ui: &Ui| {
351 let rows = rows.borrow();
352 let mut mounted: Vec<(usize, &Vec<NodeId>)> =
353 rows.mounted.iter().map(|(row, (hosts, _))| (rows.position[row], hosts)).collect();
354 mounted.sort_by_key(|(position, _)| *position);
355 ui.set_children(id, mounted.into_iter().flat_map(|(_, hosts)| hosts.iter().copied()).collect());
356 }
357 };
358 let unmount = move |ui: &Ui, rows: &mut Rows<T, K>, row: RowKey| {
359 if let Some((hosts, owner)) = rows.mounted.remove(&row) {
360 owner.dispose();
361 for host in hosts {
362 ui.destroy(host);
363 }
364 }
365 };
366 {
368 let (weak, rows, arrange, unmount) = (ui.downgrade(), rows.clone(), arrange.clone(), unmount);
369 ui.on_event(id, move |event| {
370 let Some(ui) = weak.upgrade() else { return };
371 match event {
372 UiEvent::RowShown(row) => {
373 let item = {
374 let rows = rows.borrow();
375 if rows.mounted.contains_key(row) {
376 return;
377 }
378 let Some(item) = rows.items.get(row).cloned() else { return };
379 item
380 };
381 let owner = rows_scope.child();
382 let hosts = owner.with(|| mount(&ui, *row, item));
383 let gone = {
387 let mut rows = rows.borrow_mut();
388 match rows.items.contains_key(row) {
389 true => {
390 rows.mounted.insert(*row, (hosts, owner));
391 None
392 }
393 false => Some(hosts),
394 }
395 };
396 if let Some(hosts) = gone {
397 owner.dispose();
398 for host in hosts {
399 ui.destroy(host);
400 }
401 }
402 }
403 UiEvent::RowHidden(row) => unmount(&ui, &mut rows.borrow_mut(), *row),
404 _ => return,
405 }
406 arrange(&ui);
407 });
408 }
409
410 {
413 let (ui, rows) = (ui.clone(), rows.clone());
414 let pending = handle.as_ref().map(|h| h.0.clone());
415 let update = move || {
416 let items = each.get();
417 untrack(|| {
418 let mut row_files = Vec::new();
419 let (order, was) = {
420 let mut rows = rows.borrow_mut();
421 let rows = &mut *rows;
422 let was: HashSet<RowKey> = rows.order.iter().copied().collect();
423 let mut row_keys = HashMap::with_capacity(items.len());
424 let mut keys = HashMap::with_capacity(items.len());
425 let mut by_key = HashMap::with_capacity(items.len());
426 let mut order = Vec::with_capacity(items.len());
427 for item in items {
428 let k = key(&item);
429 let row = match rows.row_keys.get(&k) {
433 Some(row) if !row_keys.contains_key(&k) => *row,
434 _ => {
435 rows.next_key += 1;
436 RowKey(rows.next_key - 1)
437 }
438 };
439 if let Some(path) = files.as_ref().and_then(|file| file(&item)) {
440 row_files.push((row, path));
441 }
442 row_keys.entry(k.clone()).or_insert(row);
443 keys.insert(row, k);
444 by_key.insert(row, item);
445 order.push(row);
446 }
447 rows.position = order.iter().enumerate().map(|(i, row)| (*row, i)).collect();
448 rows.items = by_key;
449 rows.row_keys = row_keys;
450 rows.keys = keys;
451 rows.order = order.clone();
452 let gone: Vec<RowKey> =
453 rows.mounted.keys().filter(|row| !rows.items.contains_key(row)).copied().collect();
454 for row in gone {
455 unmount(&ui, rows, row);
456 }
457 (order, was)
458 };
459 if files.is_some() {
461 ui.set_prop(id, Prop::RowFiles(row_files));
462 }
463 let pending = pending.as_ref().and_then(|state| state.borrow_mut().pending.take());
465 let scroll = pending.and_then(|k| rows.borrow().row_keys.get(&k).copied());
466 let Some(selected) = selected else {
467 ui.set_prop(id, Prop::Rows(order));
468 if let Some(row) = scroll {
469 ui.scroll_to_row(id, row);
470 }
471 return arrange(&ui);
472 };
473 let keys = selected.get_untracked();
477 let (kept, shown) = {
478 let rows = rows.borrow();
479 let kept: Vec<K> = keys.iter().filter(|k| rows.row_keys.contains_key(k)).cloned().collect();
480 let mut shown: Vec<RowKey> = kept.iter().map(|k| rows.row_keys[k]).collect();
481 shown.sort_by_key(|row| rows.position[row]);
482 (kept, shown)
483 };
484 let staying = shown.iter().filter(|row| was.contains(row)).copied().collect();
485 ui.set_prop(id, Prop::Selected(staying));
486 ui.set_prop(id, Prop::Rows(order));
487 ui.set_prop(id, Prop::Selected(shown));
489 if let Some(row) = scroll {
490 ui.scroll_to_row(id, row);
491 }
492 if kept.len() != keys.len() {
493 selected.set(kept);
494 }
495 arrange(&ui);
496 });
497 };
498 scope.with(|| effect(update));
499 }
500
501 if let Some(selected) = selected {
503 let (ui_, rows_) = (ui.clone(), rows.clone());
504 let update = move || {
505 let keys = selected.get();
506 let rows = rows_.borrow();
507 let mut selection: Vec<RowKey> = keys.iter().filter_map(|k| rows.row_keys.get(k).copied()).collect();
509 selection.sort_by_key(|row| rows.position[row]);
510 drop(rows);
511 untrack(|| ui_.set_prop(id, Prop::Selected(selection)));
512 };
513 scope.with(|| effect(update));
514 let rows = rows.clone();
515 ui.on_event(id, move |event| {
516 if let UiEvent::Changed(EventValue::Rows(selection)) = event {
517 let keys: Vec<K> = {
518 let rows = rows.borrow();
519 selection.iter().filter_map(|row| rows.keys.get(row).cloned()).collect()
520 };
521 selected.set(keys);
522 }
523 });
524 }
525 if let Some(on_activate) = on_activate {
526 let rows = rows.clone();
527 ui.on_event(id, move |event| {
528 if let UiEvent::RowActivated(row) = event {
529 let key = rows.borrow().keys.get(row).cloned();
530 if let Some(key) = key {
531 on_activate(key);
532 }
533 }
534 });
535 }
536 if let Some(handle) = handle {
537 let rows = rows.clone();
538 handle.0.borrow_mut().connection = Some(Connection {
539 ui: ui.downgrade(),
540 id,
541 row_of: Rc::new(move |k| rows.borrow().row_keys.get(k).copied()),
542 });
543 }
544 id
545}
546
547impl List<(), (), ()> {
552 #[doc(hidden)]
553 pub fn __tag() -> ListWithoutEach {
554 ListWithoutEach(Element::new(WidgetKind::List))
555 }
556}
557
558#[doc(hidden)]
559pub struct ListWithoutEach(Element);
560
561impl ListWithoutEach {
562 pub fn each<T: Clone + 'static>(self, each: impl IntoValue<Vec<T>>) -> ListWithoutKey<T> {
563 ListWithoutKey { element: self.0, each: each.into_value() }
564 }
565}
566
567impl ElementBuilder for ListWithoutEach {
568 fn element(&mut self) -> &mut Element {
569 &mut self.0
570 }
571}
572
573#[doc(hidden)]
574pub struct ListWithoutKey<T: 'static> {
575 element: Element,
576 each: Value<Vec<T>>,
577}
578
579impl<T: Clone + 'static> ListWithoutKey<T> {
580 pub fn key<K: Eq + Hash + Clone + 'static>(self, key: impl Fn(&T) -> K + 'static) -> List<T, K, ()> {
581 List::with_element(self.element, self.each, Rc::new(key), ())
582 }
583}
584
585impl<T: 'static> ElementBuilder for ListWithoutKey<T> {
586 fn element(&mut self) -> &mut Element {
587 &mut self.element
588 }
589}
590
591impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> List<T, K, ()> {
592 #[doc(hidden)]
593 pub fn __children<V: View>(self, render: impl Fn(T) -> V + 'static) -> List<T, K> {
594 let List { element, each, key, mode, style, selected, on_activate, estimate, handle, files, .. } = self;
595 let render = RowRender(Rc::new(move |item| AnyView::new(render(item))) as Rc<dyn Fn(T) -> AnyView>);
596 List { element, each, key, render, mode, style, selected, on_activate, estimate, handle, files }
597 }
598}