Skip to main content

tablo_core/schema/
tree.rs

1//! Composes field slots, layout containers, and embedded values into one tree.
2
3use std::{
4    collections::HashMap,
5    sync::atomic::{AtomicBool, AtomicUsize, Ordering},
6};
7
8use topcoat::{Result, context::Cx, view::*};
9
10use super::{
11    Schema,
12    condition::{Condition, disable, watch},
13    embedded::Embedded,
14    fields::{Field, Placement},
15    layouts::{Grid, Group, Section, Step, Tab, Tabs, Wizard, spanned},
16};
17use crate::values::{FieldError, FieldErrors, FormValue, FormValues};
18
19#[derive(Debug)]
20pub(crate) enum Node {
21    /// A field, by its index in the root schema's field list.
22    Field(usize),
23    Section(Box<Section>),
24    Group(Box<Group>),
25    Grid(Box<Grid>),
26    /// A `Tabs` block, whose children are its `Tab` nodes.
27    Tabs(Box<Tabs>),
28    /// One tab, placed only in a `Tabs` block's children.
29    Tab(Box<Tab>),
30    /// A `Wizard` block, whose children are its `Step` nodes.
31    Wizard(Box<Wizard>),
32    /// One step, placed only in a `Wizard` block's children.
33    Step(Box<Step>),
34    Embedded(Box<Embedded>),
35}
36
37/// Holds the values and errors a schema's controls render with.
38pub struct Source<'a> {
39    values: &'a FormValues,
40    errors: &'a FieldErrors,
41    /// The conditions each watched field's key drives.
42    watched: HashMap<String, Vec<Condition>>,
43    /// The prefix of the form's DOM ids and of its signals' keys; empty for a form alone on its
44    /// page.
45    scope: String,
46    /// Where a searchable or dependent choice fetches its options; `None` where no route serves
47    /// them.
48    options: Option<String>,
49    /// Whether the form edits a stored record.
50    editing: bool,
51    /// The keys the request's field access hides or locks.
52    mask: super::FormMask,
53    /// What every control's name starts with: a related form's `{slug}.`, empty otherwise.
54    prefix: String,
55    /// How many tabs hold the node rendering now, which tells a nested block's DOM ids from its
56    /// outer tab's.
57    tab_depth: AtomicUsize,
58    /// Whether a dialog frames the form, whose sections then render without a panel.
59    flat: bool,
60    /// Whether a panel holds the node rendering now: a section's, a tab block's or a related
61    /// form's. A section inside one renders as a heading over its fields, never a panel in a
62    /// panel.
63    in_panel: AtomicBool,
64}
65
66impl<'a> Source<'a> {
67    /// Renders controls hydrated with `values` and inline `errors`.
68    pub fn form(values: &'a FormValues, errors: &'a FieldErrors) -> Self {
69        Self {
70            values,
71            errors,
72            watched: HashMap::new(),
73            scope: String::new(),
74            options: None,
75            editing: false,
76            mask: super::FormMask::default(),
77            prefix: String::new(),
78            tab_depth: AtomicUsize::new(0),
79            flat: false,
80            in_panel: AtomicBool::new(false),
81        }
82    }
83
84    /// Renders sections without a panel when `flat`, for a form a dialog frames.
85    pub(crate) fn flat(mut self, flat: bool) -> Self {
86        self.flat = flat;
87        self
88    }
89
90    /// Whether sections render without a panel.
91    pub(super) fn is_flat(&self) -> bool {
92        self.flat
93    }
94
95    /// Renders the form inside a panel another form draws, where its sections are headings.
96    pub(crate) fn within_panel(self) -> Self {
97        self.in_panel.store(true, Ordering::Relaxed);
98        self
99    }
100
101    /// Whether a panel holds the node rendering now.
102    pub(crate) fn in_panel(&self) -> bool {
103        self.in_panel.load(Ordering::Relaxed)
104    }
105
106    /// Renders what follows inside a panel when `inside`, and returns whether it was before.
107    pub(crate) fn set_in_panel(&self, inside: bool) -> bool {
108        self.in_panel.swap(inside, Ordering::Relaxed)
109    }
110
111    /// Renders the edit form of a stored record, where `disabled_on_edit` disables a control.
112    pub(crate) fn editing(mut self, editing: bool) -> Self {
113        self.editing = editing;
114        self
115    }
116
117    /// Renders nothing for the keys `mask` hides, and disables the controls of the ones it locks.
118    pub(crate) fn masked(mut self, mask: super::FormMask) -> Self {
119        self.mask = mask;
120        self
121    }
122
123    /// Renders a form sharing its page with another: its DOM ids and its signals' keys carry
124    /// `scope`, so neither form's labels, conditions or variants reach the other's.
125    pub(crate) fn scoped(mut self, scope: impl Into<String>) -> Self {
126        self.scope = scope.into();
127        self
128    }
129
130    /// Renders a related form inside its owner's: every control posts under `prefix`, while its
131    /// values, errors, mask and conditions keep the related form's own keys.
132    pub(crate) fn posting_under(mut self, prefix: impl Into<String>) -> Self {
133        self.prefix = prefix.into();
134        self
135    }
136
137    /// Fetches a searchable or dependent choice's options from `url`.
138    pub(crate) fn options_at(mut self, url: impl Into<String>) -> Self {
139        self.options = Some(url.into());
140        self
141    }
142
143    /// The prefix of the form's DOM ids and of its signals' keys.
144    pub(crate) fn scope(&self) -> &str {
145        &self.scope
146    }
147
148    /// Renders each watched field with the handlers its conditions follow.
149    pub(crate) fn watching(mut self, watched: HashMap<String, Vec<Condition>>) -> Self {
150        self.watched = watched;
151        self
152    }
153
154    /// Renders `view` guarded by `condition`, or as it is without one.
155    pub(crate) fn guard<'v>(
156        &self,
157        cx: &'v Cx,
158        condition: Option<&Condition>,
159        view: BoxView<'v>,
160    ) -> BoxView<'v> {
161        match condition {
162            Some(condition) => condition.guard(cx, &self.scope, self.values, view),
163            None => view,
164        }
165    }
166
167    /// How many tabs hold the node rendering now.
168    pub(crate) fn tab_depth(&self) -> usize {
169        self.tab_depth.load(Ordering::Relaxed)
170    }
171
172    /// Renders what follows inside `depth` tabs.
173    pub(crate) fn set_tab_depth(&self, depth: usize) {
174        self.tab_depth.store(depth, Ordering::Relaxed);
175    }
176
177    /// Whether `condition` holds in the submission, as the page first renders it: always without
178    /// one.
179    pub(crate) fn holds(&self, condition: Option<&Condition>) -> bool {
180        condition.is_none_or(|condition| condition.holds(self.values))
181    }
182
183    pub(crate) fn value(&self, name: &str) -> Option<&FormValue> {
184        self.values.get(name)
185    }
186
187    /// The text `name` holds: a scalar control's value.
188    pub(crate) fn text(&self, name: &str) -> Option<&str> {
189        self.values.text(name)
190    }
191
192    /// The rows `name` holds: a repeater's, none when it holds none.
193    pub(crate) fn rows(&self, name: &str) -> &[FormValues] {
194        self.values.rows(name).unwrap_or_default()
195    }
196
197    /// The errors the controls render under.
198    pub(crate) fn errors(&self) -> &FieldErrors {
199        self.errors
200    }
201
202    /// Where a searchable or dependent choice fetches its options.
203    pub(crate) fn options(&self) -> Option<&str> {
204        self.options.as_deref()
205    }
206
207    /// The DOM id of the control posting `name`.
208    pub(crate) fn id(&self, name: &str) -> String {
209        self.placement(name, None).id(name)
210    }
211
212    /// Where the field posting `name` renders in this form, under its parent's value `parent`.
213    fn placement<'p>(&'p self, name: &str, parent: Option<&'p str>) -> Placement<'p> {
214        Placement {
215            parent,
216            scope: &self.scope,
217            options: self.options.as_deref(),
218            editing: self.editing,
219            locked: self.mask.locks(name),
220            prefix: &self.prefix,
221        }
222    }
223
224    /// Returns the message the field `field` renders under its control.
225    pub(crate) fn error_for(&self, field: &Field) -> Option<&FieldError> {
226        self.errors.first(field.name())
227    }
228}
229
230impl Node {
231    /// Renders this node from `source`, reading field slots from `fields`.
232    pub(crate) async fn render<'a>(
233        &self,
234        cx: &'a Cx,
235        fields: &[Field],
236        source: &Source<'_>,
237    ) -> Result<BoxView<'a>> {
238        match self {
239            Node::Field(index) => {
240                if !shows(&fields[*index], source) {
241                    return Ok(().boxed());
242                }
243                let field = &fields[*index];
244                // A repeater's rows render from the keys and errors of each of their controls.
245                if let Some(repeater) = field.as_repeater() {
246                    let view = Box::pin(repeater.render(cx, field, source)).await?;
247                    let view = spanned(cx, field.span(), view);
248                    return Ok(source.guard(cx, field.condition(), view));
249                }
250                let error = source.error_for(field);
251                let parent = field.parent_key().and_then(|key| source.text(key));
252                let mut view = Box::pin(field.render_under(
253                    cx,
254                    source.value(field.name()),
255                    error,
256                    source.placement(field.name(), parent),
257                ))
258                .await?;
259                if let Some(conditions) = source.watched.get(field.name()) {
260                    let posted = format!("{}{}", source.prefix, field.name());
261                    view = watch(
262                        cx,
263                        field,
264                        &posted,
265                        conditions,
266                        &source.scope,
267                        source.values,
268                        view,
269                    );
270                }
271                if let Some(condition) = field.disabling() {
272                    view = disable(cx, condition, &source.scope, source.values, view);
273                }
274                let view = spanned(cx, field.span(), view);
275                Ok(source.guard(cx, field.condition(), view))
276            }
277            // A block whose every field is masked renders no heading over nothing.
278            Node::Section(_) | Node::Group(_) | Node::Grid(_) | Node::Tabs(_) | Node::Wizard(_)
279                if !self.shows_any(fields, source) =>
280            {
281                Ok(().boxed())
282            }
283            Node::Section(s) => {
284                let view = Box::pin(s.render(cx, fields, source)).await?;
285                Ok(source.guard(cx, s.condition.as_ref(), view))
286            }
287            Node::Group(g) => {
288                let view = Box::pin(g.render(cx, fields, source)).await?;
289                Ok(source.guard(cx, g.condition.as_ref(), view))
290            }
291            Node::Grid(g) => {
292                let view = Box::pin(g.render(cx, fields, source)).await?;
293                Ok(source.guard(cx, g.condition.as_ref(), view))
294            }
295            Node::Tabs(t) => {
296                let view = Box::pin(t.render(cx, fields, source)).await?;
297                Ok(source.guard(cx, t.condition.as_ref(), view))
298            }
299            // A tab renders through its block, which lays out its trigger and its panel.
300            Node::Tab(t) => Box::pin(render_nodes(cx, &t.children.nodes, fields, source)).await,
301            Node::Wizard(w) => {
302                let view = Box::pin(w.render(cx, fields, source)).await?;
303                Ok(source.guard(cx, w.condition.as_ref(), view))
304            }
305            // A step renders through its block, which lays out its trigger and its panel.
306            Node::Step(s) => Box::pin(render_nodes(cx, &s.children.nodes, fields, source)).await,
307            Node::Embedded(e) => Box::pin(e.render(cx, fields, source)).await,
308        }
309    }
310
311    /// Whether a field under this node renders an error from `source`: under its own key, or a
312    /// repeater's under one of its rows' keys.
313    pub(crate) fn has_error(&self, fields: &[Field], source: &Source<'_>) -> bool {
314        let mut any = false;
315        self.visit_fields(&mut |index| {
316            let name = fields[index].name();
317            any |= source.errors.iter().any(|error| {
318                error.key == name
319                    || error
320                        .key
321                        .strip_prefix(name)
322                        .is_some_and(|rest| rest.starts_with('.'))
323            });
324        });
325        any
326    }
327
328    /// The first field slot under this node, in declaration order.
329    pub(crate) fn first_field(&self) -> Option<usize> {
330        let mut first = None;
331        self.visit_fields(&mut |index| {
332            first.get_or_insert(index);
333        });
334        first
335    }
336
337    /// Calls `f` with every field slot under this node, in declaration order.
338    fn visit_fields(&self, f: &mut impl FnMut(usize)) {
339        match self {
340            Node::Field(index) => f(*index),
341            Node::Embedded(e) => e.visit_fields(f),
342            node => {
343                for child in node.children().unwrap_or_default() {
344                    child.visit_fields(f);
345                }
346            }
347        }
348    }
349
350    /// Whether some field under this node renders under `source`'s mask.
351    pub(crate) fn shows_any(&self, fields: &[Field], source: &Source<'_>) -> bool {
352        match self {
353            Node::Field(index) => shows(&fields[*index], source),
354            Node::Embedded(e) => {
355                let mut any = false;
356                e.visit_fields(&mut |index| any |= shows(&fields[index], source));
357                any
358            }
359            node => node
360                .children()
361                .unwrap_or_default()
362                .iter()
363                .any(|child| child.shows_any(fields, source)),
364        }
365    }
366
367    /// Returns the nodes a layout container holds, or `None` for a field slot and an embedded
368    /// value.
369    pub(crate) fn children(&self) -> Option<&[Node]> {
370        match self {
371            Node::Section(s) => Some(&s.children.nodes),
372            Node::Group(g) => Some(&g.children.nodes),
373            Node::Grid(g) => Some(&g.children.nodes),
374            Node::Tabs(t) => Some(&t.children.nodes),
375            Node::Tab(t) => Some(&t.children.nodes),
376            Node::Wizard(w) => Some(&w.children.nodes),
377            Node::Step(s) => Some(&s.children.nodes),
378            Node::Field(_) | Node::Embedded(_) => None,
379        }
380    }
381
382    fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
383        match self {
384            Node::Section(s) => Some(&mut s.children.nodes),
385            Node::Group(g) => Some(&mut g.children.nodes),
386            Node::Grid(g) => Some(&mut g.children.nodes),
387            Node::Tabs(t) => Some(&mut t.children.nodes),
388            Node::Tab(t) => Some(&mut t.children.nodes),
389            Node::Wizard(w) => Some(&mut w.children.nodes),
390            Node::Step(s) => Some(&mut s.children.nodes),
391            Node::Field(_) | Node::Embedded(_) => None,
392        }
393    }
394
395    /// Shifts every field slot under this node by `by`.
396    pub(crate) fn offset(&mut self, by: usize) {
397        match self {
398            Node::Field(index) => *index += by,
399            Node::Embedded(e) => e.offset(by),
400            _ => {
401                for child in self.children_mut().into_iter().flatten() {
402                    child.offset(by);
403                }
404            }
405        }
406    }
407}
408
409impl<F> Schema<F> {
410    /// The first field whose control posts keys besides its own or fetches from its resource's
411    /// routes: a file field, a repeater, an embedded value's leaf, a searchable or dependent
412    /// choice. A related form, posting under its owner's prefix, carries none of them.
413    pub(crate) fn needs_own_keys(&self) -> Option<&str> {
414        let mut embedded = Vec::new();
415        for node in &self.nodes {
416            node.embedded_fields(&mut embedded);
417        }
418        self.fields
419            .iter()
420            .enumerate()
421            .find(|(index, field)| {
422                embedded.contains(index)
423                    || field.is_file()
424                    || field.as_repeater().is_some()
425                    || field.parent_key().is_some()
426                    || field
427                        .as_choice()
428                        .is_some_and(|choice| choice.is_searchable())
429            })
430            .map(|(_, field)| field.name())
431    }
432}
433
434impl Node {
435    /// Adds to `out` every field slot an embedded value under this node holds.
436    fn embedded_fields(&self, out: &mut Vec<usize>) {
437        match self {
438            Node::Embedded(e) => e.visit_fields(&mut |index| out.push(index)),
439            node => {
440                for child in node.children().unwrap_or_default() {
441                    child.embedded_fields(out);
442                }
443            }
444        }
445    }
446}
447
448/// Whether `field` renders under `source`'s mask: not when hidden, nor a locked repeater, whose
449/// rows' order posts its key.
450fn shows(field: &Field, source: &Source<'_>) -> bool {
451    !(source.mask.hides(field.name())
452        || field.is_hidden(source.editing)
453        || (source.mask.locks(field.name()) && field.as_repeater().is_some()))
454}
455
456/// Renders `nodes` in order as one view.
457pub(crate) async fn render_nodes<'a>(
458    cx: &'a Cx,
459    nodes: &[Node],
460    fields: &[Field],
461    source: &Source<'_>,
462) -> Result<BoxView<'a>> {
463    let mut views = Vec::with_capacity(nodes.len());
464    for node in nodes {
465        views.push(node.render(cx, fields, source).await?);
466    }
467    Ok(view! {
468        for v in views {
469            (v)
470        }
471    }
472    .boxed())
473}
474
475/// Converts a field, a layout block, a tuple of either, or a schema into a [`Schema`].
476///
477/// `F` is the record form whose controls the schema places, `()` for a page's or an action's
478/// schema: a control converts into the schema of its own form only.
479#[diagnostic::on_unimplemented(
480    message = "`{Self}` cannot be placed in a `Schema<{F}>`",
481    label = "not a control, layout block, schema, or tuple of 2 to 12 of them for this schema",
482    note = "a resource's form places its record form's own controls, from `controls()`; \
483            `Field::text` and the other constructors build a page's or an action's controls"
484)]
485pub trait IntoSchema<F = ()> {
486    fn into_schema(self) -> Schema<F>;
487}
488
489/// Moves a control or a schema to the form `G`: what `#[derive(RecordForm)]` hands its controls
490/// over with.
491#[doc(hidden)]
492pub trait Retype {
493    type As<G>;
494
495    fn retype<G>(self) -> Self::As<G>;
496}
497
498impl<F> IntoSchema<F> for Schema<F> {
499    fn into_schema(self) -> Schema<F> {
500        self
501    }
502}
503
504impl IntoSchema for Field {
505    fn into_schema(self) -> Schema {
506        Schema::from_parts(vec![Node::Field(0)], vec![self])
507    }
508}
509
510/// Generates the single-node [`IntoSchema`] impls for every layout container, holding a schema or
511/// nothing.
512macro_rules! container_nodes {
513    ($($ty:ident),+ $(,)?) => {
514        $(
515            impl<F> IntoSchema<F> for $ty<Schema<F>> {
516                fn into_schema(self) -> Schema<F> {
517                    let mut fields = Vec::new();
518                    let block = self.map(|mut children| {
519                        fields = std::mem::take(&mut children.fields);
520                        children.retype()
521                    });
522                    Schema::from_parts(vec![Node::$ty(Box::new(block))], fields)
523                }
524            }
525
526            impl<F> IntoSchema<F> for $ty<()> {
527                fn into_schema(self) -> Schema<F> {
528                    self.holding(Schema::<F>::default()).into_schema()
529                }
530            }
531        )+
532    };
533}
534
535container_nodes!(Section, Group, Grid);
536
537impl<F> IntoSchema<F> for Tabs<Schema<F>> {
538    fn into_schema(self) -> Schema<F> {
539        let mut fields = Vec::new();
540        let block = self.map(|mut children| {
541            fields = std::mem::take(&mut children.fields);
542            children.retype()
543        });
544        Schema::from_parts(vec![Node::Tabs(Box::new(block))], fields)
545    }
546}
547
548/// Generates the tuple impls of [`IntoSchema`] from one list per arity.
549macro_rules! into_schema_tuples {
550    ($($T:ident => $v:ident),+ $(,)?) => {
551        impl<Form, $($T),+> IntoSchema<Form> for ($($T,)+)
552        where
553            $($T: IntoSchema<Form>,)+
554        {
555            fn into_schema(self) -> Schema<Form> {
556                let ($($v,)+) = self;
557                let mut schema = Schema::default();
558                $( schema.append($v.into_schema()); )+
559                schema
560            }
561        }
562    };
563}
564
565into_schema_tuples!(A => a, B => b);
566into_schema_tuples!(A => a, B => b, C => c);
567into_schema_tuples!(A => a, B => b, C => c, D => d);
568into_schema_tuples!(A => a, B => b, C => c, D => d, E => e);
569into_schema_tuples!(A => a, B => b, C => c, D => d, E => e, F => f);
570into_schema_tuples!(A => a, B => b, C => c, D => d, E => e, F => f, G => g);
571into_schema_tuples!(
572    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h
573);
574into_schema_tuples!(
575    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i
576);
577into_schema_tuples!(
578    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j
579);
580into_schema_tuples!(
581    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k
582);
583into_schema_tuples!(
584    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k, L => l
585);