Skip to main content

tablo_core/schema/layouts/
section.rs

1//! The `Section` block: a titled panel, optionally described, iconed, collapsible or laid out
2//! aside its heading.
3
4use tablo_ui::{card_content, card_description, card_header, card_title};
5use topcoat::{
6    Result,
7    context::Cx,
8    icon::{IconData, icon},
9    view::{StaticClass, class, *},
10};
11
12use super::{
13    super::{
14        Schema,
15        condition::Condition,
16        fields::Field,
17        tree::{IntoSchema, Source, render_nodes},
18    },
19    Span, spanned,
20};
21
22/// Renders a `Section`'s titled panel: a title row, ruled off from the body under it.
23const PANEL: StaticClass = class!(
24    "flex flex-col rounded-xl border border-border bg-card text-card-foreground shadow-card",
25    "[&>[data-section-title]:not(:last-child)]:border-b [&>[data-section-title]]:border-border",
26);
27
28/// Renders a collapsible section's title row: the whole row toggles the body, which an open
29/// section rules off under it.
30const SUMMARY: StaticClass = class!(
31    "flex cursor-pointer list-none items-center gap-2 px-6 py-4 outline-none",
32    "focus-visible:ring-[3px] focus-visible:ring-ring/50 [&::-webkit-details-marker]:hidden",
33    "[[open]>&]:border-b [[open]>&]:border-border",
34);
35
36/// Renders a section with no panel of its own, a rule above it when another block precedes it.
37/// Alone in its form the title goes: the dialog around the form already names the record.
38const FLAT: StaticClass = class!(
39    "flex flex-col gap-4 [&:not(:first-of-type)]:border-t [&:not(:first-of-type)]:border-border",
40    "[&:not(:first-of-type)]:pt-6 [&:only-of-type>[data-section-title]]:hidden",
41);
42
43/// Renders a section inside another panel: a heading over the fields, a rule above it when a block
44/// precedes it in the panel.
45const SUBSECTION: StaticClass = class!(
46    "flex flex-col gap-4 [&:not(:first-child)]:border-t [&:not(:first-child)]:border-border",
47    "[&:not(:first-child)]:pt-6",
48);
49
50/// Whether a section folds its body away.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52enum Collapse {
53    /// The body always shows.
54    Never,
55    /// The title toggles the body, which the page opens on.
56    Open,
57    /// The title toggles the body, which the page opens folded unless it holds a field error.
58    Closed,
59}
60
61/// What a section shows around its body: everything but its children.
62#[derive(Debug)]
63struct Look {
64    title: crate::Text,
65    description: Option<crate::Text>,
66    icon: Option<IconData>,
67    collapse: Collapse,
68    aside: bool,
69    extra_class: Option<String>,
70}
71
72/// A titled block holding a form's fields ([`schema`](Self::schema)) or a detail page's columns
73/// ([`columns`](Self::columns), which `detail` declares).
74///
75/// ```rust
76/// # #[derive(Debug, toasty::Model, tablo_core::PanelModel)]
77/// # struct User { #[key] #[auto] id: uuid::Uuid, name: String, email: String, bio: String }
78/// use tablo_core::{Field, Schema, Section};
79///
80/// let user = User::fields();
81/// Schema::new((
82///     Section::new("Account")
83///         .description("How the user signs in.")
84///         .aside()
85///         .schema((Field::text(user.name()), Field::text(user.email()))),
86///     Section::new("About")
87///         .collapsed()
88///         .schema(Field::text(user.bio()).multiline(4)),
89/// ));
90/// ```
91///
92/// A collapsible section renders a `<details>` element, so it opens and folds without a script.
93/// Its fields render and post while it is folded; a form section holding a field error renders
94/// open, and the browser opens a folded section holding a control it refuses on submit. An
95/// [`aside`](Self::aside) section does not collapse.
96#[derive(Debug)]
97pub struct Section<C = Schema> {
98    look: Look,
99    pub(crate) children: C,
100    pub(crate) condition: Option<Condition>,
101    pub(super) span: Option<Span>,
102}
103
104impl Section<()> {
105    pub fn new(title: impl Into<crate::Text>) -> Self {
106        Self {
107            look: Look {
108                title: title.into(),
109                description: None,
110                icon: None,
111                collapse: Collapse::Never,
112                aside: false,
113                extra_class: None,
114            },
115            children: (),
116            condition: None,
117            span: None,
118        }
119    }
120
121    /// Holds a form's fields and blocks.
122    pub fn schema<F>(self, children: impl IntoSchema<F>) -> Section<Schema<F>> {
123        self.holding(children.into_schema())
124    }
125}
126
127impl<C> Section<C> {
128    /// Adds an additive `class` hook on the panel container.
129    pub fn class(mut self, class: impl Into<String>) -> Self {
130        self.look.extra_class = Some(class.into());
131        self
132    }
133
134    /// Shows `description` under the title.
135    pub fn description(mut self, description: impl Into<crate::Text>) -> Self {
136        self.look.description = Some(description.into());
137        self
138    }
139
140    /// Shows `icon` before the title.
141    pub fn icon(mut self, data: IconData) -> Self {
142        self.look.icon = Some(data);
143        self
144    }
145
146    /// Lets the title fold the body away; the page opens on it shown.
147    pub fn collapsible(mut self) -> Self {
148        self.look.collapse = Collapse::Open;
149        self
150    }
151
152    /// Lets the title fold the body away, and opens the page on it folded.
153    pub fn collapsed(mut self) -> Self {
154        self.look.collapse = Collapse::Closed;
155        self
156    }
157
158    /// Lays the title and description out beside the body rather than over it, on a screen wide
159    /// enough for both.
160    pub fn aside(mut self) -> Self {
161        self.look.aside = true;
162        self
163    }
164
165    pub(crate) fn holding<D>(self, children: D) -> Section<D> {
166        self.map(|_| children)
167    }
168
169    pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Section<D> {
170        Section {
171            look: self.look,
172            children: f(self.children),
173            condition: self.condition,
174            span: self.span,
175        }
176    }
177
178    /// The titled panel around `body`, or the title alone when the section holds nothing; inside
179    /// another `panel`, the title over `body`.
180    pub(crate) fn chrome_in<'a>(
181        &self,
182        cx: &'a Cx,
183        body: Option<BoxView<'a>>,
184        panel: bool,
185    ) -> BoxView<'a> {
186        if panel {
187            subsection(cx, &self.look, self.span, body)
188        } else {
189            section_chrome(cx, &self.look, self.span, body, false)
190        }
191    }
192}
193
194// The chrome is a free function, not a method of the generic block, so tablo-core compiles its
195// view once rather than once for every detail model an app declares.
196
197/// The section `look` describes around `body`; `errored` opens a folded section holding a field
198/// error.
199fn section_chrome<'a>(
200    cx: &'a Cx,
201    look: &Look,
202    span: Option<Span>,
203    body: Option<BoxView<'a>>,
204    errored: bool,
205) -> BoxView<'a> {
206    spanned(cx, span, panel(cx, look, body, errored))
207}
208
209/// The section's panel, as `section_chrome` spans it.
210fn panel<'a>(cx: &'a Cx, look: &Look, body: Option<BoxView<'a>>, errored: bool) -> BoxView<'a> {
211    let extra = look.extra_class.clone();
212    let heading = heading(cx, look);
213    let description = look.description.clone();
214    match body {
215        Some(body) if look.aside => view! {
216            <div
217                class=(class!("grid gap-x-8 gap-y-4 md:grid-cols-3", extra.clone()))
218                data-section=""
219                data-section-aside=""
220            >
221                <div class="flex flex-col gap-1.5" data-section-title="">
222                    (heading)
223                    if let Some(description) = description {
224                        card_description((description))
225                    }
226                </div>
227                <div class=(class!(PANEL, "md:col-span-2"))>
228                    card_content(
229                        attrs: attributes! { class="flex flex-col gap-6 py-6" },
230                        (body)
231                    )
232                </div>
233            </div>
234        }
235        .boxed(),
236        Some(body) if look.collapse != Collapse::Never => {
237            let open = look.collapse == Collapse::Open || errored;
238            view! {
239                <details
240                    class=(class!(PANEL, extra.clone()))
241                    data-section=""
242                    open=(open)
243                >
244                    <summary class=(SUMMARY) data-section-title="">
245                        <div class="flex min-w-0 flex-1 flex-col gap-1.5">
246                            (heading)
247                            if let Some(description) = description {
248                                card_description((description))
249                            }
250                        </div>
251                        icon(
252                            data: tablo_ui::icons::CHEVRON_DOWN,
253                            attrs: attributes! {
254                                class="shrink-0 text-muted-foreground transition-transform \
255                                       [[open]>summary>&]:rotate-180"
256                            }
257                        )
258                    </summary>
259                    card_content(
260                        attrs: attributes! { class="flex flex-col gap-6 py-6" },
261                        (body)
262                    )
263                </details>
264            }
265            .boxed()
266        }
267        body => view! {
268            <div class=(class!(PANEL, extra.clone())) data-section="">
269                card_header(
270                    attrs: attributes! { data-section-title="" },
271                    (heading)
272                    if let Some(description) = description {
273                        card_description((description))
274                    }
275                )
276                if let Some(body) = body {
277                    card_content(
278                        attrs: attributes! { class="flex flex-col gap-6 py-6" },
279                        (body)
280                    )
281                }
282            </div>
283        }
284        .boxed(),
285    }
286}
287
288/// The section `look` describes as a heading over `body`, for a form a dialog frames. Nothing folds
289/// here: a dialog's form is short, and a section always shows what it asks for.
290fn flat<'a>(cx: &'a Cx, look: &Look, span: Option<Span>, body: Option<BoxView<'a>>) -> BoxView<'a> {
291    let extra = look.extra_class.clone();
292    let heading = heading(cx, look);
293    let description = look.description.clone();
294    let view = view! {
295        <div class=(class!(FLAT, extra)) data-section="">
296            <div data-section-title="">(heading)</div>
297            if let Some(description) = description {
298                card_description((description))
299            }
300            if let Some(body) = body {
301                <div class="flex flex-col gap-6">(body)</div>
302            }
303        </div>
304    }
305    .boxed();
306    spanned(cx, span, view)
307}
308
309/// The section `look` describes inside another panel: its title and description over `body`,
310/// ruled off from a block before it. It neither folds nor sits aside: the panel around it already
311/// frames the fields.
312fn subsection<'a>(
313    cx: &'a Cx,
314    look: &Look,
315    span: Option<Span>,
316    body: Option<BoxView<'a>>,
317) -> BoxView<'a> {
318    let extra = look.extra_class.clone();
319    let heading = heading(cx, look);
320    let description = look.description.clone();
321    let view = view! {
322        <div class=(class!(SUBSECTION, extra)) data-section="" data-subsection="">
323            <div class="flex flex-col gap-1" data-section-title="">
324                (heading)
325                if let Some(description) = description {
326                    card_description((description))
327                }
328            </div>
329            if let Some(body) = body {
330                <div class="flex flex-col gap-6">(body)</div>
331            }
332        </div>
333    }
334    .boxed();
335    spanned(cx, span, view)
336}
337
338/// `body` under `title`, as a section declaring nothing else renders it: a related form's inside
339/// its owner's form. Without a title, `body` as it is.
340pub(crate) fn titled<'a>(cx: &'a Cx, title: Option<crate::Text>, body: BoxView<'a>) -> BoxView<'a> {
341    let Some(title) = title else {
342        return body;
343    };
344    let look = Look {
345        title,
346        description: None,
347        icon: None,
348        collapse: Collapse::Never,
349        aside: false,
350        extra_class: None,
351    };
352    section_chrome(cx, &look, None, Some(body), false)
353}
354
355/// The section's title, after its icon.
356fn heading<'a>(cx: &'a Cx, look: &Look) -> BoxView<'a> {
357    let title = look.title.clone();
358    match look.icon.clone() {
359        Some(data) => view! {
360            <div class="flex items-center gap-2">
361                icon(
362                    data: data,
363                    attrs: attributes! { class="shrink-0 text-muted-foreground" }
364                )
365                card_title((title))
366            </div>
367        }
368        .boxed(),
369        None => view! { card_title((title)) }.boxed(),
370    }
371}
372
373impl Section<Schema> {
374    pub(crate) async fn render<'a>(
375        &self,
376        cx: &'a Cx,
377        fields: &[Field],
378        source: &Source<'_>,
379    ) -> Result<BoxView<'a>> {
380        // A section inside another panel is a heading over its fields: a card in a card frames
381        // the same fields twice.
382        let nested = source.in_panel();
383        if self.children.nodes.is_empty() {
384            return Ok(if source.is_flat() {
385                flat(cx, &self.look, self.span, None)
386            } else if nested {
387                subsection(cx, &self.look, self.span, None)
388            } else {
389                section_chrome(cx, &self.look, self.span, None, false)
390            });
391        }
392        let errored = self
393            .children
394            .nodes
395            .iter()
396            .any(|node| node.has_error(fields, source));
397        let outer = source.set_in_panel(true);
398        let body = render_nodes(cx, &self.children.nodes, fields, source).await;
399        source.set_in_panel(outer);
400        let body = body?;
401        if source.is_flat() {
402            return Ok(flat(cx, &self.look, self.span, Some(body)));
403        }
404        if nested {
405            return Ok(subsection(cx, &self.look, self.span, Some(body)));
406        }
407        Ok(section_chrome(
408            cx,
409            &self.look,
410            self.span,
411            Some(body),
412            errored,
413        ))
414    }
415}