rustango_cms/widget/mod.rs
1//! Widget descriptors — the single primitive both flat extension
2//! fields ([`crate::page_type::ExtensionField`]) and stream-block
3//! fields ([`crate::block::BlockField::Widget`], landing in a later
4//! slice) use to describe one form input.
5//!
6//! ## Why one shared primitive
7//!
8//! A custom input should not need a stack of parallel artifacts
9//! (server class, client class, adapter, template, CSS, media
10//! manifest) wired together by string-keyed names that fail at
11//! runtime.
12//!
13//! Here a widget is **one Tera template + one `WidgetKind` enum
14//! variant** (or one inventory registration for custom widgets — see
15//! [`register_widget!`](crate::register_widget!)). Every widget is server-rendered;
16//! the only client JS the admin ships is generic add/remove/reorder
17//! for stream lists and doesn't know what a widget is.
18//!
19//! ## Surface
20//!
21//! - [`WidgetKind`] enumerates every built-in input type. New kinds
22//! only show up here; templates pick them up automatically.
23//! - [`Widget`] carries `(kind, name, label, value, options, …)` —
24//! the runtime metadata for one rendered input.
25//! - [`registry`] holds the inventory plumbing for **third-party
26//! custom widgets** that ship outside this crate.
27
28pub mod registry;
29
30use serde::{Deserialize, Serialize};
31
32/// Which form input to draw. Templates dispatch on this variant via
33/// the bundled `rcms_admin/_widget.html` Tera macro.
34///
35/// Serialized as a flat lowercase string (`"text"`, `"datetimetz"`,
36/// `"multiselect"`, …) so `{% if w.kind == "datetimetz" %}` matches
37/// every template author intuitively.
38///
39/// Custom widgets keep the kind as `"custom"`; the third-party
40/// widget's wire name lives in [`Widget::custom_name`] so the macro
41/// can dispatch to the right registered template.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "lowercase")]
44pub enum WidgetKind {
45 // ---- text-shaped ------------------------------------------------
46 /// Single-line `<input type="text">`.
47 Text,
48 /// Multi-line `<textarea>` — plain content.
49 Textarea,
50 /// Multi-line `<textarea>` with a "preview as markdown" affordance.
51 /// Rendered through [`crate::markdown::render`] on the public site.
52 Markdown,
53 /// Rich-text WYSIWYG widget (v1: same shape as Markdown — a
54 /// `<textarea>` with `data-widget="richtext"` to which host apps
55 /// can attach their own enhancer, e.g. EasyMDE / TipTap).
56 RichText,
57 /// `<input type="email">` — browser validates the shape.
58 Email,
59 /// `<input type="url">`.
60 Url,
61 /// `<input type="tel">`.
62 Tel,
63 /// `<input type="password">`. Rare in a CMS surface but
64 /// completes the set (e.g. for storing API keys on snippets).
65 Password,
66 /// `<input type="hidden">` — passes values through without
67 /// drawing an input.
68 Hidden,
69
70 // ---- numeric ----------------------------------------------------
71 /// `<input type="number">`. No min/max bound by default.
72 Number,
73 /// `<input type="number">` constrained to integers.
74 Integer,
75 /// `<input type="number" step="any">` for free-form decimals.
76 Float,
77 /// `<input type="range">` slider — pair with `min`/`max`/`step`.
78 Range,
79
80 // ---- boolean / checkbox ----------------------------------------
81 /// Single `<input type="checkbox">` — present-or-absent.
82 Boolean,
83
84 // ---- date / time -----------------------------------------------
85 /// `<input type="date">`. Stored as ISO-8601 `YYYY-MM-DD`.
86 Date,
87 /// `<input type="time">`. Stored as `HH:MM[:SS]`.
88 Time,
89 /// `<input type="datetime-local">`. Stored as
90 /// `YYYY-MM-DDTHH:MM[:SS]` (no timezone).
91 Datetime,
92 /// Pair of `<input type="datetime-local">` + a timezone
93 /// `<select>` (IANA names). Value is the RFC 3339 string the
94 /// public-side renderer can parse with `chrono::DateTime`.
95 DatetimeTz,
96
97 // ---- color -----------------------------------------------------
98 /// `<input type="color">` — hex `#RRGGBB`.
99 Color,
100
101 // ---- file / media ----------------------------------------------
102 /// `<input type="file">` — raw upload, no library indirection.
103 /// Distinct from [`Self::MediaPicker`] (which picks an existing
104 /// `cms_media` row by id).
105 File,
106 /// Media library picker — value is the `cms_media.id` as a
107 /// stringified integer. Empty = no selection.
108 MediaPicker,
109 /// Page chooser — modal `<dialog>` overlay listing pages by
110 /// title; value is the `cms_page.id` as a stringified integer.
111 /// Empty = no selection. Backs the
112 /// `PageChooserBlock` + any FK-to-page extension field.
113 PageChooser,
114 /// Snippet chooser — modal `<dialog>` overlay listing snippets
115 /// (optionally filtered to one `type_name` via
116 /// [`Widget::custom_name`]); value is the `cms_snippet.id` as a
117 /// stringified integer. Backs the
118 /// `SnippetChooserBlock`.
119 SnippetChooser,
120 /// Snippet many-to-many chooser — multi-select chooser listing
121 /// snippets of one `type_name` (in [`Widget::custom_name`]);
122 /// value is a JSON-array string of selected `cms_snippet.id`
123 /// values in chooser order. Backs page ↔ snippet
124 /// many-to-many relations. Storage lives in the
125 /// `cms_page_snippet_m2m` through-table — the widget's
126 /// [`Widget::name`] is the M2M `relation_name`, [`Widget::value`]
127 /// is the JSON array the editor submits. Hosts call
128 /// [`crate::page_snippet_m2m::replace_all`] from their
129 /// `save_extension` override and
130 /// [`crate::page_snippet_m2m::related_snippets`] from
131 /// `load_extension` (or `public_context`) until the derive-macro
132 /// hook lands to do that wiring automatically.
133 SnippetM2M,
134 /// Document chooser — modal `<dialog>` overlay listing media
135 /// rows of `kind = "document"`; value is the `cms_media.id` as
136 /// a stringified integer. Distinct from [`Self::MediaPicker`]
137 /// (which filters to images today). Backs the
138 /// `DocumentChooserBlock`.
139 DocumentChooser,
140 /// Generic model chooser — modal overlay over any
141 /// `register_chooser!`ed model. The registered chooser **slug**
142 /// lives in [`Widget::custom_name`] and becomes the
143 /// `data-chooser-kind`, which the cms-ux.js overlay resolves to
144 /// `/cms-admin/__chooser/<slug>`. Value is the chosen row's id as
145 /// a stringified integer. Build with [`Widget::model_chooser`].
146 ModelChooser,
147
148 // ---- choice (flat — variant is first-class) -------------------
149 /// Stacked `<input type="radio">` group. Single-choice. Reads
150 /// `(value, label)` pairs from [`Widget::options`].
151 Radio,
152 /// `<select>` dropdown. Single-choice. Reads from
153 /// [`Widget::options`].
154 Select,
155 /// Stacked `<input type="checkbox">` group. Multi-choice; value
156 /// is a JSON array string. Reads from [`Widget::options`].
157 Checkboxes,
158 /// `<select multiple>`. Multi-choice; value is a JSON array
159 /// string. Reads from [`Widget::options`].
160 MultiSelect,
161
162 // ---- streamfield -----------------------------------------------
163 /// StreamField — a list of composable blocks
164 /// (Heading / Paragraph / Image / Quote / nested two-column / …).
165 /// The list of *allowed* block types lives in [`Widget::allowed`];
166 /// every entry must resolve to a registered [`crate::Block`].
167 ///
168 /// Storage shape: a JSON-array string of
169 /// `{type, id, value}` envelopes — see [`crate::block`] for the
170 /// full wire-format spec. Round-tripped through the editor as one
171 /// hidden form field; the admin macro renders the recursive
172 /// stream editor and the server deserializes the JSON on submit.
173 Stream,
174
175 // ---- escape hatch ----------------------------------------------
176 /// Third-party-registered widget. The wire name lives in
177 /// [`Widget::custom_name`]; look it up via
178 /// [`registry::find_custom_widget`] and render its template.
179 Custom,
180}
181
182impl WidgetKind {
183 /// Lowercase wire-format tag matching the serde rename. Used by
184 /// the template macro's `{% if w.kind == "…" %}` arms and tests.
185 #[must_use]
186 pub fn as_tag(&self) -> &'static str {
187 match self {
188 Self::Text => "text",
189 Self::Textarea => "textarea",
190 Self::Markdown => "markdown",
191 Self::RichText => "richtext",
192 Self::Email => "email",
193 Self::Url => "url",
194 Self::Tel => "tel",
195 Self::Password => "password",
196 Self::Hidden => "hidden",
197 Self::Number => "number",
198 Self::Integer => "integer",
199 Self::Float => "float",
200 Self::Range => "range",
201 Self::Boolean => "boolean",
202 Self::Date => "date",
203 Self::Time => "time",
204 Self::Datetime => "datetime",
205 Self::DatetimeTz => "datetimetz",
206 Self::Color => "color",
207 Self::File => "file",
208 Self::MediaPicker => "mediapicker",
209 Self::PageChooser => "pagechooser",
210 Self::SnippetChooser => "snippetchooser",
211 Self::SnippetM2M => "snippetm2m",
212 Self::DocumentChooser => "documentchooser",
213 Self::ModelChooser => "modelchooser",
214 Self::Radio => "radio",
215 Self::Select => "select",
216 Self::Checkboxes => "checkboxes",
217 Self::MultiSelect => "multiselect",
218 Self::Stream => "stream",
219 Self::Custom => "custom",
220 }
221 }
222
223 /// `true` for widgets whose wire contract POSTs a JSON-encoded
224 /// string in a single form field — `Checkboxes` / `MultiSelect`
225 /// (JSON arrays of strings), `Stream` (JSON array of block
226 /// envelopes), and `SnippetM2M` (JSON array of i64 snippet ids,
227 /// ordered).
228 #[must_use]
229 pub fn is_multi_value(&self) -> bool {
230 matches!(
231 self,
232 Self::Checkboxes | Self::MultiSelect | Self::Stream | Self::SnippetM2M,
233 )
234 }
235
236 /// `true` for widgets whose value is author-facing free text worth
237 /// translating per locale — single/multi-line text, Markdown source,
238 /// and RichText HTML. Everything else is structural (ids, numbers,
239 /// dates, choices) or an identifier (`Email`/`Url`/`Tel`) and is
240 /// never stored as a translation override. Drives the StreamField
241 /// translation walker in [`crate::block::translate`].
242 #[must_use]
243 pub fn is_translatable_text(&self) -> bool {
244 matches!(
245 self,
246 Self::Text | Self::Textarea | Self::Markdown | Self::RichText,
247 )
248 }
249}
250
251/// Runtime descriptor for one rendered form input. Built by
252/// `PageTypeHandler::extension_fields` (and, in a later slice, by
253/// `Block::fields` → `BlockField::Widget`) and consumed by the
254/// `_widget.html` Tera macro.
255///
256/// ## Fields
257///
258/// - `name` — HTML form `name=`. Also the key the POST handler
259/// `form_map.get(...)` reads back on submit.
260/// - `kind` — picks the input type. See [`WidgetKind`].
261/// - `custom_name` — wire name for a [`WidgetKind::Custom`]
262/// registration. Looked up at render time via
263/// [`registry::find_custom_widget`]. Ignored for built-in kinds.
264/// - `label` — display label above / next to the input.
265/// - `value` — pre-fill value. For multi-value widgets
266/// ([`WidgetKind::Checkboxes`] / [`WidgetKind::MultiSelect`]) the
267/// value is the JSON-array string the client POSTs back verbatim.
268/// - `options` — `(value, label)` pairs for choice widgets.
269/// - `help` — short hint rendered under the input.
270/// - `placeholder` — `placeholder=` attribute for text-shaped
271/// inputs.
272/// - `required` — emits the HTML5 `required` attribute.
273/// - `min` / `max` / `step` — clamps for numeric / date / range
274/// inputs.
275/// - `max_length` — max-length cap for string inputs.
276/// - `read_only` — emits HTML5 `readonly`; for fully-non-editable
277/// display use the page-level
278/// [`crate::page_type::DisplayField`] instead.
279#[derive(Debug, Clone, Serialize, Deserialize)]
280pub struct Widget {
281 pub name: String,
282 pub kind: WidgetKind,
283 #[serde(default)]
284 pub custom_name: String,
285 /// Pre-rendered HTML for [`WidgetKind::Custom`] widgets — the
286 /// admin handler walks each widget, looks up the registered
287 /// template via [`registry::find_custom_widget`], renders it
288 /// once before stamping into Tera context, and stores the
289 /// result here. The bundled `_widget.html` macro emits it
290 /// `| safe`. Empty for non-Custom widgets.
291 #[serde(default)]
292 pub custom_html: String,
293 pub label: String,
294 #[serde(default)]
295 pub value: String,
296 /// Choice options as `(value, label)` pairs. Always serialized
297 /// (even when empty) so the bundled `_widget.html` macro's
298 /// `{% for opt in w.options %}` loops don't throw an
299 /// undefined-variable error on widgets that don't use options.
300 #[serde(default)]
301 pub options: Vec<(String, String)>,
302 /// String fields below are always serialized (empty = falsy in
303 /// Tera) so `{% if w.foo %}` checks in `_widget.html` don't
304 /// trip Tera's "Variable not found" error when the slot is
305 /// unset. Same rule applies to `variant`, `pattern`, etc.
306 #[serde(default)]
307 pub help: String,
308 #[serde(default)]
309 pub placeholder: String,
310 #[serde(default)]
311 pub required: bool,
312 #[serde(default)]
313 pub min: Option<f64>,
314 #[serde(default)]
315 pub max: Option<f64>,
316 #[serde(default)]
317 pub step: Option<String>,
318 #[serde(default)]
319 pub max_length: Option<u32>,
320 /// HTML5 `minlength` for string-shaped widgets.
321 #[serde(default)]
322 pub min_length: Option<u32>,
323 /// HTML5 `pattern` regex for string-shaped widgets — browser
324 /// validates on form submit.
325 #[serde(default)]
326 pub pattern: String,
327 #[serde(default)]
328 pub read_only: bool,
329 /// For [`WidgetKind::Stream`] only — the block `type_name`s
330 /// permitted at the top level of this stream. Boot-time
331 /// validation in [`crate::block::validate_block_registry`]
332 /// verifies every entry resolves to a registered
333 /// [`crate::Block`]. Empty for non-Stream widgets.
334 #[serde(default)]
335 pub allowed: Vec<String>,
336 /// Style variant — handler opt-in to a visual variant of the
337 /// canonical widget. Today only `"switch"` is recognised by the
338 /// `_widget.html` macro (on [`WidgetKind::Boolean`], renders the
339 /// checkbox as an iOS-style toggle). Empty = use the default.
340 #[serde(default)]
341 pub variant: String,
342}
343
344impl Widget {
345 /// Smallest possible widget — just `(kind, name, label)`. Caller
346 /// fluently adds the rest via `.with_*` methods.
347 #[must_use]
348 pub fn new(kind: WidgetKind, name: impl Into<String>, label: impl Into<String>) -> Self {
349 Self {
350 name: name.into(),
351 kind,
352 custom_name: String::new(),
353 custom_html: String::new(),
354 label: label.into(),
355 value: String::new(),
356 options: Vec::new(),
357 help: String::new(),
358 placeholder: String::new(),
359 required: false,
360 min: None,
361 max: None,
362 step: None,
363 max_length: None,
364 min_length: None,
365 pattern: String::new(),
366 read_only: false,
367 allowed: Vec::new(),
368 variant: String::new(),
369 }
370 }
371
372 /// Fluent: set HTML5 `minlength`.
373 #[must_use]
374 pub fn with_min_length(mut self, n: u32) -> Self {
375 self.min_length = Some(n);
376 self
377 }
378
379 /// Fluent: set HTML5 `pattern` regex.
380 #[must_use]
381 pub fn with_pattern(mut self, p: impl Into<String>) -> Self {
382 self.pattern = p.into();
383 self
384 }
385
386 /// Style variant opt-in. Currently meaningful for
387 /// [`WidgetKind::Boolean`] (`"switch"` flips to iOS-style toggle).
388 #[must_use]
389 pub fn with_variant(mut self, variant: impl Into<String>) -> Self {
390 self.variant = variant.into();
391 self
392 }
393
394 /// Shortcut for a [`WidgetKind::Stream`] widget — pairs the
395 /// `name` / `label` with the list of allowed top-level block
396 /// `type_name`s. Every entry must resolve to a registered
397 /// [`crate::Block`] (boot-time validation enforces this).
398 #[must_use]
399 pub fn stream<S: Into<String>>(
400 name: impl Into<String>,
401 label: impl Into<String>,
402 allowed: impl IntoIterator<Item = S>,
403 ) -> Self {
404 Self {
405 allowed: allowed.into_iter().map(Into::into).collect(),
406 ..Self::new(WidgetKind::Stream, name, label)
407 }
408 }
409
410 /// Shortcut for a [`WidgetKind::Custom`] widget — pairs the
411 /// `kind` with the third-party registration `custom_name` looked
412 /// up at render time through [`registry::find_custom_widget`].
413 #[must_use]
414 pub fn custom(
415 custom_name: impl Into<String>,
416 name: impl Into<String>,
417 label: impl Into<String>,
418 ) -> Self {
419 Self {
420 custom_name: custom_name.into(),
421 ..Self::new(WidgetKind::Custom, name, label)
422 }
423 }
424
425 #[must_use]
426 pub fn with_value(mut self, v: impl Into<String>) -> Self {
427 self.value = v.into();
428 self
429 }
430
431 #[must_use]
432 pub fn with_help(mut self, h: impl Into<String>) -> Self {
433 self.help = h.into();
434 self
435 }
436
437 #[must_use]
438 pub fn with_placeholder(mut self, p: impl Into<String>) -> Self {
439 self.placeholder = p.into();
440 self
441 }
442
443 #[must_use]
444 pub fn required(mut self) -> Self {
445 self.required = true;
446 self
447 }
448
449 #[must_use]
450 pub fn read_only(mut self) -> Self {
451 self.read_only = true;
452 self
453 }
454
455 #[must_use]
456 pub fn with_options<I, V, L>(mut self, options: I) -> Self
457 where
458 I: IntoIterator<Item = (V, L)>,
459 V: Into<String>,
460 L: Into<String>,
461 {
462 self.options = options
463 .into_iter()
464 .map(|(v, l)| (v.into(), l.into()))
465 .collect();
466 self
467 }
468
469 /// Convenience constructor for the Page↔Snippet M2M
470 /// chooser. The widget's `name` becomes the M2M
471 /// `relation_name` (the field on the page that this chooser
472 /// populates), and `snippet_type_name` lands in
473 /// [`Self::custom_name`] where the template reads it. Hosts
474 /// then call [`Self::with_options`] with the eligible
475 /// `(snippet_id, snippet_title)` pairs they fetched from
476 /// `cms_snippet` for that type — until the derive-macro hook
477 /// lands and does the population automatically.
478 ///
479 /// ```ignore
480 /// use rustango_cms::widget::Widget;
481 /// // In the handler's `widgets()` impl, after fetching
482 /// // `let cats = Snippet::objects().where_(...).fetch(pool).await?;`
483 /// vec![Widget::snippet_m2m("categories", "Categories", "Category")
484 /// .with_options(cats.iter().map(|s|
485 /// (s.id.get().copied().unwrap_or_default().to_string(),
486 /// s.title.clone())))]
487 /// ```
488 #[must_use]
489 pub fn snippet_m2m(
490 relation_name: impl Into<String>,
491 label: impl Into<String>,
492 snippet_type_name: impl Into<String>,
493 ) -> Self {
494 let mut w = Self::new(WidgetKind::SnippetM2M, relation_name, label);
495 w.custom_name = snippet_type_name.into();
496 w
497 }
498
499 /// Build a generic model-chooser widget for the
500 /// `register_chooser!`ed model registered under `chooser_slug`.
501 /// The value is the chosen row's id (stringified). The slug rides
502 /// in [`Self::custom_name`] → `data-chooser-kind` → the cms-ux.js
503 /// overlay's `/cms-admin/__chooser/<slug>` endpoint.
504 ///
505 /// ```ignore
506 /// use rustango_cms::widget::Widget;
507 /// // In a PageTypeHandler's `widgets()` impl:
508 /// vec![Widget::model_chooser("author_id", "Author", "author")
509 /// .with_value(stored_id)]
510 /// ```
511 #[must_use]
512 pub fn model_chooser(
513 field_name: impl Into<String>,
514 label: impl Into<String>,
515 chooser_slug: impl Into<String>,
516 ) -> Self {
517 let mut w = Self::new(WidgetKind::ModelChooser, field_name, label);
518 w.custom_name = chooser_slug.into();
519 w
520 }
521
522 #[must_use]
523 pub fn with_min(mut self, m: f64) -> Self {
524 self.min = Some(m);
525 self
526 }
527
528 #[must_use]
529 pub fn with_max(mut self, m: f64) -> Self {
530 self.max = Some(m);
531 self
532 }
533
534 #[must_use]
535 pub fn with_step(mut self, s: impl Into<String>) -> Self {
536 self.step = Some(s.into());
537 self
538 }
539
540 #[must_use]
541 pub fn with_max_length(mut self, n: u32) -> Self {
542 self.max_length = Some(n);
543 self
544 }
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 #[test]
552 fn snippet_m2m_kind_round_trips_as_tag() {
553 assert_eq!(WidgetKind::SnippetM2M.as_tag(), "snippetm2m");
554 }
555
556 #[test]
557 fn snippet_m2m_is_multi_value() {
558 assert!(WidgetKind::SnippetM2M.is_multi_value());
559 assert!(WidgetKind::Stream.is_multi_value());
560 assert!(WidgetKind::MultiSelect.is_multi_value());
561 assert!(WidgetKind::Checkboxes.is_multi_value());
562 // Sanity: single-value kinds still report false so the
563 // boundary between scalar and JSON-array wire shape is
564 // explicit.
565 assert!(!WidgetKind::Text.is_multi_value());
566 assert!(!WidgetKind::SnippetChooser.is_multi_value());
567 }
568
569 #[test]
570 fn snippet_m2m_constructor_sets_custom_name_to_type() {
571 let w = Widget::snippet_m2m("categories", "Categories", "Category");
572 assert_eq!(w.kind, WidgetKind::SnippetM2M);
573 assert_eq!(w.name, "categories");
574 assert_eq!(w.label, "Categories");
575 // `custom_name` carries the snippet type the template uses
576 // to render the "Snippets of type X" hint + the eventual
577 // type filter on the chooser.
578 assert_eq!(w.custom_name, "Category");
579 }
580}