Skip to main content

tablo_core/schema/
repeater.rs

1//! Repeaters: a list of values stored in one `#[document]` column, edited one row per item.
2//!
3//! Each row posts its item's keys under `{key}.{row}.`, and the repeater's own key posts the rows
4//! in the order they show, so a row the browser adds, removes or moves needs no other key.
5//! [`Schema::read`] reads them into the repeater's key as [`FormValue::Rows`], each row holding its
6//! item's values: the edit's stored value, a hidden repeater and the parse then see one key like
7//! any other field's.
8//!
9//! The browser adds a row by copying the blank row the repeater renders in a `<template>`, its
10//! keys carrying [`ROW`] for the row's number (`assets/repeaters.js`).
11
12use std::collections::HashSet;
13
14use tablo_ui::{
15    ButtonSize, ButtonVariant, FieldLegendVariant, button, field_error as ui_field_error,
16    field_legend, field_set,
17};
18use topcoat::{Result, context::Cx, icon::icon, view::*};
19
20use super::{
21    FormInput, Schema,
22    fields::{Field, Items},
23    read::Pairs,
24    tree::Source,
25};
26use crate::values::{FieldError, FieldErrors, FormValue, FormValues};
27
28/// What the blank row's keys carry for the number the browser gives a row it adds.
29pub(crate) const ROW: &str = "__row__";
30
31/// The most rows one repeater takes: each renders in full when the form comes back refused, so
32/// an unbounded list would let a small submission render a page of any size.
33pub const MAX_REPEATER_ROWS: usize = 100;
34
35/// A repeater's control: its item's controls, one row each.
36pub(crate) struct RepeaterControl {
37    item: fn() -> Schema,
38    /// The add button's label, over "Add item".
39    pub(crate) add_label: Option<crate::Text>,
40    /// How many rows it takes, set by `min_items` and `max_items`.
41    pub(crate) bounds: Items,
42    /// Whether the rows render as a table, set by `table`.
43    pub(crate) table: bool,
44}
45
46impl RepeaterControl {
47    /// One row's controls.
48    pub(crate) fn item_schema(&self) -> Schema {
49        (self.item)()
50    }
51
52    /// A repeater whose rows hold `item`'s controls.
53    #[cfg(test)]
54    pub(crate) fn of(item: fn() -> Schema) -> Self {
55        Self {
56            item,
57            add_label: None,
58            bounds: Items::default(),
59            table: false,
60        }
61    }
62
63    pub(crate) fn new<T: FormInput>() -> Self {
64        Self {
65            item: T::schema,
66            add_label: None,
67            bounds: Items::default(),
68            table: false,
69        }
70    }
71
72    /// Reads the rows posted under `key`, in the order `key` lists them, each through its item's
73    /// schema. A row's key that its item does not declare, or that a row `key` does not list
74    /// posts, stays unclaimed for the unknown-key check to refuse. `None` when the submission does
75    /// not post `key`, so an edit keeps the stored rows.
76    ///
77    /// # Errors
78    ///
79    /// `key` lists something other than row numbers, a row twice, a row posting none of its
80    /// item's keys, or more than [`MAX_REPEATER_ROWS`] rows. A browser posts every control of each
81    /// row it shows, so none of these comes from the form.
82    pub(super) fn read(
83        &self,
84        key: &str,
85        pairs: &mut Pairs<'_>,
86    ) -> std::result::Result<Option<FormValue>, String> {
87        let Some(order) = pairs.claim(key).pop() else {
88            return Ok(None);
89        };
90        let item = (self.item)();
91        let mut seen = HashSet::new();
92        let mut rows = Vec::new();
93        for token in order.split(',').map(str::trim).filter(|t| !t.is_empty()) {
94            if rows.len() == MAX_REPEATER_ROWS {
95                return Err(format!("`{key}` lists more than {MAX_REPEATER_ROWS} rows"));
96            }
97            let row: usize = token
98                .parse()
99                .map_err(|_| format!("`{key}` lists `{token}`, which is not a row"))?;
100            if !seen.insert(row) {
101                return Err(format!("`{key}` lists row {row} twice"));
102            }
103            let mut posted = Vec::new();
104            for leaf in item.fields().map(Field::name) {
105                for value in pairs.claim(&row_key(key, &row.to_string(), leaf)) {
106                    posted.push((leaf.to_string(), value.to_string()));
107                }
108            }
109            if posted.is_empty() {
110                return Err(format!("`{key}` lists row {row}, which posts nothing"));
111            }
112            rows.push(item.read_in(&posted, pairs.zone.clone())?);
113        }
114        Ok(Some(FormValue::Rows(rows)))
115    }
116
117    /// Adds to `errors` what the item's controls' own rules refuse in each of `rows`, under the
118    /// key the row's control posts: a choice that is not one of its options, an email field's
119    /// address, a text field's declared length, bounds and pattern. Each row checks against the
120    /// row `stored` holds at its position, so a value the record stores there is not checked
121    /// again.
122    pub(crate) async fn check(
123        &self,
124        cx: &Cx,
125        key: &str,
126        rows: &[FormValues],
127        stored: &[FormValues],
128        errors: &mut FieldErrors,
129    ) {
130        for (row, item) in rows.iter().enumerate() {
131            let (schema, values) = self.row(key, &row.to_string(), item);
132            let held = stored.get(row).map_or_else(FormValues::new, |held| {
133                self.row(key, &row.to_string(), held).1
134            });
135            Box::pin(schema.check_controls(cx, &values, &held, errors)).await;
136        }
137    }
138
139    /// The item's schema posting under the row `row` of the repeater `key`, and `item`'s keys as
140    /// that row posts them.
141    fn row(&self, key: &str, row: &str, item: &FormValues) -> (Schema, FormValues) {
142        let prefix = row_key(key, row, "");
143        let mut schema = (self.item)();
144        for field in &mut schema.fields {
145            field.prefix(&prefix);
146        }
147        let values = item
148            .iter()
149            .map(|(leaf, value)| (format!("{prefix}{leaf}"), value.clone()))
150            .collect();
151        (schema, values)
152    }
153
154    /// Renders the repeater `field` from `source`: a row per stored or posted item, and the blank
155    /// row the add button copies.
156    pub(crate) async fn render<'a>(
157        &self,
158        cx: &'a Cx,
159        field: &Field,
160        source: &Source<'_>,
161    ) -> Result<BoxView<'a>> {
162        let key = field.name().to_string();
163        let items = source.rows(&key);
164        let mut rows = Vec::with_capacity(items.len());
165        // A row's Remove button is disabled while the list holds no more rows than it needs;
166        // `assets/repeaters.js` keeps it so as rows come and go.
167        let removable = self.bounds.min.is_none_or(|min| items.len() > min);
168        for (row, item) in items.iter().enumerate() {
169            let errors = source.errors();
170            let row = row.to_string();
171            rows.push(if self.table {
172                self.render_table_row(cx, &key, &row, item, errors, removable, source)
173                    .await?
174            } else {
175                self.render_row(cx, &key, &row, item, errors, removable, source)
176                    .await?
177            });
178        }
179        let blank_errors = FieldErrors::new();
180        let blank = if self.table {
181            self.render_table_row(
182                cx,
183                &key,
184                ROW,
185                &FormValues::new(),
186                &blank_errors,
187                true,
188                source,
189            )
190            .await?
191        } else {
192            self.render_row(
193                cx,
194                &key,
195                ROW,
196                &FormValues::new(),
197                &blank_errors,
198                true,
199                source,
200            )
201            .await?
202        };
203        let order = (0..items.len())
204            .map(|row| row.to_string())
205            .collect::<Vec<_>>()
206            .join(",");
207        let next = items.len().to_string();
208        let most = self
209            .bounds
210            .max
211            .map_or(MAX_REPEATER_ROWS, |max| max.min(MAX_REPEATER_ROWS));
212        let full = items.len() >= most;
213        let min = self.bounds.min;
214        let label = field.label();
215        let add = self
216            .add_label
217            .clone()
218            .unwrap_or_else(|| crate::Text::message("tablo-repeater-add"));
219        let error = source.error_for(field).map(|error| {
220            (
221                error.message(&label).localize(cx),
222                super::fields::error_kind(error),
223            )
224        });
225        let head = self.table.then(|| self.table_head(cx));
226        let legend_id = format!("{}-legend", source.id(&key));
227        // Named as every control's error slot is, so the fieldset describes itself by it.
228        let error_id = format!("{}-error", source.id(&key));
229        let described_by = error.is_some().then(|| error_id.clone());
230        Ok(view! {
231            field_set(
232                attrs: attributes! {
233                    class="ac-field gap-3"
234                    data-repeater=(key.clone())
235                    data-repeater-next=(next)
236                    data-repeater-max=(most)
237                    data-repeater-min=(min)
238                    aria-describedby=(described_by)
239                },
240                field_legend(
241                    variant: FieldLegendVariant::Label,
242                    attrs: attributes! { id=(legend_id.clone()) class="mb-0" },
243                    (label)
244                )
245                <input type="hidden" name=(key) value=(order) data-repeater-order="">
246                if let Some((message, kind)) = error {
247                    ui_field_error(
248                        attrs: attributes! { id=(error_id) class="ac-error" data-error=(kind) },
249                        (message)
250                    )
251                }
252                if let Some(head) = head {
253                    <div class=(TABLE_BOX)>
254                        <div class="overflow-x-auto">
255                            <table class="w-full border-collapse text-sm">
256                                (head)
257                                <tbody
258                                    class="divide-y divide-border"
259                                    aria-labelledby=(legend_id)
260                                    data-repeater-rows=""
261                                >
262                                    for row in rows {
263                                        (row)
264                                    }
265                                </tbody>
266                            </table>
267                        </div>
268                        <template data-repeater-blank="">(blank)</template>
269                        <div class="flex justify-center border-t border-border p-1.5">
270                            button(
271                                variant: ButtonVariant::Ghost,
272                                size: ButtonSize::Sm,
273                                attrs: attributes! {
274                                    type="button"
275                                    class="text-primary hover:text-primary"
276                                    data-repeater-add=""
277                                    disabled=(full)
278                                },
279                                icon(
280                                    data: tablo_ui::icons::PLUS,
281                                    attrs: attributes! { aria-hidden="true" }
282                                )
283                                (add)
284                            )
285                        </div>
286                    </div>
287                } else {
288                    <ol
289                        class="flex flex-col gap-3"
290                        aria-labelledby=(legend_id)
291                        data-repeater-rows=""
292                    >
293                        for row in rows {
294                            (row)
295                        }
296                    </ol>
297                    <template data-repeater-blank="">(blank)</template>
298                    <div>
299                        button(
300                            variant: ButtonVariant::Outline,
301                            size: ButtonSize::Sm,
302                            attrs: attributes! { type="button" data-repeater-add="" disabled=(full) },
303                            (add)
304                        )
305                    </div>
306                }
307            )
308        }
309        .boxed())
310    }
311
312    /// Renders the row `row` of the repeater `key` holding `item`, its controls posting under the
313    /// row's prefix, with the buttons that move and remove it, Remove disabled unless
314    /// `removable`.
315    #[expect(
316        clippy::too_many_arguments,
317        reason = "one call site renders a stored row, the other the blank one"
318    )]
319    async fn render_row<'a>(
320        &self,
321        cx: &'a Cx,
322        key: &str,
323        row: &str,
324        item: &FormValues,
325        errors: &FieldErrors,
326        removable: bool,
327        source: &Source<'_>,
328    ) -> Result<BoxView<'a>> {
329        let (schema, values) = self.row(key, row, item);
330        let mut rendered = Source::form(&values, errors).scoped(source.scope());
331        if let Some(options) = source.options() {
332            rendered = rendered.options_at(options);
333        }
334        let controls = schema.render(cx, rendered).await?;
335        let row = row.to_string();
336        let action = move |id: &'static str, data: Attributes, disabled: bool| {
337            let label = crate::t!(cx, id);
338            view! {
339                button(
340                    variant: ButtonVariant::Ghost,
341                    size: ButtonSize::Sm,
342                    attrs: attributes! { type="button" disabled=(disabled) (data) },
343                    (label)
344                )
345            }
346        };
347        Ok(view! {
348            <li
349                class="flex flex-col gap-4 rounded-lg border border-border p-4"
350                data-repeater-row=(row)
351            >
352                (controls)
353                <div class="flex flex-wrap justify-end gap-2">
354                    (action(
355                        "tablo-repeater-up",
356                        attributes! { data-repeater-up="" },
357                        false,
358                    ))
359                    (action(
360                        "tablo-repeater-down",
361                        attributes! { data-repeater-down="" },
362                        false,
363                    ))
364                    (action(
365                        "tablo-repeater-remove",
366                        attributes! { data-repeater-remove="" },
367                        !removable,
368                    ))
369                </div>
370            </li>
371        }
372        .boxed())
373    }
374}
375
376impl RepeaterControl {
377    /// The table's header: a column per control of the item, labelled by it, and one for the
378    /// row's buttons.
379    fn table_head<'a>(&self, cx: &'a Cx) -> BoxView<'a> {
380        let item = (self.item)();
381        let labels: Vec<_> = item.cell_labels();
382        let actions = crate::t!(cx, "tablo-repeater-actions");
383        view! {
384            <thead class="bg-muted/50">
385                <tr class="border-b border-border">
386                    for (label, required) in labels {
387                        <th
388                            scope="col"
389                            class="px-3 py-2 text-start font-medium text-foreground"
390                        >
391                            (label)
392                            if required {
393                                <span class="ms-0.5 text-destructive" aria-hidden="true">
394                                    "*"
395                                </span>
396                            }
397                        </th>
398                    }
399                    <th scope="col" class="w-px p-0">
400                        <span class="sr-only">(actions)</span>
401                    </th>
402                </tr>
403            </thead>
404        }
405        .boxed()
406    }
407
408    /// Renders the row `row` of the repeater `key` holding `item` as a table row: a cell per
409    /// control, its label read by a screen reader alone since the column's header shows it, then
410    /// the buttons that move and remove it, Remove disabled unless `removable`.
411    #[expect(
412        clippy::too_many_arguments,
413        reason = "one call site renders a stored row, the other the blank one"
414    )]
415    async fn render_table_row<'a>(
416        &self,
417        cx: &'a Cx,
418        key: &str,
419        row: &str,
420        item: &FormValues,
421        errors: &FieldErrors,
422        removable: bool,
423        source: &Source<'_>,
424    ) -> Result<BoxView<'a>> {
425        let (schema, values) = self.row(key, row, item);
426        let mut rendered = Source::form(&values, errors).scoped(source.scope());
427        if let Some(options) = source.options() {
428            rendered = rendered.options_at(options);
429        }
430        let cells = schema.render_cells(cx, rendered).await?;
431        let row = row.to_string();
432        let action = move |id: &'static str, glyph, data: Attributes, disabled: bool| {
433            let label = crate::t!(cx, id);
434            view! {
435                button(
436                    variant: ButtonVariant::Ghost,
437                    size: ButtonSize::Icon,
438                    attrs: attributes! {
439                        type="button"
440                        class="size-8 text-muted-foreground"
441                        aria-label=(label.clone())
442                        title=(label)
443                        disabled=(disabled)
444                        (data)
445                    },
446                    icon(data: glyph, attrs: attributes! { aria-hidden="true" })
447                )
448            }
449        };
450        Ok(view! {
451            <tr class=(TABLE_ROW) data-repeater-row=(row)>
452                for cell in cells {
453                    <td class="border-e border-border p-0 align-top">(cell)</td>
454                }
455                <td class="w-px px-1 py-0.5 align-top whitespace-nowrap">
456                    (action(
457                        "tablo-repeater-up",
458                        tablo_ui::icons::ARROW_UP,
459                        attributes! { data-repeater-up="" },
460                        false,
461                    ))
462                    (action(
463                        "tablo-repeater-down",
464                        tablo_ui::icons::ARROW_DOWN,
465                        attributes! { data-repeater-down="" },
466                        false,
467                    ))
468                    (action(
469                        "tablo-repeater-remove",
470                        tablo_ui::icons::TRASH,
471                        attributes! { data-repeater-remove="" class="hover:text-destructive" },
472                        !removable,
473                    ))
474                </td>
475            </tr>
476        }
477        .boxed())
478    }
479}
480
481/// Renders a table repeater's box: one border around the header, the rows and the add button.
482const TABLE_BOX: &str = "overflow-hidden rounded-lg border border-border bg-background";
483
484/// Renders a table repeater's row: each control fills its cell, borderless, its focus ring drawn
485/// inside the cell, its label left to a screen reader and its error under it.
486const TABLE_ROW: &str = "[&_[data-slot=field-label]]:sr-only [&_[data-slot=field]]:gap-0 \
487     [&_:is(input,select,textarea)]:rounded-none [&_:is(input,select,textarea)]:border-0 \
488     [&_:is(input,select,textarea)]:bg-transparent [&_:is(input,select,textarea)]:shadow-none \
489     [&_:is(input,select,textarea)]:focus-visible:ring-inset \
490     [&_:is(input,select,textarea)]:focus-visible:ring-offset-0 [&_.ac-error]:px-3 \
491     [&_.ac-error]:pb-2";
492
493/// The key the row `row` of the repeater `key` posts its item's `leaf` under.
494pub(crate) fn row_key(key: &str, row: &str, leaf: &str) -> String {
495    format!("{key}.{row}.{leaf}")
496}
497
498/// The repeater's value holding `items`: what a record form hydrates the repeater with, and what
499/// a hand-written one writes.
500pub fn write_items<T: FormInput>(items: &[T]) -> FormValue {
501    FormValue::Rows(
502        items
503            .iter()
504            .map(|item| {
505                let mut out = FormValues::new();
506                item.write(&mut out);
507                out
508            })
509            .collect(),
510    )
511}
512
513/// The items the repeater `key` holds in a submission [read](crate::Schema::read) through its
514/// schema, none when it posts nothing: what a record form's parse reads the repeater with, and
515/// what a hand-written one or an action input reads.
516///
517/// # Errors
518///
519/// Each row's refusals, under the key the row's control posts, or the repeater's own when it holds
520/// text or a list.
521pub fn parse_items<T: FormInput>(
522    cx: &Cx,
523    key: &str,
524    values: &FormValues,
525) -> std::result::Result<Vec<T>, Vec<FieldError>> {
526    let rows: &[FormValues] = match values.get(key) {
527        None => &[],
528        Some(FormValue::Rows(rows)) => rows,
529        Some(_) => return Err(vec![crate::values::unreadable(key)]),
530    };
531    let mut items = Vec::with_capacity(rows.len());
532    let mut errors = Vec::new();
533    for (row, values) in rows.iter().enumerate() {
534        match T::parse(cx, values) {
535            Ok(item) => items.push(item),
536            Err(failures) => errors.extend(failures.into_iter().map(|failure| FieldError {
537                key: row_key(key, &row.to_string(), &failure.key),
538                kind: failure.kind,
539            })),
540        }
541    }
542    if errors.is_empty() {
543        Ok(items)
544    } else {
545        Err(errors)
546    }
547}
548
549#[cfg(test)]
550mod tests;