Skip to main content

mitsuami_core/
table.rs

1//! `Table`: the platform's table control, rows of cells under column
2//! headers, with cells built by the core.
3//!
4//! A table is a [`List`](crate::List) whose rows are cells: its data,
5//! selection, activation and scrolling work the same way, and the
6//! platform realises its rows the same way. For each row it shows, the
7//! core mounts a cell host per column (a `Container` carrying its
8//! [`CellKey`]), and disposes them when it lets the row go. The platform
9//! sizes the columns, and the user resizes them; each cell is laid out at
10//! the width its column gives it (`ColumnWidths`).
11//!
12//! The app sorts: the platform shows which column the table is sorted by
13//! and reports the user pressing a header, and the app's data follows.
14
15use 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/// How a [`Table`] is sorted: by the column with this sort key, and which
33/// way.
34#[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
50/// A column of a [`Table`]: its header's title, and the view each row
51/// shows in its cell.
52///
53/// ```ignore
54/// TableColumn::new("Size", |entry: Entry| Text::new(human_size(entry.size)))
55///     .width(80)
56///     .sort_key(SortBy::Size)
57/// ```
58pub 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
67/// What a column's cell shows for an item.
68type Render<T> = Rc<dyn Fn(T) -> AnyView>;
69
70impl<T: 'static> TableColumn<T> {
71    /// `title` can be a message (`t!`), which follows the language.
72    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    /// How wide it starts; the user can resize it, as the platform lets
84    /// them. Without, it's as wide as the platform makes a column.
85    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    /// Takes the room the table has past its columns' widths, shared with
94    /// the other columns that do: a file's name, say.
95    pub fn expand(mut self) -> TableColumn<T> {
96        self.expand = true;
97        self
98    }
99
100    /// Its cells fill their row: as wide as the column and as high as the
101    /// row, without the space the platform puts around a cell's content,
102    /// for drawings that join from row to row (a commit graph). The row is
103    /// as high as the platform makes it, which is the platform's own row
104    /// height on some (GTK's, WinUI's are higher than AppKit's), so draw to
105    /// the cell's size rather than a fixed one.
106    pub fn fills_row(mut self) -> TableColumn<T> {
107        self.fills_row = true;
108        self
109    }
110
111    /// Makes the column sortable: pressing its header sorts the table by
112    /// this key, which the table's [`sort`](Table::sort) signal holds. The
113    /// key is of the signal's type.
114    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
120/// Columns' sort keys, in order: `None` for a column that doesn't sort.
121type SortKeys = Vec<Option<Rc<dyn Any>>>;
122
123/// Installs the binding on the built table.
124type InstallSort = Box<dyn FnOnce(&Ui, NodeId, SortKeys)>;
125
126/// Binds a table's sort to the app's signal, once the columns are known.
127struct SortBinding {
128    type_name: &'static str,
129    is_key: fn(&dyn Any) -> bool,
130    install: InstallSort,
131}
132
133/// A virtualised table: rows of cells under column headers, shown by the
134/// platform's own table control.
135///
136/// ```ignore
137/// Table::new(move || files.get(), |f| f.path.clone())
138///     .column(TableColumn::new("Name", |f: File| Text::new(f.name)).expand().sort_key(By::Name))
139///     .column(TableColumn::new("Size", |f: File| Text::new(f.size_text())).width(80).sort_key(By::Size))
140///     .sort(sort)                    // Signal<Sort<By>>: the column and order
141///     .selected(selected)            // Signal<Vec<K>>: the selected keys
142///     .on_activate(|path| open(path))
143/// ```
144///
145/// As in a [`List`](crate::List), only the rows the platform shows are
146/// mounted. A row is as high as its highest cell, or as the platform's
147/// rows are, if they're higher; a cell is as high as its content, where
148/// the platform places it in its row.
149///
150/// Rows are read by screen readers (and found by tests) as rows named by
151/// their cells' text, and the cells as cells named by theirs.
152///
153/// The type's defaults make `Table` alone name the widget, for
154/// [`Tweak<Table>`](Tweak).
155pub 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    /// Rows can be dragged out of the app, carrying the files their items
195    /// stand for, as a `List`'s [`drag_files`](crate::List::drag_files).
196    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    /// Adds a column, after the others.
202    pub fn column(mut self, column: TableColumn<T>) -> Self {
203        self.columns.push(column);
204        self
205    }
206
207    /// Adds columns, after the others.
208    pub fn columns(mut self, columns: impl IntoIterator<Item = TableColumn<T>>) -> Self {
209        self.columns.extend(columns);
210        self
211    }
212
213    /// Binds how the table is sorted, both ways: its header shows it, and
214    /// pressing a sortable column's header sets it, as the platform sorts
215    /// (the same column the other way round, another one ascending). The
216    /// app sorts the data by it. Columns are sortable by their
217    /// [`sort_key`](TableColumn::sort_key)s, of this signal's type.
218    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    /// Binds the selection, as the selected rows' keys, both ways. Tables
228    /// with a selection bound select one row at a time unless
229    /// [`selection_mode`](Table::selection_mode) says otherwise.
230    pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
231        self.selected = Some(selected);
232        self
233    }
234
235    /// How many rows can be selected, as a `List`'s
236    /// [`selection_mode`](crate::List::selection_mode).
237    pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
238        self.mode = Some(mode.into_value());
239        self
240    }
241
242    /// How the table sits in its surroundings, as a `List`'s
243    /// [`list_style`](crate::List::list_style).
244    pub fn list_style(mut self, style: ListStyle) -> Self {
245        self.style = Some(style);
246        self
247    }
248
249    /// Called with a row's key when it's activated: double-clicked, or Enter
250    /// pressed on it.
251    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    /// Runs `handler` when `key` is pressed while the table, or a control
257    /// inside it, has keyboard focus, and the focused control doesn't use
258    /// the key itself (the arrows, Home and End, typing to
259    /// select, and what else the platform's table takes): Space for a preview, Delete for Move to Trash.
260    /// A key goes to the nearest node around the focused control that
261    /// takes it. Nothing shows keys taken this way, so give the command a
262    /// menu item or a button too, and pick the keys the platform's own apps
263    /// use (`platform!`).
264    ///
265    /// ```ignore
266    /// Table::new(..).on_key(' ', preview)
267    /// ```
268    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    /// How high rows are likely to be, for platforms that size rows before
274    /// they're shown (AppKit). By default, the rows shown so far tell.
275    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    /// Connects a [`ListHandle`], to scroll the table from code.
284    pub fn handle(mut self, handle: ListHandle<K>) -> Self {
285        self.handle = Some(handle);
286        self
287    }
288
289    /// Raw platform settings: see [`Tweak`]. They run on the table view,
290    /// not the scroll view around it.
291    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        // Sent again only when a title changes (a message, with the language).
345        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                    // One cell of a grid, which its content fills both
359                    // ways when the row is higher.
360                    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
394/// A filling cell's host: its content fills it.
395fn 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
404/// Shows the app's sort in the header, and sets it from the user's.
405fn 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
425// `view!` tags: `<Table each=… key=… column=… column=…/>`. `each` and
426// `key` come first; each step is a type of its own, so a missing one is a
427// compile error. Style attributes work at every step, table attributes
428// after `key`.
429
430impl 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}