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::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#[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
49pub 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 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 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 pub fn expand(mut self) -> TableColumn<T> {
90 self.expand = true;
91 self
92 }
93
94 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
103type SortKeys = Vec<Option<Rc<dyn Any>>>;
105
106type InstallSort = Box<dyn FnOnce(&Ui, NodeId, SortKeys)>;
108
109struct SortBinding {
111 type_name: &'static str,
112 is_key: fn(&dyn Any) -> bool,
113 install: InstallSort,
114}
115
116pub 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 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 pub fn column(mut self, column: TableColumn<T>) -> Self {
186 self.columns.push(column);
187 self
188 }
189
190 pub fn columns(mut self, columns: impl IntoIterator<Item = TableColumn<T>>) -> Self {
192 self.columns.extend(columns);
193 self
194 }
195
196 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 pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
214 self.selected = Some(selected);
215 self
216 }
217
218 pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
221 self.mode = Some(mode.into_value());
222 self
223 }
224
225 pub fn list_style(mut self, style: ListStyle) -> Self {
228 self.style = Some(style);
229 self
230 }
231
232 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 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 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 pub fn handle(mut self, handle: ListHandle<K>) -> Self {
268 self.handle = Some(handle);
269 self
270 }
271
272 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 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
353fn 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
374impl 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}