1use std::any::Any;
16use std::hash::Hash;
17use std::rc::Rc;
18
19use mitsuami_reactive::{IntoValue, Signal, Value, effect};
20
21use crate::command::{EventValue, UiEvent};
22use crate::element::{Element, ElementBuilder};
23use crate::list::{FileFn, KeyFn, ListHandle, Mount, RowParts, build_rows};
24use crate::services::Shortcut;
25use crate::style::{Display, Style, Track};
26use crate::tweak::Tweak;
27use crate::ui::Ui;
28use crate::units::Length;
29use crate::view::{AnyView, View};
30use crate::widget::{CellKey, ColumnData, ColumnSort, ListStyle, NodeId, Prop, SelectionMode, SortOrder, WidgetKind};
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub struct Sort<S> {
36 pub by: S,
37 pub order: SortOrder,
38}
39
40impl<S> Sort<S> {
41 pub fn ascending(by: S) -> Sort<S> {
42 Sort { by, order: SortOrder::Ascending }
43 }
44
45 pub fn descending(by: S) -> Sort<S> {
46 Sort { by, order: SortOrder::Descending }
47 }
48}
49
50pub struct TableColumn<T: 'static> {
59 title: Value<String>,
60 width: Option<f32>,
61 expand: bool,
62 fills_row: bool,
63 sort_key: Option<Rc<dyn Any>>,
64 render: Render<T>,
65}
66
67type Render<T> = Rc<dyn Fn(T) -> AnyView>;
69
70impl<T: 'static> TableColumn<T> {
71 pub fn new<V: View>(title: impl IntoValue<String>, render: impl Fn(T) -> V + 'static) -> TableColumn<T> {
73 TableColumn {
74 title: title.into_value(),
75 width: None,
76 expand: false,
77 fills_row: false,
78 sort_key: None,
79 render: Rc::new(move |item| AnyView::new(render(item))),
80 }
81 }
82
83 pub fn width(mut self, width: impl Into<Length>) -> TableColumn<T> {
86 self.width = match width.into() {
87 Length::Px(px) => Some(px),
88 _ => None,
89 };
90 self
91 }
92
93 pub fn expand(mut self) -> TableColumn<T> {
96 self.expand = true;
97 self
98 }
99
100 pub fn fills_row(mut self) -> TableColumn<T> {
107 self.fills_row = true;
108 self
109 }
110
111 pub fn sort_key<S: PartialEq + Clone + 'static>(mut self, key: S) -> TableColumn<T> {
115 self.sort_key = Some(Rc::new(key));
116 self
117 }
118}
119
120type SortKeys = Vec<Option<Rc<dyn Any>>>;
122
123type InstallSort = Box<dyn FnOnce(&Ui, NodeId, SortKeys)>;
125
126struct SortBinding {
128 type_name: &'static str,
129 is_key: fn(&dyn Any) -> bool,
130 install: InstallSort,
131}
132
133pub struct Table<T: 'static = (), K: 'static = ()> {
156 element: Element,
157 each: Value<Vec<T>>,
158 key: KeyFn<T, K>,
159 columns: Vec<TableColumn<T>>,
160 sort: Option<SortBinding>,
161 mode: Option<Value<SelectionMode>>,
162 style: Option<ListStyle>,
163 selected: Option<Signal<Vec<K>>>,
164 on_activate: Option<Rc<dyn Fn(K)>>,
165 estimate: Option<f32>,
166 handle: Option<ListHandle<K>>,
167 files: Option<FileFn<T>>,
168}
169
170impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> Table<T, K> {
171 pub fn new(each: impl IntoValue<Vec<T>>, key: impl Fn(&T) -> K + 'static) -> Table<T, K> {
172 Table::with_element(Element::new(WidgetKind::Table), each.into_value(), Rc::new(key))
173 }
174}
175
176impl<T: 'static, K: 'static> Table<T, K> {
177 fn with_element(element: Element, each: Value<Vec<T>>, key: KeyFn<T, K>) -> Table<T, K> {
178 Table {
179 element,
180 each,
181 key,
182 columns: Vec::new(),
183 sort: None,
184 mode: None,
185 style: None,
186 selected: None,
187 on_activate: None,
188 estimate: None,
189 handle: None,
190 files: None,
191 }
192 }
193
194 pub fn drag_files(mut self, file: impl Fn(&T) -> Option<std::path::PathBuf> + 'static) -> Self {
197 self.files = Some(Rc::new(file));
198 self
199 }
200
201 pub fn column(mut self, column: TableColumn<T>) -> Self {
203 self.columns.push(column);
204 self
205 }
206
207 pub fn columns(mut self, columns: impl IntoIterator<Item = TableColumn<T>>) -> Self {
209 self.columns.extend(columns);
210 self
211 }
212
213 pub fn sort<S: PartialEq + Clone + 'static>(mut self, sort: Signal<Sort<S>>) -> Self {
219 self.sort = Some(SortBinding {
220 type_name: std::any::type_name::<S>(),
221 is_key: |key| key.is::<S>(),
222 install: Box::new(move |ui, id, keys| install_sort(ui, id, sort, keys)),
223 });
224 self
225 }
226
227 pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
231 self.selected = Some(selected);
232 self
233 }
234
235 pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
238 self.mode = Some(mode.into_value());
239 self
240 }
241
242 pub fn list_style(mut self, style: ListStyle) -> Self {
245 self.style = Some(style);
246 self
247 }
248
249 pub fn on_activate(mut self, handler: impl Fn(K) + 'static) -> Self {
252 self.on_activate = Some(Rc::new(handler));
253 self
254 }
255
256 pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Self {
269 self.element.on_key(key.into(), handler);
270 self
271 }
272
273 pub fn estimated_row_height(mut self, height: impl Into<Length>) -> Self {
276 self.estimate = match height.into() {
277 Length::Px(px) => Some(px),
278 _ => None,
279 };
280 self
281 }
282
283 pub fn handle(mut self, handle: ListHandle<K>) -> Self {
285 self.handle = Some(handle);
286 self
287 }
288
289 pub fn native(mut self, tweak: Tweak<Table>) -> Self {
292 tweak.apply(&mut self.element);
293 self
294 }
295}
296
297impl<T: 'static, K: 'static> ElementBuilder for Table<T, K> {
298 fn element(&mut self) -> &mut Element {
299 &mut self.element
300 }
301}
302
303impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> View for Table<T, K> {
304 fn build(self, ui: &Ui) -> NodeId {
305 let Table {
306 mut element,
307 each,
308 key,
309 columns,
310 sort,
311 mode,
312 style,
313 selected,
314 on_activate,
315 estimate,
316 handle,
317 files,
318 } = self;
319 let data: Vec<(Value<String>, ColumnData)> = columns
320 .iter()
321 .map(|column| {
322 let sortable = match (&sort, &column.sort_key) {
323 (Some(sort), Some(key)) if (sort.is_key)(&**key) => true,
324 (Some(sort), Some(_)) => panic!(
325 "mitsuami: the sort key of the table's column \"{}\" isn't a {}, the type of its sort",
326 mitsuami_reactive::untrack(|| column.title.get()),
327 sort.type_name
328 ),
329 _ => false,
330 };
331 let data = ColumnData {
332 title: String::new(),
333 width: column.width,
334 expand: column.expand,
335 sortable,
336 fills_row: column.fills_row,
337 };
338 (column.title.clone(), data)
339 })
340 .collect();
341 let titled = move || -> Vec<ColumnData> {
342 data.iter().map(|(title, data)| ColumnData { title: title.get(), ..data.clone() }).collect()
343 };
344 if columns.iter().any(|c| matches!(c.title, Value::Dynamic(_))) {
346 element.prop(Value::Dynamic(Rc::new(titled)), Prop::Columns);
347 } else {
348 element.prop(Value::Static(titled()), Prop::Columns);
349 }
350 let keys: SortKeys = columns.iter().map(|c| c.sort_key.clone()).collect();
351 let renders: Vec<(Render<T>, bool)> = columns.into_iter().map(|c| (c.render, c.fills_row)).collect();
352 let mount: Mount<T> = Rc::new(move |ui: &Ui, row, item: T| {
353 renders
354 .iter()
355 .enumerate()
356 .map(|(column, (render, fills_row))| {
357 let host = ui.create(WidgetKind::Container, vec![Prop::Cell(CellKey { row, column })]);
358 if *fills_row {
361 ui.set_style(host, fill_style());
362 }
363 let content = render(item.clone()).build(ui);
364 ui.append_child(host, content);
365 host
366 })
367 .collect()
368 });
369 let id = build_rows(
370 ui,
371 element,
372 RowParts {
373 each,
374 key,
375 mount,
376 mode,
377 style,
378 selected,
379 on_activate,
380 estimate,
381 handle,
382 files,
383 moves: None,
384 tree: None,
385 },
386 );
387 if let Some(sort) = sort {
388 (sort.install)(ui, id, keys);
389 }
390 id
391 }
392}
393
394fn fill_style() -> Style {
396 Style {
397 display: Display::Grid,
398 grid_template_columns: vec![Track::MinMax(Length::Px(0.0), Length::Fr(1.0))],
399 grid_template_rows: vec![Track::Size(Length::Fr(1.0))],
400 ..Style::default()
401 }
402}
403
404fn install_sort<S: PartialEq + Clone + 'static>(ui: &Ui, id: NodeId, sort: Signal<Sort<S>>, keys: SortKeys) {
406 let keys: Rc<Vec<Option<S>>> =
407 Rc::new(keys.into_iter().map(|k| k.and_then(|k| k.downcast_ref::<S>().cloned())).collect());
408 {
409 let (ui, keys) = (ui.clone(), keys.clone());
410 effect(move || {
411 let Sort { by, order } = sort.get();
412 let column = keys.iter().position(|k| k.as_ref() == Some(&by));
413 ui.set_prop(id, Prop::Sort(column.map(|column| ColumnSort { column, order })));
414 });
415 }
416 ui.on_event(id, move |event| {
417 if let UiEvent::Changed(EventValue::Sort(ColumnSort { column, order })) = event
418 && let Some(Some(by)) = keys.get(*column)
419 {
420 sort.set(Sort { by: by.clone(), order: *order });
421 }
422 });
423}
424
425impl Table<(), ()> {
431 #[doc(hidden)]
432 pub fn __tag() -> TableWithoutEach {
433 TableWithoutEach(Element::new(WidgetKind::Table))
434 }
435}
436
437#[doc(hidden)]
438pub struct TableWithoutEach(Element);
439
440impl TableWithoutEach {
441 pub fn each<T: Clone + 'static>(self, each: impl IntoValue<Vec<T>>) -> TableWithoutKey<T> {
442 TableWithoutKey { element: self.0, each: each.into_value() }
443 }
444}
445
446impl ElementBuilder for TableWithoutEach {
447 fn element(&mut self) -> &mut Element {
448 &mut self.0
449 }
450}
451
452#[doc(hidden)]
453pub struct TableWithoutKey<T: 'static> {
454 element: Element,
455 each: Value<Vec<T>>,
456}
457
458impl<T: Clone + 'static> TableWithoutKey<T> {
459 pub fn key<K: Eq + Hash + Clone + 'static>(self, key: impl Fn(&T) -> K + 'static) -> Table<T, K> {
460 Table::with_element(self.element, self.each, Rc::new(key))
461 }
462}
463
464impl<T: 'static> ElementBuilder for TableWithoutKey<T> {
465 fn element(&mut self) -> &mut Element {
466 &mut self.element
467 }
468}