Skip to main content

rustango_cms/widget/
registry.rs

1//! Third-party custom widget registry.
2//!
3//! Out-of-tree crates ship new widget types via
4//! [`register_widget!`](crate::register_widget!). Each registration carries the wire-format
5//! `name` (used by [`crate::widget::WidgetKind::Custom`] and looked
6//! up at render time) and the **Tera template path** the bundled
7//! `_widget.html` macro should include for that name.
8//!
9//! ## Why no JS class
10//!
11//! A widget needs no client-side class keyed by a string name that
12//! could fail at runtime if mismatched. The plumbing
13//! here is *just* a Tera template — the same one the server uses to
14//! render the widget. Native HTML5 inputs cover most needs
15//! (`<input type="color">`, `<input type="date">`, `<input
16//! type="range">`); for the rare widget that wants client-side
17//! sprinkle (e.g. a map preview reacting to lat/lng inputs), the
18//! template can emit a `<script>` tag inline or a `data-*` hook the
19//! host app's own bundle reads. No framework-imposed JS class
20//! registry.
21//!
22//! ## Example
23//!
24//! ```ignore
25//! use rustango_cms::register_widget;
26//! register_widget!("latlng", "widgets/latlng.html");
27//! ```
28//!
29//! Inside a `PageTypeHandler::extension_fields` impl:
30//!
31//! ```ignore
32//! Widget::new(
33//!     WidgetKind::Custom { name: "latlng".to_owned() },
34//!     "office_loc",
35//!     "Office location",
36//! )
37//! ```
38
39/// One registered custom widget — wire-format `name` paired with the
40/// Tera template that renders it. Submitted via [`register_widget!`](crate::register_widget!)
41/// and collected at startup by the [`inventory`] crate.
42pub struct CustomWidgetRegistration {
43    /// Wire-format name. Matched against
44    /// [`crate::widget::WidgetKind::Custom { name }`] at render
45    /// time. Must be globally unique across the process — duplicate
46    /// registrations panic at boot via [`validate_registry`].
47    pub name: &'static str,
48    /// Tera template path used by the bundled `_widget.html` macro
49    /// via `{% include template %}`. The template receives the
50    /// active [`crate::widget::Widget`] as `w`.
51    pub template: &'static str,
52}
53
54inventory::collect!(CustomWidgetRegistration);
55
56/// Register a custom widget at module-load time. Picks up
57/// `rustango_cms::inventory` (re-exported in [`crate`]) so callers
58/// don't need their own `inventory` dep.
59///
60/// ```ignore
61/// use rustango_cms::register_widget;
62/// register_widget!("latlng", "widgets/latlng.html");
63/// ```
64#[macro_export]
65macro_rules! register_widget {
66    ($name:expr, $template:expr) => {
67        $crate::inventory::submit! {
68            $crate::widget::registry::CustomWidgetRegistration {
69                name: $name,
70                template: $template,
71            }
72        }
73    };
74}
75
76/// Iterator over every registered custom widget. Returned references
77/// are `'static` — registrations are process-global.
78pub fn registered_widgets() -> impl Iterator<Item = &'static CustomWidgetRegistration> {
79    inventory::iter::<CustomWidgetRegistration>()
80}
81
82/// Look up the registered template path for a custom widget by
83/// name. Returns `None` when the name isn't registered — callers
84/// (the `_widget.html` macro path) treat this as an editor-visible
85/// error rather than panicking.
86#[must_use]
87pub fn find_custom_widget(name: &str) -> Option<&'static CustomWidgetRegistration> {
88    registered_widgets().find(|w| w.name == name)
89}
90
91/// Surface duplicate registrations at boot. Returns the list of
92/// duplicate names; the empty Vec means clean. Host apps should
93/// call this once at startup and panic / log on non-empty output —
94/// silent duplicates would lead to one of two competing templates
95/// winning arbitrarily depending on link order.
96#[must_use]
97pub fn duplicate_widget_names() -> Vec<&'static str> {
98    let mut seen = std::collections::HashSet::new();
99    let mut dups = Vec::new();
100    for w in registered_widgets() {
101        if !seen.insert(w.name) {
102            dups.push(w.name);
103        }
104    }
105    dups
106}
107
108/// Boot-time validation hook: checks for duplicate widget names.
109///
110/// # Panics
111/// On any duplicate widget name — boot-time crash with both
112/// occupants named is the right loud failure.
113pub fn validate_registry() {
114    let dups = duplicate_widget_names();
115    assert!(
116        dups.is_empty(),
117        "rustango_cms: duplicate custom widget registrations: {dups:?}",
118    );
119}