Skip to main content

rustango_cms/
userbar.rs

1//! On-site editor userbar.
2//!
3//! Floating overlay that appears on the bottom-right of every
4//! PUBLIC page when the visitor is logged into the CMS admin. Gives
5//! editors one-click access to: Edit this page, View revisions,
6//! Open admin, and plugin-contributed entries.
7//!
8//! ## Wiring
9//!
10//! Hosts call this from their public templates:
11//!
12//! ```tera
13//! {# bottom of every public page #}
14//! {{ rcms_userbar() | safe }}
15//! ```
16//!
17//! Visibility check: the userbar renders only when the request
18//! carries a CMS admin session cookie. Detection runs client-side
19//! (the markup is always emitted; CSS hides it if the cookie is
20//! absent) so server-side per-tenant caching of public pages stays
21//! correct.
22
23use std::collections::HashMap;
24
25/// Register the `rcms_userbar(...)` Tera function. Call alongside
26/// the other admin Tera helpers in the host's public-router setup.
27pub fn register_tera_function(tera: &mut tera::Tera) {
28    tera.register_function("rcms_userbar", rcms_userbar);
29}
30
31fn rcms_userbar(args: &HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
32    // The function takes optional `page_id` so hosts can hint which
33    // page the userbar should target. When absent, the userbar
34    // renders generic links (admin / no edit).
35    let page_id = args.get("page_id").and_then(tera::Value::as_i64);
36    // Admin prefix is a URL path supplied at registration time, not
37    // user content — don't HTML-escape it (Tera's escape_html
38    // encodes forward slashes which breaks the link href).
39    let admin_prefix = args
40        .get("admin_prefix")
41        .and_then(tera::Value::as_str)
42        .unwrap_or("/cms-admin")
43        .to_owned();
44
45    let mut plugin_items_html = String::new();
46    for item in crate::hooks::userbar_items() {
47        // The href template is plugin-supplied (compile-time string).
48        // Don't escape it for HTML — same reason as admin_prefix.
49        let href = match page_id {
50            Some(id) => item.href_template.replace("{page_id}", &id.to_string()),
51            None => item.href_template.replace("{page_id}", ""),
52        };
53        let icon = tera::escape_html(item.icon);
54        let label = tera::escape_html(item.label);
55        plugin_items_html.push_str("<a class=\"rcms-userbar-item\" href=\"");
56        plugin_items_html.push_str(&href);
57        plugin_items_html.push_str(
58            "\" target=\"_blank\" rel=\"noopener\"><span class=\"material-symbols-rounded\">",
59        );
60        plugin_items_html.push_str(&icon);
61        plugin_items_html.push_str("</span> ");
62        plugin_items_html.push_str(&label);
63        plugin_items_html.push_str("</a>");
64    }
65
66    let mut edit_html = String::new();
67    if let Some(id) = page_id {
68        edit_html.push_str("<a class=\"rcms-userbar-item\" href=\"");
69        edit_html.push_str(&admin_prefix);
70        edit_html.push_str("/pages/");
71        edit_html.push_str(&id.to_string());
72        edit_html.push_str("/edit\" target=\"_blank\" rel=\"noopener\"><span class=\"material-symbols-rounded\">edit</span> Edit page</a>");
73        edit_html.push_str("<a class=\"rcms-userbar-item\" href=\"");
74        edit_html.push_str(&admin_prefix);
75        edit_html.push_str("/pages/");
76        edit_html.push_str(&id.to_string());
77        edit_html.push_str("/history\" target=\"_blank\" rel=\"noopener\"><span class=\"material-symbols-rounded\">history</span> History</a>");
78    }
79
80    // Render: a fixed-position overlay with a toggle button + a
81    // panel of items. JS-side cookie check hides the whole thing
82    // when there's no admin session.
83    let html = format!(
84        r#"<aside class="rcms-userbar" data-rcms-userbar data-rcms-cookie-name="cms_admin_session" aria-label="Editor toolbar">
85    <button type="button" class="rcms-userbar-toggle" data-rcms-userbar-toggle aria-expanded="false">
86        <span class="material-symbols-rounded">edit_note</span>
87    </button>
88    <div class="rcms-userbar-panel" data-rcms-userbar-panel hidden>
89        {edit_html}{plugin_items_html}<a class="rcms-userbar-item" href="{prefix}" target="_blank" rel="noopener"><span class="material-symbols-rounded">dashboard</span> Open admin</a>
90    </div>
91</aside>
92<style>
93/* #314 — defensive reset. Outbound is already safe (every rule below is
94   scoped to .rcms-userbar*), but the userbar lives in the HOST page's DOM,
95   so a host theme's global element rules (a, button, aside, * , body
96   inheritance) could otherwise leak font / text-transform / box-sizing /
97   padding / margin into it. Re-assert safe values on every userbar element
98   so the bar can't be broken by the host theme. (Full two-way isolation
99   via shadow DOM remains a future option.) */
100.rcms-userbar, .rcms-userbar * {{ box-sizing: border-box; }}
101.rcms-userbar * {{
102    margin: 0;
103    padding: 0;
104    font-family: inherit;
105    line-height: normal;
106    letter-spacing: normal;
107    text-transform: none;
108    text-align: left;
109    white-space: normal;
110}}
111.rcms-userbar {{
112    position: fixed; right: 16px; bottom: 16px;
113    margin: 0;
114    z-index: 2147483000;
115    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
116    display: none;
117}}
118.rcms-userbar.is-visible {{ display: block; }}
119.rcms-userbar-toggle {{
120    width: 44px; height: 44px;
121    border-radius: 50%;
122    border: 0;
123    background: #6750a4;
124    color: #fff;
125    cursor: pointer;
126    box-shadow: 0 4px 12px rgba(0,0,0,0.18);
127    display: flex; align-items: center; justify-content: center;
128}}
129.rcms-userbar-panel {{
130    position: absolute; right: 0; bottom: 56px;
131    min-width: 200px;
132    background: #fff;
133    color: #1c1b1f;
134    border-radius: 12px;
135    box-shadow: 0 8px 24px rgba(0,0,0,0.18);
136    overflow: hidden;
137    display: none;
138}}
139.rcms-userbar-panel[data-open] {{ display: block; }}
140.rcms-userbar-item {{
141    display: flex; align-items: center; gap: 8px;
142    padding: 10px 14px;
143    color: inherit; text-decoration: none;
144    font-size: 14px;
145}}
146.rcms-userbar-item:hover {{ background: #f3f0f6; }}
147.rcms-userbar-item .material-symbols-rounded {{ font-size: 18px; }}
148@media (prefers-color-scheme: dark) {{
149    .rcms-userbar-panel {{ background: #1c1b1f; color: #e6e1e5; }}
150    .rcms-userbar-item:hover {{ background: #2a292e; }}
151}}
152</style>
153<script>
154(function () {{
155    var bar = document.querySelector("[data-rcms-userbar]");
156    if (!bar) return;
157    // Show the bar only if the admin session cookie is present.
158    var cookieName = bar.getAttribute("data-rcms-cookie-name") || "cms_admin_session";
159    var hasSession = document.cookie.split(";").some(function (c) {{
160        return c.trim().split("=")[0] === cookieName;
161    }});
162    // Also accept the framework's session cookie names.
163    if (!hasSession) {{
164        hasSession = ["rustango_tenant_session", "rustango_operator_session", "sessionid"].some(function (name) {{
165            return document.cookie.split(";").some(function (c) {{
166                return c.trim().split("=")[0] === name;
167            }});
168        }});
169    }}
170    if (hasSession) bar.classList.add("is-visible");
171    var toggle = bar.querySelector("[data-rcms-userbar-toggle]");
172    var panel = bar.querySelector("[data-rcms-userbar-panel]");
173    if (toggle && panel) {{
174        toggle.addEventListener("click", function () {{
175            var open = panel.hasAttribute("data-open");
176            if (open) {{ panel.removeAttribute("data-open"); }}
177            else {{ panel.setAttribute("data-open", ""); }}
178            toggle.setAttribute("aria-expanded", String(!open));
179        }});
180    }}
181}})();
182</script>"#,
183        edit_html = edit_html,
184        plugin_items_html = plugin_items_html,
185        prefix = admin_prefix,
186    );
187    Ok(tera::Value::String(html))
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn renders_open_admin_link_even_without_page_id() {
196        let mut tera = tera::Tera::default();
197        register_tera_function(&mut tera);
198        let args: HashMap<String, tera::Value> = HashMap::new();
199        let v = rcms_userbar(&args).unwrap();
200        let html = v.as_str().unwrap();
201        assert!(html.contains("Open admin"));
202        assert!(!html.contains("Edit page"));
203    }
204
205    #[test]
206    fn renders_edit_link_with_page_id() {
207        let mut args: HashMap<String, tera::Value> = HashMap::new();
208        args.insert("page_id".to_owned(), tera::Value::from(42_i64));
209        let v = rcms_userbar(&args).unwrap();
210        let html = v.as_str().unwrap();
211        assert!(html.contains("/cms-admin/pages/42/edit"));
212        assert!(html.contains("/cms-admin/pages/42/history"));
213    }
214
215    #[test]
216    fn respects_admin_prefix() {
217        let mut args: HashMap<String, tera::Value> = HashMap::new();
218        args.insert("page_id".to_owned(), tera::Value::from(7_i64));
219        args.insert("admin_prefix".to_owned(), tera::Value::from("/admin"));
220        let v = rcms_userbar(&args).unwrap();
221        let html = v.as_str().unwrap();
222        assert!(html.contains("/admin/pages/7/edit"));
223    }
224}