Skip to main content

rustango_cms/
hooks.rs

1//! Runtime extension-point registry.
2//!
3//! Hooks are typed: each hook has a precise signature, and registration is
4//! compile-time via `inventory::submit!` rather than runtime
5//! `HashMap<&str, Box<dyn Fn>>`. Plugins crate-side `submit!` a
6//! handler; CMS-side call sites collect every registered handler
7//! and fan out.
8//!
9//! ## Available hooks
10//!
11//! The v1 surface is intentionally narrow — the 6 hooks below cover
12//! the common plugin use cases. More can land as
13//! customers ask.
14//!
15//! | Hook | When | Signature |
16//! |---|---|---|
17//! | [`AfterPublishPage`]    | After `page_edit_submit` saves a Published row | `fn(&Page)` |
18//! | [`BeforeServePage`]     | Just before the public renderer fires | `fn(&Page, &HeaderMap) -> Option<Response>` |
19//! | [`AdminMenuItem`]       | Registers a sidebar entry | static struct |
20//! | [`PageActionMenuItem`]  | Registers a kebab-menu entry on the page editor | static struct |
21//! | [`PageListingButton`]   | Registers a per-row action on the page tree | static struct |
22//! | [`AdminSearchArea`]     | Registers an extra source for global search | static fn returning hits |
23//!
24//! ## Registering
25//!
26//! ```ignore
27//! use rustango_cms::hooks::{register_after_publish_page, AfterPublishPage};
28//! use rustango_cms::Page;
29//!
30//! fn warm_cdn_cache(page: &Page) {
31//!     tracing::info!("warming CDN for {}", page.url_path);
32//! }
33//!
34//! register_after_publish_page!(warm_cdn_cache);
35//! ```
36//!
37//! ## Failure semantics
38//!
39//! Hooks fire in registration order. A panicking hook does NOT abort
40//! the request — the call site catches the panic, logs it, and
41//! continues to the next handler. The only exception is
42//! [`BeforeServePage`], which can return `Some(Response)` to
43//! short-circuit the renderer.
44
45use axum::http::HeaderMap;
46use axum::response::Response;
47
48use crate::page::Page;
49
50// ---------------------------------------------------------------
51// AfterPublishPage
52// ---------------------------------------------------------------
53
54/// Fired after a page transitions to (or stays in) Published
55/// following `page_edit_submit`. Use for fire-and-forget side
56/// effects: warm a CDN, ping a webhook, push to a feed indexer.
57#[derive(Debug, Clone, Copy)]
58pub struct AfterPublishPage(pub fn(&Page));
59
60inventory::collect!(AfterPublishPage);
61
62/// Register an [`AfterPublishPage`] handler at compile time.
63///
64/// ```ignore
65/// fn my_handler(page: &Page) { /* ... */ }
66/// register_after_publish_page!(my_handler);
67/// ```
68#[macro_export]
69macro_rules! register_after_publish_page {
70    ($f:expr) => {
71        ::rustango_cms::inventory::submit! {
72            $crate::hooks::AfterPublishPage($f)
73        }
74    };
75}
76
77/// Fan out: call every registered `AfterPublishPage` handler in
78/// registration order. Panics are caught + logged so one buggy
79/// plugin can't break the publish path.
80pub fn fire_after_publish_page(page: &Page) {
81    for hook in inventory::iter::<AfterPublishPage>() {
82        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (hook.0)(page)));
83        if let Err(e) = result {
84            tracing::warn!(
85                target: "rustango_cms::hooks",
86                hook = "after_publish_page",
87                error = ?e,
88                "hook panicked (continuing)"
89            );
90        }
91    }
92}
93
94// ---------------------------------------------------------------
95// BeforeServePage
96// ---------------------------------------------------------------
97
98/// Fired in the public router just after `resolve_path` returns a
99/// page and *before* the renderer fires. Return `Some(Response)` to
100/// short-circuit (redirect, 403, custom render, etc.); `None` to
101/// let the normal renderer handle it.
102///
103/// Multiple hooks register in order; the first one to return
104/// `Some(Response)` wins.
105#[derive(Debug, Clone, Copy)]
106pub struct BeforeServePage(pub fn(&Page, &HeaderMap) -> Option<Response>);
107
108inventory::collect!(BeforeServePage);
109
110#[macro_export]
111macro_rules! register_before_serve_page {
112    ($f:expr) => {
113        ::rustango_cms::inventory::submit! {
114            $crate::hooks::BeforeServePage($f)
115        }
116    };
117}
118
119/// Fan out: returns the first short-circuit response or `None`.
120pub fn fire_before_serve_page(page: &Page, headers: &HeaderMap) -> Option<Response> {
121    for hook in inventory::iter::<BeforeServePage>() {
122        let result =
123            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (hook.0)(page, headers)));
124        match result {
125            Ok(Some(resp)) => return Some(resp),
126            Ok(None) => continue,
127            Err(e) => {
128                tracing::warn!(
129                    target: "rustango_cms::hooks",
130                    hook = "before_serve_page",
131                    error = ?e,
132                    "hook panicked (continuing)"
133                );
134            }
135        }
136    }
137    None
138}
139
140// ---------------------------------------------------------------
141// AdminMenuItem
142// ---------------------------------------------------------------
143
144/// One sidebar entry contributed by a plugin. Renders below the
145/// built-in Settings section. The icon name is a Material-symbols
146/// glyph (e.g. `"analytics"`, `"chat"`, `"science"`).
147#[derive(Debug, Clone, Copy)]
148pub struct AdminMenuItem {
149    /// Stable identifier (used for dedup + active-state matching).
150    pub key: &'static str,
151    /// Display label.
152    pub label: &'static str,
153    /// Material-symbols icon name.
154    pub icon: &'static str,
155    /// Absolute URL or admin-relative URL the entry links to.
156    pub href: &'static str,
157}
158
159inventory::collect!(AdminMenuItem);
160
161#[macro_export]
162macro_rules! register_admin_menu_item {
163    ($key:expr, $label:expr, $icon:expr, $href:expr) => {
164        ::rustango_cms::inventory::submit! {
165            $crate::hooks::AdminMenuItem {
166                key: $key,
167                label: $label,
168                icon: $icon,
169                href: $href,
170            }
171        }
172    };
173}
174
175/// Collect every registered AdminMenuItem for the sidebar
176/// templates. Stable ordering by `key`.
177#[must_use]
178pub fn admin_menu_items() -> Vec<&'static AdminMenuItem> {
179    let mut items: Vec<&'static AdminMenuItem> = inventory::iter::<AdminMenuItem>().collect();
180    items.sort_by_key(|i| i.key);
181    items
182}
183
184// ---------------------------------------------------------------
185// HelpMenuItem (#127)
186// ---------------------------------------------------------------
187
188/// One sidebar entry rendered under a dedicated "Help" section.
189/// Same field shape as [`AdminMenuItem`] — kept distinct so plugins
190/// can contribute docs / shortcuts links without polluting the
191/// generic plugin section.
192#[derive(Debug, Clone, Copy)]
193pub struct HelpMenuItem {
194    pub key: &'static str,
195    pub label: &'static str,
196    pub icon: &'static str,
197    pub href: &'static str,
198}
199
200inventory::collect!(HelpMenuItem);
201
202#[macro_export]
203macro_rules! register_help_menu_item {
204    ($key:expr, $label:expr, $icon:expr, $href:expr) => {
205        ::rustango_cms::inventory::submit! {
206            $crate::hooks::HelpMenuItem {
207                key: $key,
208                label: $label,
209                icon: $icon,
210                href: $href,
211            }
212        }
213    };
214}
215
216#[must_use]
217pub fn help_menu_items() -> Vec<&'static HelpMenuItem> {
218    let mut items: Vec<&'static HelpMenuItem> = inventory::iter::<HelpMenuItem>().collect();
219    items.sort_by_key(|i| i.key);
220    items
221}
222
223// ---------------------------------------------------------------
224// AccountSettingsPanel (#128)
225// ---------------------------------------------------------------
226
227/// One panel contributed to the per-user `/cms-admin/me` page.
228/// Pre-rendered HTML the template emits via `| safe` — hosts wire
229/// their own POST endpoints (the registry stays read-only).
230#[derive(Debug, Clone, Copy)]
231pub struct AccountSettingsPanel {
232    pub key: &'static str,
233    pub label: &'static str,
234    pub icon: &'static str,
235    pub html: &'static str,
236}
237
238inventory::collect!(AccountSettingsPanel);
239
240#[macro_export]
241macro_rules! register_account_settings_panel {
242    ($key:expr, $label:expr, $icon:expr, $html:expr) => {
243        ::rustango_cms::inventory::submit! {
244            $crate::hooks::AccountSettingsPanel {
245                key: $key,
246                label: $label,
247                icon: $icon,
248                html: $html,
249            }
250        }
251    };
252}
253
254// ---------------------------------------------------------------
255// UserbarItem (#148)
256// ---------------------------------------------------------------
257
258/// Plugin-contributed entry in the on-site editor userbar.
259/// `href_template` may include `{page_id}` — the renderer substitutes
260/// the live page id (or empty string when no page context).
261#[derive(Debug, Clone, Copy)]
262pub struct UserbarItem {
263    pub key: &'static str,
264    pub label: &'static str,
265    pub icon: &'static str,
266    pub href_template: &'static str,
267}
268
269inventory::collect!(UserbarItem);
270
271#[macro_export]
272macro_rules! register_userbar_item {
273    ($key:expr, $label:expr, $icon:expr, $href:expr) => {
274        ::rustango_cms::inventory::submit! {
275            $crate::hooks::UserbarItem {
276                key: $key,
277                label: $label,
278                icon: $icon,
279                href_template: $href,
280            }
281        }
282    };
283}
284
285#[must_use]
286pub fn userbar_items() -> Vec<&'static UserbarItem> {
287    let mut items: Vec<&'static UserbarItem> = inventory::iter::<UserbarItem>().collect();
288    items.sort_by_key(|i| i.key);
289    items
290}
291
292// ---------------------------------------------------------------
293// DashboardWidget (#144)
294// ---------------------------------------------------------------
295
296/// One widget contributed to /cms-admin/dashboard. Pre-rendered
297/// HTML; hosts compose whatever data shape they like (charts,
298/// counts, recent rows, etc.) and emit the fragment.
299#[derive(Debug, Clone, Copy)]
300pub struct DashboardWidget {
301    pub key: &'static str,
302    pub label: &'static str,
303    pub icon: &'static str,
304    pub html: &'static str,
305}
306
307inventory::collect!(DashboardWidget);
308
309#[macro_export]
310macro_rules! register_dashboard_widget {
311    ($key:expr, $label:expr, $icon:expr, $html:expr) => {
312        ::rustango_cms::inventory::submit! {
313            $crate::hooks::DashboardWidget {
314                key: $key,
315                label: $label,
316                icon: $icon,
317                html: $html,
318            }
319        }
320    };
321}
322
323#[must_use]
324pub fn dashboard_widgets() -> Vec<&'static DashboardWidget> {
325    let mut items: Vec<&'static DashboardWidget> = inventory::iter::<DashboardWidget>().collect();
326    items.sort_by_key(|i| i.key);
327    items
328}
329
330#[must_use]
331pub fn account_settings_panels() -> Vec<&'static AccountSettingsPanel> {
332    let mut items: Vec<&'static AccountSettingsPanel> =
333        inventory::iter::<AccountSettingsPanel>().collect();
334    items.sort_by_key(|i| i.key);
335    items
336}
337
338// ---------------------------------------------------------------
339// BulkActionSpec (#134)
340// ---------------------------------------------------------------
341
342/// Plugin-contributed bulk action declaration.
343///
344/// Each spec targets a specific listing resource (e.g. `"cms_page"`,
345/// `"cms_snippet"`, `"cms_media"`). The framework renders the button
346/// on every matching listing's bulk bar; clicking it POSTs the
347/// selected ids to `action_url`. Hosts wire that route themselves —
348/// the hook stays decoupled from the request lifecycle so plugins
349/// don't need to interact with the framework's tenancy / session
350/// extractors.
351///
352/// The existing per-handler `bulk_actions()` shape on
353/// [`crate::library::LibraryTypeHandler`] keeps working unchanged;
354/// this hook provides an additional, cross-listing extension point
355/// for plugins that want to contribute actions without owning a
356/// page-type or library-type handler.
357#[derive(Debug, Clone, Copy)]
358pub struct BulkActionSpec {
359    /// Resource slug — `"cms_page"`, `"cms_snippet"`, `"cms_media"`,
360    /// `"cms_redirect"`, etc. Listings filter by this.
361    pub resource: &'static str,
362    /// Stable identifier (used for dedup + the POST body's `action`
363    /// key).
364    pub key: &'static str,
365    /// Display label rendered in the bulk-bar dropdown.
366    pub label: &'static str,
367    /// Material-symbols icon name.
368    pub icon: &'static str,
369    /// When true, the button renders in the danger style + the
370    /// confirm modal is shown before submit.
371    pub danger: bool,
372    /// Confirmation message shown via the existing `data-confirm`
373    /// modal. Empty means no confirm step.
374    pub confirm_message: &'static str,
375    /// URL the form POSTs to. The framework appends the selected
376    /// ids as `ids=<id>&ids=<id>…` and the spec's `key` as
377    /// `action=<key>`. Host wires the route to receive that shape.
378    pub action_url: &'static str,
379}
380
381inventory::collect!(BulkActionSpec);
382
383#[macro_export]
384macro_rules! register_bulk_action {
385    (
386        resource = $resource:expr,
387        key = $key:expr,
388        label = $label:expr,
389        icon = $icon:expr,
390        danger = $danger:expr,
391        confirm = $confirm:expr,
392        action_url = $action_url:expr $(,)?
393    ) => {
394        ::rustango_cms::inventory::submit! {
395            $crate::hooks::BulkActionSpec {
396                resource: $resource,
397                key: $key,
398                label: $label,
399                icon: $icon,
400                danger: $danger,
401                confirm_message: $confirm,
402                action_url: $action_url,
403            }
404        }
405    };
406}
407
408/// Every plugin-contributed bulk action whose `resource` matches
409/// `resource`. Stable ordering by `key`.
410#[must_use]
411pub fn bulk_actions_for(resource: &str) -> Vec<&'static BulkActionSpec> {
412    let mut items: Vec<&'static BulkActionSpec> = inventory::iter::<BulkActionSpec>()
413        .filter(|a| a.resource == resource)
414        .collect();
415    items.sort_by_key(|i| i.key);
416    items
417}
418
419// Built-ins shipped by rustango-cms itself. Hosts can register more
420// via `register_help_menu_item!`.
421inventory::submit! {
422    HelpMenuItem {
423        key: "docs",
424        label: "Documentation",
425        icon: "menu_book",
426        href: "https://rustango-cms.dev/docs",
427    }
428}
429inventory::submit! {
430    HelpMenuItem {
431        key: "keyboard-shortcuts",
432        // Special marker href — the sidebar template renders this
433        // entry as a `data-kbd-modal-open` button instead of a link,
434        // so the click opens the cheat sheet from #121 in-page.
435        label: "Keyboard shortcuts",
436        icon: "keyboard",
437        href: "#kbd-cheatsheet",
438    }
439}
440inventory::submit! {
441    HelpMenuItem {
442        key: "styleguide",
443        label: "Styleguide",
444        icon: "palette",
445        href: "/cms-admin/styleguide",
446    }
447}
448
449// ---------------------------------------------------------------
450// PageActionMenuItem
451// ---------------------------------------------------------------
452
453/// One kebab-menu entry on the page editor (next to the existing
454/// "View live" / "Open preview" / "Form fields" entries).
455#[derive(Debug, Clone, Copy)]
456pub struct PageActionMenuItem {
457    pub key: &'static str,
458    pub label: &'static str,
459    pub icon: &'static str,
460    /// Receives `(page_id)` as a path parameter — hosts use a
461    /// `{page_id}` placeholder if needed (left as-is otherwise).
462    pub href_template: &'static str,
463}
464
465inventory::collect!(PageActionMenuItem);
466
467#[macro_export]
468macro_rules! register_page_action_menu_item {
469    ($key:expr, $label:expr, $icon:expr, $href:expr) => {
470        ::rustango_cms::inventory::submit! {
471            $crate::hooks::PageActionMenuItem {
472                key: $key,
473                label: $label,
474                icon: $icon,
475                href_template: $href,
476            }
477        }
478    };
479}
480
481/// Collect every registered PageActionMenuItem, with the page id
482/// interpolated into each entry's `href_template`.
483#[must_use]
484pub fn page_action_menu_items(page_id: i64) -> Vec<serde_json::Value> {
485    let mut items: Vec<&'static PageActionMenuItem> =
486        inventory::iter::<PageActionMenuItem>().collect();
487    items.sort_by_key(|i| i.key);
488    items
489        .into_iter()
490        .map(|i| {
491            serde_json::json!({
492                "key": i.key,
493                "label": i.label,
494                "icon": i.icon,
495                "href": i.href_template.replace("{page_id}", &page_id.to_string()),
496            })
497        })
498        .collect()
499}
500
501// ---------------------------------------------------------------
502// PageListingButton
503// ---------------------------------------------------------------
504
505/// One per-row action on the page tree (next to "Edit" / "+ Child"
506/// / "Clone" / "Delete").
507#[derive(Debug, Clone, Copy)]
508pub struct PageListingButton {
509    pub key: &'static str,
510    pub label: &'static str,
511    pub icon: &'static str,
512    pub href_template: &'static str,
513}
514
515inventory::collect!(PageListingButton);
516
517#[macro_export]
518macro_rules! register_page_listing_button {
519    ($key:expr, $label:expr, $icon:expr, $href:expr) => {
520        ::rustango_cms::inventory::submit! {
521            $crate::hooks::PageListingButton {
522                key: $key,
523                label: $label,
524                icon: $icon,
525                href_template: $href,
526            }
527        }
528    };
529}
530
531#[must_use]
532pub fn page_listing_buttons(page_id: i64) -> Vec<serde_json::Value> {
533    let mut items: Vec<&'static PageListingButton> =
534        inventory::iter::<PageListingButton>().collect();
535    items.sort_by_key(|i| i.key);
536    items
537        .into_iter()
538        .map(|i| {
539            serde_json::json!({
540                "key": i.key,
541                "label": i.label,
542                "icon": i.icon,
543                "href": i.href_template.replace("{page_id}", &page_id.to_string()),
544            })
545        })
546        .collect()
547}
548
549// ---------------------------------------------------------------
550// PageHeaderButton (#140)
551// ---------------------------------------------------------------
552
553/// One button rendered alongside Save / Publish on the page editor
554/// header. Differs from [`PageActionMenuItem`] — that lives inside the
555/// kebab dropdown; this is a top-level button always visible.
556#[derive(Debug, Clone, Copy)]
557pub struct PageHeaderButton {
558    pub key: &'static str,
559    pub label: &'static str,
560    pub icon: &'static str,
561    pub href_template: &'static str,
562    /// Visual style. Accepted: `"primary"` (filled), `"tonal"`,
563    /// `"outlined"` (default), `"danger"`. Unknown values fall back
564    /// to outlined so a typo doesn't kill the page.
565    pub style: &'static str,
566}
567
568inventory::collect!(PageHeaderButton);
569
570#[macro_export]
571macro_rules! register_page_header_button {
572    (
573        key = $key:expr,
574        label = $label:expr,
575        icon = $icon:expr,
576        href = $href:expr,
577        style = $style:expr $(,)?
578    ) => {
579        ::rustango_cms::inventory::submit! {
580            $crate::hooks::PageHeaderButton {
581                key: $key,
582                label: $label,
583                icon: $icon,
584                href_template: $href,
585                style: $style,
586            }
587        }
588    };
589}
590
591/// Resolve every registered header button against `page_id`,
592/// substituting `{page_id}` into each href.
593#[must_use]
594pub fn page_header_buttons(page_id: i64) -> Vec<serde_json::Value> {
595    let mut items: Vec<&'static PageHeaderButton> = inventory::iter::<PageHeaderButton>().collect();
596    items.sort_by_key(|i| i.key);
597    items
598        .into_iter()
599        .map(|i| {
600            serde_json::json!({
601                "key": i.key,
602                "label": i.label,
603                "icon": i.icon,
604                "style": i.style,
605                "href": i.href_template.replace("{page_id}", &page_id.to_string()),
606            })
607        })
608        .collect()
609}
610
611/// Collect raw page-listing buttons (no `{page_id}` substitution).
612/// Used by the page-list template which loops over rows and does the
613/// substitution per row inside Tera.
614#[must_use]
615pub fn page_listing_buttons_raw() -> Vec<serde_json::Value> {
616    let mut items: Vec<&'static PageListingButton> =
617        inventory::iter::<PageListingButton>().collect();
618    items.sort_by_key(|i| i.key);
619    items
620        .into_iter()
621        .map(|i| {
622            serde_json::json!({
623                "key": i.key,
624                "label": i.label,
625                "icon": i.icon,
626                "href_template": i.href_template,
627            })
628        })
629        .collect()
630}
631
632// ---------------------------------------------------------------
633// AdminSearchArea
634// ---------------------------------------------------------------
635
636/// One hit row from a plugin-contributed search source.
637#[derive(Debug, Clone, serde::Serialize)]
638pub struct AdminSearchHit {
639    pub label: String,
640    pub href: String,
641    /// Optional one-line subtitle (used for slug / path / category).
642    pub subtitle: String,
643}
644
645/// Plugin-contributed search source for `/cms-admin/search`.
646/// Receives the query string; returns up to N hits to merge into
647/// the global search response.
648#[derive(Debug, Clone, Copy)]
649pub struct AdminSearchArea {
650    pub key: &'static str,
651    pub label: &'static str,
652    pub search: fn(&str) -> Vec<AdminSearchHit>,
653}
654
655inventory::collect!(AdminSearchArea);
656
657#[macro_export]
658macro_rules! register_admin_search_area {
659    ($key:expr, $label:expr, $search:expr) => {
660        ::rustango_cms::inventory::submit! {
661            $crate::hooks::AdminSearchArea {
662                key: $key,
663                label: $label,
664                search: $search,
665            }
666        }
667    };
668}
669
670/// Run every registered AdminSearchArea against `query` and return
671/// a flattened `(area_label, hits)` list.
672#[must_use]
673pub fn run_admin_search_areas(query: &str) -> Vec<(&'static str, Vec<AdminSearchHit>)> {
674    let mut out = Vec::new();
675    for area in inventory::iter::<AdminSearchArea>() {
676        let hits = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (area.search)(query)))
677            .unwrap_or_else(|e| {
678                tracing::warn!(
679                    target: "rustango_cms::hooks",
680                    hook = "admin_search_area",
681                    area = %area.key,
682                    error = ?e,
683                    "search area panicked (continuing)"
684                );
685                Vec::new()
686            });
687        if !hits.is_empty() {
688            out.push((area.label, hits));
689        }
690    }
691    out
692}
693
694// ---------------------------------------------------------------
695// AdminCss / AdminJs (#422)
696// ---------------------------------------------------------------
697
698/// A blob of CSS injected into every admin page's `<head>`. The string is emitted verbatim
699/// inside a `<style>` tag (host-trusted), so plugins can restyle the
700/// chrome, hide elements, or theme their own admin pages without
701/// shipping a separate stylesheet route.
702#[derive(Debug, Clone, Copy)]
703pub struct AdminCss(pub &'static str);
704
705inventory::collect!(AdminCss);
706
707/// Register global admin CSS.
708///
709/// ```ignore
710/// register_admin_css!(".my-plugin-badge { color: rebeccapurple; }");
711/// ```
712#[macro_export]
713macro_rules! register_admin_css {
714    ($css:expr) => {
715        ::rustango_cms::inventory::submit! {
716            $crate::hooks::AdminCss($css)
717        }
718    };
719}
720
721/// Every registered global admin CSS blob, in registration order.
722#[must_use]
723pub fn admin_css() -> Vec<&'static str> {
724    inventory::iter::<AdminCss>().map(|c| c.0).collect()
725}
726
727/// A blob of JS injected just before `</body>` on every admin page.
728/// Emitted verbatim inside a
729/// `<script>` tag (host-trusted).
730#[derive(Debug, Clone, Copy)]
731pub struct AdminJs(pub &'static str);
732
733inventory::collect!(AdminJs);
734
735/// Register global admin JS.
736#[macro_export]
737macro_rules! register_admin_js {
738    ($js:expr) => {
739        ::rustango_cms::inventory::submit! {
740            $crate::hooks::AdminJs($js)
741        }
742    };
743}
744
745/// Every registered global admin JS blob, in registration order.
746#[must_use]
747pub fn admin_js() -> Vec<&'static str> {
748    inventory::iter::<AdminJs>().map(|j| j.0).collect()
749}
750
751#[cfg(test)]
752mod tests {
753    use super::*;
754
755    // Dogfood the registries (compiled only in test builds).
756    inventory::submit! { AdminCss(".rcms-admin-css-marker{display:none}") }
757    inventory::submit! { AdminJs("/* rcms-admin-js-marker */") }
758
759    #[test]
760    fn admin_css_and_js_collect_registered_blobs() {
761        assert!(
762            admin_css()
763                .iter()
764                .any(|c| c.contains("rcms-admin-css-marker")),
765            "registered CSS blob is collected"
766        );
767        assert!(
768            admin_js()
769                .iter()
770                .any(|j| j.contains("rcms-admin-js-marker")),
771            "registered JS blob is collected"
772        );
773    }
774
775    #[test]
776    fn page_action_href_template_substitutes_page_id() {
777        let raw = PageActionMenuItem {
778            key: "x",
779            label: "X",
780            icon: "extension",
781            href_template: "/cms-admin/x/plugin?page={page_id}",
782        };
783        let rendered = raw.href_template.replace("{page_id}", "42");
784        assert_eq!(rendered, "/cms-admin/x/plugin?page=42");
785    }
786
787    #[test]
788    fn bulk_action_spec_fields_round_trip() {
789        let spec = BulkActionSpec {
790            resource: "cms_page",
791            key: "archive_old",
792            label: "Archive old",
793            icon: "archive",
794            danger: false,
795            confirm_message: "Archive every selected old page?",
796            action_url: "/plugin/archive",
797        };
798        assert_eq!(spec.resource, "cms_page");
799        assert!(!spec.danger);
800        assert!(spec.confirm_message.contains("Archive"));
801    }
802
803    #[test]
804    fn page_listing_button_href_template_substitutes_page_id() {
805        let raw = PageListingButton {
806            key: "x",
807            label: "X",
808            icon: "extension",
809            href_template: "/plugin/{page_id}/do",
810        };
811        let rendered = raw.href_template.replace("{page_id}", "7");
812        assert_eq!(rendered, "/plugin/7/do");
813    }
814}