Skip to main content

tablo_core/panel/shell/
document.rs

1//! The HTML document around a page: head, assets, favicon and theme.
2
3use topcoat::{
4    Result,
5    context::Cx,
6    metadata::{metadata, tag},
7    view::{BoxView, View, ViewExt, view},
8};
9
10use super::{Scheme, ShellAssets, current};
11use crate::panel::{Panel, state::PanelState};
12
13impl Panel {
14    /// Renders a complete HTML document around a page, with the shell settings of the panel the
15    /// request is under. A page outside every prefix belongs to no panel, so it renders without
16    /// them; such a page renders through [`PanelHandle::document`](crate::PanelHandle::document).
17    pub async fn document<'a>(
18        cx: &'a Cx,
19        title: impl Into<String>,
20        body: impl View + 'a,
21    ) -> Result<BoxView<'a>> {
22        Self::render_document(
23            cx,
24            current(cx).map(|panel| &**panel),
25            title.into(),
26            body.boxed(),
27        )
28        .await
29    }
30
31    /// Renders the HTML document with `panel`'s assets, favicon and dark-mode default.
32    pub(crate) async fn render_document<'a>(
33        cx: &'a Cx,
34        panel: Option<&PanelState>,
35        title: String,
36        body: BoxView<'a>,
37    ) -> Result<BoxView<'a>> {
38        let head: BoxView<'_> = match panel.and_then(|panel| panel.shell_assets) {
39            Some(ShellAssets { stylesheet, font }) => view! {
40                topcoat::dev::script()
41                topcoat::runtime::script()
42                topcoat::font::link(font: font)
43                <link rel="stylesheet" href=(stylesheet)>
44                // Modules, so each script's top-level names stay its own: as classic scripts they
45                // share one global scope, where a later script's `partsOf` replaces an earlier one's.
46                // A module is deferred like these were.
47                for script in tablo_ui::SHELL_SCRIPTS {
48                    <script src=(script) type="module"></script>
49                }
50                // Where `rich_text.js` imports the editor from, once a page holds a rich text
51                // control: no page loads it before.
52                <meta name="tablo-tiptap" content=(tablo_ui::TIPTAP_JS)>
53            }
54            .boxed(),
55            None => view! { topcoat::dev::script() }.boxed(),
56        };
57        // Runtime navigation keeps the socket, and the socket answers as the panel of the page
58        // that opened it. A script this document has not run makes the browser load the page
59        // instead, so a script of the request's panel alone keeps a socket on its panel's pages.
60        // It says nothing and does nothing: only its text counts. Asked of the request and not of
61        // `panel`, because a page outside the prefix opens a socket of no panel, and has a mark
62        // of its own so that leaving a panel loads the page too.
63        let panel_mark = match current(cx) {
64            Some(panel) => format!("// {}", panel.realm.prefix),
65            None => "// no panel".to_owned(),
66        };
67        // The server renders the stored choice on every page: runtime navigation copies
68        // `<html>`'s attributes from the next page and runs no script.
69        let html_class =
70            Scheme::renders_dark(cx, panel.is_some_and(|panel| panel.dark_mode)).then_some("dark");
71        let favicon = panel
72            .and_then(|panel| panel.brand.as_ref())
73            .and_then(|brand| brand.favicon.clone());
74        // Runtime navigation copies `lang` and `dir` with the class, so a page reads in its own
75        // locale.
76        let (_, locale) = crate::i18n::catalog_and_locale(cx);
77        let (lang, dir) = (locale.id().clone(), locale.id().direction());
78        let page = metadata(cx).await?;
79        let brand = panel.and_then(|panel| panel.brand.as_ref());
80        let theme = brand
81            .map(|brand| brand.current_theme(cx))
82            .unwrap_or_default();
83        // The page sets in the font the shell links, whichever the app picked, then lays the
84        // brand's colors over the theme: after the stylesheet, so both win.
85        let font = panel
86            .and_then(|panel| panel.shell_assets)
87            .map(|ShellAssets { font, .. }| font_style(font.family()));
88        // A theme with faces of its own declares them; the browser fetches one only once a rule
89        // sets text in it.
90        let faces = topcoat::asset::try_asset_config(cx)
91            .filter(|_| panel.is_some_and(|panel| panel.shell_assets.is_some()))
92            .map(|assets| face_style(theme, |asset| assets.resolve(cx, asset)));
93        let style: String = faces
94            .into_iter()
95            .chain(font)
96            .chain(brand.and_then(super::Brand::style))
97            .collect();
98        let style = (!style.is_empty()).then_some(style);
99        let environment = panel.and_then(|panel| panel.environment.as_ref());
100        let title = match environment {
101            Some(environment) => format!("[{}] {title}", environment.name(cx)),
102            None => title,
103        };
104        let ribbon = environment.map(|environment| environment.ribbon(cx));
105        Ok(view! {
106            <!DOCTYPE html>
107            <html
108                lang=(lang)
109                dir=(dir)
110                class=(html_class)
111                data-tablo-theme=(theme.attribute())
112            >
113                <head>
114                    <meta charset="utf-8">
115                    // Without it a phone lays the page out 980px wide and zooms it out.
116                    <meta name="viewport" content="width=device-width, initial-scale=1">
117                    tag::robots(metadata: page)
118                    <title>(title)</title>
119                    if let Some(favicon) = favicon {
120                        <link rel="icon" href=(favicon)>
121                    }
122                    (head)
123                    if let Some(style) = style {
124                        <style>(style)</style>
125                    }
126                    <script>(panel_mark)</script>
127                </head>
128                <body>
129                    (body)
130                    if let Some(ribbon) = ribbon {
131                        (ribbon)
132                    }
133                </body>
134            </html>
135        }
136        .boxed())
137    }
138}
139
140/// The `@font-face` rules of `theme`'s faces, each file's URL as `url` resolves it; empty for a
141/// theme in the app's own font.
142fn face_style(theme: super::Theme, url: impl Fn(topcoat::asset::Asset) -> String) -> String {
143    theme
144        .faces()
145        .iter()
146        .map(|(family, file, weights)| {
147            let url = css_string(&url(*file));
148            format!(
149                "@font-face{{font-family:\"{family}\";src:url(\"{url}\") format(\"woff2\");\
150                 font-weight:{weights};font-style:normal;font-display:swap}}"
151            )
152        })
153        .collect()
154}
155
156/// The style sheet that sets the page in `family`, ahead of the theme's fallbacks.
157fn font_style(family: &str) -> String {
158    let family = css_string(family);
159    format!(":root{{--tablo-font:\"{family}\"}}")
160}
161
162/// `text` escaped to sit between double quotes in a `<style>` element: a quote, a backslash or a
163/// newline would end the CSS string early, and a `<` could end the element.
164fn css_string(text: &str) -> String {
165    let mut escaped = String::with_capacity(text.len());
166    for c in text.chars() {
167        match c {
168            '\\' => escaped.push_str("\\\\"),
169            '"' => escaped.push_str("\\\""),
170            '\n' => escaped.push_str("\\a "),
171            '\r' => escaped.push_str("\\d "),
172            '<' => escaped.push_str("\\3c "),
173            c => escaped.push(c),
174        }
175    }
176    escaped
177}
178
179#[cfg(test)]
180mod tests;