Skip to main content

tablo_core/schema/
layouts.rs

1//! Holds the `Section`, `Group`, `Grid`, `Tabs` and `Wizard` blocks that lay out a form's fields or
2//! a detail page's columns.
3
4use tablo_ui::field_group as ui_field_group;
5use topcoat::{
6    Result,
7    context::Cx,
8    icon::{IconData, icon},
9    view::{StaticClass, class, *},
10};
11
12use super::{
13    super::Color,
14    Schema,
15    condition::{Condition, Watched},
16    fields::Field,
17    tree::{IntoSchema, Node, Retype, Source, render_nodes},
18};
19
20mod section;
21mod span;
22mod wizard;
23
24pub use section::Section;
25pub(crate) use section::titled;
26pub(crate) use span::{Span, spanned};
27pub(crate) use wizard::ExtraStep;
28pub use wizard::{Step, Wizard};
29
30/// An unlabelled block grouping a form's fields or a detail page's columns.
31#[derive(Debug)]
32pub struct Group<C = Schema> {
33    pub(crate) children: C,
34    pub(crate) condition: Option<Condition>,
35    span: Option<Span>,
36}
37
38impl Default for Group<()> {
39    fn default() -> Self {
40        Self {
41            children: (),
42            condition: None,
43            span: None,
44        }
45    }
46}
47
48impl Group<()> {
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Holds a form's fields and blocks.
54    pub fn schema<F>(self, children: impl IntoSchema<F>) -> Group<Schema<F>> {
55        self.holding(children.into_schema())
56    }
57}
58
59impl<C> Group<C> {
60    pub(crate) fn holding<D>(self, children: D) -> Group<D> {
61        self.map(|_| children)
62    }
63
64    pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Group<D> {
65        Group {
66            children: f(self.children),
67            condition: self.condition,
68            span: self.span,
69        }
70    }
71
72    /// The group around `body`.
73    pub(crate) fn chrome<'a>(&self, cx: &'a Cx, body: BoxView<'a>) -> BoxView<'a> {
74        group_chrome(cx, self.span, body)
75    }
76}
77
78fn group_chrome<'a>(cx: &'a Cx, span: Option<Span>, body: BoxView<'a>) -> BoxView<'a> {
79    spanned(cx, span, view! { ui_field_group((body)) }.boxed())
80}
81
82impl Group<Schema> {
83    pub(crate) async fn render<'a>(
84        &self,
85        cx: &'a Cx,
86        fields: &[Field],
87        source: &Source<'_>,
88    ) -> Result<BoxView<'a>> {
89        let body = render_nodes(cx, &self.children.nodes, fields, source).await?;
90        Ok(self.chrome(cx, body))
91    }
92}
93
94/// A block of `cols` columns, clamped to 1..12, laying out a form's fields or a detail page's
95/// columns.
96///
97/// The grid lays its columns out once it is wide enough for them: 28rem for two columns, 42rem for
98/// three and 56rem for four or more. Narrower, it stacks its children in one column. It measures
99/// its own width rather than the screen's, so a grid in a narrow column stacks on a wide screen. A
100/// child spans more than one column through its `span`. A control taller than a line, a rich-text
101/// editor, a text area, a checkbox list, a repeater or a file list, spans the whole row unless it
102/// declares a span, and so do a detail page's rich-text and repeater entries: a short neighbor
103/// beside one would leave its column empty below it.
104///
105/// ```rust
106/// # #[derive(Debug, toasty::Model, tablo_core::PanelModel)]
107/// # struct Product {
108/// #     #[key] #[auto] id: uuid::Uuid, name: String, description: String, visible: bool,
109/// # }
110/// use tablo_core::{Field, Grid, Group, Schema, Section};
111///
112/// let product = Product::fields();
113/// Schema::new(Grid::new(3).schema((
114///     Group::new().span(2).schema(Section::new("Product").schema((
115///         Field::text(product.name()),
116///         Field::text(product.description()).multiline(4),
117///     ))),
118///     Section::new("Status").schema(Field::toggle(product.visible())),
119/// )));
120/// ```
121#[derive(Debug)]
122pub struct Grid<C = Schema> {
123    cols: u8,
124    pub(crate) children: C,
125    pub(crate) condition: Option<Condition>,
126    span: Option<Span>,
127}
128
129impl Grid<()> {
130    pub fn new(cols: u8) -> Self {
131        Self {
132            cols: cols.clamp(1, 12),
133            children: (),
134            condition: None,
135            span: None,
136        }
137    }
138
139    /// Holds a form's fields and blocks.
140    pub fn schema<F>(self, children: impl IntoSchema<F>) -> Grid<Schema<F>> {
141        self.holding(children.into_schema())
142    }
143}
144
145impl<C> Grid<C> {
146    pub(crate) fn holding<D>(self, children: D) -> Grid<D> {
147        self.map(|_| children)
148    }
149
150    pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Grid<D> {
151        Grid {
152            cols: self.cols,
153            children: f(self.children),
154            condition: self.condition,
155            span: self.span,
156        }
157    }
158
159    /// The grid around `body`.
160    pub(crate) fn chrome<'a>(&self, cx: &'a Cx, body: BoxView<'a>) -> BoxView<'a> {
161        grid_chrome(cx, self.cols, self.span, body)
162    }
163}
164
165fn grid_chrome<'a>(cx: &'a Cx, cols: u8, span: Option<Span>, body: BoxView<'a>) -> BoxView<'a> {
166    // Static literals for Tailwind scanner — `format!("grid grid-cols-{}")` would be
167    // purged because Tailwind only sees literal substrings. `--tablo-cols` tells a spanning
168    // child how many columns the grid lays out at its current width.
169    let class: &'static str = match cols {
170        1 => "grid grid-cols-1 gap-4 [--tablo-cols:1]",
171        2 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @md:grid-cols-2 @md:[--tablo-cols:2]",
172        3 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @2xl:grid-cols-3 @2xl:[--tablo-cols:3]",
173        4 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-4 @4xl:[--tablo-cols:4]",
174        5 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-5 @4xl:[--tablo-cols:5]",
175        6 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-6 @4xl:[--tablo-cols:6]",
176        7 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-7 @4xl:[--tablo-cols:7]",
177        8 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-8 @4xl:[--tablo-cols:8]",
178        9 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-9 @4xl:[--tablo-cols:9]",
179        10 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-10 @4xl:[--tablo-cols:10]",
180        11 => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-11 @4xl:[--tablo-cols:11]",
181        _ => "grid grid-cols-1 gap-4 [--tablo-cols:1] @4xl:grid-cols-12 @4xl:[--tablo-cols:12]",
182    };
183    // The grid measures the container around it: an element cannot query its own width.
184    let grid = view! { <div class="@container"><div class=(class)>(body)</div></div> }.boxed();
185    spanned(cx, span, grid)
186}
187
188impl Grid<Schema> {
189    pub(crate) async fn render<'a>(
190        &self,
191        cx: &'a Cx,
192        fields: &[Field],
193        source: &Source<'_>,
194    ) -> Result<BoxView<'a>> {
195        let body = render_nodes(cx, &self.children.nodes, fields, source).await?;
196        Ok(self.chrome(cx, body))
197    }
198}
199
200/// Generates `visible_when` for every layout block holding a form's fields.
201macro_rules! conditional_blocks {
202    ($($ty:ident),+ $(,)?) => {
203        $(
204            impl<F> $ty<Schema<F>> {
205                /// Shows the block and every field it holds only while `watched` posts one of
206                /// `values`, as [`TextField::visible_when`](crate::TextField::visible_when) shows a
207                /// field.
208                pub fn visible_when(
209                    mut self,
210                    watched: &impl Watched<F>,
211                    values: impl IntoIterator<Item = impl Into<String>>,
212                ) -> Self {
213                    self.condition = Some(Condition::new(watched, values));
214                    self
215                }
216            }
217        )+
218    };
219}
220
221conditional_blocks!(Section, Group, Grid, Tabs, Tab, Wizard, Step);
222
223/// Generates `span` and `span_full` for every block a [`Grid`] lays out.
224macro_rules! spanning_blocks {
225    ($($ty:ident),+ $(,)?) => {
226        $(
227            impl<C> $ty<C> {
228                /// Spans `columns` of the [`Grid`] holding the block, clamped to 1..12. While the
229                /// grid stacks its children, or lays out fewer columns, the block spans them all.
230                /// Outside a grid, the span does nothing.
231                pub fn span(mut self, columns: u8) -> Self {
232                    self.span = Some(Span::columns(columns));
233                    self
234                }
235
236                /// Spans every column of the [`Grid`] holding the block.
237                pub fn span_full(mut self) -> Self {
238                    self.span = Some(Span::Full);
239                    self
240                }
241            }
242        )+
243    };
244}
245
246spanning_blocks!(Section, Group, Grid, Tabs, Wizard);
247
248/// Renders a `Tabs` block: a card whose header is the list of triggers, the way a list page shows
249/// its tabs. Inside a section's card, or the dialog around a framed form, it draws no card of its
250/// own and its tabs sit flush with the fields around them.
251const TABS: StaticClass = class!(
252    "flex min-w-0 flex-col rounded-xl border border-border bg-card text-card-foreground shadow-card",
253    "in-[[data-section],[data-pick-page]]:rounded-none in-[[data-section],[data-pick-page]]:border-0",
254    "in-[[data-section],[data-pick-page]]:bg-transparent in-[[data-section],[data-pick-page]]:shadow-none",
255);
256/// Renders a `Tabs` block's list of triggers: a rule the selected tab's underline covers, which
257/// scrolls sideways without a scrollbar when the tabs outgrow it.
258const TAB_LIST: StaticClass = class!(
259    "flex max-w-full items-stretch gap-1 overflow-x-auto overflow-y-hidden border-b border-border",
260    "px-3 [scrollbar-width:none] sm:px-4 [&::-webkit-scrollbar]:hidden",
261    "in-[[data-section],[data-pick-page]]:px-0",
262);
263/// Renders one trigger, which the selected tab underlines.
264const TAB_TRIGGER: StaticClass = class!(
265    "-mb-px inline-flex h-11 shrink-0 items-center gap-2 border-b-2 border-transparent px-2.5",
266    "text-sm font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none",
267    "hover:text-foreground focus-visible:text-foreground focus-visible:ring-2",
268    "focus-visible:ring-ring/50 focus-visible:ring-inset aria-selected:border-primary",
269    "aria-selected:text-foreground data-tab-error:text-destructive",
270    "data-tab-error:aria-selected:border-destructive",
271);
272/// Renders the panel of one tab, padded as a card's content unless the block draws no card.
273const TAB_PANEL: StaticClass = class!(
274    "flex flex-col gap-6 p-4 outline-none sm:p-6",
275    "in-[[data-section],[data-pick-page]]:px-0 in-[[data-section],[data-pick-page]]:pb-0",
276);
277
278/// A block showing one [`Tab`] at a time, each holding a form's fields
279/// ([`Tab::schema`]) or a detail page's columns ([`Tab::columns`]).
280///
281/// ```rust
282/// # #[derive(Debug, toasty::Model, tablo_core::PanelModel)]
283/// # struct User { #[key] #[auto] id: uuid::Uuid, name: String, email: String, bio: String }
284/// use tablo_core::{Field, Schema, Tab, Tabs};
285///
286/// let user = User::fields();
287/// Schema::new(Tabs::new([
288///     Tab::new("Account").schema((Field::text(user.name()), Field::text(user.email()))),
289///     Tab::new("About").schema(Field::text(user.bio()).multiline(4)),
290/// ]));
291/// ```
292///
293/// Every tab's fields render and post: an inactive tab's are only hidden, so a submission carries
294/// them as if no tab held them, and the browser's own checks still refuse what they refuse. The
295/// page opens on the first tab holding a field error, else on the first tab; the browser opens
296/// the tab of a control it refuses on submit. A tab whose every field or column the request may
297/// not see renders no trigger, and a block with no such tab renders nothing.
298#[derive(Debug)]
299pub struct Tabs<C = Schema> {
300    /// The block's tabs, each one node.
301    pub(crate) children: C,
302    pub(crate) condition: Option<Condition>,
303    span: Option<Span>,
304}
305
306impl<C: HoldsTabs> Tabs<C> {
307    /// Holds `tabs`, in the order their triggers show.
308    pub fn new(tabs: impl IntoIterator<Item = Tab<C>>) -> Self {
309        let mut children = C::default();
310        for tab in tabs {
311            children.push_tab(tab);
312        }
313        Self {
314            children,
315            condition: None,
316            span: None,
317        }
318    }
319}
320
321impl<C> Tabs<C> {
322    pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Tabs<D> {
323        Tabs {
324            children: f(self.children),
325            condition: self.condition,
326            span: self.span,
327        }
328    }
329
330    /// The block around its rendered `tabs`.
331    pub(crate) fn chrome<'a>(&self, cx: &'a Cx, tabs: Vec<TabView<'a>>) -> BoxView<'a> {
332        spanned(cx, self.span, tabs_chrome(cx, tabs))
333    }
334}
335
336/// One tab of a [`Tabs`] block: a titled trigger and the fields or columns it shows.
337///
338/// ```rust
339/// # #[derive(Debug, toasty::Model, tablo_core::PanelModel)]
340/// # struct User { #[key] #[auto] id: uuid::Uuid, name: String, bio: String }
341/// use tablo_core::{Color, Field, Tab};
342///
343/// let user = User::fields();
344/// Tab::new("About")
345///     .icon(tablo_ui::icons::USER)
346///     .badge("New")
347///     .badge_color(Color::Info)
348///     .schema(Field::text(user.bio()).multiline(4));
349/// ```
350#[derive(Debug)]
351pub struct Tab<C = Schema> {
352    face: TabFace,
353    pub(crate) children: C,
354    pub(crate) condition: Option<Condition>,
355}
356
357/// What a tab's trigger shows.
358#[derive(Debug)]
359pub(crate) struct TabFace {
360    label: crate::Text,
361    icon: Option<IconData>,
362    badge: Option<crate::Text>,
363    badge_color: Option<Color>,
364}
365
366impl Tab<()> {
367    pub fn new(label: impl Into<crate::Text>) -> Self {
368        Self {
369            face: TabFace {
370                label: label.into(),
371                icon: None,
372                badge: None,
373                badge_color: None,
374            },
375            children: (),
376            condition: None,
377        }
378    }
379
380    /// Holds a form's fields and blocks.
381    pub fn schema<F>(self, children: impl IntoSchema<F>) -> Tab<Schema<F>> {
382        self.holding(children.into_schema())
383    }
384}
385
386impl<C> Tab<C> {
387    pub(crate) fn holding<D>(self, children: D) -> Tab<D> {
388        self.map(|_| children)
389    }
390
391    pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Tab<D> {
392        Tab {
393            face: self.face,
394            children: f(self.children),
395            condition: self.condition,
396        }
397    }
398
399    /// Shows `icon` before the label.
400    pub fn icon(mut self, data: IconData) -> Self {
401        self.face.icon = Some(data);
402        self
403    }
404
405    /// Shows a badge reading `text` after the label, such as a count or `"New"`.
406    pub fn badge(mut self, text: impl Into<crate::Text>) -> Self {
407        self.face.badge = Some(text.into());
408        self
409    }
410
411    /// Leads the badge with a dot in `color`.
412    pub fn badge_color(mut self, color: Color) -> Self {
413        self.face.badge_color = Some(color);
414        self
415    }
416
417    /// What the trigger shows.
418    pub(crate) fn face(&self) -> &TabFace {
419        &self.face
420    }
421}
422
423/// What a [`Tabs`] block holds its tabs in: a form's [`Schema`] or a detail page's
424/// [`Detail`](crate::Detail).
425#[doc(hidden)]
426pub trait HoldsTabs: Default + Sized {
427    fn push_tab(&mut self, tab: Tab<Self>);
428}
429
430impl<F> HoldsTabs for Schema<F> {
431    fn push_tab(&mut self, tab: Tab<Self>) {
432        let mut fields = Vec::new();
433        let tab = tab.map(|mut children| {
434            fields = std::mem::take(&mut children.fields);
435            children.retype()
436        });
437        self.append(Schema::from_parts(vec![Node::Tab(Box::new(tab))], fields));
438    }
439}
440
441/// The DOM id prefix of the tab whose first field or column renders under `id`, inside `depth`
442/// tabs: an outer tab and the first tab of a block it holds start at the same field.
443pub(crate) fn tab_id(id: &str, depth: usize) -> String {
444    format!("{id}-{depth}")
445}
446
447/// One tab of a [`Tabs`] block, rendered: its trigger and its panel apart, so a condition on the
448/// tab guards each.
449pub(crate) struct TabView<'a> {
450    pub(crate) trigger: BoxView<'a>,
451    pub(crate) panel: BoxView<'a>,
452}
453
454/// Renders the tab `id` of a block whose active tab is `active`: a trigger showing `face`, and a
455/// panel holding `body`, hidden unless `active`. `errored` marks the trigger of a tab holding a
456/// field error.
457pub(crate) fn tab_view<'a>(
458    cx: &'a Cx,
459    id: &str,
460    face: &TabFace,
461    active: bool,
462    errored: bool,
463    body: BoxView<'a>,
464) -> TabView<'a> {
465    let tab = format!("{id}-tab");
466    let panel = format!("{id}-tabpanel");
467    let (labelled_by, panel_id) = (tab.clone(), panel.clone());
468    let label = face.label.localize(cx);
469    let glyph = face.icon.clone();
470    let badge = face.badge.as_ref().map(|text| text.localize(cx));
471    let color = face.badge_color;
472    let selected = if active { "true" } else { "false" };
473    let tabindex = if active { "0" } else { "-1" };
474    let trigger = view! {
475        <button
476            type="button"
477            role="tab"
478            id=(tab)
479            aria-controls=(panel)
480            aria-selected=(selected)
481            tabindex=(tabindex)
482            data-tab-error=(errored)
483            class=(TAB_TRIGGER)
484        >
485            if let Some(data) = glyph {
486                icon(
487                    data: data,
488                    attrs: attributes! { class="size-4 shrink-0" aria-hidden="true" }
489                )
490            }
491            (label)
492            if let Some(text) = badge {
493                <span class="contents tabular-nums" data-tab-badge="">
494                    (crate::display::badge(cx, text, color, None))
495                </span>
496            }
497        </button>
498    }
499    .boxed();
500    let panel = view! {
501        <div
502            role="tabpanel"
503            id=(panel_id)
504            aria-labelledby=(labelled_by)
505            tabindex="0"
506            hidden=(!active)
507            data-tab-panel=""
508            class=(TAB_PANEL)
509        >
510            (body)
511        </div>
512    }
513    .boxed();
514    TabView { trigger, panel }
515}
516
517/// The block around its rendered `tabs`: the triggers in a list over the panels.
518fn tabs_chrome<'a>(cx: &'a Cx, tabs: Vec<TabView<'a>>) -> BoxView<'a> {
519    let (triggers, panels): (Vec<_>, Vec<_>) =
520        tabs.into_iter().map(|tab| (tab.trigger, tab.panel)).unzip();
521    view! {
522        <div data-tabs="" class=(TABS)>
523            <div role="tablist" class=(TAB_LIST)>
524                for trigger in triggers {
525                    (trigger)
526                }
527            </div>
528            for panel in panels {
529                (panel)
530            }
531        </div>
532    }
533    .boxed()
534}
535
536impl Tabs<Schema> {
537    pub(crate) async fn render<'a>(
538        &self,
539        cx: &'a Cx,
540        fields: &[Field],
541        source: &Source<'_>,
542    ) -> Result<BoxView<'a>> {
543        let tabs: Vec<(&Node, &Tab)> = self
544            .children
545            .nodes
546            .iter()
547            .filter_map(|node| match node {
548                Node::Tab(tab) if node.shows_any(fields, source) => Some((node, &**tab)),
549                _ => None,
550            })
551            .collect();
552        let errored: Vec<bool> = tabs
553            .iter()
554            .map(|(node, _)| node.has_error(fields, source))
555            .collect();
556        // The first tab holding an error, else the first the page shows.
557        let active = errored.iter().position(|e| *e).unwrap_or_else(|| {
558            tabs.iter()
559                .position(|(_, tab)| source.holds(tab.condition.as_ref()))
560                .unwrap_or(0)
561        });
562        let depth = source.tab_depth();
563        let mut views = Vec::with_capacity(tabs.len());
564        for (index, (node, tab)) in tabs.iter().enumerate() {
565            let id = node
566                .first_field()
567                .map(|field| tab_id(&source.id(fields[field].name()), depth))
568                .unwrap_or_default();
569            source.set_tab_depth(depth + 1);
570            // The block is a card, or sits flush in one: either way its sections are headings.
571            let outer = source.set_in_panel(true);
572            let body = render_nodes(cx, &tab.children.nodes, fields, source).await;
573            source.set_in_panel(outer);
574            source.set_tab_depth(depth);
575            let body = body?;
576            let view = tab_view(cx, &id, tab.face(), index == active, errored[index], body);
577            views.push(TabView {
578                trigger: source.guard(cx, tab.condition.as_ref(), view.trigger),
579                panel: source.guard(cx, tab.condition.as_ref(), view.panel),
580            });
581        }
582        Ok(self.chrome(cx, views))
583    }
584}