Skip to main content

tablo_core/schema/layouts/
wizard.rs

1//! Holds the `Wizard` block, which walks a form's fields one step at a time.
2
3use topcoat::{
4    Result,
5    context::Cx,
6    view::{StaticClass, class, *},
7};
8
9use super::{Span, spanned, tab_id};
10use crate::schema::{
11    Schema,
12    condition::Condition,
13    fields::Field,
14    tree::{IntoSchema, Node, Retype, Source, render_nodes},
15};
16
17/// Renders the row of step triggers, which numbers them through a CSS counter: a step a condition
18/// hides takes no number.
19const STEP_LIST: StaticClass =
20    class!("flex flex-wrap items-center gap-x-6 gap-y-2 [counter-reset:tablo-step]");
21/// Renders one trigger, which the current step raises and an error marks.
22const STEP_TRIGGER: StaticClass = class!(
23    "group inline-flex items-center gap-2 rounded-md text-sm font-medium text-muted-foreground \
24     outline-none [counter-increment:tablo-step] focus-visible:ring-[3px] \
25     focus-visible:ring-ring/50 aria-[current=step]:text-foreground \
26     data-wizard-error:text-destructive"
27);
28/// Renders a trigger's number, filled on the current step and outlined on a passed one.
29const STEP_NUMBER: StaticClass = class!(
30    "flex size-7 shrink-0 items-center justify-center rounded-full border border-input text-xs \
31     before:content-[counter(tablo-step)] group-data-wizard-done:border-primary \
32     group-data-wizard-done:text-primary group-aria-[current=step]:border-primary \
33     group-aria-[current=step]:bg-primary group-aria-[current=step]:text-primary-foreground \
34     group-data-wizard-error:border-destructive group-data-wizard-error:text-destructive"
35);
36
37/// A block walking a form's fields one [`Step`] at a time, with a button to the next step and one
38/// back.
39///
40/// ```rust
41/// # #[derive(Debug, toasty::Model, tablo_core::PanelModel)]
42/// # struct User { #[key] #[auto] id: uuid::Uuid, name: String, email: String, bio: String }
43/// use tablo_core::{Field, Schema, Step, Wizard};
44///
45/// let user = User::fields();
46/// Schema::new(Wizard::new([
47///     Step::new("Account").schema((Field::text(user.name()), Field::text(user.email()))),
48///     Step::new("About").schema(Field::text(user.bio()).multiline(4)),
49/// ]));
50/// ```
51///
52/// Every step's fields render and post, as a [`Tabs`](crate::Tabs) block's do, and the form's
53/// own buttons save from any step. The next step opens once the browser's own checks pass on the
54/// current one's controls; a later step's trigger runs them on each step before it, and an earlier
55/// one's opens it without. Enter in a field moves to the next step rather than saving, until the
56/// last. The page opens on the first step holding a field error, else on the first step; the
57/// browser opens the step of a control it refuses on submit. A step whose every field the request
58/// may not see renders no trigger, and a block with no such step renders nothing.
59///
60/// A resource form whose top level holds a wizard that no condition hides walks each `has_one`
61/// [related form](crate::Relation::has_one) as a last step of its own, titled after the relation.
62#[derive(Debug)]
63pub struct Wizard<C = Schema> {
64    /// The block's steps, each one node.
65    pub(crate) children: C,
66    pub(crate) condition: Option<Condition>,
67    pub(super) span: Option<Span>,
68}
69
70impl Wizard<()> {
71    /// Holds `steps`, in the order the form walks them.
72    pub fn new<F>(steps: impl IntoIterator<Item = Step<Schema<F>>>) -> Wizard<Schema<F>> {
73        let mut children = Schema::<F>::default();
74        for step in steps {
75            let mut fields = Vec::new();
76            let step = step.map(|mut children| {
77                fields = std::mem::take(&mut children.fields);
78                children.retype()
79            });
80            children.append(Schema::from_parts(vec![Node::Step(Box::new(step))], fields));
81        }
82        Wizard {
83            children,
84            condition: None,
85            span: None,
86        }
87    }
88}
89
90impl<C> Wizard<C> {
91    pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Wizard<D> {
92        Wizard {
93            children: f(self.children),
94            condition: self.condition,
95            span: self.span,
96        }
97    }
98}
99
100impl<F> IntoSchema<F> for Wizard<Schema<F>> {
101    fn into_schema(self) -> Schema<F> {
102        let mut fields = Vec::new();
103        let block = self.map(|mut children| {
104            fields = std::mem::take(&mut children.fields);
105            children.retype()
106        });
107        Schema::from_parts(vec![Node::Wizard(Box::new(block))], fields)
108    }
109}
110
111/// One step of a [`Wizard`] block: a titled trigger and the fields it shows.
112#[derive(Debug)]
113pub struct Step<C = Schema> {
114    label: crate::Text,
115    pub(crate) children: C,
116    pub(crate) condition: Option<Condition>,
117}
118
119impl Step<()> {
120    pub fn new(label: impl Into<crate::Text>) -> Self {
121        Self {
122            label: label.into(),
123            children: (),
124            condition: None,
125        }
126    }
127
128    /// Holds a form's fields and blocks.
129    pub fn schema<F>(self, children: impl IntoSchema<F>) -> Step<Schema<F>> {
130        self.map(|_| children.into_schema())
131    }
132}
133
134impl<C> Step<C> {
135    pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Step<D> {
136        Step {
137            label: self.label,
138            children: f(self.children),
139            condition: self.condition,
140        }
141    }
142}
143
144/// A step a form adds after a wizard's own: a related form, which renders outside the schema.
145pub(crate) struct ExtraStep<'a> {
146    /// The base of its trigger's and panel's DOM ids, distinct within the page.
147    pub(crate) id: String,
148    pub(crate) label: crate::Text,
149    /// Whether its body holds a field error, which opens it unless an earlier step holds one.
150    pub(crate) errored: bool,
151    pub(crate) body: BoxView<'a>,
152}
153
154impl Wizard<Schema> {
155    pub(crate) async fn render<'a>(
156        &self,
157        cx: &'a Cx,
158        fields: &[Field],
159        source: &Source<'_>,
160    ) -> Result<BoxView<'a>> {
161        self.render_with(cx, fields, source, Vec::new()).await
162    }
163
164    /// Renders the block with `extra` walked after its own steps.
165    pub(crate) async fn render_with<'a>(
166        &self,
167        cx: &'a Cx,
168        fields: &[Field],
169        source: &Source<'_>,
170        extra: Vec<ExtraStep<'a>>,
171    ) -> Result<BoxView<'a>> {
172        let steps: Vec<(&Node, &Step)> = self
173            .children
174            .nodes
175            .iter()
176            .filter_map(|node| match node {
177                Node::Step(step) if node.shows_any(fields, source) => Some((node, &**step)),
178                _ => None,
179            })
180            .collect();
181        let errored: Vec<bool> = steps
182            .iter()
183            .map(|(node, _)| node.has_error(fields, source))
184            .chain(extra.iter().map(|step| step.errored))
185            .collect();
186        // The first step holding an error, else the first the page shows.
187        let shown: Vec<bool> = steps
188            .iter()
189            .map(|(_, step)| source.holds(step.condition.as_ref()))
190            .chain(extra.iter().map(|_| true))
191            .collect();
192        let active = errored
193            .iter()
194            .position(|e| *e)
195            .unwrap_or_else(|| shown.iter().position(|s| *s).unwrap_or(0));
196        let first = shown.iter().position(|s| *s);
197        let last = shown.iter().rposition(|s| *s);
198        let depth = source.tab_depth();
199        let mut triggers = Vec::with_capacity(steps.len());
200        let mut panels = Vec::with_capacity(steps.len());
201        for (index, (node, step)) in steps.iter().enumerate() {
202            let id = node
203                .first_field()
204                .map(|field| tab_id(&source.id(fields[field].name()), depth))
205                .unwrap_or_default();
206            source.set_tab_depth(depth + 1);
207            let body = render_nodes(cx, &step.children.nodes, fields, source).await;
208            source.set_tab_depth(depth);
209            let (trigger, panel) = step_view(
210                cx,
211                &id,
212                &step.label,
213                index.cmp(&active),
214                errored[index],
215                body?,
216            );
217            triggers.push(source.guard(cx, step.condition.as_ref(), trigger));
218            panels.push(source.guard(cx, step.condition.as_ref(), panel));
219        }
220        let own = steps.len();
221        for (offset, step) in extra.into_iter().enumerate() {
222            let index = own + offset;
223            let place = index.cmp(&active);
224            let (trigger, panel) =
225                step_view(cx, &step.id, &step.label, place, errored[index], step.body);
226            triggers.push(trigger);
227            panels.push(panel);
228        }
229        let view = view! {
230            <div data-wizard="" class="flex flex-col gap-6">
231                <div class=(STEP_LIST)>
232                    for trigger in triggers {
233                        (trigger)
234                    }
235                </div>
236                for panel in panels {
237                    (panel)
238                }
239                <div class="flex items-center justify-between gap-2">
240                    tablo_ui::button(
241                        variant: tablo_ui::ButtonVariant::Outline,
242                        attrs: attributes! {
243                            type="button"
244                            data-wizard-back=""
245                            hidden=(first.is_none_or(|first| active <= first))
246                        },
247                        (crate::t!(cx, "tablo-wizard-back"))
248                    )
249                    tablo_ui::button(
250                        variant: tablo_ui::ButtonVariant::Secondary,
251                        attrs: attributes! {
252                            type="button"
253                            data-wizard-next=""
254                            class="ms-auto"
255                            hidden=(last.is_none_or(|last| active >= last))
256                        },
257                        (crate::t!(cx, "tablo-wizard-next"))
258                    )
259                </div>
260            </div>
261        }
262        .boxed();
263        Ok(spanned(cx, self.span, view))
264    }
265}
266
267/// Renders the step `id`: a trigger reading `label`, and a panel holding `body`, shown only when
268/// `place` is the current step's. `errored` marks the trigger of a step holding a field error.
269fn step_view<'a>(
270    cx: &'a Cx,
271    id: &str,
272    label: &crate::Text,
273    place: std::cmp::Ordering,
274    errored: bool,
275    body: BoxView<'a>,
276) -> (BoxView<'a>, BoxView<'a>) {
277    let trigger_id = format!("{id}-step");
278    let panel_id = format!("{id}-steppanel");
279    let labelled_by = trigger_id.clone();
280    let controls = panel_id.clone();
281    let label = label.localize(cx);
282    let current = place.is_eq();
283    let trigger = view! {
284        <button
285            type="button"
286            id=(trigger_id)
287            aria-controls=(controls)
288            aria-current=(current.then_some("step"))
289            data-wizard-trigger=""
290            data-wizard-done=(place.is_lt())
291            data-wizard-error=(errored)
292            class=(STEP_TRIGGER)
293        >
294            <span aria-hidden="true" class=(STEP_NUMBER)></span>
295            (label)
296        </button>
297    }
298    .boxed();
299    let panel = view! {
300        <div
301            role="group"
302            id=(panel_id)
303            aria-labelledby=(labelled_by)
304            hidden=(!current)
305            data-wizard-step=""
306            class="flex flex-col gap-6"
307        >
308            (body)
309        </div>
310    }
311    .boxed();
312    (trigger, panel)
313}