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::tweak::Tweak;
26use crate::ui::Ui;
27use crate::units::Length;
28use crate::view::{AnyView, View};
29use crate::widget::{CellKey, ColumnData, ColumnSort, ListStyle, NodeId, Prop, SelectionMode, SortOrder, WidgetKind};
30
31/// How a [`Table`] is sorted: by the column with this sort key, and which
32/// way.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub struct Sort<S> {
35    pub by: S,
36    pub order: SortOrder,
37}
38
39impl<S> Sort<S> {
40    pub fn ascending(by: S) -> Sort<S> {
41        Sort { by, order: SortOrder::Ascending }
42    }
43
44    pub fn descending(by: S) -> Sort<S> {
45        Sort { by, order: SortOrder::Descending }
46    }
47}
48
49/// A column of a [`Table`]: its header's title, and the view each row
50/// shows in its cell.
51///
52/// ```ignore
53/// TableColumn::new("Size", |entry: Entry| Text::new(human_size(entry.size)))
54///     .width(80)
55///     .sort_key(SortBy::Size)
56/// ```
57pub struct TableColumn<T: 'static> {
58    title: Value<String>,
59    width: Option<f32>,
60    expand: bool,
61    sort_key: Option<Rc<dyn Any>>,
62    render: Rc<dyn Fn(T) -> AnyView>,
63}
64
65impl<T: 'static> TableColumn<T> {
66    /// `title` can be a message (`t!`), which follows the language.
67    pub fn new<V: View>(title: impl IntoValue<String>, render: impl Fn(T) -> V + 'static) -> TableColumn<T> {
68        TableColumn {
69            title: title.into_value(),
70            width: None,
71            expand: false,
72            sort_key: None,
73            render: Rc::new(move |item| AnyView::new(render(item))),
74        }
75    }
76
77    /// How wide it starts; the user can resize it, as the platform lets
78    /// them. Without, it's as wide as the platform makes a column.
79    pub fn width(mut self, width: impl Into<Length>) -> TableColumn<T> {
80        self.width = match width.into() {
81            Length::Px(px) => Some(px),
82            _ => None,
83        };
84        self
85    }
86
87    /// Takes the room the table has past its columns' widths, shared with
88    /// the other columns that do: a file's name, say.
89    pub fn expand(mut self) -> TableColumn<T> {
90        self.expand = true;
91        self
92    }
93
94    /// Makes the column sortable: pressing its header sorts the table by
95    /// this key, which the table's [`sort`](Table::sort) signal holds. The
96    /// key is of the signal's type.
97    pub fn sort_key<S: PartialEq + Clone + 'static>(mut self, key: S) -> TableColumn<T> {
98        self.sort_key = Some(Rc::new(key));
99        self
100    }
101}
102
103/// Columns' sort keys, in order: `None` for a column that doesn't sort.
104type SortKeys = Vec<Option<Rc<dyn Any>>>;
105
106/// Installs the binding on the built table.
107type InstallSort = Box<dyn FnOnce(&Ui, NodeId, SortKeys)>;
108
109/// Binds a table's sort to the app's signal, once the columns are known.
110struct SortBinding {
111    type_name: &'static str,
112    is_key: fn(&dyn Any) -> bool,
113    install: InstallSort,
114}
115
116/// A virtualised table: rows of cells under column headers, shown by the
117/// platform's own table control.
118///
119/// ```ignore
120/// Table::new(move || files.get(), |f| f.path.clone())
121///     .column(TableColumn::new("Name", |f: File| Text::new(f.name)).expand().sort_key(By::Name))
122///     .column(TableColumn::new("Size", |f: File| Text::new(f.size_text())).width(80).sort_key(By::Size))
123///     .sort(sort)                    // Signal<Sort<By>>: the column and order
124///     .selected(selected)            // Signal<Vec<K>>: the selected keys
125///     .on_activate(|path| open(path))
126/// ```
127///
128/// As in a [`List`](crate::List), only the rows the platform shows are
129/// mounted. A row is as high as its highest cell, or as the platform's
130/// rows are, if they're higher; a cell is as high as its content, where
131/// the platform places it in its row.
132///
133/// Rows are read by screen readers (and found by tests) as rows named by
134/// their cells' text, and the cells as cells named by theirs.
135///
136/// The type's defaults make `Table` alone name the widget, for
137/// [`Tweak<Table>`](Tweak).
138pub struct Table<T: 'static = (), K: 'static = ()> {
139    element: Element,
140    each: Value<Vec<T>>,
141    key: KeyFn<T, K>,
142    columns: Vec<TableColumn<T>>,
143    sort: Option<SortBinding>,
144    mode: Option<Value<SelectionMode>>,
145    style: Option<ListStyle>,
146    selected: Option<Signal<Vec<K>>>,
147    on_activate: Option<Rc<dyn Fn(K)>>,
148    estimate: Option<f32>,
149    handle: Option<ListHandle<K>>,
150    files: Option<FileFn<T>>,
151}
152
153impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> Table<T, K> {
154    pub fn new(each: impl IntoValue<Vec<T>>, key: impl Fn(&T) -> K + 'static) -> Table<T, K> {
155        Table::with_element(Element::new(WidgetKind::Table), each.into_value(), Rc::new(key))
156    }
157}
158
159impl<T: 'static, K: 'static> Table<T, K> {
160    fn with_element(element: Element, each: Value<Vec<T>>, key: KeyFn<T, K>) -> Table<T, K> {
161        Table {
162            element,
163            each,
164            key,
165            columns: Vec::new(),
166            sort: None,
167            mode: None,
168            style: None,
169            selected: None,
170            on_activate: None,
171            estimate: None,
172            handle: None,
173            files: None,
174        }
175    }
176
177    /// Rows can be dragged out of the app, carrying the files their items
178    /// stand for, as a `List`'s [`drag_files`](crate::List::drag_files).
179    pub fn drag_files(mut self, file: impl Fn(&T) -> Option<std::path::PathBuf> + 'static) -> Self {
180        self.files = Some(Rc::new(file));
181        self
182    }
183
184    /// Adds a column, after the others.
185    pub fn column(mut self, column: TableColumn<T>) -> Self {
186        self.columns.push(column);
187        self
188    }
189
190    /// Adds columns, after the others.
191    pub fn columns(mut self, columns: impl IntoIterator<Item = TableColumn<T>>) -> Self {
192        self.columns.extend(columns);
193        self
194    }
195
196    /// Binds how the table is sorted, both ways: its header shows it, and
197    /// pressing a sortable column's header sets it, as the platform sorts
198    /// (the same column the other way round, another one ascending). The
199    /// app sorts the data by it. Columns are sortable by their
200    /// [`sort_key`](TableColumn::sort_key)s, of this signal's type.
201    pub fn sort<S: PartialEq + Clone + 'static>(mut self, sort: Signal<Sort<S>>) -> Self {
202        self.sort = Some(SortBinding {
203            type_name: std::any::type_name::<S>(),
204            is_key: |key| key.is::<S>(),
205            install: Box::new(move |ui, id, keys| install_sort(ui, id, sort, keys)),
206        });
207        self
208    }
209
210    /// Binds the selection, as the selected rows' keys, both ways. Tables
211    /// with a selection bound select one row at a time unless
212    /// [`selection_mode`](Table::selection_mode) says otherwise.
213    pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
214        self.selected = Some(selected);
215        self
216    }
217
218    /// How many rows can be selected, as a `List`'s
219    /// [`selection_mode`](crate::List::selection_mode).
220    pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
221        self.mode = Some(mode.into_value());
222        self
223    }
224
225    /// How the table sits in its surroundings, as a `List`'s
226    /// [`list_style`](crate::List::list_style).
227    pub fn list_style(mut self, style: ListStyle) -> Self {
228        self.style = Some(style);
229        self
230    }
231
232    /// Called with a row's key when it's activated: double-clicked, or Enter
233    /// pressed on it.
234    pub fn on_activate(mut self, handler: impl Fn(K) + 'static) -> Self {
235        self.on_activate = Some(Rc::new(handler));
236        self
237    }
238
239    /// Runs `handler` when `key` is pressed while the table, or a control
240    /// inside it, has keyboard focus, and the focused control doesn't use
241    /// the key itself (the arrows, Home and End, typing to
242    /// select, and what else the platform's table takes): Space for a preview, Delete for Move to Trash.
243    /// A key goes to the nearest node around the focused control that
244    /// takes it. Nothing shows keys taken this way, so give the command a
245    /// menu item or a button too, and pick the keys the platform's own apps
246    /// use (`platform!`).
247    ///
248    /// ```ignore
249    /// Table::new(..).on_key(' ', preview)
250    /// ```
251    pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Self {
252        self.element.on_key(key.into(), handler);
253        self
254    }
255
256    /// How high rows are likely to be, for platforms that size rows before
257    /// they're shown (AppKit). By default, the rows shown so far tell.
258    pub fn estimated_row_height(mut self, height: impl Into<Length>) -> Self {
259        self.estimate = match height.into() {
260            Length::Px(px) => Some(px),
261            _ => None,
262        };
263        self
264    }
265
266    /// Connects a [`ListHandle`], to scroll the table from code.
267    pub fn handle(mut self, handle: ListHandle<K>) -> Self {
268        self.handle = Some(handle);
269        self
270    }
271
272    /// Raw platform settings: see [`Tweak`]. They run on the table view,
273    /// not the scroll view around it.
274    pub fn native(mut self, tweak: Tweak<Table>) -> Self {
275        tweak.apply(&mut self.element);
276        self
277    }
278}
279
280impl<T: 'static, K: 'static> ElementBuilder for Table<T, K> {
281    fn element(&mut self) -> &mut Element {
282        &mut self.element
283    }
284}
285
286impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> View for Table<T, K> {
287    fn build(self, ui: &Ui) -> NodeId {
288        let Table {
289            mut element,
290            each,
291            key,
292            columns,
293            sort,
294            mode,
295            style,
296            selected,
297            on_activate,
298            estimate,
299            handle,
300            files,
301        } = self;
302        let data: Vec<(Value<String>, ColumnData)> = columns
303            .iter()
304            .map(|column| {
305                let sortable = match (&sort, &column.sort_key) {
306                    (Some(sort), Some(key)) if (sort.is_key)(&**key) => true,
307                    (Some(sort), Some(_)) => panic!(
308                        "mitsuami: the sort key of the table's column \"{}\" isn't a {}, the type of its sort",
309                        mitsuami_reactive::untrack(|| column.title.get()),
310                        sort.type_name
311                    ),
312                    _ => false,
313                };
314                let data = ColumnData { title: String::new(), width: column.width, expand: column.expand, sortable };
315                (column.title.clone(), data)
316            })
317            .collect();
318        let titled = move || -> Vec<ColumnData> {
319            data.iter().map(|(title, data)| ColumnData { title: title.get(), ..data.clone() }).collect()
320        };
321        // Sent again only when a title changes (a message, with the language).
322        if columns.iter().any(|c| matches!(c.title, Value::Dynamic(_))) {
323            element.prop(Value::Dynamic(Rc::new(titled)), Prop::Columns);
324        } else {
325            element.prop(Value::Static(titled()), Prop::Columns);
326        }
327        let keys: SortKeys = columns.iter().map(|c| c.sort_key.clone()).collect();
328        let renders: Vec<Rc<dyn Fn(T) -> AnyView>> = columns.into_iter().map(|c| c.render).collect();
329        let mount: Mount<T> = Rc::new(move |ui: &Ui, row, item: T| {
330            renders
331                .iter()
332                .enumerate()
333                .map(|(column, render)| {
334                    let host = ui.create(WidgetKind::Container, vec![Prop::Cell(CellKey { row, column })]);
335                    let content = render(item.clone()).build(ui);
336                    ui.append_child(host, content);
337                    host
338                })
339                .collect()
340        });
341        let id = build_rows(
342            ui,
343            element,
344            RowParts { each, key, mount, mode, style, selected, on_activate, estimate, handle, files },
345        );
346        if let Some(sort) = sort {
347            (sort.install)(ui, id, keys);
348        }
349        id
350    }
351}
352
353/// Shows the app's sort in the header, and sets it from the user's.
354fn install_sort<S: PartialEq + Clone + 'static>(ui: &Ui, id: NodeId, sort: Signal<Sort<S>>, keys: SortKeys) {
355    let keys: Rc<Vec<Option<S>>> =
356        Rc::new(keys.into_iter().map(|k| k.and_then(|k| k.downcast_ref::<S>().cloned())).collect());
357    {
358        let (ui, keys) = (ui.clone(), keys.clone());
359        effect(move || {
360            let Sort { by, order } = sort.get();
361            let column = keys.iter().position(|k| k.as_ref() == Some(&by));
362            ui.set_prop(id, Prop::Sort(column.map(|column| ColumnSort { column, order })));
363        });
364    }
365    ui.on_event(id, move |event| {
366        if let UiEvent::Changed(EventValue::Sort(ColumnSort { column, order })) = event
367            && let Some(Some(by)) = keys.get(*column)
368        {
369            sort.set(Sort { by: by.clone(), order: *order });
370        }
371    });
372}
373
374// `view!` tags: `<Table each=… key=… column=… column=…/>`. `each` and
375// `key` come first; each step is a type of its own, so a missing one is a
376// compile error. Style attributes work at every step, table attributes
377// after `key`.
378
379impl Table<(), ()> {
380    #[doc(hidden)]
381    pub fn __tag() -> TableWithoutEach {
382        TableWithoutEach(Element::new(WidgetKind::Table))
383    }
384}
385
386#[doc(hidden)]
387pub struct TableWithoutEach(Element);
388
389impl TableWithoutEach {
390    pub fn each<T: Clone + 'static>(self, each: impl IntoValue<Vec<T>>) -> TableWithoutKey<T> {
391        TableWithoutKey { element: self.0, each: each.into_value() }
392    }
393}
394
395impl ElementBuilder for TableWithoutEach {
396    fn element(&mut self) -> &mut Element {
397        &mut self.0
398    }
399}
400
401#[doc(hidden)]
402pub struct TableWithoutKey<T: 'static> {
403    element: Element,
404    each: Value<Vec<T>>,
405}
406
407impl<T: Clone + 'static> TableWithoutKey<T> {
408    pub fn key<K: Eq + Hash + Clone + 'static>(self, key: impl Fn(&T) -> K + 'static) -> Table<T, K> {
409        Table::with_element(self.element, self.each, Rc::new(key))
410    }
411}
412
413impl<T: 'static> ElementBuilder for TableWithoutKey<T> {
414    fn element(&mut self) -> &mut Element {
415        &mut self.element
416    }
417}