Skip to main content

rustango_cms/
template_inspector.rs

1//! Template inspector: shows a signed-in admin which templates rendered a
2//! public page, and where each one comes from.
3//!
4//! An admin turns it on under **Preferences → Show templates on the site**
5//! (stored on their user, `data.show_templates`). While it is on and they
6//! browse the site:
7//!
8//! - every content block's HTML is wrapped in comment markers naming its
9//!   template (`<!--rcms-template:blocks/hero.html-->…`), which change
10//!   nothing about the layout;
11//! - a small panel lists the page template, the templates it extends, and
12//!   each block template, with its source — this site's own copy, the
13//!   project's `templates/` folder, or built into Rustango-CMS — and a link
14//!   to the **Templates** editor, opened from the admin bar's **Templates**
15//!   button ([`crate::admin_bar`]); hovering a block outlines it and names
16//!   its template.
17//!
18//! Visitors never get any of it: it needs an admin session, the page is
19//! sent `no-store`, and the page cache already skips signed-in requests.
20//! The flag travels with the request's task ([`scope`]), so the render
21//! code needs no extra parameter.
22
23use std::future::Future;
24
25use rustango::tenancy::auth::User;
26
27rustango::__private_runtime::tokio::task_local! {
28    static ACTIVE: bool;
29}
30
31/// The user-data key holding the preference.
32pub const PREFERENCE: &str = "show_templates";
33
34/// Whether this signed-in admin wants templates shown.
35#[must_use]
36pub fn wanted(user: &User) -> bool {
37    user.is_superuser && user.data.get(PREFERENCE).and_then(serde_json::Value::as_bool) == Some(true)
38}
39
40/// Run `fut` (a page render) with the inspector on or off.
41pub async fn scope<F: Future>(on: bool, fut: F) -> F::Output {
42    ACTIVE.scope(on, fut).await
43}
44
45/// Whether the current render is being inspected.
46#[must_use]
47pub fn active() -> bool {
48    ACTIVE.try_with(|on| *on).unwrap_or(false)
49}
50
51/// A block's HTML, marked with the template that rendered it.
52#[must_use]
53pub fn mark(template: &str, html: &str) -> String {
54    format!("<!--rcms-template:{}-->{html}<!--/rcms-template-->", template.replace("--", "-"))
55}
56
57/// `&`, `<`, `>` and `"` escaped; template names stay readable.
58fn escape(text: &str) -> String {
59    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
60}
61
62/// Where a template comes from.
63fn source(tenant_slug: &str, name: &str) -> (&'static str, bool) {
64    let tt = crate::tenant_templates::installed();
65    if tt.as_ref().is_some_and(|t| t.read_override(tenant_slug, name).is_some()) {
66        ("This site's copy", true)
67    } else if tt.as_ref().is_some_and(|t| t.read_global(name).is_some()) {
68        ("Project templates/ folder", true)
69    } else {
70        ("Built into Rustango-CMS", false)
71    }
72}
73
74/// The page with the inspector panel added before `</body>`.
75#[must_use]
76pub fn annotate(html: String, tera: &tera::Tera, page_template: &str, tenant_slug: &str) -> String {
77    // The page template and the chain it extends.
78    let mut layout = vec![page_template.to_owned()];
79    if let Some(t) = tera.templates.get(page_template) {
80        layout.extend(t.parents.iter().cloned());
81    }
82    // Block templates, in page order, once each.
83    let mut blocks: Vec<String> = Vec::new();
84    let mut rest = html.as_str();
85    while let Some(at) = rest.find("<!--rcms-template:") {
86        rest = &rest[at + "<!--rcms-template:".len()..];
87        let name = rest.split("-->").next().unwrap_or_default().to_owned();
88        if !blocks.contains(&name) {
89            blocks.push(name);
90        }
91    }
92    let row = |name: &str| {
93        let (from, editable) = source(tenant_slug, name);
94        let link = if editable {
95            format!(
96                "<a href=\"/cms-admin/templates/edit?name={}\" target=\"_blank\" rel=\"noopener\">Edit</a>",
97                escape(name)
98            )
99        } else {
100            String::new()
101        };
102        format!(
103            "<li><code>{}</code><span>{}</span>{link}</li>",
104            escape(name),
105            escape(from)
106        )
107    };
108    let layout_rows: String = layout.iter().map(|n| row(n)).collect();
109    let block_rows: String = if blocks.is_empty() {
110        "<li><span>No content blocks on this page.</span></li>".to_owned()
111    } else {
112        blocks.iter().map(|n| row(n)).collect()
113    };
114    let panel = format!(
115        "{STYLE}<aside id=\"rcms-tpl-panel\" aria-label=\"Templates on this page\" hidden>\
116         <div id=\"rcms-tpl-body\">\
117         <h2>Page</h2><ul>{layout_rows}</ul>\
118         <h2>Blocks</h2><ul>{block_rows}</ul>\
119         <p>Hover a block on the page to see its template. Only you see this; \
120         turn it off under Preferences in the admin.</p>\
121         </div></aside>{SCRIPT}"
122    );
123    match html.rfind("</body>") {
124        Some(at) => {
125            let mut out = html;
126            out.insert_str(at, &panel);
127            out
128        }
129        None => html + &panel,
130    }
131}
132
133const STYLE: &str = "<style>\
134#rcms-tpl-panel{position:fixed;right:16px;bottom:68px;z-index:2147483646;width:min(420px,calc(100vw - 32px));\
135font:13px/1.45 system-ui,sans-serif;color:#1b1b1f;background:#fff;border:1px solid #d0d3dc;border-radius:12px;\
136box-shadow:0 12px 32px rgb(0 0 0/.18);overflow:hidden}\
137#rcms-tpl-panel[hidden]{display:none}\
138#rcms-tpl-body{padding:4px 12px 10px;max-height:50vh;overflow:auto}\
139#rcms-tpl-panel h2{font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:#6b6c75;margin:10px 0 4px}\
140#rcms-tpl-panel ul{list-style:none;margin:0;padding:0}\
141#rcms-tpl-panel li{display:flex;flex-wrap:wrap;gap:2px 8px;align-items:baseline;padding:4px 0;border-top:1px solid #eef0f4}\
142#rcms-tpl-panel li:first-child{border-top:0}\
143#rcms-tpl-panel code{font:12px ui-monospace,monospace;color:#1b1b1f}\
144#rcms-tpl-panel span{color:#6b6c75;font-size:12px}\
145#rcms-tpl-panel a{margin-left:auto;color:#7c3aed;font-weight:600;text-decoration:none}\
146#rcms-tpl-panel p{margin:8px 0 0;color:#6b6c75;font-size:12px}\
147.rcms-tpl-hover{outline:2px dashed #7c3aed!important;outline-offset:2px}\
148#rcms-tpl-label{position:fixed;z-index:2147483647;pointer-events:none;font:12px ui-monospace,monospace;\
149background:#7c3aed;color:#fff;padding:2px 6px;border-radius:4px}\
150</style>";
151
152const SCRIPT: &str = "<script>(()=>{\
153const panel=document.getElementById('rcms-tpl-panel');\
154const show=(open)=>{panel.hidden=!open;document.querySelectorAll('[data-rcms-templates]').forEach((b)=>b.setAttribute('aria-expanded',String(open)));};\
155document.addEventListener('click',(ev)=>{if(!ev.target.closest('[data-rcms-templates]'))return;\
156show(panel.hidden);try{localStorage.setItem('rcms-tpl-open',panel.hidden?'0':'1');}catch(e){}});\
157document.addEventListener('DOMContentLoaded',()=>{try{show(localStorage.getItem('rcms-tpl-open')==='1');}catch(e){}});\
158const owners=new Map();\
159const walk=document.createTreeWalker(document.body,NodeFilter.SHOW_COMMENT);\
160const open=[];\
161for(let n=walk.nextNode();n;n=walk.nextNode()){\
162const v=n.nodeValue;\
163if(v.startsWith('rcms-template:')){open.push({name:v.slice(14),start:n});}\
164else if(v==='/rcms-template'&&open.length){const m=open.pop();\
165for(let e=m.start.nextSibling;e&&e!==n;e=e.nextSibling){if(e.nodeType===1&&!owners.has(e))owners.set(e,m.name);}}}\
166const label=document.createElement('div');label.id='rcms-tpl-label';label.hidden=true;document.body.appendChild(label);\
167let current=null;\
168document.addEventListener('mouseover',(ev)=>{\
169let el=ev.target;while(el&&!owners.has(el))el=el.parentElement;\
170if(current&&current!==el)current.classList.remove('rcms-tpl-hover');\
171current=el;if(!el){label.hidden=true;return;}\
172el.classList.add('rcms-tpl-hover');label.textContent=owners.get(el);\
173const r=el.getBoundingClientRect();label.style.left=Math.max(4,r.left)+'px';label.style.top=Math.max(4,r.top-22)+'px';label.hidden=false;});\
174})();</script>";
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn blocks_are_marked_and_listed_once_in_page_order() {
182        let html = format!(
183            "<html><body><main>{}{}{}</main></body></html>",
184            mark("blocks/hero.html", "<section>a</section>"),
185            mark("blocks/cards.html", "<section>b</section>"),
186            mark("blocks/hero.html", "<section>c</section>"),
187        );
188        let out = annotate(html, &tera::Tera::default(), "page.html", "demo");
189        let panel = &out[out.find("rcms-tpl-panel").unwrap()..];
190        let hero = panel.find("<code>blocks/hero.html</code>").unwrap();
191        let cards = panel.find("<code>blocks/cards.html</code>").unwrap();
192        assert!(hero < cards, "page order");
193        assert_eq!(panel.matches("<code>blocks/hero.html</code>").count(), 1, "listed once");
194        assert!(panel.contains("<code>page.html</code>"));
195        assert!(out.find("rcms-tpl-panel").unwrap() < out.find("</body>").unwrap(), "before </body>");
196    }
197
198    #[tokio::test]
199    async fn the_flag_lives_only_inside_its_scope() {
200        assert!(!active());
201        assert!(scope(true, async { active() }).await);
202        assert!(!scope(false, async { active() }).await);
203        assert!(!active());
204    }
205}