use std::any::Any;
use std::hash::Hash;
use std::rc::Rc;
use mitsuami_reactive::{IntoValue, Signal, Value, effect};
use crate::command::{EventValue, UiEvent};
use crate::element::{Element, ElementBuilder};
use crate::list::{FileFn, KeyFn, ListHandle, Mount, RowParts, build_rows};
use crate::services::Shortcut;
use crate::style::{Display, Style, Track};
use crate::tweak::Tweak;
use crate::ui::Ui;
use crate::units::Length;
use crate::view::{AnyView, View};
use crate::widget::{CellKey, ColumnData, ColumnSort, ListStyle, NodeId, Prop, SelectionMode, SortOrder, WidgetKind};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Sort<S> {
pub by: S,
pub order: SortOrder,
}
impl<S> Sort<S> {
pub fn ascending(by: S) -> Sort<S> {
Sort { by, order: SortOrder::Ascending }
}
pub fn descending(by: S) -> Sort<S> {
Sort { by, order: SortOrder::Descending }
}
}
pub struct TableColumn<T: 'static> {
title: Value<String>,
width: Option<f32>,
expand: bool,
fills_row: bool,
sort_key: Option<Rc<dyn Any>>,
render: Render<T>,
}
type Render<T> = Rc<dyn Fn(T) -> AnyView>;
impl<T: 'static> TableColumn<T> {
pub fn new<V: View>(title: impl IntoValue<String>, render: impl Fn(T) -> V + 'static) -> TableColumn<T> {
TableColumn {
title: title.into_value(),
width: None,
expand: false,
fills_row: false,
sort_key: None,
render: Rc::new(move |item| AnyView::new(render(item))),
}
}
pub fn width(mut self, width: impl Into<Length>) -> TableColumn<T> {
self.width = match width.into() {
Length::Px(px) => Some(px),
_ => None,
};
self
}
pub fn expand(mut self) -> TableColumn<T> {
self.expand = true;
self
}
pub fn fills_row(mut self) -> TableColumn<T> {
self.fills_row = true;
self
}
pub fn sort_key<S: PartialEq + Clone + 'static>(mut self, key: S) -> TableColumn<T> {
self.sort_key = Some(Rc::new(key));
self
}
}
type SortKeys = Vec<Option<Rc<dyn Any>>>;
type InstallSort = Box<dyn FnOnce(&Ui, NodeId, SortKeys)>;
struct SortBinding {
type_name: &'static str,
is_key: fn(&dyn Any) -> bool,
install: InstallSort,
}
pub struct Table<T: 'static = (), K: 'static = ()> {
element: Element,
each: Value<Vec<T>>,
key: KeyFn<T, K>,
columns: Vec<TableColumn<T>>,
sort: Option<SortBinding>,
mode: Option<Value<SelectionMode>>,
style: Option<ListStyle>,
selected: Option<Signal<Vec<K>>>,
on_activate: Option<Rc<dyn Fn(K)>>,
estimate: Option<f32>,
handle: Option<ListHandle<K>>,
files: Option<FileFn<T>>,
}
impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> Table<T, K> {
pub fn new(each: impl IntoValue<Vec<T>>, key: impl Fn(&T) -> K + 'static) -> Table<T, K> {
Table::with_element(Element::new(WidgetKind::Table), each.into_value(), Rc::new(key))
}
}
impl<T: 'static, K: 'static> Table<T, K> {
fn with_element(element: Element, each: Value<Vec<T>>, key: KeyFn<T, K>) -> Table<T, K> {
Table {
element,
each,
key,
columns: Vec::new(),
sort: None,
mode: None,
style: None,
selected: None,
on_activate: None,
estimate: None,
handle: None,
files: None,
}
}
pub fn drag_files(mut self, file: impl Fn(&T) -> Option<std::path::PathBuf> + 'static) -> Self {
self.files = Some(Rc::new(file));
self
}
pub fn column(mut self, column: TableColumn<T>) -> Self {
self.columns.push(column);
self
}
pub fn columns(mut self, columns: impl IntoIterator<Item = TableColumn<T>>) -> Self {
self.columns.extend(columns);
self
}
pub fn sort<S: PartialEq + Clone + 'static>(mut self, sort: Signal<Sort<S>>) -> Self {
self.sort = Some(SortBinding {
type_name: std::any::type_name::<S>(),
is_key: |key| key.is::<S>(),
install: Box::new(move |ui, id, keys| install_sort(ui, id, sort, keys)),
});
self
}
pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
self.selected = Some(selected);
self
}
pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
self.mode = Some(mode.into_value());
self
}
pub fn list_style(mut self, style: ListStyle) -> Self {
self.style = Some(style);
self
}
pub fn on_activate(mut self, handler: impl Fn(K) + 'static) -> Self {
self.on_activate = Some(Rc::new(handler));
self
}
pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Self {
self.element.on_key(key.into(), handler);
self
}
pub fn estimated_row_height(mut self, height: impl Into<Length>) -> Self {
self.estimate = match height.into() {
Length::Px(px) => Some(px),
_ => None,
};
self
}
pub fn handle(mut self, handle: ListHandle<K>) -> Self {
self.handle = Some(handle);
self
}
pub fn native(mut self, tweak: Tweak<Table>) -> Self {
tweak.apply(&mut self.element);
self
}
}
impl<T: 'static, K: 'static> ElementBuilder for Table<T, K> {
fn element(&mut self) -> &mut Element {
&mut self.element
}
}
impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> View for Table<T, K> {
fn build(self, ui: &Ui) -> NodeId {
let Table {
mut element,
each,
key,
columns,
sort,
mode,
style,
selected,
on_activate,
estimate,
handle,
files,
} = self;
let data: Vec<(Value<String>, ColumnData)> = columns
.iter()
.map(|column| {
let sortable = match (&sort, &column.sort_key) {
(Some(sort), Some(key)) if (sort.is_key)(&**key) => true,
(Some(sort), Some(_)) => panic!(
"mitsuami: the sort key of the table's column \"{}\" isn't a {}, the type of its sort",
mitsuami_reactive::untrack(|| column.title.get()),
sort.type_name
),
_ => false,
};
let data = ColumnData {
title: String::new(),
width: column.width,
expand: column.expand,
sortable,
fills_row: column.fills_row,
};
(column.title.clone(), data)
})
.collect();
let titled = move || -> Vec<ColumnData> {
data.iter().map(|(title, data)| ColumnData { title: title.get(), ..data.clone() }).collect()
};
if columns.iter().any(|c| matches!(c.title, Value::Dynamic(_))) {
element.prop(Value::Dynamic(Rc::new(titled)), Prop::Columns);
} else {
element.prop(Value::Static(titled()), Prop::Columns);
}
let keys: SortKeys = columns.iter().map(|c| c.sort_key.clone()).collect();
let renders: Vec<(Render<T>, bool)> = columns.into_iter().map(|c| (c.render, c.fills_row)).collect();
let mount: Mount<T> = Rc::new(move |ui: &Ui, row, item: T| {
renders
.iter()
.enumerate()
.map(|(column, (render, fills_row))| {
let host = ui.create(WidgetKind::Container, vec![Prop::Cell(CellKey { row, column })]);
if *fills_row {
ui.set_style(host, fill_style());
}
let content = render(item.clone()).build(ui);
ui.append_child(host, content);
host
})
.collect()
});
let id = build_rows(
ui,
element,
RowParts {
each,
key,
mount,
mode,
style,
selected,
on_activate,
estimate,
handle,
files,
moves: None,
tree: None,
},
);
if let Some(sort) = sort {
(sort.install)(ui, id, keys);
}
id
}
}
fn fill_style() -> Style {
Style {
display: Display::Grid,
grid_template_columns: vec![Track::MinMax(Length::Px(0.0), Length::Fr(1.0))],
grid_template_rows: vec![Track::Size(Length::Fr(1.0))],
..Style::default()
}
}
fn install_sort<S: PartialEq + Clone + 'static>(ui: &Ui, id: NodeId, sort: Signal<Sort<S>>, keys: SortKeys) {
let keys: Rc<Vec<Option<S>>> =
Rc::new(keys.into_iter().map(|k| k.and_then(|k| k.downcast_ref::<S>().cloned())).collect());
{
let (ui, keys) = (ui.clone(), keys.clone());
effect(move || {
let Sort { by, order } = sort.get();
let column = keys.iter().position(|k| k.as_ref() == Some(&by));
ui.set_prop(id, Prop::Sort(column.map(|column| ColumnSort { column, order })));
});
}
ui.on_event(id, move |event| {
if let UiEvent::Changed(EventValue::Sort(ColumnSort { column, order })) = event
&& let Some(Some(by)) = keys.get(*column)
{
sort.set(Sort { by: by.clone(), order: *order });
}
});
}
impl Table<(), ()> {
#[doc(hidden)]
pub fn __tag() -> TableWithoutEach {
TableWithoutEach(Element::new(WidgetKind::Table))
}
}
#[doc(hidden)]
pub struct TableWithoutEach(Element);
impl TableWithoutEach {
pub fn each<T: Clone + 'static>(self, each: impl IntoValue<Vec<T>>) -> TableWithoutKey<T> {
TableWithoutKey { element: self.0, each: each.into_value() }
}
}
impl ElementBuilder for TableWithoutEach {
fn element(&mut self) -> &mut Element {
&mut self.0
}
}
#[doc(hidden)]
pub struct TableWithoutKey<T: 'static> {
element: Element,
each: Value<Vec<T>>,
}
impl<T: Clone + 'static> TableWithoutKey<T> {
pub fn key<K: Eq + Hash + Clone + 'static>(self, key: impl Fn(&T) -> K + 'static) -> Table<T, K> {
Table::with_element(self.element, self.each, Rc::new(key))
}
}
impl<T: 'static> ElementBuilder for TableWithoutKey<T> {
fn element(&mut self) -> &mut Element {
&mut self.element
}
}