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