Skip to main content

rustango_cms/
library.rs

1//! `Library` — reusable content (renamed from "snippets").
2//!
3//! Library items are non-page records that pages reference by id —
4//! authors, FAQ entries, hero banners, callout blocks, etc. The
5//! pattern mirrors `register_page_type!`: each type implements
6//! [`LibraryTypeHandler`], registers via the
7//! [`crate::register_library_type!`] macro, gets a row in
8//! `cms_library_type`, and exposes its own extension table for the
9//! actual content.
10//!
11//! ```ignore
12//! #[derive(Default)]
13//! pub struct AuthorEntry;
14//!
15//! #[async_trait::async_trait]
16//! impl rustango_cms::library::LibraryTypeHandler for AuthorEntry {
17//!     fn app_label(&self) -> &'static str { "blog" }
18//!     fn type_name(&self) -> &'static str { "Author" }
19//!     fn verbose_name(&self) -> &'static str { "Author" }
20//!     fn extension_table(&self) -> Option<&'static str> { Some("blog_author") }
21//! }
22//!
23//! rustango_cms::register_library_type!(AuthorEntry);
24//! ```
25
26use async_trait::async_trait;
27use chrono::{DateTime, Utc};
28use rustango::sql::Auto;
29use rustango::Model;
30use serde::{Deserialize, Serialize};
31
32/// Registry row keyed on `type_name`. Seeded on boot from the
33/// inventory of `register_library_type!`-registered handlers,
34/// mirroring `PageType`.
35#[derive(Model, Debug, Clone, Serialize, Deserialize)]
36#[rustango(
37    table = "cms_library_type",
38    app = "cms",
39    admin(
40        list_display = "app_label, type_name, verbose_name, extension_table",
41        ordering = "type_name",
42    )
43)]
44pub struct LibraryType {
45    #[rustango(primary_key)]
46    pub id: Auto<i64>,
47    #[rustango(max_length = 64, index)]
48    pub app_label: String,
49    #[rustango(max_length = 64, index)]
50    pub type_name: String,
51    #[rustango(max_length = 128)]
52    pub verbose_name: String,
53    /// Optional name of the user-authored extension table that holds
54    /// the typed fields. `None` when the handler is metadata-only.
55    #[rustango(max_length = 128)]
56    pub extension_table: String,
57    #[rustango(auto_now_add)]
58    pub created_at: Auto<DateTime<Utc>>,
59    #[rustango(auto_now)]
60    pub updated_at: Auto<DateTime<Utc>>,
61}
62
63/// One column shown in the snippet list view for a given type.
64/// A column can be a
65/// scalar field on `cms_snippet`, a `data.<key>` JSON lookup, a
66/// method-field rendered by the handler, or a computed value
67/// derived at render time.
68#[derive(Debug, Clone)]
69pub enum ListColumn {
70    /// Scalar column on `cms_snippet` (`slug`, `title`,
71    /// `updated_at`, …). Renders with type-aware formatting.
72    Field {
73        column: &'static str,
74        label: &'static str,
75    },
76    /// `data.<key>` JSON lookup. Renders with the requested kind so
77    /// e.g. a boolean in `data` shows as a checkbox.
78    JsonField {
79        key: &'static str,
80        label: &'static str,
81        kind: ListColumnKind,
82    },
83    /// Method field — the admin calls
84    /// [`LibraryTypeHandler::render_cell`] with the column name plus
85    /// the snippet row; the handler returns pre-escaped display
86    /// HTML.
87    Method {
88        name: &'static str,
89        label: &'static str,
90    },
91    /// Runtime-derived column. Same render pathway as `Method`
92    /// (cells route through `render_cell`), but declared separately
93    /// so authors can express intent — `Method` connotes "computed
94    /// by a method on the typed extension", `Computed` connotes
95    /// "derived from any context the handler wants".
96    Computed {
97        name: &'static str,
98        label: &'static str,
99    },
100}
101
102impl ListColumn {
103    /// Visible header label for this column.
104    #[must_use]
105    pub fn label(&self) -> &'static str {
106        match self {
107            Self::Field { label, .. }
108            | Self::JsonField { label, .. }
109            | Self::Method { label, .. }
110            | Self::Computed { label, .. } => label,
111        }
112    }
113
114    /// Stable identifier — used by the per-user column picker
115    /// to persist hide/show state across reloads.
116    #[must_use]
117    pub fn key(&self) -> &'static str {
118        match self {
119            Self::Field { column, .. } => column,
120            Self::JsonField { key, .. } => key,
121            Self::Method { name, .. } | Self::Computed { name, .. } => name,
122        }
123    }
124}
125
126/// Sort direction for [`LibraryTypeHandler::default_ordering`].
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum OrderDir {
129    Asc,
130    Desc,
131}
132
133impl OrderDir {
134    #[must_use]
135    pub fn is_desc(self) -> bool {
136        matches!(self, Self::Desc)
137    }
138}
139
140/// Visual emphasis for a bulk action button. Maps to the
141/// `.btn` / `.btn-outlined` / `.btn-danger` CSS variants.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum BulkActionStyle {
144    Primary,
145    Outlined,
146    Danger,
147}
148
149/// One bulk action exposed above the list table — pair the
150/// multi-select checkbox column with a labeled button. Submits
151/// as POST `/cms-admin/library/{type}/bulk` with
152/// `action=<name>&ids=<id>&ids=<id>...`; the handler routes the
153/// selection to [`LibraryTypeHandler::handle_bulk_action`].
154#[derive(Debug, Clone)]
155pub struct BulkAction {
156    /// Stable identifier sent as the `action=` form field.
157    pub name: &'static str,
158    /// Visible button label.
159    pub label: &'static str,
160    /// Optional Material-symbols icon name.
161    pub icon: Option<&'static str>,
162    /// Optional confirmation prompt — when set, the JS submit
163    /// handler calls `window.confirm(message)` first.
164    pub confirm_message: Option<&'static str>,
165    /// Visual emphasis.
166    pub style: BulkActionStyle,
167}
168
169impl BulkAction {
170    /// Smallest constructor — `(name, label, style)`. Add icon /
171    /// confirm fluently.
172    #[must_use]
173    pub fn new(name: &'static str, label: &'static str, style: BulkActionStyle) -> Self {
174        Self {
175            name,
176            label,
177            icon: None,
178            confirm_message: None,
179            style,
180        }
181    }
182
183    #[must_use]
184    pub fn with_icon(mut self, icon: &'static str) -> Self {
185        self.icon = Some(icon);
186        self
187    }
188
189    #[must_use]
190    pub fn with_confirm(mut self, msg: &'static str) -> Self {
191        self.confirm_message = Some(msg);
192        self
193    }
194}
195
196/// One row contributed by [`LibraryTypeHandler::menu_picker_entries`]
197/// to the WP-style menu builder's Library tab. Each entry
198/// renders as a draggable picker card; dropping one into the tree
199/// creates a MenuItem with `external_url = url` and `label`
200/// inherited.
201#[derive(Debug, Clone, serde::Serialize)]
202pub struct MenuPickerEntry {
203    /// Human label shown on the picker card and used as the menu
204    /// item's default label.
205    pub label: String,
206    /// Destination URL the menu item points at. Stored as
207    /// `MenuItem.external_url` on save.
208    pub url: String,
209    /// Optional kind hint surfaced as a chip on the picker card
210    /// (e.g. "Partner", "Doc", "Microsite"). Useful when one
211    /// library type contributes multiple kinds.
212    #[serde(default)]
213    pub kind_hint: Option<String>,
214}
215
216impl MenuPickerEntry {
217    #[must_use]
218    pub fn new(label: impl Into<String>, url: impl Into<String>) -> Self {
219        Self {
220            label: label.into(),
221            url: url.into(),
222            kind_hint: None,
223        }
224    }
225
226    #[must_use]
227    pub fn with_kind_hint(mut self, hint: impl Into<String>) -> Self {
228        self.kind_hint = Some(hint.into());
229        self
230    }
231}
232
233/// How a scalar value should render in the list.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum ListColumnKind {
236    Text,
237    Bool,
238    Integer,
239    Float,
240    Date,
241    DateTime,
242}
243
244/// Trait every library type implements. Mirrors
245/// [`crate::PageTypeHandler`] — same registration story, same
246/// per-tenant seeding pass.
247#[async_trait]
248pub trait LibraryTypeHandler: Send + Sync + 'static {
249    /// App label.
250    fn app_label(&self) -> &'static str;
251    /// Canonical type name. Unique per tenant.
252    fn type_name(&self) -> &'static str;
253    /// Human-readable name for the admin sidebar.
254    fn verbose_name(&self) -> &'static str;
255    /// SQL table where the typed extension data lives, or `None` for
256    /// a metadata-only registration (rare; useful for "Author" rows
257    /// that just hold name + bio in `cms_library_type` itself).
258    fn extension_table(&self) -> Option<&'static str> {
259        None
260    }
261
262    /// Optional Tera template for this type's rows on public pages.
263    /// When `Some("<path>")`, `{{ snippet_html(type="Category", id=4) }}`
264    /// renders that row through it, with `{ snippet: <row JSON> }` in
265    /// context. Only the rows a page asks for are fetched and rendered,
266    /// once each however often the page references them.
267    ///
268    /// `None` (default) — snippet has no public-side surface; the
269    /// only consumers are admin / API.
270    fn render_template(&self) -> Option<&'static str> {
271        None
272    }
273
274    /// Whether an individual element of this type may name its own
275    /// template, overriding [`Self::render_template`] for that row
276    /// alone. The name is read from the element's `data.template`.
277    ///
278    /// `false` (default) — every row of the type renders through the
279    /// one template the handler declares, which is what a "Category"
280    /// or "Author" wants: uniform presentation is the point.
281    ///
282    /// `true` — the element *is* the presentation. A reporting widget
283    /// that carries its own query and its own markup, a campaign
284    /// banner an editor restyles per placement: these differ per row
285    /// by design, and a type-wide template would just be a dispatch
286    /// table keyed on the row.
287    ///
288    /// Opt-in rather than always-on so a stray `template` key in a
289    /// row's `data` can't silently repoint an existing type's render.
290    ///
291    /// Types that opt in render through `snippet_html` even when
292    /// [`Self::render_template`] is `None` — an element template alone
293    /// is enough. Rows that name nothing and have no type default
294    /// render empty.
295    fn allows_element_template(&self) -> bool {
296        false
297    }
298
299    /// Columns rendered in this type's list view. Defaults to the
300    /// title + slug + updated_at trio when not overridden.
301    fn list_display(&self) -> Vec<ListColumn> {
302        vec![
303            ListColumn::Field {
304                column: "title",
305                label: "Title",
306            },
307            ListColumn::Field {
308                column: "slug",
309                label: "Slug",
310            },
311            ListColumn::Field {
312                column: "updated_at",
313                label: "Updated",
314            },
315        ]
316    }
317
318    /// Fields the search bar matches against. Defaults to
319    /// `["title", "slug"]`; case-insensitive `ILIKE '%q%'`.
320    fn search_fields(&self) -> Vec<&'static str> {
321        vec!["title", "slug"]
322    }
323
324    /// `data.<key>` keys exposed as filter dropdowns. The admin
325    /// reads distinct values + counts per key and renders one chip
326    /// per option. Defaults to no filters.
327    fn list_filter(&self) -> Vec<&'static str> {
328        Vec::new()
329    }
330
331    /// Render a method-field cell. Called for every
332    /// [`ListColumn::Method`] and [`ListColumn::Computed`] entry.
333    /// Return pre-escaped HTML — the admin emits it via Tera's
334    /// `| safe`. The default empty implementation is fine when a
335    /// handler declares no method / computed columns.
336    fn render_cell(&self, _name: &str, _snippet: &crate::snippet::Snippet) -> String {
337        String::new()
338    }
339
340    /// Default ordering for the list view — applied in order. The
341    /// admin's `?ordering=` query param overrides this. Defaults to
342    /// "most-recently-updated first" so freshly-edited rows surface
343    /// at the top without authors needing to think about ordering.
344    fn default_ordering(&self) -> Vec<(&'static str, OrderDir)> {
345        vec![("updated_at", OrderDir::Desc)]
346    }
347
348    /// Bulk actions exposed above the list table. Each entry adds
349    /// a labeled button next to a "Select all" checkbox; the
350    /// multi-select checkbox column is auto-mounted when this returns
351    /// any entry. Implementations that declare bulk actions MUST
352    /// override [`Self::handle_bulk_action`] — the default panics.
353    fn bulk_actions(&self) -> Vec<BulkAction> {
354        Vec::new()
355    }
356
357    /// Per-row action chips overriding the built-in Edit / Delete
358    /// pair when set. Each [`BulkAction`] becomes a small inline
359    /// button; the `name` is sent as the form action via a fetch
360    /// `POST /cms-admin/library/{type}/row-action/{id}?action=<name>`.
361    /// Defaults to empty (built-in chips render).
362    fn row_actions(&self) -> Vec<BulkAction> {
363        Vec::new()
364    }
365
366    /// Override the per-row HTML template. Defaults to `None` — the
367    /// admin renders rows via the built-in column loop. Setting this
368    /// gives full control of the row markup; the template receives
369    /// `row` (the snippet + computed cells) and `columns`
370    /// (`list_display` metadata) in scope.
371    fn list_row_template(&self) -> Option<&'static str> {
372        None
373    }
374
375    /// Override the edit-form template body. Defaults to `None` —
376    /// the admin renders the default linear field stack. Setting
377    /// this gives full control of the form layout; the template
378    /// runs inside the page-edit `<form>` element so inputs submit
379    /// alongside the canonical save.
380    fn edit_template(&self) -> Option<&'static str> {
381        None
382    }
383
384    /// Opt this library type in to versioned snapshots.
385    /// When `true`, every successful save on a
386    /// snippet of this type also captures a [`crate::snippet::SnippetRevision`]
387    /// row, and the editor surfaces a History card with revert.
388    /// Defaults to `false` — fixed-shape snippet types keep the
389    /// existing zero-overhead lifecycle.
390    fn revisions_enabled(&self) -> bool {
391        false
392    }
393
394    /// Opt this library type in to preview-on-save.
395    /// When `true`, the editor surfaces an
396    /// \"Open preview\" action that renders the unsaved form state.
397    /// Defaults to `false`. Hosts that want preview implement their
398    /// own preview route + override this.
399    fn preview_enabled(&self) -> bool {
400        false
401    }
402
403    /// Permission hook — return `false` to hide a row from the list
404    /// view + reject direct GET access to its edit page. The default grants
405    /// every row (true). Hosts wire role-aware logic by overriding.
406    fn can_view(&self, _snippet: &crate::snippet::Snippet) -> bool {
407        true
408    }
409
410    /// Permission hook — return `false` to disable the Edit chip +
411    /// reject POST edits on the row. The default grants every row (true).
412    fn can_edit(&self, _snippet: &crate::snippet::Snippet) -> bool {
413        true
414    }
415
416    /// Permission hook — return `false` to hide the Delete chip +
417    /// reject DELETE on the row. The default grants every row (true).
418    fn can_delete(&self, _snippet: &crate::snippet::Snippet) -> bool {
419        true
420    }
421
422    /// Cross-field validation hook. Called BEFORE save with the
423    /// form payload as a key/value map. Return `Err` with one or
424    /// more field-scoped error messages to fail the save and render
425    /// them inline. Defaults to "always ok".
426    fn validate(
427        &self,
428        _form: &std::collections::HashMap<String, String>,
429    ) -> Result<(), Vec<(String, String)>> {
430        Ok(())
431    }
432
433    /// Opt-in hook for the WP-style menu builder. Return a
434    /// list of [`MenuPickerEntry`] values to surface this library
435    /// type's snippets in the **Library** picker tab on the menu
436    /// edit screen. Each entry contributes a draggable picker card
437    /// that drops into the menu as an external-URL `MenuItem`.
438    ///
439    /// Default: empty — most library types (authors, callouts,
440    /// blocks) don't have a single canonical URL and shouldn't show
441    /// up in the menu picker. Override on types whose snippets
442    /// represent linkable resources (e.g. external partner sites,
443    /// downloadable docs, microsite shortcuts).
444    ///
445    /// # Errors
446    /// Driver errors from the snippet fetch when an implementation
447    /// queries the pool. The default returns `Ok(Vec::new())` so
448    /// implementors only opt-in when they have real data to surface.
449    async fn menu_picker_entries(
450        &self,
451        _pool: &rustango::sql::Pool,
452    ) -> Result<Vec<MenuPickerEntry>, rustango::sql::ExecError> {
453        Ok(Vec::new())
454    }
455
456    /// Async bulk-action dispatcher. Called when the list view
457    /// submits a bulk action. Returns the number of rows touched.
458    /// Default panics — handlers that declare [`Self::bulk_actions`]
459    /// MUST override this.
460    ///
461    /// # Errors
462    /// Driver errors from the underlying ORM calls.
463    async fn handle_bulk_action(
464        &self,
465        _pool: &rustango::sql::Pool,
466        action: &str,
467        _ids: &[i64],
468    ) -> Result<usize, rustango::sql::ExecError> {
469        unimplemented!(
470            "library type `{}` declared bulk actions but didn't override handle_bulk_action(); unknown action `{action}`",
471            self.type_name(),
472        )
473    }
474}
475
476/// Handler-registration entry submitted via `inventory::submit!`. The
477/// `factory` reconstructs the handler at runtime; mirrors
478/// `PageTypeHandlerRegistration`.
479pub struct LibraryTypeHandlerRegistration {
480    pub factory: fn() -> Box<dyn LibraryTypeHandler>,
481}
482
483inventory::collect!(LibraryTypeHandlerRegistration);
484
485/// Walk every `register_library_type!`-registered handler. Used by
486/// the seeder + admin to enumerate types at runtime.
487pub fn registered_handlers() -> impl Iterator<Item = Box<dyn LibraryTypeHandler>> {
488    inventory::iter::<LibraryTypeHandlerRegistration>
489        .into_iter()
490        .map(|r| (r.factory)())
491}
492
493/// Locate a handler by `type_name`. Returns `None` for unknown
494/// types — useful for the admin's lookup-then-route flow.
495#[must_use]
496pub fn find_handler(type_name: &str) -> Option<Box<dyn LibraryTypeHandler>> {
497    registered_handlers().find(|h| h.type_name() == type_name)
498}
499
500/// Seed `cms_library_type` rows for every registered handler across
501/// every active org. Wire into the same `Cli::seed` callback the
502/// page-type seeder uses.
503///
504/// # Errors
505/// Driver / tenancy errors from any tenant; short-circuits on the
506/// first failure (mirrors `ensure_seeded` for `PageType`).
507/// Upsert one `cms_library_type` row keyed by `type_name`. Exposed
508/// so `crate::seed::ensure_seeded` can share the seeding loop with
509/// `register_page_type!`.
510pub async fn ensure_library_type_row(
511    pool: &rustango::sql::Pool,
512    handler: &dyn LibraryTypeHandler,
513) -> Result<(), rustango::sql::ExecError> {
514    upsert_one(pool, handler).await
515}
516
517async fn upsert_one(
518    pool: &rustango::sql::Pool,
519    handler: &dyn LibraryTypeHandler,
520) -> Result<(), rustango::sql::ExecError> {
521    use rustango::core::Column as _;
522    use rustango::sql::FetcherPool as _;
523    let mut existing: Vec<LibraryType> = LibraryType::objects()
524        .where_(LibraryType::type_name.eq(handler.type_name().to_string()))
525        .fetch(pool)
526        .await?;
527    let extension_table = handler.extension_table().unwrap_or("").to_owned();
528    if let Some(mut row) = existing.pop() {
529        row.app_label = handler.app_label().to_owned();
530        row.verbose_name = handler.verbose_name().to_owned();
531        row.extension_table = extension_table;
532        row.save(pool).await?;
533    } else {
534        let mut row = LibraryType {
535            id: Auto::Unset,
536            app_label: handler.app_label().to_owned(),
537            type_name: handler.type_name().to_owned(),
538            verbose_name: handler.verbose_name().to_owned(),
539            extension_table,
540            created_at: Auto::Unset,
541            updated_at: Auto::Unset,
542        };
543        row.insert(pool).await?;
544    }
545    Ok(())
546}
547
548/// Register a library type at compile time. Pair with a
549/// `#[derive(Default)] impl LibraryTypeHandler` block. Mirrors
550/// [`crate::register_page_type!`].
551#[macro_export]
552macro_rules! register_library_type {
553    ($ty:ty) => {
554        $crate::inventory::submit! {
555            $crate::library::LibraryTypeHandlerRegistration {
556                factory: || ::std::boxed::Box::new(<$ty>::default()),
557            }
558        }
559    };
560}
561
562#[cfg(test)]
563mod menu_picker_entry_tests {
564    use super::*;
565
566    #[test]
567    fn serializes_with_optional_kind_hint() {
568        let e = MenuPickerEntry::new("Partner site", "https://partner.example.com")
569            .with_kind_hint("Partner");
570        let v = serde_json::to_value(&e).unwrap();
571        assert_eq!(v["label"], "Partner site");
572        assert_eq!(v["url"], "https://partner.example.com");
573        assert_eq!(v["kind_hint"], "Partner");
574    }
575
576    #[test]
577    fn omits_kind_hint_when_absent() {
578        let e = MenuPickerEntry::new("Docs", "https://docs.example.com");
579        let v = serde_json::to_value(&e).unwrap();
580        // serde defaults to `null` for `Option::None` — the template
581        // uses `e.kind_hint | default(value=e.library_type)` so null
582        // falls through to the library-type label.
583        assert!(v["kind_hint"].is_null());
584    }
585}