Skip to main content

rustango_cms/
page_type.rs

1//! Page types: the [`PageTypeHandler`] trait every page kind implements,
2//! its inventory registry ([`find_handler`], [`registered_handlers`]),
3//! and the editor-form types the handler returns ([`ExtensionField`],
4//! [`TabSpec`], [`InlinePanelSpec`], [`DisplayField`]).
5//!
6//! `#[derive(PageType)]` generates the handler and forwards the
7//! author-overridable hooks to [`PageTypeOverrides`].
8
9use async_trait::async_trait;
10use rustango::sql::{ExecError, Pool};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13
14/// Form-field metadata returned by [`PageTypeHandler::extension_fields`].
15/// The admin's page-edit form renders one input per entry under the
16/// "Content" section so authors can write into the type's extension
17/// table without leaving the editor.
18///
19/// Kept stable for back-compat with v0.x handler authors. Internally
20/// the admin converts to the richer [`crate::Widget`] before
21/// rendering — new handlers can also return `Widget`s directly via
22/// [`Self::from_widget`] for access to the full widget set (Date,
23/// Color, Choice, …).
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ExtensionField {
26    /// HTML form `name` — also the key on the form submission. Used
27    /// by [`PageTypeHandler::save_extension`] to pull the value back
28    /// out of the posted form.
29    pub name: String,
30    /// Display label for the input.
31    pub label: String,
32    /// Render hint — picks which widget the admin draws.
33    pub kind: ExtensionFieldKind,
34    /// Pre-fill value (the current row's value, when editing).
35    pub value: String,
36    /// Optional helptext shown below the input.
37    pub help: String,
38    /// Optional max length (string/text inputs only).
39    pub max_length: Option<u32>,
40}
41
42impl ExtensionField {
43    /// Convert into a [`crate::Widget`] — the unified widget
44    /// descriptor the admin renderer + the stream-block editor both
45    /// consume. `options` is left empty (the admin handler
46    /// populates it for `MediaPicker` widgets from the media
47    /// library).
48    #[must_use]
49    pub fn into_widget(self) -> crate::Widget {
50        crate::Widget {
51            name: self.name,
52            kind: self.kind.into(),
53            custom_name: String::new(),
54            custom_html: String::new(),
55            label: self.label,
56            value: self.value,
57            options: Vec::new(),
58            help: self.help,
59            placeholder: String::new(),
60            required: false,
61            min: None,
62            max: None,
63            step: None,
64            max_length: self.max_length,
65            min_length: None,
66            pattern: String::new(),
67            read_only: false,
68            allowed: Vec::new(),
69            variant: String::new(),
70        }
71    }
72
73    /// Wrap a [`crate::Widget`] back into the legacy
74    /// [`ExtensionField`] shape — useful for handlers that author
75    /// against the richer widget set but still want to return the
76    /// legacy `Vec<ExtensionField>`.
77    ///
78    /// `max_length`, `value`, `help`, `label`, `name` are preserved.
79    /// Widget kinds outside the legacy set
80    /// ([`ExtensionFieldKind`]'s six variants) downgrade to
81    /// [`ExtensionFieldKind::Text`] — handlers that need the full
82    /// set should switch to returning `Vec<Widget>` (a follow-up
83    /// trait method lands with the stream-block slice).
84    #[must_use]
85    pub fn from_widget(w: crate::Widget) -> Self {
86        let kind = ExtensionFieldKind::from_widget_kind(w.kind);
87        Self {
88            name: w.name,
89            label: w.label,
90            kind,
91            value: w.value,
92            help: w.help,
93            max_length: w.max_length,
94        }
95    }
96}
97
98/// Which admin widget to draw for an [`ExtensionField`].
99///
100/// Stable v0.x surface — six variants the original handler authors
101/// know. The full [`crate::WidgetKind`] (25+ kinds: Date, Color,
102/// Radio, Checkboxes, …) is reachable by returning [`crate::Widget`]
103/// instances directly. `ExtensionFieldKind` converts cleanly via
104/// `From` impls in both directions.
105#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
106#[serde(rename_all = "lowercase")]
107pub enum ExtensionFieldKind {
108    /// Single-line `<input type="text">`.
109    Text,
110    /// Multi-line `<textarea>` — plain content.
111    Textarea,
112    /// Multi-line `<textarea>` with a "preview as markdown" affordance.
113    /// Rendered through [`crate::markdown::render`] on the public site.
114    Markdown,
115    /// Media picker — value is the `cms_media.id` as a stringified
116    /// integer. Empty = no selection.
117    MediaPicker,
118    /// `<input type="number">` for integer-shaped fields.
119    Number,
120    /// `<input type="url">`.
121    Url,
122}
123
124impl ExtensionFieldKind {
125    /// Best-effort downgrade from the richer [`crate::WidgetKind`]
126    /// back to the v0.x six-variant surface. Out-of-set widgets
127    /// (Date, Color, Choice, …) downgrade to [`Self::Text`]; the
128    /// legacy mapping is lossless.
129    #[must_use]
130    pub fn from_widget_kind(k: crate::WidgetKind) -> Self {
131        use crate::WidgetKind as WK;
132        match k {
133            WK::Text => Self::Text,
134            WK::Textarea => Self::Textarea,
135            WK::Markdown => Self::Markdown,
136            WK::MediaPicker => Self::MediaPicker,
137            WK::Number | WK::Integer | WK::Float => Self::Number,
138            WK::Url => Self::Url,
139            _ => Self::Text,
140        }
141    }
142}
143
144impl From<ExtensionFieldKind> for crate::WidgetKind {
145    fn from(k: ExtensionFieldKind) -> Self {
146        match k {
147            ExtensionFieldKind::Text => Self::Text,
148            ExtensionFieldKind::Textarea => Self::Textarea,
149            ExtensionFieldKind::Markdown => Self::Markdown,
150            ExtensionFieldKind::MediaPicker => Self::MediaPicker,
151            ExtensionFieldKind::Number => Self::Number,
152            ExtensionFieldKind::Url => Self::Url,
153        }
154    }
155}
156
157/// The framework-default children listing, backing
158/// [`PageTypeHandler::children_query`]'s default: the same live children
159/// as [`published_children`].
160///
161/// It used to return every child, drafts included, into the public
162/// template context — so a fresh site listed unpublished titles to
163/// anonymous visitors. A type that really wants drafts listed
164/// overrides `children_query` with [`all_children`].
165///
166/// # Errors
167/// Driver / query failures from the page lookup.
168pub async fn default_children(
169    pool: &Pool,
170    page: &crate::page::Page,
171) -> Result<Vec<crate::page::Page>, ExecError> {
172    published_children(pool, page).await
173}
174
175/// Every immediate child, ordered `sort_order, id` — drafts, scheduled
176/// and expired pages included. For admin-side listings; never the
177/// public default.
178///
179/// # Errors
180/// Driver / query failures from the page lookup.
181pub async fn all_children(
182    pool: &Pool,
183    page: &crate::page::Page,
184) -> Result<Vec<crate::page::Page>, ExecError> {
185    use rustango::core::Column as _;
186    use rustango::sql::FetcherPool as _;
187    let id = page.id.get().copied().unwrap_or_default();
188    crate::page::Page::objects()
189        .where_(crate::page::Page::parent_id.eq(id))
190        .order_by(&[("sort_order", false), ("id", false)])
191        .fetch(pool)
192        .await
193}
194
195/// Immediate children a visitor can open right now, ordered
196/// `sort_order, id`: published and not expired, or scheduled and past
197/// go-live — the same rule the resolver serves by
198/// ([`crate::resolver::visible_now`]). Error pages are left out: they
199/// are served for a status code, not listed as content (as in
200/// `auto_menu`). The building block for an index/listing page's
201/// [`PageTypeHandler::children_query`] override.
202///
203/// # Errors
204/// Driver / query failures from the page lookup.
205pub async fn published_children(
206    pool: &Pool,
207    page: &crate::page::Page,
208) -> Result<Vec<crate::page::Page>, ExecError> {
209    use rustango::sql::FetcherPool as _;
210    published_children_qs(pool, page)
211        .await
212        .order_by(&[("sort_order", false), ("id", false)])
213        .fetch(pool)
214        .await
215}
216
217/// The [`published_children`] rows of `page`, unordered.
218async fn published_children_qs(
219    pool: &Pool,
220    page: &crate::page::Page,
221) -> rustango::query::QuerySet<crate::page::Page> {
222    use crate::page::{Page, PageStatus};
223    use rustango::core::Column as _;
224    let id = page.id.get().copied().unwrap_or_default();
225    let now = chrono::Utc::now();
226    // `resolver::visible_now`, in SQL so the limit counts only listed
227    // pages: published and not expired, or scheduled, past go-live and
228    // not expired.
229    let not_expired = || Page::expire_at.is_null().or(Page::expire_at.gt(now));
230    let mut qs = Page::objects()
231        .where_(Page::parent_id.eq(id))
232        .where_(
233            Page::status
234                .eq(PageStatus::Published.as_str().to_owned())
235                .and(not_expired())
236                .or(Page::status
237                    .eq(PageStatus::Scheduled.as_str().to_owned())
238                    .and(Page::go_live_at.lte(now))
239                    .and(not_expired())),
240        );
241    if let Some(tid) = crate::error_pages::error_page_type_id(pool).await {
242        qs = qs.where_(Page::page_type_id.ne(tid));
243    }
244    qs
245}
246
247/// How [`published_children_page`] orders a page's children.
248#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
249#[non_exhaustive]
250pub enum ChildOrder {
251    /// `sort_order, id` — the editor's arrangement, as in
252    /// [`published_children`].
253    #[default]
254    Position,
255    /// Newest `published_at` first, undated pages last; newer ids first
256    /// among equals. For a blog or news index.
257    NewestFirst,
258    /// Oldest `published_at` first, undated pages last; older ids first
259    /// among equals.
260    OldestFirst,
261}
262
263/// One window of a page's [`published_children`].
264#[derive(Debug, Clone, Default)]
265pub struct ChildrenPage {
266    /// The children in this window, in the requested order.
267    pub pages: Vec<crate::page::Page>,
268    /// How many live children the page has in all, for "page 2 of 7".
269    pub total: usize,
270}
271
272/// One window of the live children of `page`: the same rows as
273/// [`published_children`], ordered by `order`, counted and paged in SQL.
274///
275/// [`published_children`] reads every child. An index with hundreds of
276/// children should return a window from
277/// [`PageTypeHandler::children_query`] instead, so the renderer's
278/// follow-up reads (tags, translations, grandchildren) stay that size
279/// too; the next windows can be served from a [`PageTypeHandler::routes`]
280/// pattern such as `page/(?P<n>\d+)` through [`PageTypeHandler::route_context`].
281///
282/// ```ignore
283/// async fn children_query(&self, pool: &Pool, page: &Page)
284///     -> Result<Option<Vec<Page>>, ExecError>
285/// {
286///     let first = rustango_cms::published_children_page(
287///         pool, page, rustango_cms::ChildOrder::NewestFirst, 20, 0,
288///     ).await?;
289///     Ok(Some(first.pages))
290/// }
291/// ```
292///
293/// There is no default cap: a cap on the default `sort_order` listing
294/// would quietly drop a blog's newest posts, so the type chooses both the
295/// order and the size.
296///
297/// # Errors
298/// Driver / query failures from the count or the page lookup.
299pub async fn published_children_page(
300    pool: &Pool,
301    page: &crate::page::Page,
302    order: ChildOrder,
303    limit: usize,
304    offset: usize,
305) -> Result<ChildrenPage, ExecError> {
306    use rustango::core::NullsOrder;
307    use rustango::sql::{CounterPool as _, FetcherPool as _};
308    let qs = published_children_qs(pool, page).await;
309    let total = usize::try_from(qs.clone().count(pool).await?).unwrap_or_default();
310    let keys: &[(&'static str, bool, NullsOrder)] = match order {
311        ChildOrder::Position => &[
312            ("sort_order", false, NullsOrder::Default),
313            ("id", false, NullsOrder::Default),
314        ],
315        ChildOrder::NewestFirst => &[
316            ("published_at", true, NullsOrder::Last),
317            ("id", true, NullsOrder::Default),
318        ],
319        ChildOrder::OldestFirst => &[
320            ("published_at", false, NullsOrder::Last),
321            ("id", false, NullsOrder::Default),
322        ],
323    };
324    let pages = qs
325        .order_by_with_nulls(keys)
326        .limit(i64::try_from(limit).unwrap_or(i64::MAX))
327        // A huge offset must not wrap negative (backends differ).
328        .offset(i64::try_from(offset).unwrap_or(i64::MAX))
329        .fetch(pool)
330        .await?;
331    Ok(ChildrenPage { pages, total })
332}
333
334/// A page kind registered by user code (e.g. `BlogPostPage`, `LandingPage`).
335///
336/// Each impl owns the typed extension table that backs its kind, the
337/// template used to render it, its admin form, and the parent/child
338/// type whitelist.
339///
340/// **Registering.** Prefer `#[derive(PageType)]`, which emits this impl
341/// plus the inventory registration and forwards the overridable hooks
342/// to [`PageTypeOverrides`]. A hand-written impl registers with
343/// [`register_page_type!`](crate::register_page_type) and needs only the
344/// four required methods (`app_label`, `type_name`, `verbose_name`,
345/// `default_template`); every other hook has a no-op default.
346///
347/// **When hooks run.** Render hooks (`load_extension`, `public_context`,
348/// `children_query`, `routes` / `route_context`) run on every public
349/// request for a page of this type. Editor hooks (`widgets`,
350/// `extra_tabs`, `inline_panels`, `display_fields`) run on the admin
351/// edit form; `save_extension` / `save_inline_panel` on its POST, after
352/// the `cms_page` row is saved; `preview_extension` on live preview.
353///
354/// Handlers are process-global — instances are constructed via
355/// [`PageTypeHandlerRegistration::factory`] and live for the
356/// lifetime of the binary. The matching DB row in
357/// `cms_page_type` is per-tenant and seeded by
358/// [`crate::ensure_seeded`](crate::seed::ensure_seeded).
359#[async_trait]
360pub trait PageTypeHandler: Send + Sync + 'static {
361    /// Logical app this handler belongs to (e.g. `"cms_articles"`).
362    /// Lets multiple crates contribute page types without
363    /// `type_name` collisions, and groups them in the admin.
364    fn app_label(&self) -> &'static str;
365
366    /// Stable identifier — stored in `cms_page_type.type_name`. Must
367    /// be globally unique across the process.
368    fn type_name(&self) -> &'static str;
369
370    /// Human-readable label for the admin UI.
371    fn verbose_name(&self) -> &'static str;
372
373    /// Default Tera template path the renderer should use. A page can
374    /// override it per row via [`Page::template_override`](crate::Page::template_override).
375    fn default_template(&self) -> &'static str;
376
377    /// Page types that are allowed as a parent for instances of this
378    /// type. Empty slice = no restriction (the *child-side* guard).
379    fn allowed_parent_types(&self) -> &'static [&'static str] {
380        &[]
381    }
382
383    /// Page types that are allowed as direct children of instances of
384    /// this type. Empty slice = no restriction (the *parent-side*
385    /// guard). Symmetric with [`Self::allowed_parent_types`]: both
386    /// sides must agree at create / move time.
387    fn allowed_child_types(&self) -> &'static [&'static str] {
388        &[]
389    }
390
391    /// Whether this type is a **leaf** — it accepts no child pages at
392    /// all. Distinct from `allowed_child_types() == []`, which means "no
393    /// restriction" (any type may be a child). Returning `true` is the
394    /// first-class way to say "this page can't have children"
395    /// without the sentinel hack of whitelisting a
396    /// non-existent child type. Enforced parent-side at create / move
397    /// time.
398    fn is_leaf(&self) -> bool {
399        false
400    }
401
402    /// Whether this type may be created from the admin "Add page"
403    /// menu. Defaults to `true`; abstract / programmatically-only
404    /// types should override to `false`.
405    fn is_creatable(&self) -> bool {
406        true
407    }
408
409    /// Material-symbols icon name for the page-type picker tile.
410    /// Defaults to `None` — picker renders a generic glyph. Authors
411    /// set it via `#[page_type(icon = "article")]` on the
412    /// `#[derive(PageType)]` struct, or by overriding this method on
413    /// hand-rolled handlers.
414    fn icon(&self) -> Option<&'static str> {
415        None
416    }
417
418    /// One-line description shown under `verbose_name` in the
419    /// page-type picker. Defaults to `None`. Authors set it via
420    /// `#[page_type(description = "…")]`.
421    fn description(&self) -> Option<&'static str> {
422        None
423    }
424
425    /// Opt this page type in to a public RSS 2.0 / Atom 1.0 feed
426    /// (powered by [`rustango::syndication`]). The returned slug is
427    /// the URL path segment under `/feed/<slug>/rss.xml` +
428    /// `/feed/<slug>/atom.xml`; pick something URL-friendly and
429    /// distinct from other page types' slugs.
430    ///
431    /// Returning `None` (the default) means no feed is emitted for
432    /// this type — its pages still render normally; they just
433    /// don't appear in any aggregate feed.
434    ///
435    /// The feed lists every published, indexable [`crate::Page`]
436    /// row of this type in `published_at desc` order. See
437    /// [`crate::feed`] for the URL shape and content mapping.
438    fn feed_kind(&self) -> Option<&'static str> {
439        None
440    }
441
442    /// Opt this page type in to a multi-step approval workflow.
443    /// Returns the [`Workflow`](crate::workflow::Workflow) `name` of the workflow
444    /// to apply to pages of this type, or `None` to leave them on the
445    /// direct-publish path.
446    ///
447    /// When this returns `Some("Editorial review")`, the page editor
448    /// for pages of this type renders a Submit-for-review action
449    /// that creates a `cms_workflow_state` row and walks the page
450    /// through the workflow's tasks. Pages can only finish a
451    /// workflow once the final task is approved.
452    ///
453    /// The workflow with the returned name must exist + be active in
454    /// the tenant's `cms_workflow` table — admins create + manage
455    /// workflows at `/cms-admin/workflows`. If the named workflow
456    /// doesn't exist or is inactive, pages fall back to the
457    /// direct-publish path.
458    fn workflow_slug(&self) -> Option<&'static str> {
459        None
460    }
461
462    /// Gate every page of this type behind an access requirement — the
463    /// per-**type** analogue of the per-page Privacy tab. Return
464    /// `None` (the default) to leave the type public; return
465    /// [`crate::view_restriction::TypeViewRestriction::login`] to require
466    /// any authenticated member, or
467    /// [`crate::view_restriction::TypeViewRestriction::permission`] to
468    /// require one of a set of permission codenames (checked through the
469    /// framework permission engine).
470    ///
471    /// A page/subtree restriction set on an individual page (or an
472    /// ancestor) is more specific and overrides this type-level default.
473    /// The derive forwards to
474    /// [`PageTypeOverrides::view_restriction`] automatically.
475    fn view_restriction(&self) -> Option<crate::view_restriction::TypeViewRestriction> {
476        None
477    }
478
479    /// Which representation this type serves on its public URL.
480    ///
481    /// Defaults to [`crate::page_view::PageViewMode::Auto`], which
482    /// derives the answer from [`Self::default_template`]: a blank
483    /// template means the type is JSON-only, anything else means HTML.
484    /// Return [`crate::page_view::PageViewMode::Api`] to serve JSON at
485    /// the page's own URL under `Accept: application/json` even when a
486    /// template exists — the template still answers browsers.
487    ///
488    /// Set it declaratively with `#[page_type(view_mode = "api")]`,
489    /// which also makes the otherwise-mandatory `template` attribute
490    /// optional. Without the attribute the derive forwards to
491    /// [`PageTypeOverrides::view_mode`].
492    fn view_mode(&self) -> crate::page_view::PageViewMode {
493        crate::page_view::PageViewMode::Auto
494    }
495
496    /// Load the typed extension row for a given page id and return
497    /// it as JSON for the renderer's Tera context.
498    ///
499    /// The default implementation returns `Value::Null` — types
500    /// with no extension table (e.g. a `HomePage` whose data lives
501    /// entirely on the base Page row) get a null `extension` value
502    /// in the template context.
503    ///
504    /// # Errors
505    /// Driver / query failures from the extension lookup.
506    async fn load_extension(&self, _pool: &Pool, _page_id: i64) -> Result<Value, ExecError> {
507        Ok(Value::Null)
508    }
509
510    /// URL patterns this page type serves IN ADDITION to its
511    /// canonical `url_path`.
512    ///
513    /// Each [`crate::routable::RouteSpec`] declares a regex pattern
514    /// (matched against the suffix BELOW the page's `url_path`) and
515    /// a stable name. When the public resolver can't find an exact
516    /// `url_path` match it walks ancestor candidates and asks each
517    /// candidate's handler whether any of its routes accept the
518    /// remaining suffix. On match, the renderer dispatches to
519    /// [`Self::route_context`] for handler-injected ctx, and the
520    /// matched [`crate::routable::RouteMatch`] is exposed to the
521    /// template as `route_name` + `route_captures`.
522    ///
523    /// Default: empty — page types without routable patterns pay
524    /// nothing.
525    fn routes(&self) -> Vec<crate::routable::RouteSpec> {
526        Vec::new()
527    }
528
529    /// Handler-computed ctx injected when a routable pattern matched.
530    /// Mirrors [`Self::public_context`] but receives the matched
531    /// route's name + named capture groups. Override to load
532    /// route-specific data — the year's posts when `archive_year`
533    /// matched, the tagged posts when `tag` matched, etc.
534    ///
535    /// Default returns an empty map; the renderer still threads
536    /// `route_name` and `route_captures` into the context so a
537    /// handler that only needs the captures (no extra fetches) can
538    /// stay on the default.
539    ///
540    /// # Errors
541    /// Driver / query failures from the route-specific computation.
542    async fn route_context(
543        &self,
544        _pool: &Pool,
545        _page: &crate::page::Page,
546        _matched: &crate::routable::RouteMatch,
547    ) -> Result<serde_json::Map<String, Value>, ExecError> {
548        Ok(serde_json::Map::new())
549    }
550
551    /// What a matched routable pattern renders: the usual template, a
552    /// template of its own ([`crate::routable::RouteOutcome::Template`]),
553    /// or the site's 404 page when the record the URL names does not
554    /// exist ([`crate::routable::RouteOutcome::NotFound`]). Receives the
555    /// map [`Self::route_context`] returned, so the choice can depend on
556    /// loaded data (one template per kind of record, a missing id).
557    fn route_outcome(
558        &self,
559        _matched: &crate::routable::RouteMatch,
560        _route_ctx: &serde_json::Map<String, Value>,
561    ) -> crate::routable::RouteOutcome {
562        crate::routable::RouteOutcome::Render
563    }
564
565    /// Inject handler-computed values into the public render's Tera
566    /// context, for hand-rolled
567    /// data — e.g. a `HomePage` that exposes a `latest_posts` list
568    /// to its template without baking the query into the template
569    /// layer.
570    ///
571    /// The default returns an empty map; override in
572    /// [`PageTypeOverrides`] (or hand-rolled handlers) to surface
573    /// extras. Framework keys (`page`, `page_type`, `extension`,
574    /// `children`, `ancestors`, `url_prefix`, `locale`,
575    /// `translations`, `theme_*`, `_snippets_html`, `_stream_html`,
576    /// `_pages_by_id`) are stamped AFTER the handler's keys, so
577    /// `public_context` can't shadow them — pick distinct names
578    /// for custom keys.
579    ///
580    /// # Errors
581    /// Driver / query failures from the handler-side computation.
582    async fn public_context(
583        &self,
584        _pool: &Pool,
585        _page: &crate::page::Page,
586    ) -> Result<serde_json::Map<String, Value>, ExecError> {
587        Ok(serde_json::Map::new())
588    }
589
590    /// Build the `children` ctx var the public renderer hands to the
591    /// page template — index-style pages (a blog index, an archive)
592    /// lean on this to choose which children they list and in what
593    /// order.
594    ///
595    /// The default is [`published_children`]: the live children, ordered
596    /// `sort_order, id`, all of them. A type with many children should
597    /// return one window from [`published_children_page`] instead, which
598    /// also takes the order; the renderer's follow-up reads (tags,
599    /// translations, grandchildren) are sized by what this returns.
600    ///
601    /// The result lands in two places in the template context:
602    /// `children` (the typed list) AND a thread-local backing the
603    /// `children_filtered(...)` Tera function (see [`crate::children_filtered`]),
604    /// which filters and limits this list in memory.
605    ///
606    /// # Errors
607    /// Driver / query failures from the page lookup.
608    async fn children_query(
609        &self,
610        pool: &Pool,
611        page: &crate::page::Page,
612    ) -> Result<Vec<crate::page::Page>, ExecError> {
613        default_children(pool, page).await
614    }
615
616    /// Describe the extension-row's fields so the admin page-editor
617    /// can render a form section for them. The default returns an
618    /// empty list — types without an extension table get no extra
619    /// inputs in the editor.
620    ///
621    /// `page_id` is provided so handlers can pre-fill values from
622    /// the existing row (the typical impl: load the row, then map
623    /// each column into an `ExtensionField` with `value`).
624    ///
625    /// # Errors
626    /// Driver / query failures from the extension lookup.
627    async fn extension_fields(
628        &self,
629        _pool: &Pool,
630        _page_id: i64,
631    ) -> Result<Vec<ExtensionField>, ExecError> {
632        Ok(Vec::new())
633    }
634
635    /// Rich-widget alternative to [`Self::extension_fields`].
636    /// Returns full [`crate::Widget`] instances so handlers can
637    /// expose the entire 26-kind widget catalog (Date, DatetimeTz,
638    /// Color, Range, Radio, Select, Checkboxes, MultiSelect,
639    /// Custom, …) instead of being limited to the legacy six
640    /// [`ExtensionFieldKind`] variants.
641    ///
642    /// Default impl delegates to [`Self::extension_fields`] +
643    /// [`ExtensionField::into_widget`], so handlers that haven't
644    /// overridden this method keep working unchanged. Handlers
645    /// that want the new kinds override `widgets` instead of
646    /// `extension_fields`; the admin form-render path always calls
647    /// `widgets`, so a single override surfaces every kind in the
648    /// editor at once.
649    ///
650    /// # Errors
651    /// Driver / query failures propagated from the handler-side
652    /// computation.
653    async fn widgets(&self, pool: &Pool, page_id: i64) -> Result<Vec<crate::Widget>, ExecError> {
654        Ok(self
655            .extension_fields(pool, page_id)
656            .await?
657            .into_iter()
658            .map(ExtensionField::into_widget)
659            .collect())
660    }
661
662    /// Declared Page↔Snippet many-to-many relations as
663    /// `(relation_name, snippet_type)` pairs. Macro-generated
664    /// from the struct-level `#[page_type(snippet_m2m(name = "Type", …))]`
665    /// attribute; the default is none. The public renderer resolves each
666    /// relation's chosen rows into `snippet_relations.<name>` so templates
667    /// can iterate the related snippets.
668    fn snippet_m2m_relations(&self) -> Vec<(&'static str, &'static str)> {
669        Vec::new()
670    }
671
672    /// Build a virtual extension `Value` from a posted form `HashMap`
673    /// without touching the persisted row. Powers the "preview
674    /// unsaved changes" iframe in the page editor — the renderer
675    /// substitutes the result for [`Self::load_extension`] so the
676    /// preview reflects the current form state.
677    ///
678    /// Default impl walks [`Self::widgets`] and maps each widget's
679    /// `name` to the form value, with kind-aware coercion (booleans
680    /// from `"on"`/`"true"`, multi-value kinds parsed as JSON arrays,
681    /// numeric kinds parsed into `serde_json::Number`). Handlers
682    /// whose persisted shape differs from the widget surface should
683    /// override.
684    ///
685    /// # Errors
686    /// Driver / query failures from the widgets lookup (the
687    /// form-to-JSON mapping itself is infallible).
688    async fn preview_extension(
689        &self,
690        pool: &Pool,
691        page_id: i64,
692        form: &std::collections::HashMap<String, String>,
693    ) -> Result<Value, ExecError> {
694        let widgets = self.widgets(pool, page_id).await.unwrap_or_default();
695        let mut map = serde_json::Map::new();
696        for w in widgets {
697            let raw = form.get(&w.name).map(String::as_str).unwrap_or_default();
698            // One coercion table for page fields and builder fields (#660).
699            let val = crate::page_builder::values::coerce(w.kind, raw);
700            map.insert(w.name, val);
701        }
702        Ok(Value::Object(map))
703    }
704
705    /// Persist the posted form values into this type's extension
706    /// table. Called by the admin's page-edit POST handler after the
707    /// canonical `cms_page` row has been saved. Upsert keyed on
708    /// `page_id` is the standard pattern.
709    ///
710    /// `form` is the full form HashMap; handlers should pull out
711    /// only the keys whose `name` they returned from
712    /// [`Self::extension_fields`].
713    ///
714    /// # Errors
715    /// Driver / query failures from the upsert.
716    async fn save_extension(
717        &self,
718        _pool: &Pool,
719        _page_id: i64,
720        _form: &std::collections::HashMap<String, String>,
721    ) -> Result<(), ExecError> {
722        Ok(())
723    }
724
725    /// Handler-contributed tabs appended to the page-editor's tab
726    /// strip after the built-in `Content` / `Promote` / `Theme` /
727    /// `Revisions` ones. Each [`TabSpec`] carries a stable `name`
728    /// (used in the URL hash + localStorage for "remember last
729    /// active tab"), a `label`, an optional Material-symbols `icon`
730    /// + small `badge` chip, and a pre-rendered HTML body the
731    /// admin template emits inside the main `<form>`.
732    ///
733    /// Because custom tab bodies sit inside the canonical form, any
734    /// `<input name="…">` inside one shows up in the
735    /// `HashMap<String, String>` handed to [`Self::save_extension`]
736    /// — handlers can persist tab-scoped fields the same way they
737    /// persist [`Self::widgets`] entries.
738    ///
739    /// Default impl returns an empty list — the built-in tabs are
740    /// always present and self-contained, so handlers that don't
741    /// need a custom tab pay nothing.
742    ///
743    /// # Errors
744    /// Driver / query failures from the handler-side computation.
745    async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
746        Ok(Vec::new())
747    }
748
749    /// Inline panels — 1-N collections of sub-rows that the page
750    /// editor renders as a sortable list of cards. Each [`InlinePanelSpec`] declares the panel's
751    /// stable `name`, the human `label`, the per-row `fields`, and
752    /// optional cardinality bounds.
753    ///
754    /// Default impl returns an empty list — handlers that don't use
755    /// inline panels pay nothing. Handlers that do override this
756    /// method must also implement [`Self::load_inline_panel`] and
757    /// [`Self::save_inline_panel`] for the rows to round-trip.
758    ///
759    /// Async with the pool and the page (`0` for a page not saved yet), so
760    /// a panel can take its options or its locks from the database.
761    ///
762    /// # Errors
763    /// Driver / query failures building the specs.
764    async fn inline_panels(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<InlinePanelSpec>, ExecError> {
765        Ok(Vec::new())
766    }
767
768    /// Fetch existing rows for `panel_name` keyed under `page_id`.
769    /// Each returned `serde_json::Map` is one row; keys match the
770    /// `name` of the [`InlinePanelSpec::fields`] entries.
771    ///
772    /// Default impl returns an empty list.
773    ///
774    /// # Errors
775    /// Driver / query failures from the row lookup.
776    async fn load_inline_panel(
777        &self,
778        _pool: &Pool,
779        _page_id: i64,
780        _panel_name: &str,
781    ) -> Result<Vec<serde_json::Map<String, Value>>, ExecError> {
782        Ok(Vec::new())
783    }
784
785    /// Persist the posted rows for `panel_name` under `page_id`. The
786    /// admin POST handler parses inline-panel form keys
787    /// (`inline__<panel_name>__<row_idx>__<field>`) into row dicts
788    /// and calls this with the full set; the handler is responsible
789    /// for the upsert / delete-removed semantics. Sort order is the
790    /// position in the `rows` slice.
791    ///
792    /// Default impl is a no-op.
793    ///
794    /// # Errors
795    /// Driver / query failures from the upsert.
796    async fn save_inline_panel(
797        &self,
798        _pool: &Pool,
799        _page_id: i64,
800        _panel_name: &str,
801        _rows: &[serde_json::Map<String, Value>],
802    ) -> Result<(), ExecError> {
803        Ok(())
804    }
805
806    /// Per-row panels: each row's id and title, in order. See
807    /// [`InlinePanelSpec::per_row`](InlinePanelSpec#structfield.per_row).
808    ///
809    /// # Errors
810    /// Driver / query failures.
811    async fn inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str) -> Result<Vec<InlineRowSummary>, ExecError> {
812        Ok(Vec::new())
813    }
814
815    /// Per-row panels: one row's values, keyed by widget name (`None` id:
816    /// a new row's starting values). `Ok(None)`: no such row on this page.
817    ///
818    /// # Errors
819    /// Driver / query failures.
820    async fn inline_row(
821        &self,
822        _pool: &Pool,
823        _page_id: i64,
824        _panel: &str,
825        _row_id: Option<i64>,
826    ) -> Result<Option<serde_json::Map<String, Value>>, ExecError> {
827        Ok(None)
828    }
829
830    /// Per-row panels: store one row from its posted values (`None` id:
831    /// add it). Values arrive as the browser posts them; an unchecked
832    /// switch is absent.
833    ///
834    /// # Errors
835    /// Driver / query failures (validation problems are `Invalid`).
836    async fn save_inline_row(
837        &self,
838        _pool: &Pool,
839        _page_id: i64,
840        _panel: &str,
841        _row_id: Option<i64>,
842        _values: &serde_json::Map<String, Value>,
843    ) -> Result<InlineRowSaved, ExecError> {
844        Ok(InlineRowSaved::Invalid(vec![crate::admin::cms_admin::FieldError::new("_form", "This panel can't be saved.")]))
845    }
846
847    /// Per-row panels: remove one row. `Ok(false)`: refused.
848    ///
849    /// # Errors
850    /// Driver / query failures.
851    async fn delete_inline_row(&self, _pool: &Pool, _page_id: i64, _panel: &str, _row_id: i64) -> Result<bool, ExecError> {
852        Ok(false)
853    }
854
855    /// Per-row panels: store a new order (`ids` first to last).
856    ///
857    /// # Errors
858    /// Driver / query failures.
859    async fn reorder_inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str, _ids: &[i64]) -> Result<(), ExecError> {
860        Ok(())
861    }
862
863    /// Computed / display-only fields shown in an "At a glance"
864    /// panel at the top of the page-edit form. Each entry is a
865    /// pre-rendered HTML chip (the value is `| safe`d into the
866    /// template) authored by the handler from arbitrary data:
867    /// row counts, word counts, derived flags, audit timestamps,
868    /// linked-snippet previews, etc.
869    ///
870    /// This is the first-class hook for read-only computed values
871    /// in the editor (static help text and plain model fields can't
872    /// show them).
873    /// `display_fields` runs at edit-form GET, so each value is
874    /// recomputed every load and reflects the latest DB state.
875    ///
876    /// Default impl returns an empty list — handlers that don't
877    /// need it pay nothing.
878    ///
879    /// # Errors
880    /// Driver / query failures from any computation the handler
881    /// runs against the pool.
882    async fn display_fields(
883        &self,
884        _pool: &Pool,
885        _page_id: i64,
886    ) -> Result<Vec<DisplayField>, ExecError> {
887        Ok(Vec::new())
888    }
889}
890
891/// One computed display chip rendered in the page-edit form's "At
892/// a glance" panel. See [`PageTypeHandler::display_fields`].
893///
894/// `html` is trusted — emitted through `| safe` in the bundled
895/// template. Handlers escape user-controlled content themselves
896/// (e.g. via `tera::escape_html` or by passing through
897/// [`crate::markdown::render`] which sanitizes).
898#[derive(Debug, Clone, Serialize, Deserialize)]
899pub struct DisplayField {
900    /// Short label, e.g. "Word count" or "Last edited".
901    pub label: String,
902    /// Pre-rendered HTML fragment. Emitted with `| safe`.
903    pub html: String,
904    /// Optional helptext shown beneath the value.
905    #[serde(default, skip_serializing_if = "String::is_empty")]
906    pub help: String,
907    /// Optional material-symbols icon name shown next to the label
908    /// (e.g. `"format_list_numbered"`, `"schedule"`).
909    #[serde(default, skip_serializing_if = "Option::is_none")]
910    pub icon: Option<String>,
911}
912
913impl DisplayField {
914    /// Smallest possible chip — just `(label, html)`. Caller adds
915    /// `help` / `icon` fluently if needed.
916    #[must_use]
917    pub fn new(label: impl Into<String>, html: impl Into<String>) -> Self {
918        Self {
919            label: label.into(),
920            html: html.into(),
921            help: String::new(),
922            icon: None,
923        }
924    }
925
926    #[must_use]
927    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
928        self.icon = Some(icon.into());
929        self
930    }
931
932    #[must_use]
933    pub fn with_help(mut self, help: impl Into<String>) -> Self {
934        self.help = help.into();
935        self
936    }
937}
938
939/// How a custom tab's body is supplied. Three shapes:
940///
941/// - `Html(s)` — pre-rendered HTML (backwards-compatible escape
942///   hatch; what `TabSpec::new(..., html)` produces).
943/// - `Template { path, context }` — a Tera template path + a
944///   per-tab context map. The page editor renders the template
945///   server-side with the standard admin chrome context PLUS the
946///   spec's own `context` map merged in, and drops the resulting
947///   HTML into the tab panel.
948/// - `Widgets(widgets)` — declarative form fields. The editor
949///   renders each [`crate::Widget`] via the same `_widget.html`
950///   macro the Content tab's main stack uses, so widget visuals +
951///   behavior stay identical wherever they appear.
952#[derive(Debug, Clone, Serialize, Deserialize)]
953#[serde(rename_all = "snake_case")]
954pub enum TabBody {
955    Html(String),
956    Template {
957        path: String,
958        #[serde(default)]
959        context: serde_json::Map<String, serde_json::Value>,
960    },
961    Widgets(Vec<crate::widget::Widget>),
962    /// Field group panel. Groups widgets
963    /// under a heading; `layout` picks vertical stack vs side-by-side.
964    /// Optional `help` renders as a hint paragraph between the
965    /// heading and the field grid.
966    Group {
967        heading: String,
968        #[serde(default, skip_serializing_if = "String::is_empty")]
969        help: String,
970        #[serde(default)]
971        layout: PanelLayout,
972        widgets: Vec<crate::widget::Widget>,
973    },
974    /// Help panel. Static informational block — no form
975    /// fields. The body is HTML emitted via `| safe` after CMS-side
976    /// authoring; trust source is the handler author.
977    Help {
978        content: String,
979    },
980}
981
982/// Layout direction for [`TabBody::Group`].
983#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
984#[serde(rename_all = "snake_case")]
985pub enum PanelLayout {
986    /// Stack widgets vertically (default).
987    #[default]
988    Column,
989    /// Lay widgets out side-by-side (responsive flex; collapses to
990    /// column on narrow viewports).
991    Row,
992}
993
994impl PanelLayout {
995    /// CSS class suffix — used by `_panel_group.html` to switch the
996    /// flex direction.
997    #[must_use]
998    pub fn class_suffix(self) -> &'static str {
999        match self {
1000            Self::Column => "column",
1001            Self::Row => "row",
1002        }
1003    }
1004}
1005
1006/// One inline panel declaration — a 1-N relation between the page
1007/// and a child table the handler maintains. See
1008/// [`PageTypeHandler::inline_panels`]. The admin editor renders each row
1009/// as a card of widgets (any [`crate::Widget`] kind: selects, switches,
1010/// the media chooser…) with add, remove and move up / down, in the
1011/// Content tab or in a tab of its own ([`Self::in_tab`]).
1012///
1013/// Every row carries its `id` (when the loaded row has one) in a hidden
1014/// field, so [`PageTypeHandler::save_inline_panel`] can tell existing
1015/// rows from new ones. A loaded row's `__title` key, when set, is shown
1016/// as the card's heading.
1017#[derive(Debug, Clone, Serialize, Deserialize)]
1018pub struct InlinePanelSpec {
1019    /// Stable identifier — used in form field names
1020    /// (`inline__<name>__<row>__<field>`). Snake_case conventional.
1021    pub name: String,
1022    /// Visible label shown above the panel.
1023    pub label: String,
1024    /// Per-row field surface. Each entry renders one input per row.
1025    pub fields: Vec<ExtensionField>,
1026    /// Optional minimum row count (inclusive). When set + the editor
1027    /// submits fewer rows, the save handler logs a warning but
1028    /// doesn't reject — handlers enforce hard rules themselves.
1029    #[serde(default, skip_serializing_if = "Option::is_none")]
1030    pub min_num: Option<usize>,
1031    /// Optional maximum row count (inclusive).
1032    #[serde(default, skip_serializing_if = "Option::is_none")]
1033    pub max_num: Option<usize>,
1034    /// Optional helptext shown beneath the panel header.
1035    #[serde(default, skip_serializing_if = "String::is_empty")]
1036    pub help: String,
1037    /// Optional material-symbols icon name.
1038    #[serde(default, skip_serializing_if = "Option::is_none")]
1039    pub icon: Option<String>,
1040    /// Per-row widgets. When non-empty they replace [`Self::fields`],
1041    /// giving rows every widget kind. Names are the row keys.
1042    #[serde(default)]
1043    pub widgets: Vec<crate::widget::Widget>,
1044    /// Render the panel in its own editor tab with this label instead
1045    /// of the Content tab. Panels naming the same tab share it.
1046    #[serde(default, skip_serializing_if = "Option::is_none")]
1047    pub tab: Option<String>,
1048    /// What one row is called, e.g. "Cause" (the add button reads
1049    /// "Add cause").
1050    #[serde(default)]
1051    pub row_label: String,
1052    /// Editors may add rows.
1053    #[serde(default = "yes")]
1054    pub can_add: bool,
1055    /// Editors may remove rows.
1056    #[serde(default = "yes")]
1057    pub can_delete: bool,
1058    /// Editors may reorder rows (the saved order is the row order).
1059    #[serde(default = "yes")]
1060    pub can_order: bool,
1061    /// Per-row mode: the tab lists only each row's title; a card's fields
1062    /// load when it is opened, it saves with its own Save button, and add,
1063    /// remove and reorder take effect at once. The page's Save sends
1064    /// nothing for this panel. Uses the `*_inline_row*` hooks instead of
1065    /// [`PageTypeHandler::load_inline_panel`] / `save_inline_panel`. For
1066    /// panels with many rows.
1067    #[serde(default)]
1068    pub per_row: bool,
1069}
1070
1071/// One row of a per-row inline panel, as its card header shows it.
1072#[derive(Debug, Clone, Serialize, Deserialize)]
1073pub struct InlineRowSummary {
1074    pub id: i64,
1075    pub title: String,
1076}
1077
1078/// What [`PageTypeHandler::save_inline_row`] did.
1079#[derive(Debug, Clone)]
1080pub enum InlineRowSaved {
1081    /// Stored; the row's id and the title its card should show.
1082    Saved { id: i64, title: String },
1083    /// Not stored: one message per field (`"_form"` for the whole row).
1084    Invalid(Vec<crate::admin::cms_admin::FieldError>),
1085}
1086
1087fn yes() -> bool {
1088    true
1089}
1090
1091impl InlinePanelSpec {
1092    /// Smallest valid spec — `(name, label, fields)`. Helpers below
1093    /// add `min` / `max` / `help` / `icon` fluently.
1094    #[must_use]
1095    pub fn new(
1096        name: impl Into<String>,
1097        label: impl Into<String>,
1098        fields: Vec<ExtensionField>,
1099    ) -> Self {
1100        Self {
1101            name: name.into(),
1102            label: label.into(),
1103            fields,
1104            min_num: None,
1105            max_num: None,
1106            help: String::new(),
1107            icon: None,
1108            widgets: Vec::new(),
1109            tab: None,
1110            row_label: String::new(),
1111            can_add: true,
1112            can_delete: true,
1113            can_order: true,
1114            per_row: false,
1115        }
1116    }
1117
1118    /// Per-row mode — see [`Self::per_row`](InlinePanelSpec#structfield.per_row).
1119    #[must_use]
1120    pub fn per_row(mut self) -> Self {
1121        self.per_row = true;
1122        self
1123    }
1124
1125    /// A panel whose rows are full widgets — see [`Self::widgets`].
1126    #[must_use]
1127    pub fn with_widgets(
1128        name: impl Into<String>,
1129        label: impl Into<String>,
1130        widgets: Vec<crate::widget::Widget>,
1131    ) -> Self {
1132        let mut spec = Self::new(name, label, Vec::new());
1133        spec.widgets = widgets;
1134        spec
1135    }
1136
1137    /// Show the panel in its own editor tab labelled `tab`.
1138    #[must_use]
1139    pub fn in_tab(mut self, tab: impl Into<String>) -> Self {
1140        self.tab = Some(tab.into());
1141        self
1142    }
1143
1144    /// Name one row, e.g. "Cause".
1145    #[must_use]
1146    pub fn with_row_label(mut self, label: impl Into<String>) -> Self {
1147        self.row_label = label.into();
1148        self
1149    }
1150
1151    /// Which row operations editors get. A panel whose rows another
1152    /// system owns sets `add` and `delete` to `false`.
1153    #[must_use]
1154    pub fn allow(mut self, add: bool, delete: bool, order: bool) -> Self {
1155        self.can_add = add;
1156        self.can_delete = delete;
1157        self.can_order = order;
1158        self
1159    }
1160
1161    /// The widgets one row renders: [`Self::widgets`], or the legacy
1162    /// [`Self::fields`] converted.
1163    #[must_use]
1164    pub fn row_widgets(&self) -> Vec<crate::widget::Widget> {
1165        if self.widgets.is_empty() {
1166            self.fields.iter().cloned().map(ExtensionField::into_widget).collect()
1167        } else {
1168            self.widgets.clone()
1169        }
1170    }
1171
1172    #[must_use]
1173    pub fn with_min(mut self, min: usize) -> Self {
1174        self.min_num = Some(min);
1175        self
1176    }
1177
1178    #[must_use]
1179    pub fn with_max(mut self, max: usize) -> Self {
1180        self.max_num = Some(max);
1181        self
1182    }
1183
1184    #[must_use]
1185    pub fn with_help(mut self, help: impl Into<String>) -> Self {
1186        self.help = help.into();
1187        self
1188    }
1189
1190    #[must_use]
1191    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
1192        self.icon = Some(icon.into());
1193        self
1194    }
1195}
1196
1197/// One handler-contributed tab appended to the page-editor's
1198/// built-in tab strip (Content / Promote / Theme / Revisions). See
1199/// [`PageTypeHandler::extra_tabs`].
1200///
1201/// The body is one of [`TabBody::Html`] (pre-rendered HTML — the
1202/// escape hatch), [`TabBody::Template`] (Tera template path + extra
1203/// context — render with the standard admin context vars in scope),
1204/// or [`TabBody::Widgets`] (declarative widget list — rendered via
1205/// `_widget.html` so the form fields look identical to the Content
1206/// tab's stack).
1207///
1208/// Inputs declared inside the rendered HTML land in
1209/// [`PageTypeHandler::save_extension`]'s form HashMap automatically;
1210/// every variant lives inside the page-edit `<form>`.
1211///
1212/// `name` must be unique within a page's tab set. Mixing with the
1213/// built-in names (`content`, `promote`, `theme`, `revisions`) is
1214/// allowed and lets a handler override the BUILT-IN tab body without
1215/// forking the template; the tab JS keys off `data-tab-trigger="<name>"`
1216/// so identical names render the same panel.
1217#[derive(Debug, Clone, Serialize, Deserialize)]
1218pub struct TabSpec {
1219    /// Stable identifier — kebab-case is conventional. Used for
1220    /// `aria-controls`, URL hash links, and the per-page localStorage
1221    /// "remember last active tab" key.
1222    pub name: String,
1223    /// Visible label on the tab button.
1224    pub label: String,
1225    /// Optional Material-symbols icon name (e.g. `"workflow"`,
1226    /// `"insights"`). Rendered to the left of `label`.
1227    #[serde(default, skip_serializing_if = "Option::is_none")]
1228    pub icon: Option<String>,
1229    /// Optional small chip rendered after `label` (e.g. an unread
1230    /// count, "new", or a small status indicator).
1231    #[serde(default, skip_serializing_if = "Option::is_none")]
1232    pub badge: Option<String>,
1233    /// What goes inside the tab panel — see [`TabBody`].
1234    pub body: TabBody,
1235}
1236
1237impl TabSpec {
1238    /// Smallest possible spec — just `(name, label, html)`. The
1239    /// `html` is treated as pre-rendered + emitted via Tera's
1240    /// `| safe`. Backwards-compatible with the v0.2 surface.
1241    #[must_use]
1242    pub fn new(name: impl Into<String>, label: impl Into<String>, html: impl Into<String>) -> Self {
1243        Self {
1244            name: name.into(),
1245            label: label.into(),
1246            icon: None,
1247            badge: None,
1248            body: TabBody::Html(html.into()),
1249        }
1250    }
1251
1252    /// Tera-template-backed tab. The renderer mounts `path` with the
1253    /// standard admin context plus the per-tab context map (empty
1254    /// until filled with [`Self::with_context_value`]). Example:
1255    /// `TabSpec::template("seo", "SEO", "blog/seo_tab.html")`.
1256    #[must_use]
1257    pub fn template(
1258        name: impl Into<String>,
1259        label: impl Into<String>,
1260        path: impl Into<String>,
1261    ) -> Self {
1262        Self {
1263            name: name.into(),
1264            label: label.into(),
1265            icon: None,
1266            badge: None,
1267            body: TabBody::Template {
1268                path: path.into(),
1269                context: serde_json::Map::new(),
1270            },
1271        }
1272    }
1273
1274    /// Widget-group-backed tab. Same rendering pipeline the Content
1275    /// tab uses — each widget is emitted via `_widget.html`'s macro.
1276    /// Inputs submit alongside the page-edit form so the handler's
1277    /// [`PageTypeHandler::save_extension`] picks them up by name.
1278    #[must_use]
1279    pub fn widgets(
1280        name: impl Into<String>,
1281        label: impl Into<String>,
1282        widgets: Vec<crate::widget::Widget>,
1283    ) -> Self {
1284        Self {
1285            name: name.into(),
1286            label: label.into(),
1287            icon: None,
1288            badge: None,
1289            body: TabBody::Widgets(widgets),
1290        }
1291    }
1292
1293    /// Field-group tab — heading + (optional help) +
1294    /// widgets stacked under one section. Use [`Self::with_layout`]
1295    /// to switch to row layout.
1296    #[must_use]
1297    pub fn group(
1298        name: impl Into<String>,
1299        label: impl Into<String>,
1300        heading: impl Into<String>,
1301        widgets: Vec<crate::widget::Widget>,
1302    ) -> Self {
1303        Self {
1304            name: name.into(),
1305            label: label.into(),
1306            icon: None,
1307            badge: None,
1308            body: TabBody::Group {
1309                heading: heading.into(),
1310                help: String::new(),
1311                layout: PanelLayout::Column,
1312                widgets,
1313            },
1314        }
1315    }
1316
1317    /// Help tab — static HTML content, no form fields.
1318    /// The body is emitted via `| safe`, so authors control the markup.
1319    #[must_use]
1320    pub fn help(
1321        name: impl Into<String>,
1322        label: impl Into<String>,
1323        content: impl Into<String>,
1324    ) -> Self {
1325        Self {
1326            name: name.into(),
1327            label: label.into(),
1328            icon: None,
1329            badge: None,
1330            body: TabBody::Help {
1331                content: content.into(),
1332            },
1333        }
1334    }
1335
1336    /// Switch a Group-body tab to a different layout. No-op on other
1337    /// body variants.
1338    #[must_use]
1339    pub fn with_layout(mut self, layout: PanelLayout) -> Self {
1340        if let TabBody::Group {
1341            layout: ref mut existing,
1342            ..
1343        } = self.body
1344        {
1345            *existing = layout;
1346        }
1347        self
1348    }
1349
1350    /// Attach help text to a Group-body tab. No-op on other body
1351    /// variants.
1352    #[must_use]
1353    pub fn with_help(mut self, help: impl Into<String>) -> Self {
1354        if let TabBody::Group {
1355            help: ref mut existing,
1356            ..
1357        } = self.body
1358        {
1359            *existing = help.into();
1360        }
1361        self
1362    }
1363
1364    #[must_use]
1365    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
1366        self.icon = Some(icon.into());
1367        self
1368    }
1369
1370    #[must_use]
1371    pub fn with_badge(mut self, badge: impl Into<String>) -> Self {
1372        self.badge = Some(badge.into());
1373        self
1374    }
1375
1376    /// Insert a context entry — only meaningful for the
1377    /// [`TabBody::Template`] variant; a no-op on `Html` / `Widgets`.
1378    /// Chain multiple times for multiple values.
1379    #[must_use]
1380    pub fn with_context_value(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
1381        if let TabBody::Template { context, .. } = &mut self.body {
1382            context.insert(key.into(), value);
1383        }
1384        self
1385    }
1386}
1387
1388/// Inventory entry — drop one of these next to each
1389/// `PageTypeHandler` impl (or use [`crate::register_page_type!`])
1390/// and it becomes discoverable at runtime via [`registered_handlers`].
1391pub struct PageTypeHandlerRegistration {
1392    pub factory: fn() -> Box<dyn PageTypeHandler>,
1393}
1394
1395inventory::collect!(PageTypeHandlerRegistration);
1396
1397/// All `PageTypeHandler`s registered in the current binary.
1398pub fn registered_handlers() -> impl Iterator<Item = Box<dyn PageTypeHandler>> {
1399    inventory::iter::<PageTypeHandlerRegistration>
1400        .into_iter()
1401        .map(|r| (r.factory)())
1402}
1403
1404/// Look up a registered handler by `type_name`.
1405pub fn find_handler(type_name: &str) -> Option<Box<dyn PageTypeHandler>> {
1406    registered_handlers().find(|p| p.type_name() == type_name)
1407}
1408
1409/// `true` when **any** registered handler declares a per-type
1410/// [`PageTypeHandler::view_restriction`] (#members). Cached — the
1411/// handler registry is static for the life of the process — so the
1412/// hot menu-filtering path can skip the per-type restriction lookup
1413/// entirely on binaries that gate nothing by type.
1414#[must_use]
1415pub fn any_type_view_restriction() -> bool {
1416    static CACHED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1417    *CACHED.get_or_init(|| registered_handlers().any(|h| h.view_restriction().is_some()))
1418}
1419
1420/// Optional-override trait for declarative page types defined via
1421/// `#[derive(PageType)]`. The derive emits the full
1422/// [`PageTypeHandler`] impl and delegates every author-overridable
1423/// method (`allowed_parent_types`, `allowed_child_types`,
1424/// `is_creatable`, `feed_kind`, `display_fields`, `extra_tabs`) to
1425/// `<Self as PageTypeOverrides>::*`. Every method has a sensible
1426/// default; an author that doesn't need overrides writes a one-line
1427/// `impl PageTypeOverrides for MyPage {}`.
1428///
1429/// ## Why a separate trait
1430///
1431/// The derive can't conditionally emit a default impl (Rust forbids
1432/// two impls of the same trait for the same type). Splitting the
1433/// overridable methods into a sibling trait gives authors a clean
1434/// opt-in: write the impl, override what you need, accept defaults
1435/// for the rest. The `PageTypeHandler` impl the derive emits handles
1436/// the wire-up.
1437#[async_trait]
1438pub trait PageTypeOverrides: Send + Sync + 'static {
1439    /// Allowed parent types — see [`PageTypeHandler::allowed_parent_types`].
1440    fn allowed_parent_types(&self) -> &'static [&'static str] {
1441        &[]
1442    }
1443
1444    /// Allowed child types — see [`PageTypeHandler::allowed_child_types`].
1445    fn allowed_child_types(&self) -> &'static [&'static str] {
1446        &[]
1447    }
1448
1449    /// Whether this type may be created from the admin — see
1450    /// [`PageTypeHandler::is_creatable`].
1451    fn is_creatable(&self) -> bool {
1452        true
1453    }
1454
1455    /// Public feed slug — see [`PageTypeHandler::feed_kind`].
1456    /// The derive prefers a struct-level
1457    /// `#[page_type(feed_kind = "…")]` attr over this default, so
1458    /// most authors set it via the attribute, not by overriding here.
1459    fn feed_kind(&self) -> Option<&'static str> {
1460        None
1461    }
1462
1463    /// Workflow opt-in slug — see [`PageTypeHandler::workflow_slug`].
1464    /// The derive prefers a struct-level
1465    /// `#[page_type(workflow = "Editorial review")]` attr over this
1466    /// default. Override here only when the workflow needs to be
1467    /// computed (e.g. choose between workflows based on tenant
1468    /// configuration).
1469    fn workflow_slug(&self) -> Option<&'static str> {
1470        None
1471    }
1472
1473    /// Per-type access gate — see [`PageTypeHandler::view_restriction`].
1474    /// Override to require a login or a permission codename for every
1475    /// page of this type. The derive forwards to this automatically.
1476    fn view_restriction(&self) -> Option<crate::view_restriction::TypeViewRestriction> {
1477        None
1478    }
1479
1480    /// Which representation this type serves — see
1481    /// [`PageTypeHandler::view_mode`]. Override to return
1482    /// [`crate::page_view::PageViewMode::Api`] when the type should
1483    /// answer JSON on its own URL. The derive forwards to this unless
1484    /// `#[page_type(view_mode = "…")]` is set, which wins.
1485    fn view_mode(&self) -> crate::page_view::PageViewMode {
1486        crate::page_view::PageViewMode::Auto
1487    }
1488
1489    /// Computed display chips — see [`PageTypeHandler::display_fields`].
1490    async fn display_fields(
1491        &self,
1492        _pool: &Pool,
1493        _page_id: i64,
1494    ) -> Result<Vec<DisplayField>, ExecError> {
1495        Ok(Vec::new())
1496    }
1497
1498    /// Handler-injected template ctx — see
1499    /// [`PageTypeHandler::public_context`]. The derive forwards to
1500    /// this override automatically; hand-rolled handlers can opt in
1501    /// via `impl PageTypeOverrides for MyHandler { … }`.
1502    ///
1503    /// With `#[derive(PageType)]`, `self` is the page's **stored row**
1504    /// (its extension fields as saved), so `self.<field>` reads the
1505    /// page's own values. A page without a saved row yet gets the
1506    /// type's `Default` value. The same holds for
1507    /// [`Self::route_context`].
1508    async fn public_context(
1509        &self,
1510        _pool: &Pool,
1511        _page: &crate::page::Page,
1512    ) -> Result<serde_json::Map<String, Value>, ExecError> {
1513        Ok(serde_json::Map::new())
1514    }
1515
1516    /// Override the children listing this page exposes to its template —
1517    /// see [`PageTypeHandler::children_query`]. Return `Ok(None)` (the
1518    /// default) to keep the framework behavior ([`published_children`]:
1519    /// live children, `sort_order, id`).
1520    /// Return `Ok(Some(pages))` to
1521    /// make this type an index that lists e.g. only published children in
1522    /// a custom order — [`published_children`] is the common building
1523    /// block, and [`published_children_page`] the bounded one for an
1524    /// index with many children:
1525    ///
1526    /// ```ignore
1527    /// async fn children_query(&self, pool, page)
1528    ///     -> Result<Option<Vec<Page>>, ExecError>
1529    /// {
1530    ///     Ok(Some(rustango_cms::published_children(pool, page).await?))
1531    /// }
1532    /// ```
1533    ///
1534    /// The derive forwards to this override automatically.
1535    async fn children_query(
1536        &self,
1537        _pool: &Pool,
1538        _page: &crate::page::Page,
1539    ) -> Result<Option<Vec<crate::page::Page>>, ExecError> {
1540        Ok(None)
1541    }
1542
1543    /// Routable URL patterns — see [`PageTypeHandler::routes`].
1544    fn routes(&self) -> Vec<crate::routable::RouteSpec> {
1545        Vec::new()
1546    }
1547
1548    /// Route-specific ctx — see [`PageTypeHandler::route_context`].
1549    async fn route_context(
1550        &self,
1551        _pool: &Pool,
1552        _page: &crate::page::Page,
1553        _matched: &crate::routable::RouteMatch,
1554    ) -> Result<serde_json::Map<String, Value>, ExecError> {
1555        Ok(serde_json::Map::new())
1556    }
1557
1558    /// What a matched route renders — see [`PageTypeHandler::route_outcome`].
1559    fn route_outcome(
1560        &self,
1561        _matched: &crate::routable::RouteMatch,
1562        _route_ctx: &serde_json::Map<String, Value>,
1563    ) -> crate::routable::RouteOutcome {
1564        crate::routable::RouteOutcome::Render
1565    }
1566
1567    /// Handler-contributed tabs — see [`PageTypeHandler::extra_tabs`].
1568    async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
1569        Ok(Vec::new())
1570    }
1571
1572    /// Inline panels — see [`PageTypeHandler::inline_panels`].
1573    async fn inline_panels(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<InlinePanelSpec>, ExecError> {
1574        Ok(Vec::new())
1575    }
1576
1577    /// A panel's rows — see [`PageTypeHandler::load_inline_panel`].
1578    async fn load_inline_panel(
1579        &self,
1580        _pool: &Pool,
1581        _page_id: i64,
1582        _panel_name: &str,
1583    ) -> Result<Vec<serde_json::Map<String, Value>>, ExecError> {
1584        Ok(Vec::new())
1585    }
1586
1587    /// Store a panel's posted rows — see [`PageTypeHandler::save_inline_panel`].
1588    async fn save_inline_panel(
1589        &self,
1590        _pool: &Pool,
1591        _page_id: i64,
1592        _panel_name: &str,
1593        _rows: &[serde_json::Map<String, Value>],
1594    ) -> Result<(), ExecError> {
1595        Ok(())
1596    }
1597
1598    /// Per-row panels: each row's id and title, in order. See
1599    /// [`InlinePanelSpec::per_row`](InlinePanelSpec#structfield.per_row).
1600    ///
1601    /// # Errors
1602    /// Driver / query failures.
1603    async fn inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str) -> Result<Vec<InlineRowSummary>, ExecError> {
1604        Ok(Vec::new())
1605    }
1606
1607    /// Per-row panels: one row's values, keyed by widget name (`None` id:
1608    /// a new row's starting values). `Ok(None)`: no such row on this page.
1609    ///
1610    /// # Errors
1611    /// Driver / query failures.
1612    async fn inline_row(
1613        &self,
1614        _pool: &Pool,
1615        _page_id: i64,
1616        _panel: &str,
1617        _row_id: Option<i64>,
1618    ) -> Result<Option<serde_json::Map<String, Value>>, ExecError> {
1619        Ok(None)
1620    }
1621
1622    /// Per-row panels: store one row from its posted values (`None` id:
1623    /// add it). Values arrive as the browser posts them; an unchecked
1624    /// switch is absent.
1625    ///
1626    /// # Errors
1627    /// Driver / query failures (validation problems are `Invalid`).
1628    async fn save_inline_row(
1629        &self,
1630        _pool: &Pool,
1631        _page_id: i64,
1632        _panel: &str,
1633        _row_id: Option<i64>,
1634        _values: &serde_json::Map<String, Value>,
1635    ) -> Result<InlineRowSaved, ExecError> {
1636        Ok(InlineRowSaved::Invalid(vec![crate::admin::cms_admin::FieldError::new("_form", "This panel can't be saved.")]))
1637    }
1638
1639    /// Per-row panels: remove one row. `Ok(false)`: refused.
1640    ///
1641    /// # Errors
1642    /// Driver / query failures.
1643    async fn delete_inline_row(&self, _pool: &Pool, _page_id: i64, _panel: &str, _row_id: i64) -> Result<bool, ExecError> {
1644        Ok(false)
1645    }
1646
1647    /// Per-row panels: store a new order (`ids` first to last).
1648    ///
1649    /// # Errors
1650    /// Driver / query failures.
1651    async fn reorder_inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str, _ids: &[i64]) -> Result<(), ExecError> {
1652        Ok(())
1653    }
1654}
1655
1656#[cfg(all(test, feature = "sqlite"))]
1657mod preview_tests {
1658    use super::*;
1659    use crate::widget::{Widget, WidgetKind};
1660
1661    struct Choosers;
1662
1663    #[async_trait]
1664    impl PageTypeHandler for Choosers {
1665        fn app_label(&self) -> &'static str {
1666            "cms"
1667        }
1668        fn type_name(&self) -> &'static str {
1669            "Choosers"
1670        }
1671        fn verbose_name(&self) -> &'static str {
1672            "Choosers"
1673        }
1674        fn default_template(&self) -> &'static str {
1675            "c.html"
1676        }
1677        async fn widgets(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<Widget>, ExecError> {
1678            Ok(vec![
1679                Widget::new(WidgetKind::PageChooser, "related", "Related"),
1680                Widget::new(WidgetKind::SnippetChooser, "cta", "CTA"),
1681                Widget::new(WidgetKind::DocumentChooser, "doc", "Doc"),
1682            ])
1683        }
1684    }
1685
1686    /// Live preview types every chooser id as the saved page does.
1687    #[tokio::test]
1688    async fn preview_types_chooser_ids_like_the_saved_value() {
1689        let pool = Pool::connect("sqlite::memory:").await.expect("pool");
1690        let form = std::collections::HashMap::from([
1691            ("related".to_owned(), "7".to_owned()),
1692            ("cta".to_owned(), "3".to_owned()),
1693            ("doc".to_owned(), String::new()),
1694        ]);
1695        let v = Choosers.preview_extension(&pool, 1, &form).await.expect("preview");
1696        assert_eq!(v, serde_json::json!({ "related": 7, "cta": 3, "doc": null }));
1697    }
1698}