Skip to main content

tablo_core/column/
repeater.rs

1//! [`RepeaterColumn`]: a `#[document]` list read off the record, one item at a time.
2
3use derive_where::derive_where;
4use toasty::stmt::List;
5use topcoat::{context::Cx, view::*};
6
7use super::{Column, ColumnBase, ColumnWidth};
8use crate::{
9    Lens,
10    schema::{FormInput, read_only, value_cell},
11    values::FormValues,
12};
13
14/// A column of a list of [`FormInput`] items.
15///
16/// A detail page shows the items as a table, a row per item and a column per field. A table cell
17/// lists the same fields as `label: value`, one item after another.
18///
19/// ```rust
20/// # #[derive(Debug, Clone, toasty::Embed, tablo_core::FormInput)]
21/// # struct Link { label: String, url: String }
22/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
23/// # struct Post {
24/// #     #[key] #[auto] id: uuid::Uuid,
25/// #     #[document] links: Vec<Link>,
26/// # }
27/// tablo_core::RepeaterColumn::new(tablo_core::lens!(Post.links));
28/// ```
29#[derive_where(Clone, Debug)]
30pub struct RepeaterColumn<M, T> {
31    lens: Lens<M, Vec<T>, List<T>>,
32    base: ColumnBase,
33}
34
35impl<M, T> RepeaterColumn<M, T>
36where
37    M: toasty::schema::Model,
38    T: FormInput,
39{
40    /// Bind the column to the list `lens` reads.
41    pub fn new(lens: Lens<M, Vec<T>, List<T>>) -> Self {
42        Self {
43            base: ColumnBase::new(lens.path(), ColumnWidth::Grow),
44            lens,
45        }
46    }
47
48    base_builders!();
49
50    /// Each item's keys as its row posts them.
51    fn spelled(&self, row: &M) -> Vec<FormValues> {
52        self.lens
53            .read(row)
54            .iter()
55            .map(|item| {
56                let mut values = FormValues::new();
57                item.write(&mut values);
58                values
59            })
60            .collect()
61    }
62}
63
64impl<M, T> Column<M> for RepeaterColumn<M, T>
65where
66    M: toasty::schema::Model + Send + Sync + 'static,
67    T: FormInput,
68{
69    base_column_methods!();
70
71    fn text(&self, cx: &Cx, row: &M) -> String {
72        let schema = T::schema();
73        self.spelled(row)
74            .iter()
75            .map(|values| {
76                schema
77                    .fields()
78                    .filter_map(|field| {
79                        let value = values.text(field.name()).unwrap_or_default();
80                        let read = field.read(cx, value)?;
81                        Some(format!("{}: {read}", field.label().localize(cx)))
82                    })
83                    .collect::<Vec<_>>()
84                    .join(", ")
85            })
86            .collect::<Vec<_>>()
87            .join("; ")
88    }
89
90    fn entry<'a>(&self, cx: &'a Cx, row: &M) -> BoxView<'a> {
91        let label = Column::label(self);
92        let items = self.spelled(row);
93        if items.is_empty() {
94            return read_only(cx, &label, value_cell(cx, ""));
95        }
96        let schema = T::schema();
97        let headers: Vec<String> = schema
98            .fields()
99            .map(|field| field.label().localize(cx))
100            .collect();
101        let rows: Vec<Vec<String>> = items
102            .iter()
103            .map(|values| {
104                schema
105                    .fields()
106                    .map(|field| {
107                        field
108                            .read(cx, values.text(field.name()).unwrap_or_default())
109                            .unwrap_or_default()
110                    })
111                    .collect()
112            })
113            .collect();
114        // The table takes the whole row of a detail page's grid, as its form control does.
115        let entry = read_only(cx, &label, items_table(cx, headers, rows));
116        view! { <div class="col-span-full">(entry)</div> }.boxed()
117    }
118}
119
120/// `rows` of read values under `headers`, one column per field of the item: a repeater's entry.
121/// A free function, so tablo-core compiles the view once rather than once per item type.
122fn items_table(cx: &Cx, headers: Vec<String>, rows: Vec<Vec<String>>) -> BoxView<'_> {
123    view! {
124        <div
125            class="mt-1 overflow-x-auto rounded-lg border border-border whitespace-normal"
126        >
127            <table class="w-full border-collapse text-sm">
128                <thead class="bg-muted/50">
129                    <tr class="border-b border-border">
130                        for header in headers {
131                            <th
132                                scope="col"
133                                class="px-3 py-2 text-start font-medium text-foreground"
134                            >
135                                (header)
136                            </th>
137                        }
138                    </tr>
139                </thead>
140                <tbody class="divide-y divide-border">
141                    for cells in rows {
142                        <tr class="divide-x divide-border">
143                            for cell in cells {
144                                <td class="px-3 py-2 align-top text-foreground/75">
145                                    (value_cell(cx, &cell))
146                                </td>
147                            }
148                        </tr>
149                    }
150                </tbody>
151            </table>
152        </div>
153    }
154    .boxed()
155}
156
157impl<M, T> crate::column::ColumnInternals<M> for RepeaterColumn<M, T>
158where
159    M: toasty::schema::Model + Send + Sync + 'static,
160    T: FormInput,
161{
162    base_internals!(binding);
163}