Skip to main content

tablo_core/
schema.rs

1//! Unified Schema primitive — fields and layout blocks that compose via `view!`.
2//!
3//! `Schema` holds layout blocks, embedded values, and [`Field`] slots and resolves every field once
4//! into one list for rendering and validation.
5
6mod cells;
7mod comparison;
8mod condition;
9mod creatable;
10pub(crate) mod embedded;
11pub(crate) mod fields;
12pub(crate) mod input;
13mod layouts;
14mod lenses;
15mod mask;
16mod options;
17mod read;
18pub(crate) mod relationship;
19pub(crate) mod repeater;
20mod state;
21mod steps;
22pub(crate) mod tree;
23
24use std::{collections::HashSet, marker::PhantomData};
25
26pub use condition::Watched;
27pub use embedded::EmbeddedForm;
28use fields::ChoiceControl;
29#[cfg(feature = "rich-text")]
30pub use fields::RichTextField;
31pub use fields::{
32    ChoiceField, CustomField, Field, FileField, IntoFormValue, IntoOptions, RepeaterField, Switch,
33    TextField, Toggle,
34};
35pub(crate) use fields::{
36    file::{FileHref, file_href},
37    is_linkable, is_rooted, option_view, read_only, stored_upload, value_cell,
38};
39pub(crate) use input::FormInput;
40pub(crate) use layouts::{ExtraStep, TabView, tab_id, tab_view, titled};
41pub use layouts::{Grid, Group, HoldsTabs, Section, Step, Tab, Tabs, Wizard};
42pub(crate) use lenses::Binding;
43pub use lenses::form_key;
44pub(crate) use mask::FormMask;
45pub use options::Options;
46pub use relationship::MAX_RELATIONSHIP_OPTIONS;
47pub(crate) use relationship::{
48    OptionLoadError, OptionSource, clamp_query_term, ensure_option_access,
49};
50pub use repeater::{MAX_REPEATER_ROWS, parse_items, write_items};
51pub(crate) use state::{Posting, Unposted};
52use topcoat::{Result, context::Cx, view::*};
53pub use tree::{IntoSchema, Source};
54pub(crate) use tree::{Node, Retype, render_nodes};
55
56use crate::values::{FieldErrors, FormValue, FormValues};
57
58/// A form with a create and an edit form: every [`RecordForm`](crate::RecordForm), which
59/// `hidden_on_create` and `hidden_on_edit` take. A page's and an action's schema have one form.
60///
61/// `form` implements it for each record form, since `schema` sits below the record form's layer.
62#[doc(hidden)]
63pub trait EditsRecords {}
64
65/// Composes fields and layout blocks and resolves every field once into one list.
66///
67/// `F` is the record form whose controls the schema places. A resource's form is a
68/// `Schema<UserForm>`, which only `UserForm::controls()` fill, so a control from another form or a
69/// field built with [`Field::text`] fails to compile there. A page's or an action's schema is a
70/// plain `Schema`, which [`Field`]'s constructors fill.
71pub struct Schema<F = ()> {
72    pub(crate) nodes: Vec<Node>,
73    pub(crate) fields: Vec<Field>,
74    form: PhantomData<fn() -> F>,
75}
76
77impl<F> Default for Schema<F> {
78    fn default() -> Self {
79        Self::from_parts(Vec::new(), Vec::new())
80    }
81}
82
83impl<F> std::fmt::Debug for Schema<F> {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.debug_struct("Schema")
86            .field("nodes", &self.nodes)
87            .field("fields", &self.fields)
88            .finish()
89    }
90}
91
92impl Schema {
93    /// A schema with no field: a page's or an action's that renders nothing. A resource's form
94    /// that places nothing is `Schema::default()`, which renders every control.
95    pub fn empty() -> Self {
96        Self::default()
97    }
98}
99
100impl<F> Retype for Schema<F> {
101    type As<G> = Schema<G>;
102
103    fn retype<G>(self) -> Schema<G> {
104        Schema::from_parts(self.nodes, self.fields)
105    }
106}
107
108impl<F> Schema<F> {
109    pub(crate) fn from_parts(nodes: Vec<Node>, fields: Vec<Field>) -> Self {
110        Self {
111            nodes,
112            fields,
113            form: PhantomData,
114        }
115    }
116
117    /// Reports whether this schema declares nothing to render.
118    pub fn is_empty(&self) -> bool {
119        self.nodes.is_empty()
120    }
121
122    /// Builds a `Schema` from any `IntoSchema` and reports duplicate field names as declaration
123    /// errors.
124    pub fn new(children: impl IntoSchema<F>) -> Self {
125        children.into_schema()
126    }
127
128    /// Every field, in the order it joins the schema: a layout's fields as it composes, in
129    /// declaration order.
130    pub fn fields(&self) -> impl Iterator<Item = &Field> {
131        self.fields.iter()
132    }
133
134    /// Renders each control required exactly when `required` names its key.
135    pub(crate) fn require(&mut self, required: &HashSet<&str>) {
136        for field in &mut self.fields {
137            let key = required.contains(field.name());
138            field.set_required(key);
139        }
140    }
141
142    /// Renders the schema from `source` and fails with declaration errors instead of rendering.
143    ///
144    /// # Errors
145    ///
146    /// A misdeclared schema fails with its errors rather than render.
147    pub async fn render<'a>(&self, cx: &'a Cx, source: Source<'_>) -> Result<BoxView<'a>> {
148        let errors = self.declaration_errors();
149        if !errors.is_empty() {
150            return Err(crate::error::misdeclared(&errors));
151        }
152        let source = source.watching(self.watched());
153        render_nodes(cx, &self.nodes, &self.fields, &source).await
154    }
155
156    /// Whether the schema draws its own panels under `mask`: every top-level block it renders is a
157    /// section or a tab block, so a frame around it would frame the panels again. A control the
158    /// mask hides renders nothing, such as the foreign key a related form leaves out.
159    pub(crate) fn frames_itself(&self, mask: &FormMask) -> bool {
160        let mut shown = self.nodes.iter().filter(|node| match node {
161            Node::Field(index) => !mask.hides(self.fields[*index].name()),
162            _ => true,
163        });
164        let mut any = false;
165        let framed = shown.all(|node| {
166            any = true;
167            matches!(node, Node::Section(_) | Node::Tabs(_))
168        });
169        any && framed
170    }
171
172    /// Appends `other`'s nodes and fields after this one's, re-slotting its field slots.
173    pub(crate) fn append(&mut self, other: Schema<F>) {
174        let Schema {
175            mut nodes, fields, ..
176        } = other;
177        let offset = self.fields.len();
178        for node in &mut nodes {
179            node.offset(offset);
180        }
181        self.fields.extend(fields);
182        self.nodes.extend(nodes);
183    }
184
185    /// The embedded node a derived value's schema holds.
186    pub(crate) fn embedded_root(&self) -> &embedded::Embedded {
187        match self.nodes.as_slice() {
188            [Node::Embedded(node)] => node,
189            _ => panic!("an embedded value's schema is its one embedded node"),
190        }
191    }
192
193    /// The create form's initial values: each field's `default`.
194    pub(crate) fn defaults(&self) -> FormValues {
195        self.fields
196            .iter()
197            .filter_map(|field| Some((field.name().to_string(), field.default_value()?.clone())))
198            .collect()
199    }
200
201    /// The keys of the controls disabled on the edit form when `editing`, else the create form.
202    pub(crate) fn disabled_keys(&self, editing: bool) -> impl Iterator<Item = &str> {
203        self.fields
204            .iter()
205            .filter(move |field| field.is_disabled(editing))
206            .map(Field::name)
207    }
208
209    /// Appends another schema's nodes after this one's.
210    pub fn extend(mut self, other: Schema<F>) -> Schema<F> {
211        self.append(other);
212        self
213    }
214
215    /// Returns the first key in `errors` that no control renders a message under: neither a
216    /// field's own key nor, for a repeater, a row's key under `{key}.`.
217    pub(crate) fn unplaced_error<'e>(&self, errors: &'e crate::FieldErrors) -> Option<&'e str> {
218        errors.iter().map(|error| error.key.as_str()).find(|key| {
219            !self
220                .fields
221                .iter()
222                .any(|field| match key.strip_prefix(field.name()) {
223                    Some(rest) => {
224                        rest.is_empty() || (rest.starts_with('.') && field.as_repeater().is_some())
225                    }
226                    None => false,
227                })
228        })
229    }
230
231    /// One [`EmptyChoice`](crate::DeclarationErrorKind::EmptyChoice) per choice with neither
232    /// options nor a relationship. Mounting checks a resource's form and its actions' inputs; a
233    /// page's schema may build its options from data that is empty for now, so rendering does
234    /// not.
235    pub(crate) fn empty_choices(&self) -> Vec<crate::DeclarationErrorKind> {
236        self.fields
237            .iter()
238            .filter(|field| field.offers_nothing())
239            .map(|field| crate::DeclarationErrorKind::EmptyChoice {
240                field: field.name().to_string(),
241            })
242            .collect()
243    }
244
245    /// What is wrong with the schema's dependent and filtered choices: a column of another model
246    /// than the relationship's source, or no relationship, and a parent the schema does not place,
247    /// or one a condition disables, which posts nothing to narrow the options by.
248    fn dependent_errors(&self) -> Vec<crate::DeclarationErrorKind> {
249        let mut errors = Vec::new();
250        for field in &self.fields {
251            let Some(choice) = field.as_choice() else {
252                continue;
253            };
254            if choice.misdeclared_parent() {
255                errors.push(crate::DeclarationErrorKind::MisdeclaredDependentChoice {
256                    field: field.name().to_string(),
257                });
258            }
259            if choice.misdeclared_filter() {
260                errors.push(crate::DeclarationErrorKind::UnfilterableChoice {
261                    field: field.name().to_string(),
262                });
263            }
264            let Some(parent) = choice.parent_key() else {
265                continue;
266            };
267            match self.fields.iter().find(|placed| placed.name() == parent) {
268                None => errors.push(crate::DeclarationErrorKind::UnplacedParentField {
269                    field: field.name().to_string(),
270                    parent: parent.to_string(),
271                }),
272                Some(parent)
273                    if choice.is_multiple()
274                        || parent.as_choice().is_some_and(ChoiceControl::is_multiple) =>
275                {
276                    errors.push(crate::DeclarationErrorKind::MultipleDependentChoice {
277                        field: field.name().to_string(),
278                    });
279                }
280                Some(_) if choice.is_listed() => {
281                    errors.push(crate::DeclarationErrorKind::ListedDependentChoice {
282                        field: field.name().to_string(),
283                    });
284                }
285                Some(parent) if parent.disabling().is_some() => {
286                    errors.push(crate::DeclarationErrorKind::DisabledWatchedField {
287                        field: parent.name().to_string(),
288                    });
289                }
290                Some(_) => {}
291            }
292        }
293        errors
294    }
295
296    /// Each key a condition, a dependent choice or a comparison watches, with the key of a field
297    /// it drives: `None` for a condition guarding no field, such as one over an empty section.
298    pub(crate) fn watchers(&self) -> Vec<(String, Option<String>)> {
299        let mut watchers = self.condition_watchers();
300        watchers.extend(self.comparison_watchers());
301        watchers.extend(self.fields.iter().filter_map(|field| {
302            field
303                .parent_key()
304                .map(|parent| (parent.to_string(), Some(field.name().to_string())))
305        }));
306        watchers
307    }
308
309    /// Each file field's `max_bytes`, under its name or `repeater.leaf` for one in a repeater's
310    /// rows: what a panel checks against the body cap it mounts the schema with.
311    pub(crate) fn file_caps(&self) -> Vec<(String, usize)> {
312        let cap = |field: &Field, name: String| {
313            field
314                .as_file()
315                .and_then(|file| file.max_bytes)
316                .map(|max| (name, max))
317        };
318        let mut caps = Vec::new();
319        for field in &self.fields {
320            caps.extend(cap(field, field.name().to_string()));
321            if let Some(repeater) = field.as_repeater() {
322                caps.extend(
323                    repeater
324                        .item_schema()
325                        .fields()
326                        .filter_map(|leaf| cap(leaf, format!("{}.{}", field.name(), leaf.name()))),
327                );
328            }
329        }
330        caps
331    }
332
333    /// Reports what is wrong with this declaration: a field whose lens binds no single column, and
334    /// two fields sharing a name.
335    pub fn declaration_errors(&self) -> Vec<crate::DeclarationErrorKind> {
336        let mut errors = self.condition_errors();
337        errors.extend(self.dependent_errors());
338        errors.extend(self.creatable_errors());
339        errors.extend(self.comparison_errors(""));
340        // A control disabled on create posts nothing there, so the create needs a value.
341        for field in &self.fields {
342            errors.extend(field.rule_errors(field.name()));
343            if let Some(repeater) = field.as_repeater() {
344                let item = repeater.item_schema();
345                for leaf in item.fields() {
346                    errors.extend(leaf.rule_errors(&format!("{}.{}", field.name(), leaf.name())));
347                }
348                errors.extend(item.comparison_errors(&format!("{}.", field.name())));
349            }
350            let blank = field.default_value().is_none_or(|value| match value {
351                FormValue::Text(text) => text.trim().is_empty(),
352                FormValue::List(items) => items.is_empty(),
353                FormValue::Rows(rows) => rows.is_empty(),
354            });
355            if field.may_post_nothing_on_create() && field.is_required() && blank {
356                errors.push(crate::DeclarationErrorKind::DisabledWithoutValue {
357                    field: field.name().to_string(),
358                });
359            }
360            if let Some(value) = field.default_value()
361                && field.refuses(value)
362            {
363                errors.push(crate::DeclarationErrorKind::UnpostedDefault {
364                    field: field.name().to_string(),
365                    value: match value {
366                        FormValue::Text(text) => text.clone(),
367                        FormValue::List(items) => format!("{items:?}"),
368                        FormValue::Rows(_) => "rows".to_string(),
369                    },
370                });
371            }
372            // A row's controls post under the repeater's key, which neither the disabled drop nor
373            // the defaults read.
374            if let Some(repeater) = field.as_repeater()
375                && let Some(leaf) = repeater.item_schema().fields().find(|leaf| {
376                    leaf.is_disabled(true)
377                        || leaf.disabling().is_some()
378                        || leaf.default_value().is_some()
379                })
380            {
381                errors.push(crate::DeclarationErrorKind::RepeaterLeafModifier {
382                    field: field.name().to_string(),
383                    leaf: leaf.name().to_string(),
384                });
385            }
386            // An edit renders each stored row, and a password never renders back: every save
387            // would replace the stored secret with what the user retyped, or with nothing.
388            if let Some(repeater) = field.as_repeater()
389                && let Some(leaf) = repeater
390                    .item_schema()
391                    .fields()
392                    .find(|leaf| leaf.is_password())
393            {
394                errors.push(crate::DeclarationErrorKind::RepeaterPassword {
395                    field: field.name().to_string(),
396                    leaf: leaf.name().to_string(),
397                });
398            }
399        }
400        let mut seen = HashSet::new();
401        for field in &self.fields {
402            match field.misdeclared() {
403                Some(error) => errors.push(error),
404                None if !seen.insert(field.name()) => {
405                    errors.push(crate::DeclarationErrorKind::DuplicateField {
406                        name: field.name().to_string(),
407                    });
408                }
409                None => {}
410            }
411        }
412        errors
413    }
414
415    /// Collects the keys of the fields this submission hides: the payload of every embedded
416    /// variant it does not choose, and every field a condition hides.
417    pub(crate) fn hidden_fields(&self, values: &FormValues) -> HashSet<String> {
418        fn walk(nodes: &[Node], values: &FormValues, out: &mut Vec<usize>) {
419            for node in nodes {
420                match node {
421                    Node::Embedded(embedded) => embedded.hidden_fields(values, out),
422                    node => {
423                        if let Some(children) = node.children() {
424                            walk(children, values, out);
425                        }
426                    }
427                }
428            }
429        }
430        let mut indices = Vec::new();
431        walk(&self.nodes, values, &mut indices);
432        indices
433            .into_iter()
434            .map(|index| self.fields[index].name().to_string())
435            .chain(self.condition_hidden(values))
436            .collect()
437    }
438
439    /// Adds to `errors` what the controls' own rules refuse in a submission: an unchecked
440    /// accepted checkbox, a multiple choice's or a repeater's count of items, an email or URL
441    /// field's value, a text field's declared length, bounds and pattern, and a choice that is not
442    /// one of its options. Skips hidden fields and keys `errors` already refuses. A value the
443    /// record already stores keeps its rules unchecked: a disabled control posts it back, and a
444    /// rule declared since must not lock the record.
445    pub(crate) async fn check_controls(
446        &self,
447        cx: &Cx,
448        values: &FormValues,
449        stored: &FormValues,
450        errors: &mut FieldErrors,
451    ) {
452        let hidden = self.hidden_fields(values);
453        let zone = crate::time_zone(cx);
454        for field in &self.fields {
455            let name = field.name();
456            if errors.contains_key(name) || hidden.contains(name) {
457                continue;
458            }
459            let Some(value) = values.get(name) else {
460                if let Some(error) = field.check_unposted(&zone) {
461                    errors.push(error);
462                }
463                continue;
464            };
465            let refusal = (stored.get(name) != Some(value))
466                .then(|| field.check(value, &zone))
467                .flatten();
468            if let Some(repeater) = field.as_repeater() {
469                // The count's refusal owns the repeater's key; each row's own keys still check.
470                if let Some(error) = refusal {
471                    errors.push(error);
472                }
473                let rows = value.as_rows().unwrap_or_default();
474                let held = stored.get(name).and_then(FormValue::as_rows);
475                repeater
476                    .check(cx, name, rows, held.unwrap_or_default(), errors)
477                    .await;
478                continue;
479            }
480            if let Some(error) =
481                refusal.or_else(|| self.comparison_refusal(field, values, stored, &hidden))
482            {
483                errors.push(error);
484                continue;
485            }
486            let parent = field.parent_key().and_then(|key| values.text(key));
487            for message in field
488                .validate_exists(cx, value, parent, stored.get(name))
489                .await
490            {
491                errors.add_field(name, message);
492            }
493        }
494    }
495
496    /// What the controls' own rules refuse in `values`, alone.
497    #[cfg(test)]
498    pub(crate) async fn checked(&self, cx: &Cx, values: &FormValues) -> FieldErrors {
499        let mut errors = FieldErrors::new();
500        self.check_controls(cx, values, &FormValues::new(), &mut errors)
501            .await;
502        errors
503    }
504
505    /// Puts back the stored value of each text field whose control posted it as rendered: see
506    /// [`Field::keep_unedited`].
507    pub(crate) fn keep_unedited(
508        &self,
509        values: &mut FormValues,
510        stored: &FormValues,
511        zone: &jiff::tz::TimeZone,
512    ) {
513        for field in &self.fields {
514            let name = field.name();
515            let (Some(value), Some(held)) = (values.get(name), stored.get(name)) else {
516                continue;
517            };
518            if let Some(kept) = field.keep_unedited(value, held, zone) {
519                values.insert(name, kept);
520            }
521        }
522    }
523
524    /// Re-checks every submitted relationship key through the write's open transaction, but a
525    /// multiple choice's keys the record's stored value in `stored` holds already.
526    pub(crate) async fn recheck_relationships(
527        &self,
528        cx: &Cx,
529        values: &FormValues,
530        stored: &FormValues,
531        ex: &mut dyn toasty::Executor,
532    ) -> FieldErrors {
533        let mut errors = FieldErrors::new();
534        let hidden = self.hidden_fields(values);
535        for field in &self.fields {
536            let name = field.name();
537            if hidden.contains(name) {
538                continue;
539            }
540            let Some(value) = values.get(name) else {
541                continue;
542            };
543            let parent = field.parent_key().and_then(|key| values.text(key));
544            for message in field
545                .recheck(cx, value, parent, stored.get(name), &mut *ex)
546                .await
547            {
548                errors.add_field(name, message);
549            }
550        }
551        errors
552    }
553
554    /// Puts back in each multiple choice's list the keys of the record's stored list `stored` it
555    /// drops that the user cannot view, through the write's open transaction: the form never
556    /// offered them, so its submission leaves them linked.
557    pub(crate) async fn keep_unseen_links(
558        &self,
559        cx: &Cx,
560        values: &mut FormValues,
561        stored: &FormValues,
562        ex: &mut dyn toasty::Executor,
563    ) {
564        for field in &self.fields {
565            let name = field.name();
566            let (Some(value), Some(held)) = (values.get(name), stored.get(name)) else {
567                continue;
568            };
569            if let Some(kept) = field.keep_unseen(cx, value, held, &mut *ex).await {
570                values.insert(name, kept);
571            }
572        }
573    }
574}
575
576#[cfg(test)]
577mod tests;