Skip to main content

tablo_core/panel/
shell.rs

1//! Renders the shell framing every admin page.
2
3use topcoat::{
4    Result,
5    asset::Asset,
6    context::Cx,
7    font::Font,
8    icon::icon,
9    router::Slot,
10    runtime::{Event, Signal, signal},
11    view::{Attributes, BoxView, Child, ViewExt, attributes, internal::ThenView, view},
12};
13
14use super::{Panel, state::current};
15use crate::{navigation::NavigationItem, topcoat_compat::async_page};
16
17/// `extra` plus the attribute that sends a sidebar link through runtime
18/// navigation. The menu button writes the `href` itself, so this carries none.
19fn sidebar_link(cx: &Cx, mut extra: Attributes) -> Attributes {
20    let mut attrs = crate::navigation::runtime_link(cx, "");
21    attrs.remove("href");
22    extra.extend(attrs);
23    extra
24}
25
26/// The application-owned assets used by [`Panel::layout_shell`].
27///
28/// Tailwind's generated stylesheet is necessarily a call-site asset because
29/// every application scans a different source tree. The Panel therefore takes
30/// the generated stylesheet and the application's chosen font as values while
31/// still owning the document markup that links them.
32#[derive(Debug, Clone, Copy)]
33pub(crate) struct ShellAssets {
34    pub(crate) stylesheet: Asset,
35    pub(crate) font: Font,
36}
37
38/// The `id` of the block that holds the page, which the skip link targets.
39const MAIN_CONTENT: &str = "main-content";
40
41impl Panel {
42    async fn sidebar_navigation<'a>(
43        cx: &'a Cx,
44        nav_items: &[NavigationItem],
45        current_path: &str,
46        current_query: &str,
47        mobile_open: Signal<bool>,
48    ) -> Result<BoxView<'a>> {
49        use tablo_ui::{
50            sidebar_group, sidebar_group_content, sidebar_group_label, sidebar_menu,
51            sidebar_menu_badge, sidebar_menu_button, sidebar_menu_item,
52        };
53        // A Panel resolves every item it owns (`Panel::resource`, `page`, `home`); one that
54        // reaches the sidebar unresolved has no URL to render: a framework bug, not user error.
55        debug_assert!(
56            nav_items.iter().all(|item| item.url().is_some()),
57            "navigation items are resolved by the Panel that owns them"
58        );
59        let nav_items = sidebar::in_sidebar_order(nav_items);
60        // One active entry, chosen the way the breadcrumbs choose theirs.
61        let active = crate::navigation::current_index(&nav_items, current_path, current_query);
62        let sections = sidebar::sidebar_sections(nav_items);
63
64        Ok(view! {
65            for (label, entries) in sections {
66                sidebar_group(
67                    sidebar_group_label((label))
68                    sidebar_group_content(
69                        sidebar_menu(
70                            attrs: attributes! { class="gap-1.5" },
71                            for (index, item) in entries {
72                                let is_active = active == Some(index);
73                                let label = item.label.localize(cx);
74                                let attrs = sidebar_link(
75                                    cx,
76                                    attributes! {
77                                        // Tapping a link in the mobile sheet closes
78                                        // it; on desktop the navigation is the effect.
79                                        @click=$(|_e: Event| mobile_open.set(false))
80                                    },
81                                );
82                                sidebar_menu_item(
83                                    sidebar_menu_button(
84                                        active: is_active,
85                                        href: item.url(),
86                                        tooltip: Some(label.as_str()),
87                                        attrs: attrs,
88                                        if let Some(data) = item.icon.clone() {
89                                            icon(data: data)
90                                        }
91                                        <span>(label.clone())</span>
92                                    )
93                                    if let Some(badge) = item.badge.clone() {
94                                        sidebar_menu_badge(
95                                            (crate::display::badge(
96                                                cx,
97                                                badge,
98                                                Some(crate::Color::Primary),
99                                                None,
100                                            ))
101                                        )
102                                    }
103                                )
104                            }
105                        )
106                    )
107                )
108            }
109        }
110        .boxed())
111    }
112
113    /// Whether the persisted [`SIDEBAR_COOKIE`] asks for an expanded
114    /// desktop sidebar (default: expanded).
115    ///
116    /// The value only seeds the runtime
117    /// signal's initial `data-state`; after hydration the browser owns the
118    /// state, and `assets/sidebar.js` mirrors changes back to the cookie.
119    fn sidebar_starts_open(cx: &Cx) -> bool {
120        request_cookie(cx, SIDEBAR_COOKIE).as_deref() != Some("collapsed")
121    }
122
123    /// Renders the shell around `slot`, its top bar showing `trail` and its sidebar marking the
124    /// entry `nav_path` is under.
125    async fn render_shell<'a>(
126        cx: &'a Cx,
127        nav_items: Vec<NavigationItem>,
128        trail: Vec<breadcrumbs::Crumb>,
129        nav_path: String,
130        current_path: String,
131        slot: Child<'a>,
132    ) -> Result<BoxView<'a>> {
133        // A hoisting body: the sidebar signals are declared while this view
134        // resolves, and a page re-run resumes them from the client.
135        Ok(async_page(async move {
136            Self::render_shell_body(cx, &nav_items, trail, &nav_path, &current_path, slot).await
137        }))
138    }
139
140    async fn render_shell_body<'a>(
141        cx: &'a Cx,
142        nav_items: &[NavigationItem],
143        trail: Vec<breadcrumbs::Crumb>,
144        nav_path: &str,
145        current_path: &str,
146        slot: Child<'a>,
147    ) -> Result<BoxView<'a>> {
148        use tablo_ui::{
149            SeparatorOrientation, SidebarCollapsible, separator, sidebar, sidebar_content,
150            sidebar_footer, sidebar_header, sidebar_inset, sidebar_provider, sidebar_trigger,
151        };
152
153        let sidebar_open = signal(cx, || Self::sidebar_starts_open(cx));
154        let mobile_open = signal(cx, || false);
155        let header_title = Self::brand_name(cx);
156        let variant = current(cx)
157            .and_then(|panel| panel.brand.as_ref())
158            .map_or_else(
159                || Theme::default().sidebar(),
160                |brand| brand.sidebar_frame(cx),
161            )
162            .variant();
163        // One navigation tree: the upstream sidebar renders its children once
164        // and shares them between the desktop panel and the mobile sheet.
165        // The query the browser sent: an entry that names parameters the request carries wins
166        // over one that names none, at the same path.
167        let current_query = topcoat::router::request::original_uri(cx)
168            .query()
169            .unwrap_or_default();
170        let navigation =
171            Self::sidebar_navigation(cx, nav_items, nav_path, current_query, mobile_open.clone())
172                .await?;
173        let sidebar_brand = Self::render_brand(cx).await?;
174        let home = current(cx)
175            .filter(|panel| panel.area_at(current_path).is_some())
176            .map(|panel| panel.realm.prefix.clone());
177        let back = home.map_or_else(|| ().boxed(), |home| area::back_link(cx, &home));
178        let crumbs = breadcrumbs::render(cx, trail);
179        let banners: Vec<BoxView<'_>> = current(cx)
180            .map(|panel| panel.banners.iter().map(|banner| banner(cx)).collect())
181            .unwrap_or_default();
182        // The user and tenant menus, present only with a session (ADR-0013). `ensure_token` runs
183        // before any streaming starts so their forms, and the language menu's, always carry a
184        // matching CSRF pair.
185        let (user_menu, tenant_menu): (BoxView<'_>, BoxView<'_>) = match crate::auth::signed(cx) {
186            Some(signed) => {
187                let csrf = crate::csrf::ensure_token(cx);
188                let items: Vec<NavigationItem> = user_menu::account_items(cx)
189                    .into_iter()
190                    .chain(
191                        current(cx)
192                            .map(|panel| panel.user_menu.clone())
193                            .unwrap_or_default(),
194                    )
195                    .collect();
196                (
197                    Self::user_menu(
198                        cx,
199                        signed.user.as_ref(),
200                        &items,
201                        crate::auth::logout_url(cx),
202                        &csrf,
203                    ),
204                    Self::tenant_menu(cx, signed.user.tenants(), &csrf),
205                )
206            }
207            // Without a session the footer still offers the theme, and the language where the
208            // panel has one to pick: only that menu's forms need a token here.
209            None => {
210                let csrf = if crate::i18n::offered(cx).len() > 1 {
211                    crate::csrf::ensure_token(cx)
212                } else {
213                    String::new()
214                };
215                (Self::theme_menu(cx, &csrf), ().boxed())
216            }
217        };
218        let toaster = Self::toaster(cx).await?;
219
220        Ok(view! {
221            // The first stop of the keyboard: past the sidebar and the top bar to the page.
222            <a
223                href=(format!("#{MAIN_CONTENT}"))
224                class="sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-50 focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:text-foreground focus:shadow-md focus:ring-2 focus:ring-ring"
225                data-skip-link=""
226            >
227                (crate::t!(cx, "tablo-shell-skip-to-content"))
228            </a>
229            sidebar_provider(
230                // A panel's sidebar is wider than the primitive's 16rem default.
231                attrs: attributes! { style="--sidebar-width:18rem" },
232                // No `sidebar_rail`: the header's `sidebar_trigger` is the one toggle.
233                sidebar(
234                    open: $(sidebar_open.get()),
235                    mobile_open: $(mobile_open.get()),
236                    collapsible: SidebarCollapsible::Icon,
237                    variant: variant,
238                    sheet_attrs: attributes! {
239                        id="mobile-sidebar-sheet"
240                        aria-label=(crate::t!(cx, "tablo-shell-navigation"))
241                        @keydown=$(|e: Event| {
242                            if e.key == "Escape" {
243                                mobile_open.set(false);
244                            }
245                        })
246                        @click=$(|e: Event| {
247                            if e.target.id == "mobile-sidebar-sheet" {
248                                mobile_open.set(false);
249                            }
250                        })
251                    },
252                    sidebar_header(
253                        // Collapsed to icons, the rail leaves the brand only its mark: centred,
254                        // it lines up with the menu icons below.
255                        <div
256                            class="flex items-center gap-2 px-2 md:group-data-[collapsible=icon]/sidebar:justify-center md:group-data-[collapsible=icon]/sidebar:px-0"
257                        >
258                            (sidebar_brand)
259                            // Below `md` the sheet covers the inset header,
260                            // so the sheet's own header carries the close
261                            // control (upstream `examples/ui`); the mobile
262                            // trigger in the inset header is behind the veil.
263                            tablo_ui::button(
264                                variant: tablo_ui::ButtonVariant::Ghost,
265                                size: tablo_ui::ButtonSize::Icon,
266                                attrs: attributes! {
267                                    type="button"
268                                    class="md:hidden ml-auto"
269                                    aria-label=(crate::t!(cx, "tablo-shell-close-sidebar"))
270                                    @click=$(|_e: Event| mobile_open.set(false))
271                                },
272                                icon(data: tablo_ui::icons::X)
273                            )
274                        </div>
275                    )
276                    sidebar_content(
277                        // The icon rail is too narrow for a scrollbar: it still scrolls, without
278                        // one.
279                        attrs: attributes! {
280                            class="md:group-data-[collapsible=icon]/sidebar:[scrollbar-width:none]"
281                        },
282                        (tenant_menu)
283                        (back)
284                        (navigation)
285                    )
286                    sidebar_footer((user_menu))
287                )
288                sidebar_inset(
289                    sidebar_header(
290                        // The desktop trigger collapses the rail; below md the
291                        // mobile trigger opens the sheet instead (shadcn
292                        // SidebarTrigger pair, upstream `examples/ui`).
293                        sidebar_trigger(
294                            open: $(sidebar_open.get()),
295                            attrs: attributes! {
296                                class="max-md:hidden"
297                                aria-controls="mobile-sidebar-sheet"
298                                @click=$(|_e: Event| sidebar_open.toggle())
299                            }
300                        )
301                        sidebar_trigger(
302                            open: $(mobile_open.get()),
303                            attrs: attributes! {
304                                class="md:hidden"
305                                aria-controls="mobile-sidebar-sheet"
306                                @click=$(|_e: Event| mobile_open.toggle())
307                            }
308                        )
309                        // The sidebar carries the brand on desktop; below md it hides in
310                        // the sheet, so the topbar names the panel there.
311                        <div
312                            class="min-w-0 truncate font-semibold text-foreground md:hidden"
313                        >
314                            (header_title)
315                        </div>
316                        // The separator stays a direct child of the topbar,
317                        // where `sidebar_inset` sizes a vertical rule.
318                        separator(
319                            orientation: SeparatorOrientation::Vertical,
320                            attrs: attributes! { class="max-sm:hidden" }
321                        )
322                        (crumbs)
323                        (super::search::topbar_end(cx))
324                    )
325                    // `sidebar_inset` is the document's one `<main>`; a second
326                    // nested landmark is invalid and confuses landmark
327                    // navigation (upstream `examples/ui` uses a plain div).
328                    // The page container (`tablo_ui::page`) owns the width
329                    // and the padding.
330                    (super::impersonation::banner(cx))
331                    for banner in banners {
332                        (banner)
333                    }
334                    // `tabindex` lets the skip link move focus here, not only scroll.
335                    <div
336                        id=(MAIN_CONTENT)
337                        tabindex="-1"
338                        class="flex flex-1 flex-col outline-none"
339                    >
340                        (slot)
341                    </div>
342                )
343                (toaster)
344            )
345            // Scripts are owned by the document (layout_shell).
346        }
347        .boxed())
348    }
349
350    /// The panel shell around a page, as a complete HTML document: the layout
351    /// every panel registers at its prefix unless [`Panel::layout`] replaces
352    /// it, and what a replacement calls to keep the shell around its own
353    /// markup.
354    ///
355    /// The stylesheet and font are supplied to the Panel builder with
356    /// [`Self::shell_assets`]. A Panel without those values remains renderable
357    /// for tests and custom document owners, but does not pretend that a CSS
358    /// bundle exists. Errors from the page slot propagate unchanged when the
359    /// document view is resolved.
360    pub fn layout_shell<'a>(cx: &'a Cx, slot: Slot<'a>) -> BoxView<'a> {
361        Box::pin(ThenView::new(Self::render_layout_shell(cx, slot)))
362    }
363
364    async fn render_layout_shell<'a>(cx: &'a Cx, slot: Slot<'a>) -> Result<BoxView<'a>> {
365        // A page a creatable choice's dialog frames shows only itself and its toasts.
366        if super::url::picking(cx) {
367            let body = async_page(async move {
368                Ok(view! {
369                    // `main` paints the frame; the block inside it is what the frame fits.
370                    <main class="min-h-dvh bg-card text-card-foreground">
371                        <div class="px-6 pt-6 pb-6" data-pick-page="">(slot)</div>
372                    </main>
373                    (Self::toaster(cx).await?)
374                }
375                .boxed())
376            });
377            let panel = current(cx).map(|panel| &**panel);
378            return Self::render_document(cx, panel, Self::brand_name(cx), body).await;
379        }
380        // The browser's URL, not a rewrite's: the error page names where the visitor is.
381        let path = topcoat::router::request::original_uri(cx)
382            .path()
383            .to_string();
384        // The sidebar of the area the path is under, else the panel's, or a single Home entry
385        // outside any panel.
386        let panel = current(cx);
387        let entries: Vec<_> = panel
388            .map(|panel| area::listed(cx, panel, panel.area_at(&path)))
389            .unwrap_or_default();
390        // One count per badge, run together rather than one after another.
391        let badges = futures_util::future::join_all(entries.iter().map(|entry| async {
392            match &entry.badge {
393                Some(badge) => Some(badge(cx).await),
394                None => None,
395            }
396        }))
397        .await;
398        crate::notification::prefetch_bell(cx).await;
399        let mut nav_items: Vec<NavigationItem> = entries
400            .iter()
401            .zip(badges)
402            .map(|(entry, badge)| {
403                let mut item = area::item(cx, entry);
404                if let Some(badge) = badge {
405                    item.badge = badge;
406                }
407                item
408            })
409            .collect();
410        if nav_items.is_empty() {
411            nav_items.push(NavigationItem::at(
412                crate::t!(cx, "tablo-shell-home"),
413                super::gate::panel_prefix(cx),
414            ));
415        }
416        let (trail, nav_path) = breadcrumbs::for_request(cx, &nav_items, &path).await;
417        let title = breadcrumbs::title(cx, &trail, &Self::brand_name(cx));
418        let shell = Self::render_shell(cx, nav_items, trail, nav_path, path, slot).await?;
419        Self::render_document(cx, current(cx).map(|panel| &**panel), title, shell).await
420    }
421}
422
423mod area;
424mod brand;
425mod breadcrumbs;
426mod document;
427mod environment;
428mod language;
429mod scheme;
430pub(super) mod sidebar;
431mod toaster;
432mod user_menu;
433
434pub(in crate::panel) use area::area_entries;
435pub use brand::{Brand, Look, Radius, SidebarFrame, Theme};
436pub use environment::Environment;
437pub(crate) use language::{LANGUAGE_SEGMENT, language_post};
438use scheme::{SIDEBAR_COOKIE, Scheme};
439
440use crate::cookie::request_cookie;