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 the public-render handler uses to
263    /// pre-render this snippet type's rows. When `Some("<path>")`
264    /// the renderer pre-fetches every row of this type, renders
265    /// each through the template (with `{ snippet: <row JSON> }`
266    /// in context), and stamps the resulting HTML into the public
267    /// Tera ctx map `_snippets_html_by_id` keyed on the snippet's
268    /// `id`.
269    ///
270    /// Templates pull the pre-rendered HTML via
271    /// `{{ snippet_html(type="Category", id=4) }}` so multiple
272    /// pages that reference the same snippet share one render.
273    ///
274    /// `None` (default) — snippet has no public-side surface; the
275    /// only consumers are admin / API.
276    fn render_template(&self) -> Option<&'static str> {
277        None
278    }
279
280    /// Whether an individual element of this type may name its own
281    /// template, overriding [`Self::render_template`] for that row
282    /// alone. The name is read from the element's `data.template`.
283    ///
284    /// `false` (default) — every row of the type renders through the
285    /// one template the handler declares, which is what a "Category"
286    /// or "Author" wants: uniform presentation is the point.
287    ///
288    /// `true` — the element *is* the presentation. A reporting widget
289    /// that carries its own query and its own markup, a campaign
290    /// banner an editor restyles per placement: these differ per row
291    /// by design, and a type-wide template would just be a dispatch
292    /// table keyed on the row.
293    ///
294    /// Opt-in rather than always-on so a stray `template` key in a
295    /// row's `data` can't silently repoint an existing type's render.
296    ///
297    /// Types that opt in participate in the public pre-render even
298    /// when [`Self::render_template`] is `None` — an element template
299    /// alone is enough. Rows that name nothing and have no type
300    /// default are skipped, exactly as before.
301    fn allows_element_template(&self) -> bool {
302        false
303    }
304
305    /// Columns rendered in this type's list view. Defaults to the
306    /// title + slug + updated_at trio when not overridden.
307    fn list_display(&self) -> Vec<ListColumn> {
308        vec![
309            ListColumn::Field {
310                column: "title",
311                label: "Title",
312            },
313            ListColumn::Field {
314                column: "slug",
315                label: "Slug",
316            },
317            ListColumn::Field {
318                column: "updated_at",
319                label: "Updated",
320            },
321        ]
322    }
323
324    /// Fields the search bar matches against. Defaults to
325    /// `["title", "slug"]`; case-insensitive `ILIKE '%q%'`.
326    fn search_fields(&self) -> Vec<&'static str> {
327        vec!["title", "slug"]
328    }
329
330    /// `data.<key>` keys exposed as filter dropdowns. The admin
331    /// reads distinct values + counts per key and renders one chip
332    /// per option. Defaults to no filters.
333    fn list_filter(&self) -> Vec<&'static str> {
334        Vec::new()
335    }
336
337    /// Render a method-field cell. Called for every
338    /// [`ListColumn::Method`] and [`ListColumn::Computed`] entry.
339    /// Return pre-escaped HTML — the admin emits it via Tera's
340    /// `| safe`. The default empty implementation is fine when a
341    /// handler declares no method / computed columns.
342    fn render_cell(&self, _name: &str, _snippet: &crate::snippet::Snippet) -> String {
343        String::new()
344    }
345
346    /// Default ordering for the list view — applied in order. The
347    /// admin's `?ordering=` query param overrides this. Defaults to
348    /// "most-recently-updated first" so freshly-edited rows surface
349    /// at the top without authors needing to think about ordering.
350    fn default_ordering(&self) -> Vec<(&'static str, OrderDir)> {
351        vec![("updated_at", OrderDir::Desc)]
352    }
353
354    /// Bulk actions exposed above the list table. Each entry adds
355    /// a labeled button next to a "Select all" checkbox; the
356    /// multi-select checkbox column is auto-mounted when this returns
357    /// any entry. Implementations that declare bulk actions MUST
358    /// override [`Self::handle_bulk_action`] — the default panics.
359    fn bulk_actions(&self) -> Vec<BulkAction> {
360        Vec::new()
361    }
362
363    /// Per-row action chips overriding the built-in Edit / Delete
364    /// pair when set. Each [`BulkAction`] becomes a small inline
365    /// button; the `name` is sent as the form action via a fetch
366    /// `POST /cms-admin/library/{type}/row-action/{id}?action=<name>`.
367    /// Defaults to empty (built-in chips render).
368    fn row_actions(&self) -> Vec<BulkAction> {
369        Vec::new()
370    }
371
372    /// Override the per-row HTML template. Defaults to `None` — the
373    /// admin renders rows via the built-in column loop. Setting this
374    /// gives full control of the row markup; the template receives
375    /// `row` (the snippet + computed cells) and `columns`
376    /// (`list_display` metadata) in scope.
377    fn list_row_template(&self) -> Option<&'static str> {
378        None
379    }
380
381    /// Override the edit-form template body. Defaults to `None` —
382    /// the admin renders the default linear field stack. Setting
383    /// this gives full control of the form layout; the template
384    /// runs inside the page-edit `<form>` element so inputs submit
385    /// alongside the canonical save.
386    fn edit_template(&self) -> Option<&'static str> {
387        None
388    }
389
390    /// Opt this library type in to versioned snapshots.
391    /// When `true`, every successful save on a
392    /// snippet of this type also captures a [`crate::snippet::SnippetRevision`]
393    /// row, and the editor surfaces a History card with revert.
394    /// Defaults to `false` — fixed-shape snippet types keep the
395    /// existing zero-overhead lifecycle.
396    fn revisions_enabled(&self) -> bool {
397        false
398    }
399
400    /// Opt this library type in to preview-on-save.
401    /// When `true`, the editor surfaces an
402    /// \"Open preview\" action that renders the unsaved form state.
403    /// Defaults to `false`. Hosts that want preview implement their
404    /// own preview route + override this.
405    fn preview_enabled(&self) -> bool {
406        false
407    }
408
409    /// Permission hook — return `false` to hide a row from the list
410    /// view + reject direct GET access to its edit page. The default grants
411    /// every row (true). Hosts wire role-aware logic by overriding.
412    fn can_view(&self, _snippet: &crate::snippet::Snippet) -> bool {
413        true
414    }
415
416    /// Permission hook — return `false` to disable the Edit chip +
417    /// reject POST edits on the row. The default grants every row (true).
418    fn can_edit(&self, _snippet: &crate::snippet::Snippet) -> bool {
419        true
420    }
421
422    /// Permission hook — return `false` to hide the Delete chip +
423    /// reject DELETE on the row. The default grants every row (true).
424    fn can_delete(&self, _snippet: &crate::snippet::Snippet) -> bool {
425        true
426    }
427
428    /// Cross-field validation hook. Called BEFORE save with the
429    /// form payload as a key/value map. Return `Err` with one or
430    /// more field-scoped error messages to fail the save and render
431    /// them inline. Defaults to "always ok".
432    fn validate(
433        &self,
434        _form: &std::collections::HashMap<String, String>,
435    ) -> Result<(), Vec<(String, String)>> {
436        Ok(())
437    }
438
439    /// Opt-in hook for the WP-style menu builder. Return a
440    /// list of [`MenuPickerEntry`] values to surface this library
441    /// type's snippets in the **Library** picker tab on the menu
442    /// edit screen. Each entry contributes a draggable picker card
443    /// that drops into the menu as an external-URL `MenuItem`.
444    ///
445    /// Default: empty — most library types (authors, callouts,
446    /// blocks) don't have a single canonical URL and shouldn't show
447    /// up in the menu picker. Override on types whose snippets
448    /// represent linkable resources (e.g. external partner sites,
449    /// downloadable docs, microsite shortcuts).
450    ///
451    /// # Errors
452    /// Driver errors from the snippet fetch when an implementation
453    /// queries the pool. The default returns `Ok(Vec::new())` so
454    /// implementors only opt-in when they have real data to surface.
455    async fn menu_picker_entries(
456        &self,
457        _pool: &rustango::sql::Pool,
458    ) -> Result<Vec<MenuPickerEntry>, rustango::sql::ExecError> {
459        Ok(Vec::new())
460    }
461
462    /// Async bulk-action dispatcher. Called when the list view
463    /// submits a bulk action. Returns the number of rows touched.
464    /// Default panics — handlers that declare [`Self::bulk_actions`]
465    /// MUST override this.
466    ///
467    /// # Errors
468    /// Driver errors from the underlying ORM calls.
469    async fn handle_bulk_action(
470        &self,
471        _pool: &rustango::sql::Pool,
472        action: &str,
473        _ids: &[i64],
474    ) -> Result<usize, rustango::sql::ExecError> {
475        unimplemented!(
476            "library type `{}` declared bulk actions but didn't override handle_bulk_action(); unknown action `{action}`",
477            self.type_name(),
478        )
479    }
480}
481
482/// Handler-registration entry submitted via `inventory::submit!`. The
483/// `factory` reconstructs the handler at runtime; mirrors
484/// `PageTypeHandlerRegistration`.
485pub struct LibraryTypeHandlerRegistration {
486    pub factory: fn() -> Box<dyn LibraryTypeHandler>,
487}
488
489inventory::collect!(LibraryTypeHandlerRegistration);
490
491/// Walk every `register_library_type!`-registered handler. Used by
492/// the seeder + admin to enumerate types at runtime.
493pub fn registered_handlers() -> impl Iterator<Item = Box<dyn LibraryTypeHandler>> {
494    inventory::iter::<LibraryTypeHandlerRegistration>
495        .into_iter()
496        .map(|r| (r.factory)())
497}
498
499/// Locate a handler by `type_name`. Returns `None` for unknown
500/// types — useful for the admin's lookup-then-route flow.
501#[must_use]
502pub fn find_handler(type_name: &str) -> Option<Box<dyn LibraryTypeHandler>> {
503    registered_handlers().find(|h| h.type_name() == type_name)
504}
505
506/// Seed `cms_library_type` rows for every registered handler across
507/// every active org. Wire into the same `Cli::seed` callback the
508/// page-type seeder uses.
509///
510/// # Errors
511/// Driver / tenancy errors from any tenant; short-circuits on the
512/// first failure (mirrors `ensure_seeded` for `PageType`).
513/// Upsert one `cms_library_type` row keyed by `type_name`. Exposed
514/// so `crate::seed::ensure_seeded` can share the seeding loop with
515/// `register_page_type!`.
516pub async fn ensure_library_type_row(
517    pool: &rustango::sql::Pool,
518    handler: &dyn LibraryTypeHandler,
519) -> Result<(), rustango::sql::ExecError> {
520    upsert_one(pool, handler).await
521}
522
523async fn upsert_one(
524    pool: &rustango::sql::Pool,
525    handler: &dyn LibraryTypeHandler,
526) -> Result<(), rustango::sql::ExecError> {
527    use rustango::core::Column as _;
528    use rustango::sql::FetcherPool as _;
529    let mut existing: Vec<LibraryType> = LibraryType::objects()
530        .where_(LibraryType::type_name.eq(handler.type_name().to_string()))
531        .fetch(pool)
532        .await?;
533    let extension_table = handler.extension_table().unwrap_or("").to_owned();
534    if let Some(mut row) = existing.pop() {
535        row.app_label = handler.app_label().to_owned();
536        row.verbose_name = handler.verbose_name().to_owned();
537        row.extension_table = extension_table;
538        row.save_pool(pool).await?;
539    } else {
540        let mut row = LibraryType {
541            id: Auto::Unset,
542            app_label: handler.app_label().to_owned(),
543            type_name: handler.type_name().to_owned(),
544            verbose_name: handler.verbose_name().to_owned(),
545            extension_table,
546            created_at: Auto::Unset,
547            updated_at: Auto::Unset,
548        };
549        row.insert_pool(pool).await?;
550    }
551    Ok(())
552}
553
554/// Register a library type at compile time. Pair with a
555/// `#[derive(Default)] impl LibraryTypeHandler` block. Mirrors
556/// [`crate::register_page_type!`].
557#[macro_export]
558macro_rules! register_library_type {
559    ($ty:ty) => {
560        $crate::inventory::submit! {
561            $crate::library::LibraryTypeHandlerRegistration {
562                factory: || ::std::boxed::Box::new(<$ty>::default()),
563            }
564        }
565    };
566}
567
568#[cfg(test)]
569mod menu_picker_entry_tests {
570    use super::*;
571
572    #[test]
573    fn serializes_with_optional_kind_hint() {
574        let e = MenuPickerEntry::new("Partner site", "https://partner.example.com")
575            .with_kind_hint("Partner");
576        let v = serde_json::to_value(&e).unwrap();
577        assert_eq!(v["label"], "Partner site");
578        assert_eq!(v["url"], "https://partner.example.com");
579        assert_eq!(v["kind_hint"], "Partner");
580    }
581
582    #[test]
583    fn omits_kind_hint_when_absent() {
584        let e = MenuPickerEntry::new("Docs", "https://docs.example.com");
585        let v = serde_json::to_value(&e).unwrap();
586        // serde defaults to `null` for `Option::None` — the template
587        // uses `e.kind_hint | default(value=e.library_type)` so null
588        // falls through to the library-type label.
589        assert!(v["kind_hint"].is_null());
590    }
591}