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 crate::page::PageStatus;
210 use rustango::core::Column as _;
211 use rustango::sql::FetcherPool as _;
212 let id = page.id.get().copied().unwrap_or_default();
213 let now = chrono::Utc::now();
214 let rows = crate::page::Page::objects()
215 .where_(crate::page::Page::parent_id.eq(id))
216 .where_(crate::page::Page::status.is_in([
217 PageStatus::Published.as_str().to_owned(),
218 PageStatus::Scheduled.as_str().to_owned(),
219 ]))
220 .order_by(&[("sort_order", false), ("id", false)])
221 .fetch(pool)
222 .await?;
223 let error_tid = crate::error_pages::error_page_type_id(pool).await;
224 Ok(rows
225 .into_iter()
226 .filter(|p| crate::resolver::visible_now(p, now))
227 .filter(|p| error_tid.map_or(true, |tid| p.page_type_id != tid))
228 .collect())
229}
230
231/// A page kind registered by user code (e.g. `BlogPostPage`, `LandingPage`).
232///
233/// Each impl owns the typed extension table that backs its kind, the
234/// template used to render it, its admin form, and the parent/child
235/// type whitelist.
236///
237/// **Registering.** Prefer `#[derive(PageType)]`, which emits this impl
238/// plus the inventory registration and forwards the overridable hooks
239/// to [`PageTypeOverrides`]. A hand-written impl registers with
240/// [`register_page_type!`](crate::register_page_type) and needs only the
241/// four required methods (`app_label`, `type_name`, `verbose_name`,
242/// `default_template`); every other hook has a no-op default.
243///
244/// **When hooks run.** Render hooks (`load_extension`, `public_context`,
245/// `children_query`, `routes` / `route_context`) run on every public
246/// request for a page of this type. Editor hooks (`widgets`,
247/// `extra_tabs`, `inline_panels`, `display_fields`) run on the admin
248/// edit form; `save_extension` / `save_inline_panel` on its POST, after
249/// the `cms_page` row is saved; `preview_extension` on live preview.
250///
251/// Handlers are process-global — instances are constructed via
252/// [`PageTypeHandlerRegistration::factory`] and live for the
253/// lifetime of the binary. The matching DB row in
254/// `cms_page_type` is per-tenant and seeded by
255/// [`crate::ensure_seeded`](crate::seed::ensure_seeded).
256#[async_trait]
257pub trait PageTypeHandler: Send + Sync + 'static {
258 /// Logical app this handler belongs to (e.g. `"cms_articles"`).
259 /// Lets multiple crates contribute page types without
260 /// `type_name` collisions, and groups them in the admin.
261 fn app_label(&self) -> &'static str;
262
263 /// Stable identifier — stored in `cms_page_type.type_name`. Must
264 /// be globally unique across the process.
265 fn type_name(&self) -> &'static str;
266
267 /// Human-readable label for the admin UI.
268 fn verbose_name(&self) -> &'static str;
269
270 /// Default Tera template path the renderer should use. A page can
271 /// override it per row via [`Page::template_override`](crate::Page::template_override).
272 fn default_template(&self) -> &'static str;
273
274 /// Page types that are allowed as a parent for instances of this
275 /// type. Empty slice = no restriction (the *child-side* guard).
276 fn allowed_parent_types(&self) -> &'static [&'static str] {
277 &[]
278 }
279
280 /// Page types that are allowed as direct children of instances of
281 /// this type. Empty slice = no restriction (the *parent-side*
282 /// guard). Symmetric with [`Self::allowed_parent_types`]: both
283 /// sides must agree at create / move time.
284 fn allowed_child_types(&self) -> &'static [&'static str] {
285 &[]
286 }
287
288 /// Whether this type is a **leaf** — it accepts no child pages at
289 /// all. Distinct from `allowed_child_types() == []`, which means "no
290 /// restriction" (any type may be a child). Returning `true` is the
291 /// first-class way to say "this page can't have children"
292 /// without the sentinel hack of whitelisting a
293 /// non-existent child type. Enforced parent-side at create / move
294 /// time.
295 fn is_leaf(&self) -> bool {
296 false
297 }
298
299 /// Whether this type may be created from the admin "Add page"
300 /// menu. Defaults to `true`; abstract / programmatically-only
301 /// types should override to `false`.
302 fn is_creatable(&self) -> bool {
303 true
304 }
305
306 /// Material-symbols icon name for the page-type picker tile.
307 /// Defaults to `None` — picker renders a generic glyph. Authors
308 /// set it via `#[page_type(icon = "article")]` on the
309 /// `#[derive(PageType)]` struct, or by overriding this method on
310 /// hand-rolled handlers.
311 fn icon(&self) -> Option<&'static str> {
312 None
313 }
314
315 /// One-line description shown under `verbose_name` in the
316 /// page-type picker. Defaults to `None`. Authors set it via
317 /// `#[page_type(description = "…")]`.
318 fn description(&self) -> Option<&'static str> {
319 None
320 }
321
322 /// Opt this page type in to a public RSS 2.0 / Atom 1.0 feed
323 /// (powered by [`rustango::syndication`]). The returned slug is
324 /// the URL path segment under `/feed/<slug>/rss.xml` +
325 /// `/feed/<slug>/atom.xml`; pick something URL-friendly and
326 /// distinct from other page types' slugs.
327 ///
328 /// Returning `None` (the default) means no feed is emitted for
329 /// this type — its pages still render normally; they just
330 /// don't appear in any aggregate feed.
331 ///
332 /// The feed lists every published, indexable [`crate::Page`]
333 /// row of this type in `published_at desc` order. See
334 /// [`crate::feed`] for the URL shape and content mapping.
335 fn feed_kind(&self) -> Option<&'static str> {
336 None
337 }
338
339 /// Opt this page type in to a multi-step approval workflow.
340 /// Returns the [`Workflow`](crate::workflow::Workflow) `name` of the workflow
341 /// to apply to pages of this type, or `None` to leave them on the
342 /// direct-publish path.
343 ///
344 /// When this returns `Some("Editorial review")`, the page editor
345 /// for pages of this type renders a Submit-for-review action
346 /// that creates a `cms_workflow_state` row and walks the page
347 /// through the workflow's tasks. Pages can only finish a
348 /// workflow once the final task is approved.
349 ///
350 /// The workflow with the returned name must exist + be active in
351 /// the tenant's `cms_workflow` table — admins create + manage
352 /// workflows at `/cms-admin/workflows`. If the named workflow
353 /// doesn't exist or is inactive, pages fall back to the
354 /// direct-publish path.
355 fn workflow_slug(&self) -> Option<&'static str> {
356 None
357 }
358
359 /// Gate every page of this type behind an access requirement — the
360 /// per-**type** analogue of the per-page Privacy tab. Return
361 /// `None` (the default) to leave the type public; return
362 /// [`crate::view_restriction::TypeViewRestriction::login`] to require
363 /// any authenticated member, or
364 /// [`crate::view_restriction::TypeViewRestriction::permission`] to
365 /// require one of a set of permission codenames (checked through the
366 /// framework permission engine).
367 ///
368 /// A page/subtree restriction set on an individual page (or an
369 /// ancestor) is more specific and overrides this type-level default.
370 /// The derive forwards to
371 /// [`PageTypeOverrides::view_restriction`] automatically.
372 fn view_restriction(&self) -> Option<crate::view_restriction::TypeViewRestriction> {
373 None
374 }
375
376 /// Which representation this type serves on its public URL.
377 ///
378 /// Defaults to [`crate::page_view::PageViewMode::Auto`], which
379 /// derives the answer from [`Self::default_template`]: a blank
380 /// template means the type is JSON-only, anything else means HTML.
381 /// Return [`crate::page_view::PageViewMode::Api`] to serve JSON at
382 /// the page's own URL under `Accept: application/json` even when a
383 /// template exists — the template still answers browsers.
384 ///
385 /// Set it declaratively with `#[page_type(view_mode = "api")]`,
386 /// which also makes the otherwise-mandatory `template` attribute
387 /// optional. Without the attribute the derive forwards to
388 /// [`PageTypeOverrides::view_mode`].
389 fn view_mode(&self) -> crate::page_view::PageViewMode {
390 crate::page_view::PageViewMode::Auto
391 }
392
393 /// Load the typed extension row for a given page id and return
394 /// it as JSON for the renderer's Tera context.
395 ///
396 /// The default implementation returns `Value::Null` — types
397 /// with no extension table (e.g. a `HomePage` whose data lives
398 /// entirely on the base Page row) get a null `extension` value
399 /// in the template context.
400 ///
401 /// # Errors
402 /// Driver / query failures from the extension lookup.
403 async fn load_extension(&self, _pool: &Pool, _page_id: i64) -> Result<Value, ExecError> {
404 Ok(Value::Null)
405 }
406
407 /// URL patterns this page type serves IN ADDITION to its
408 /// canonical `url_path`.
409 ///
410 /// Each [`crate::routable::RouteSpec`] declares a regex pattern
411 /// (matched against the suffix BELOW the page's `url_path`) and
412 /// a stable name. When the public resolver can't find an exact
413 /// `url_path` match it walks ancestor candidates and asks each
414 /// candidate's handler whether any of its routes accept the
415 /// remaining suffix. On match, the renderer dispatches to
416 /// [`Self::route_context`] for handler-injected ctx, and the
417 /// matched [`crate::routable::RouteMatch`] is exposed to the
418 /// template as `route_name` + `route_captures`.
419 ///
420 /// Default: empty — page types without routable patterns pay
421 /// nothing.
422 fn routes(&self) -> Vec<crate::routable::RouteSpec> {
423 Vec::new()
424 }
425
426 /// Handler-computed ctx injected when a routable pattern matched.
427 /// Mirrors [`Self::public_context`] but receives the matched
428 /// route's name + named capture groups. Override to load
429 /// route-specific data — the year's posts when `archive_year`
430 /// matched, the tagged posts when `tag` matched, etc.
431 ///
432 /// Default returns an empty map; the renderer still threads
433 /// `route_name` and `route_captures` into the context so a
434 /// handler that only needs the captures (no extra fetches) can
435 /// stay on the default.
436 ///
437 /// # Errors
438 /// Driver / query failures from the route-specific computation.
439 async fn route_context(
440 &self,
441 _pool: &Pool,
442 _page: &crate::page::Page,
443 _matched: &crate::routable::RouteMatch,
444 ) -> Result<serde_json::Map<String, Value>, ExecError> {
445 Ok(serde_json::Map::new())
446 }
447
448 /// Inject handler-computed values into the public render's Tera
449 /// context, for hand-rolled
450 /// data — e.g. a `HomePage` that exposes a `latest_posts` list
451 /// to its template without baking the query into the template
452 /// layer.
453 ///
454 /// The default returns an empty map; override in
455 /// [`PageTypeOverrides`] (or hand-rolled handlers) to surface
456 /// extras. Framework keys (`page`, `page_type`, `extension`,
457 /// `children`, `ancestors`, `url_prefix`, `locale`,
458 /// `translations`, `theme_*`, `_snippets_html`, `_stream_html`,
459 /// `_pages_by_id`) are stamped AFTER the handler's keys, so
460 /// `public_context` can't shadow them — pick distinct names
461 /// for custom keys.
462 ///
463 /// # Errors
464 /// Driver / query failures from the handler-side computation.
465 async fn public_context(
466 &self,
467 _pool: &Pool,
468 _page: &crate::page::Page,
469 ) -> Result<serde_json::Map<String, Value>, ExecError> {
470 Ok(serde_json::Map::new())
471 }
472
473 /// Build the `children` ctx var the public renderer hands to the
474 /// page template (by default the live children, newest first)
475 /// — index-style pages (BlogIndexPage, ArchivePage, …) lean on
476 /// this to surface only published rows in a meaningful order.
477 ///
478 /// The default returns every immediate child sorted by
479 /// `sort_order, id` (matches the pre-existing `children` shape
480 /// — drafts INCLUDED, ordering NOT chronological).
481 /// Overriding handlers typically:
482 /// - filter by `status = published`
483 /// - filter by `expire_at IS NULL OR expire_at > now`
484 /// - order by `published_at DESC` (or `sort_order ASC` for a
485 /// curated tree)
486 /// - apply a limit
487 ///
488 /// The result lands in two places in the template context:
489 /// `children` (the typed list) AND a thread-local backing the
490 /// `children_filtered(...)` Tera function (see [`crate::children_filtered`]).
491 ///
492 /// # Errors
493 /// Driver / query failures from the page lookup.
494 async fn children_query(
495 &self,
496 pool: &Pool,
497 page: &crate::page::Page,
498 ) -> Result<Vec<crate::page::Page>, ExecError> {
499 default_children(pool, page).await
500 }
501
502 /// Describe the extension-row's fields so the admin page-editor
503 /// can render a form section for them. The default returns an
504 /// empty list — types without an extension table get no extra
505 /// inputs in the editor.
506 ///
507 /// `page_id` is provided so handlers can pre-fill values from
508 /// the existing row (the typical impl: load the row, then map
509 /// each column into an `ExtensionField` with `value`).
510 ///
511 /// # Errors
512 /// Driver / query failures from the extension lookup.
513 async fn extension_fields(
514 &self,
515 _pool: &Pool,
516 _page_id: i64,
517 ) -> Result<Vec<ExtensionField>, ExecError> {
518 Ok(Vec::new())
519 }
520
521 /// Rich-widget alternative to [`Self::extension_fields`].
522 /// Returns full [`crate::Widget`] instances so handlers can
523 /// expose the entire 26-kind widget catalog (Date, DatetimeTz,
524 /// Color, Range, Radio, Select, Checkboxes, MultiSelect,
525 /// Custom, …) instead of being limited to the legacy six
526 /// [`ExtensionFieldKind`] variants.
527 ///
528 /// Default impl delegates to [`Self::extension_fields`] +
529 /// [`ExtensionField::into_widget`], so handlers that haven't
530 /// overridden this method keep working unchanged. Handlers
531 /// that want the new kinds override `widgets` instead of
532 /// `extension_fields`; the admin form-render path always calls
533 /// `widgets`, so a single override surfaces every kind in the
534 /// editor at once.
535 ///
536 /// # Errors
537 /// Driver / query failures propagated from the handler-side
538 /// computation.
539 async fn widgets(&self, pool: &Pool, page_id: i64) -> Result<Vec<crate::Widget>, ExecError> {
540 Ok(self
541 .extension_fields(pool, page_id)
542 .await?
543 .into_iter()
544 .map(ExtensionField::into_widget)
545 .collect())
546 }
547
548 /// Declared Page↔Snippet many-to-many relations as
549 /// `(relation_name, snippet_type)` pairs. Macro-generated
550 /// from the struct-level `#[page_type(snippet_m2m(name = "Type", …))]`
551 /// attribute; the default is none. The public renderer resolves each
552 /// relation's chosen rows into `snippet_relations.<name>` so templates
553 /// can iterate the related snippets.
554 fn snippet_m2m_relations(&self) -> Vec<(&'static str, &'static str)> {
555 Vec::new()
556 }
557
558 /// Build a virtual extension `Value` from a posted form `HashMap`
559 /// without touching the persisted row. Powers the "preview
560 /// unsaved changes" iframe in the page editor — the renderer
561 /// substitutes the result for [`Self::load_extension`] so the
562 /// preview reflects the current form state.
563 ///
564 /// Default impl walks [`Self::widgets`] and maps each widget's
565 /// `name` to the form value, with kind-aware coercion (booleans
566 /// from `"on"`/`"true"`, multi-value kinds parsed as JSON arrays,
567 /// numeric kinds parsed into `serde_json::Number`). Handlers
568 /// whose persisted shape differs from the widget surface should
569 /// override.
570 ///
571 /// # Errors
572 /// Driver / query failures from the widgets lookup (the
573 /// form-to-JSON mapping itself is infallible).
574 async fn preview_extension(
575 &self,
576 pool: &Pool,
577 page_id: i64,
578 form: &std::collections::HashMap<String, String>,
579 ) -> Result<Value, ExecError> {
580 let widgets = self.widgets(pool, page_id).await.unwrap_or_default();
581 let mut map = serde_json::Map::new();
582 for w in widgets {
583 let raw = form.get(&w.name).map(String::as_str).unwrap_or_default();
584 // One coercion table for page fields and builder fields (#660).
585 let val = crate::page_builder::values::coerce(w.kind, raw);
586 map.insert(w.name, val);
587 }
588 Ok(Value::Object(map))
589 }
590
591 /// Persist the posted form values into this type's extension
592 /// table. Called by the admin's page-edit POST handler after the
593 /// canonical `cms_page` row has been saved. Upsert keyed on
594 /// `page_id` is the standard pattern.
595 ///
596 /// `form` is the full form HashMap; handlers should pull out
597 /// only the keys whose `name` they returned from
598 /// [`Self::extension_fields`].
599 ///
600 /// # Errors
601 /// Driver / query failures from the upsert.
602 async fn save_extension(
603 &self,
604 _pool: &Pool,
605 _page_id: i64,
606 _form: &std::collections::HashMap<String, String>,
607 ) -> Result<(), ExecError> {
608 Ok(())
609 }
610
611 /// Handler-contributed tabs appended to the page-editor's tab
612 /// strip after the built-in `Content` / `Promote` / `Theme` /
613 /// `Revisions` ones. Each [`TabSpec`] carries a stable `name`
614 /// (used in the URL hash + localStorage for "remember last
615 /// active tab"), a `label`, an optional Material-symbols `icon`
616 /// + small `badge` chip, and a pre-rendered HTML body the
617 /// admin template emits inside the main `<form>`.
618 ///
619 /// Because custom tab bodies sit inside the canonical form, any
620 /// `<input name="…">` inside one shows up in the
621 /// `HashMap<String, String>` handed to [`Self::save_extension`]
622 /// — handlers can persist tab-scoped fields the same way they
623 /// persist [`Self::widgets`] entries.
624 ///
625 /// Default impl returns an empty list — the built-in tabs are
626 /// always present and self-contained, so handlers that don't
627 /// need a custom tab pay nothing.
628 ///
629 /// # Errors
630 /// Driver / query failures from the handler-side computation.
631 async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
632 Ok(Vec::new())
633 }
634
635 /// Inline panels — 1-N collections of sub-rows that the page
636 /// editor renders as a sortable list of cards. Each [`InlinePanelSpec`] declares the panel's
637 /// stable `name`, the human `label`, the per-row `fields`, and
638 /// optional cardinality bounds.
639 ///
640 /// Default impl returns an empty list — handlers that don't use
641 /// inline panels pay nothing. Handlers that do override this
642 /// method must also implement [`Self::load_inline_panel`] and
643 /// [`Self::save_inline_panel`] for the rows to round-trip.
644 fn inline_panels(&self) -> Vec<InlinePanelSpec> {
645 Vec::new()
646 }
647
648 /// Fetch existing rows for `panel_name` keyed under `page_id`.
649 /// Each returned `serde_json::Map` is one row; keys match the
650 /// `name` of the [`InlinePanelSpec::fields`] entries.
651 ///
652 /// Default impl returns an empty list.
653 ///
654 /// # Errors
655 /// Driver / query failures from the row lookup.
656 async fn load_inline_panel(
657 &self,
658 _pool: &Pool,
659 _page_id: i64,
660 _panel_name: &str,
661 ) -> Result<Vec<serde_json::Map<String, Value>>, ExecError> {
662 Ok(Vec::new())
663 }
664
665 /// Persist the posted rows for `panel_name` under `page_id`. The
666 /// admin POST handler parses inline-panel form keys
667 /// (`inline__<panel_name>__<row_idx>__<field>`) into row dicts
668 /// and calls this with the full set; the handler is responsible
669 /// for the upsert / delete-removed semantics. Sort order is the
670 /// position in the `rows` slice.
671 ///
672 /// Default impl is a no-op.
673 ///
674 /// # Errors
675 /// Driver / query failures from the upsert.
676 async fn save_inline_panel(
677 &self,
678 _pool: &Pool,
679 _page_id: i64,
680 _panel_name: &str,
681 _rows: &[serde_json::Map<String, Value>],
682 ) -> Result<(), ExecError> {
683 Ok(())
684 }
685
686 /// Computed / display-only fields shown in an "At a glance"
687 /// panel at the top of the page-edit form. Each entry is a
688 /// pre-rendered HTML chip (the value is `| safe`d into the
689 /// template) authored by the handler from arbitrary data:
690 /// row counts, word counts, derived flags, audit timestamps,
691 /// linked-snippet previews, etc.
692 ///
693 /// This is the first-class hook for read-only computed values
694 /// in the editor (static help text and plain model fields can't
695 /// show them).
696 /// `display_fields` runs at edit-form GET, so each value is
697 /// recomputed every load and reflects the latest DB state.
698 ///
699 /// Default impl returns an empty list — handlers that don't
700 /// need it pay nothing.
701 ///
702 /// # Errors
703 /// Driver / query failures from any computation the handler
704 /// runs against the pool.
705 async fn display_fields(
706 &self,
707 _pool: &Pool,
708 _page_id: i64,
709 ) -> Result<Vec<DisplayField>, ExecError> {
710 Ok(Vec::new())
711 }
712}
713
714/// One computed display chip rendered in the page-edit form's "At
715/// a glance" panel. See [`PageTypeHandler::display_fields`].
716///
717/// `html` is trusted — emitted through `| safe` in the bundled
718/// template. Handlers escape user-controlled content themselves
719/// (e.g. via `tera::escape_html` or by passing through
720/// [`crate::markdown::render`] which sanitizes).
721#[derive(Debug, Clone, Serialize, Deserialize)]
722pub struct DisplayField {
723 /// Short label, e.g. "Word count" or "Last edited".
724 pub label: String,
725 /// Pre-rendered HTML fragment. Emitted with `| safe`.
726 pub html: String,
727 /// Optional helptext shown beneath the value.
728 #[serde(default, skip_serializing_if = "String::is_empty")]
729 pub help: String,
730 /// Optional material-symbols icon name shown next to the label
731 /// (e.g. `"format_list_numbered"`, `"schedule"`).
732 #[serde(default, skip_serializing_if = "Option::is_none")]
733 pub icon: Option<String>,
734}
735
736impl DisplayField {
737 /// Smallest possible chip — just `(label, html)`. Caller adds
738 /// `help` / `icon` fluently if needed.
739 #[must_use]
740 pub fn new(label: impl Into<String>, html: impl Into<String>) -> Self {
741 Self {
742 label: label.into(),
743 html: html.into(),
744 help: String::new(),
745 icon: None,
746 }
747 }
748
749 #[must_use]
750 pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
751 self.icon = Some(icon.into());
752 self
753 }
754
755 #[must_use]
756 pub fn with_help(mut self, help: impl Into<String>) -> Self {
757 self.help = help.into();
758 self
759 }
760}
761
762/// How a custom tab's body is supplied. Three shapes:
763///
764/// - `Html(s)` — pre-rendered HTML (backwards-compatible escape
765/// hatch; what `TabSpec::new(..., html)` produces).
766/// - `Template { path, context }` — a Tera template path + a
767/// per-tab context map. The page editor renders the template
768/// server-side with the standard admin chrome context PLUS the
769/// spec's own `context` map merged in, and drops the resulting
770/// HTML into the tab panel.
771/// - `Widgets(widgets)` — declarative form fields. The editor
772/// renders each [`crate::Widget`] via the same `_widget.html`
773/// macro the Content tab's main stack uses, so widget visuals +
774/// behavior stay identical wherever they appear.
775#[derive(Debug, Clone, Serialize, Deserialize)]
776#[serde(rename_all = "snake_case")]
777pub enum TabBody {
778 Html(String),
779 Template {
780 path: String,
781 #[serde(default)]
782 context: serde_json::Map<String, serde_json::Value>,
783 },
784 Widgets(Vec<crate::widget::Widget>),
785 /// Field group panel. Groups widgets
786 /// under a heading; `layout` picks vertical stack vs side-by-side.
787 /// Optional `help` renders as a hint paragraph between the
788 /// heading and the field grid.
789 Group {
790 heading: String,
791 #[serde(default, skip_serializing_if = "String::is_empty")]
792 help: String,
793 #[serde(default)]
794 layout: PanelLayout,
795 widgets: Vec<crate::widget::Widget>,
796 },
797 /// Help panel. Static informational block — no form
798 /// fields. The body is HTML emitted via `| safe` after CMS-side
799 /// authoring; trust source is the handler author.
800 Help {
801 content: String,
802 },
803}
804
805/// Layout direction for [`TabBody::Group`].
806#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
807#[serde(rename_all = "snake_case")]
808pub enum PanelLayout {
809 /// Stack widgets vertically (default).
810 #[default]
811 Column,
812 /// Lay widgets out side-by-side (responsive flex; collapses to
813 /// column on narrow viewports).
814 Row,
815}
816
817impl PanelLayout {
818 /// CSS class suffix — used by `_panel_group.html` to switch the
819 /// flex direction.
820 #[must_use]
821 pub fn class_suffix(self) -> &'static str {
822 match self {
823 Self::Column => "column",
824 Self::Row => "row",
825 }
826 }
827}
828
829/// One inline panel declaration — a 1-N relation between the page
830/// and a child table the handler maintains. See
831/// [`PageTypeHandler::inline_panels`]. The admin editor renders one
832/// section per spec with the fields stacked vertically; add and remove
833/// are plain HTML buttons, with no drag-to-reorder.
834#[derive(Debug, Clone, Serialize, Deserialize)]
835pub struct InlinePanelSpec {
836 /// Stable identifier — used in form field names
837 /// (`inline__<name>__<row>__<field>`). Snake_case conventional.
838 pub name: String,
839 /// Visible label shown above the panel.
840 pub label: String,
841 /// Per-row field surface. Each entry renders one input per row.
842 pub fields: Vec<ExtensionField>,
843 /// Optional minimum row count (inclusive). When set + the editor
844 /// submits fewer rows, the save handler logs a warning but
845 /// doesn't reject — handlers enforce hard rules themselves.
846 #[serde(default, skip_serializing_if = "Option::is_none")]
847 pub min_num: Option<usize>,
848 /// Optional maximum row count (inclusive).
849 #[serde(default, skip_serializing_if = "Option::is_none")]
850 pub max_num: Option<usize>,
851 /// Optional helptext shown beneath the panel header.
852 #[serde(default, skip_serializing_if = "String::is_empty")]
853 pub help: String,
854 /// Optional material-symbols icon name.
855 #[serde(default, skip_serializing_if = "Option::is_none")]
856 pub icon: Option<String>,
857}
858
859impl InlinePanelSpec {
860 /// Smallest valid spec — `(name, label, fields)`. Helpers below
861 /// add `min` / `max` / `help` / `icon` fluently.
862 #[must_use]
863 pub fn new(
864 name: impl Into<String>,
865 label: impl Into<String>,
866 fields: Vec<ExtensionField>,
867 ) -> Self {
868 Self {
869 name: name.into(),
870 label: label.into(),
871 fields,
872 min_num: None,
873 max_num: None,
874 help: String::new(),
875 icon: None,
876 }
877 }
878
879 #[must_use]
880 pub fn with_min(mut self, min: usize) -> Self {
881 self.min_num = Some(min);
882 self
883 }
884
885 #[must_use]
886 pub fn with_max(mut self, max: usize) -> Self {
887 self.max_num = Some(max);
888 self
889 }
890
891 #[must_use]
892 pub fn with_help(mut self, help: impl Into<String>) -> Self {
893 self.help = help.into();
894 self
895 }
896
897 #[must_use]
898 pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
899 self.icon = Some(icon.into());
900 self
901 }
902}
903
904/// One handler-contributed tab appended to the page-editor's
905/// built-in tab strip (Content / Promote / Theme / Revisions). See
906/// [`PageTypeHandler::extra_tabs`].
907///
908/// The body is one of [`TabBody::Html`] (pre-rendered HTML — the
909/// escape hatch), [`TabBody::Template`] (Tera template path + extra
910/// context — render with the standard admin context vars in scope),
911/// or [`TabBody::Widgets`] (declarative widget list — rendered via
912/// `_widget.html` so the form fields look identical to the Content
913/// tab's stack).
914///
915/// Inputs declared inside the rendered HTML land in
916/// [`PageTypeHandler::save_extension`]'s form HashMap automatically;
917/// every variant lives inside the page-edit `<form>`.
918///
919/// `name` must be unique within a page's tab set. Mixing with the
920/// built-in names (`content`, `promote`, `theme`, `revisions`) is
921/// allowed and lets a handler override the BUILT-IN tab body without
922/// forking the template; the tab JS keys off `data-tab-trigger="<name>"`
923/// so identical names render the same panel.
924#[derive(Debug, Clone, Serialize, Deserialize)]
925pub struct TabSpec {
926 /// Stable identifier — kebab-case is conventional. Used for
927 /// `aria-controls`, URL hash links, and the per-page localStorage
928 /// "remember last active tab" key.
929 pub name: String,
930 /// Visible label on the tab button.
931 pub label: String,
932 /// Optional Material-symbols icon name (e.g. `"workflow"`,
933 /// `"insights"`). Rendered to the left of `label`.
934 #[serde(default, skip_serializing_if = "Option::is_none")]
935 pub icon: Option<String>,
936 /// Optional small chip rendered after `label` (e.g. an unread
937 /// count, "new", or a small status indicator).
938 #[serde(default, skip_serializing_if = "Option::is_none")]
939 pub badge: Option<String>,
940 /// What goes inside the tab panel — see [`TabBody`].
941 pub body: TabBody,
942}
943
944impl TabSpec {
945 /// Smallest possible spec — just `(name, label, html)`. The
946 /// `html` is treated as pre-rendered + emitted via Tera's
947 /// `| safe`. Backwards-compatible with the v0.2 surface.
948 #[must_use]
949 pub fn new(name: impl Into<String>, label: impl Into<String>, html: impl Into<String>) -> Self {
950 Self {
951 name: name.into(),
952 label: label.into(),
953 icon: None,
954 badge: None,
955 body: TabBody::Html(html.into()),
956 }
957 }
958
959 /// Tera-template-backed tab. The renderer mounts `path` with the
960 /// standard admin context plus the per-tab context map (empty
961 /// until filled with [`Self::with_context_value`]). Example:
962 /// `TabSpec::template("seo", "SEO", "blog/seo_tab.html")`.
963 #[must_use]
964 pub fn template(
965 name: impl Into<String>,
966 label: impl Into<String>,
967 path: impl Into<String>,
968 ) -> Self {
969 Self {
970 name: name.into(),
971 label: label.into(),
972 icon: None,
973 badge: None,
974 body: TabBody::Template {
975 path: path.into(),
976 context: serde_json::Map::new(),
977 },
978 }
979 }
980
981 /// Widget-group-backed tab. Same rendering pipeline the Content
982 /// tab uses — each widget is emitted via `_widget.html`'s macro.
983 /// Inputs submit alongside the page-edit form so the handler's
984 /// [`PageTypeHandler::save_extension`] picks them up by name.
985 #[must_use]
986 pub fn widgets(
987 name: impl Into<String>,
988 label: impl Into<String>,
989 widgets: Vec<crate::widget::Widget>,
990 ) -> Self {
991 Self {
992 name: name.into(),
993 label: label.into(),
994 icon: None,
995 badge: None,
996 body: TabBody::Widgets(widgets),
997 }
998 }
999
1000 /// Field-group tab — heading + (optional help) +
1001 /// widgets stacked under one section. Use [`Self::with_layout`]
1002 /// to switch to row layout.
1003 #[must_use]
1004 pub fn group(
1005 name: impl Into<String>,
1006 label: impl Into<String>,
1007 heading: impl Into<String>,
1008 widgets: Vec<crate::widget::Widget>,
1009 ) -> Self {
1010 Self {
1011 name: name.into(),
1012 label: label.into(),
1013 icon: None,
1014 badge: None,
1015 body: TabBody::Group {
1016 heading: heading.into(),
1017 help: String::new(),
1018 layout: PanelLayout::Column,
1019 widgets,
1020 },
1021 }
1022 }
1023
1024 /// Help tab — static HTML content, no form fields.
1025 /// The body is emitted via `| safe`, so authors control the markup.
1026 #[must_use]
1027 pub fn help(
1028 name: impl Into<String>,
1029 label: impl Into<String>,
1030 content: impl Into<String>,
1031 ) -> Self {
1032 Self {
1033 name: name.into(),
1034 label: label.into(),
1035 icon: None,
1036 badge: None,
1037 body: TabBody::Help {
1038 content: content.into(),
1039 },
1040 }
1041 }
1042
1043 /// Switch a Group-body tab to a different layout. No-op on other
1044 /// body variants.
1045 #[must_use]
1046 pub fn with_layout(mut self, layout: PanelLayout) -> Self {
1047 if let TabBody::Group {
1048 layout: ref mut existing,
1049 ..
1050 } = self.body
1051 {
1052 *existing = layout;
1053 }
1054 self
1055 }
1056
1057 /// Attach help text to a Group-body tab. No-op on other body
1058 /// variants.
1059 #[must_use]
1060 pub fn with_help(mut self, help: impl Into<String>) -> Self {
1061 if let TabBody::Group {
1062 help: ref mut existing,
1063 ..
1064 } = self.body
1065 {
1066 *existing = help.into();
1067 }
1068 self
1069 }
1070
1071 #[must_use]
1072 pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
1073 self.icon = Some(icon.into());
1074 self
1075 }
1076
1077 #[must_use]
1078 pub fn with_badge(mut self, badge: impl Into<String>) -> Self {
1079 self.badge = Some(badge.into());
1080 self
1081 }
1082
1083 /// Insert a context entry — only meaningful for the
1084 /// [`TabBody::Template`] variant; a no-op on `Html` / `Widgets`.
1085 /// Chain multiple times for multiple values.
1086 #[must_use]
1087 pub fn with_context_value(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
1088 if let TabBody::Template { context, .. } = &mut self.body {
1089 context.insert(key.into(), value);
1090 }
1091 self
1092 }
1093}
1094
1095/// Inventory entry — drop one of these next to each
1096/// `PageTypeHandler` impl (or use [`crate::register_page_type!`])
1097/// and it becomes discoverable at runtime via [`registered_handlers`].
1098pub struct PageTypeHandlerRegistration {
1099 pub factory: fn() -> Box<dyn PageTypeHandler>,
1100}
1101
1102inventory::collect!(PageTypeHandlerRegistration);
1103
1104/// All `PageTypeHandler`s registered in the current binary.
1105pub fn registered_handlers() -> impl Iterator<Item = Box<dyn PageTypeHandler>> {
1106 inventory::iter::<PageTypeHandlerRegistration>
1107 .into_iter()
1108 .map(|r| (r.factory)())
1109}
1110
1111/// Look up a registered handler by `type_name`.
1112pub fn find_handler(type_name: &str) -> Option<Box<dyn PageTypeHandler>> {
1113 registered_handlers().find(|p| p.type_name() == type_name)
1114}
1115
1116/// `true` when **any** registered handler declares a per-type
1117/// [`PageTypeHandler::view_restriction`] (#members). Cached — the
1118/// handler registry is static for the life of the process — so the
1119/// hot menu-filtering path can skip the per-type restriction lookup
1120/// entirely on binaries that gate nothing by type.
1121#[must_use]
1122pub fn any_type_view_restriction() -> bool {
1123 static CACHED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1124 *CACHED.get_or_init(|| registered_handlers().any(|h| h.view_restriction().is_some()))
1125}
1126
1127/// Optional-override trait for declarative page types defined via
1128/// `#[derive(PageType)]`. The derive emits the full
1129/// [`PageTypeHandler`] impl and delegates every author-overridable
1130/// method (`allowed_parent_types`, `allowed_child_types`,
1131/// `is_creatable`, `feed_kind`, `display_fields`, `extra_tabs`) to
1132/// `<Self as PageTypeOverrides>::*`. Every method has a sensible
1133/// default; an author that doesn't need overrides writes a one-line
1134/// `impl PageTypeOverrides for MyPage {}`.
1135///
1136/// ## Why a separate trait
1137///
1138/// The derive can't conditionally emit a default impl (Rust forbids
1139/// two impls of the same trait for the same type). Splitting the
1140/// overridable methods into a sibling trait gives authors a clean
1141/// opt-in: write the impl, override what you need, accept defaults
1142/// for the rest. The `PageTypeHandler` impl the derive emits handles
1143/// the wire-up.
1144#[async_trait]
1145pub trait PageTypeOverrides: Send + Sync + 'static {
1146 /// Allowed parent types — see [`PageTypeHandler::allowed_parent_types`].
1147 fn allowed_parent_types(&self) -> &'static [&'static str] {
1148 &[]
1149 }
1150
1151 /// Allowed child types — see [`PageTypeHandler::allowed_child_types`].
1152 fn allowed_child_types(&self) -> &'static [&'static str] {
1153 &[]
1154 }
1155
1156 /// Whether this type may be created from the admin — see
1157 /// [`PageTypeHandler::is_creatable`].
1158 fn is_creatable(&self) -> bool {
1159 true
1160 }
1161
1162 /// Public feed slug — see [`PageTypeHandler::feed_kind`].
1163 /// The derive prefers a struct-level
1164 /// `#[page_type(feed_kind = "…")]` attr over this default, so
1165 /// most authors set it via the attribute, not by overriding here.
1166 fn feed_kind(&self) -> Option<&'static str> {
1167 None
1168 }
1169
1170 /// Workflow opt-in slug — see [`PageTypeHandler::workflow_slug`].
1171 /// The derive prefers a struct-level
1172 /// `#[page_type(workflow = "Editorial review")]` attr over this
1173 /// default. Override here only when the workflow needs to be
1174 /// computed (e.g. choose between workflows based on tenant
1175 /// configuration).
1176 fn workflow_slug(&self) -> Option<&'static str> {
1177 None
1178 }
1179
1180 /// Per-type access gate — see [`PageTypeHandler::view_restriction`].
1181 /// Override to require a login or a permission codename for every
1182 /// page of this type. The derive forwards to this automatically.
1183 fn view_restriction(&self) -> Option<crate::view_restriction::TypeViewRestriction> {
1184 None
1185 }
1186
1187 /// Which representation this type serves — see
1188 /// [`PageTypeHandler::view_mode`]. Override to return
1189 /// [`crate::page_view::PageViewMode::Api`] when the type should
1190 /// answer JSON on its own URL. The derive forwards to this unless
1191 /// `#[page_type(view_mode = "…")]` is set, which wins.
1192 fn view_mode(&self) -> crate::page_view::PageViewMode {
1193 crate::page_view::PageViewMode::Auto
1194 }
1195
1196 /// Computed display chips — see [`PageTypeHandler::display_fields`].
1197 async fn display_fields(
1198 &self,
1199 _pool: &Pool,
1200 _page_id: i64,
1201 ) -> Result<Vec<DisplayField>, ExecError> {
1202 Ok(Vec::new())
1203 }
1204
1205 /// Handler-injected template ctx — see
1206 /// [`PageTypeHandler::public_context`]. The derive forwards to
1207 /// this override automatically; hand-rolled handlers can opt in
1208 /// via `impl PageTypeOverrides for MyHandler { … }`.
1209 async fn public_context(
1210 &self,
1211 _pool: &Pool,
1212 _page: &crate::page::Page,
1213 ) -> Result<serde_json::Map<String, Value>, ExecError> {
1214 Ok(serde_json::Map::new())
1215 }
1216
1217 /// Override the children listing this page exposes to its template —
1218 /// see [`PageTypeHandler::children_query`]. Return `Ok(None)` (the
1219 /// default) to keep the framework behavior (all immediate children,
1220 /// `sort_order, id`, drafts included). Return `Ok(Some(pages))` to
1221 /// make this type an index that lists e.g. only published children in
1222 /// a custom order — [`published_children`] is the common building
1223 /// block:
1224 ///
1225 /// ```ignore
1226 /// async fn children_query(&self, pool, page)
1227 /// -> Result<Option<Vec<Page>>, ExecError>
1228 /// {
1229 /// Ok(Some(rustango_cms::published_children(pool, page).await?))
1230 /// }
1231 /// ```
1232 ///
1233 /// The derive forwards to this override automatically.
1234 async fn children_query(
1235 &self,
1236 _pool: &Pool,
1237 _page: &crate::page::Page,
1238 ) -> Result<Option<Vec<crate::page::Page>>, ExecError> {
1239 Ok(None)
1240 }
1241
1242 /// Routable URL patterns — see [`PageTypeHandler::routes`].
1243 fn routes(&self) -> Vec<crate::routable::RouteSpec> {
1244 Vec::new()
1245 }
1246
1247 /// Route-specific ctx — see [`PageTypeHandler::route_context`].
1248 async fn route_context(
1249 &self,
1250 _pool: &Pool,
1251 _page: &crate::page::Page,
1252 _matched: &crate::routable::RouteMatch,
1253 ) -> Result<serde_json::Map<String, Value>, ExecError> {
1254 Ok(serde_json::Map::new())
1255 }
1256
1257 /// Handler-contributed tabs — see [`PageTypeHandler::extra_tabs`].
1258 async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
1259 Ok(Vec::new())
1260 }
1261}
1262
1263#[cfg(all(test, feature = "sqlite"))]
1264mod preview_tests {
1265 use super::*;
1266 use crate::widget::{Widget, WidgetKind};
1267
1268 struct Choosers;
1269
1270 #[async_trait]
1271 impl PageTypeHandler for Choosers {
1272 fn app_label(&self) -> &'static str {
1273 "cms"
1274 }
1275 fn type_name(&self) -> &'static str {
1276 "Choosers"
1277 }
1278 fn verbose_name(&self) -> &'static str {
1279 "Choosers"
1280 }
1281 fn default_template(&self) -> &'static str {
1282 "c.html"
1283 }
1284 async fn widgets(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<Widget>, ExecError> {
1285 Ok(vec![
1286 Widget::new(WidgetKind::PageChooser, "related", "Related"),
1287 Widget::new(WidgetKind::SnippetChooser, "cta", "CTA"),
1288 Widget::new(WidgetKind::DocumentChooser, "doc", "Doc"),
1289 ])
1290 }
1291 }
1292
1293 /// Live preview types every chooser id as the saved page does.
1294 #[tokio::test]
1295 async fn preview_types_chooser_ids_like_the_saved_value() {
1296 let pool = Pool::connect("sqlite::memory:").await.expect("pool");
1297 let form = std::collections::HashMap::from([
1298 ("related".to_owned(), "7".to_owned()),
1299 ("cta".to_owned(), "3".to_owned()),
1300 ("doc".to_owned(), String::new()),
1301 ]);
1302 let v = Choosers.preview_extension(&pool, 1, &form).await.expect("preview");
1303 assert_eq!(v, serde_json::json!({ "related": 7, "cta": 3, "doc": null }));
1304 }
1305}