Skip to main content

rustango_cms/block/
mod.rs

1//! StreamField — composable body blocks.
2//!
3//! A `Block` is one type of node that can sit in a `WidgetKind::Stream`
4//! list. Each block declares its structural shape via [`Block::fields`]
5//! — a `Vec<BlockField>` of leaves ([`BlockField::Widget`] /
6//! [`BlockField::Computed`]) and nested containers ([`BlockField::Stream`]
7//! / [`BlockField::Repeat`]). The same `BlockField` enum covers
8//! struct, stream and list blocks
9//! in one recursive shape so the validator + renderer + admin editor
10//! all reuse a single walker.
11//!
12//! ## JSON wire format
13//!
14//! A stream's stored JSON is an array of `{type, id, value}` tuples:
15//!
16//! ```json
17//! [
18//!   { "type": "heading", "id": "550e8400-…", "value": { "text": "Hi" } },
19//!   { "type": "two_column", "id": "…", "value": {
20//!       "left":  [ {"type": "image", "id": "…", "value": { "media_id": 4 } } ],
21//!       "right": [ {"type": "paragraph", "id": "…", "value": { "body": "…" } } ]
22//!   }}
23//! ]
24//! ```
25//!
26//! - Multi-field block: `value` is a flat dict keyed by [`BlockField`] `name`s.
27//! - Single-field block: canonical shape is still `{<name>: <scalar>}`,
28//!   but a bare scalar at `value` is also accepted on the way in.
29//! - `id` is a UUID v4 minted client-side on insert; never re-minted on edit.
30//! - `Repeat` (homogeneous) stores `[{type: item_type, id, value}, …]` — same
31//!   shape as `Stream`, single allowed type.
32//!
33//! ## A small trait surface
34//!
35//! The editor is one Tera macro and a block is one Rust trait, so a
36//! block needs only three required
37//! methods ([`Block::type_name`], [`Block::verbose_name`],
38//! [`Block::fields`]) and four optional ones with defaults
39//! ([`Block::icon`], [`Block::group`], [`Block::version`],
40//! [`Block::template`]). [`Block::render`] and [`Block::migrate`] have
41//! generic default impls.
42
43use serde::Serialize;
44use serde_json::Value;
45use thiserror::Error;
46
47use crate::widget::WidgetKind;
48
49pub mod registry;
50
51pub use registry::{find_block, registered_blocks, validate_block_registry, BlockRegistration};
52
53/// Per-block, sync render error. Stays sync because every render
54/// step is pure JSON → HTML — no IO during the rendering pass.
55#[derive(Debug, Error)]
56pub enum BlockError {
57    /// The stored JSON didn't match the block's [`Block::fields`]
58    /// schema. Carries a path so admin can highlight the offending
59    /// block.
60    #[error("block `{block_type}` at `{path}`: {reason}")]
61    Shape {
62        block_type: String,
63        path: String,
64        reason: String,
65    },
66
67    /// `type_name` in the stored JSON doesn't resolve to a registered
68    /// block. Surfaces as the yellow schema-drift banner in the editor.
69    #[error("unknown block type `{0}` (not registered via `register_block!`)")]
70    UnknownType(String),
71
72    /// `register_block!` returned a `Block::fields()` entry referring
73    /// to a non-existent block type via `Stream::allowed` or
74    /// `Repeat::item_type`. Caught at boot-time via
75    /// [`validate_block_registry`].
76    #[error("block `{owner}` references unregistered type `{referred}`")]
77    DanglingReference {
78        owner: &'static str,
79        referred: &'static str,
80    },
81
82    /// `block.migrate(from, value)` failed to upgrade an older
83    /// version. Original JSON is kept on the record; the editor
84    /// surfaces the failure in the schema-drift banner.
85    #[error("block `{block_type}` migrate {from}→{to} failed: {reason}")]
86    MigrateFailed {
87        block_type: String,
88        from: u32,
89        to: u32,
90        reason: String,
91    },
92
93    /// Tera failure during a block's render. The block's template path
94    /// + the underlying Tera message land in the body.
95    #[error("block `{block_type}` template `{template}` render failed: {source}")]
96    TemplateRender {
97        block_type: String,
98        template: String,
99        #[source]
100        source: tera::Error,
101    },
102}
103
104/// Per-field validators threaded into the rendered widget's HTML5
105/// attributes (`minlength`, `maxlength`, `pattern`, `min`, `max`)
106/// + the block-field-side initial value. Default value is "no
107/// constraints", so existing call sites get backwards-compatible
108/// behaviour after the migration to the sub-struct.
109#[derive(Debug, Clone, Default, Serialize)]
110pub struct BlockFieldMeta {
111    /// HTML5 `minlength` on string-shaped widgets (Text, Textarea,
112    /// Email, URL, Password, Tel).
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub min_length: Option<u32>,
115    /// HTML5 `maxlength` on string-shaped widgets. Mirrors
116    /// `Widget::max_length` already on the rendered widget — the
117    /// meta entry wins when both are set.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub max_length: Option<u32>,
120    /// HTML5 `pattern` regex on string-shaped widgets. Browser
121    /// validates on form submit; the server should re-validate
122    /// (TODO: server-side enforcement is a follow-up).
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub pattern: Option<String>,
125    /// HTML5 `min` on numeric / date widgets. Distinct from
126    /// `Widget::min` already on the rendered widget — the meta entry
127    /// wins when both are set.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub min_value: Option<f64>,
130    /// HTML5 `max` on numeric / date widgets.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub max_value: Option<f64>,
133    /// Initial value when a fresh instance of this widget is
134    /// inserted. Serialised through the widget's `value` field so
135    /// the editor shows the default in the empty-block template.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub default_value: Option<String>,
138    /// Narrows a snippet chooser to one library type (its `type_name`),
139    /// e.g. `"form"` so the picker lists forms only.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub chooser_filter: Option<String>,
142}
143
144impl BlockFieldMeta {
145    /// Empty meta — sensible default for the 19 built-in blocks
146    /// that don't declare any per-field constraints.
147    #[must_use]
148    pub fn none() -> Self {
149        Self::default()
150    }
151
152    /// `true` when every option is `None` — used by `serde` to skip
153    /// the `meta` slot on the wire when no validators are set.
154    #[must_use]
155    pub fn is_default(&self) -> bool {
156        self.min_length.is_none()
157            && self.max_length.is_none()
158            && self.pattern.is_none()
159            && self.min_value.is_none()
160            && self.max_value.is_none()
161            && self.default_value.is_none()
162            && self.chooser_filter.is_none()
163    }
164
165    /// Fluent: set HTML5 `minlength`.
166    #[must_use]
167    pub fn min_length(mut self, n: u32) -> Self {
168        self.min_length = Some(n);
169        self
170    }
171    /// Fluent: set HTML5 `maxlength`.
172    #[must_use]
173    pub fn max_length(mut self, n: u32) -> Self {
174        self.max_length = Some(n);
175        self
176    }
177    /// Fluent: set HTML5 `pattern` regex.
178    #[must_use]
179    pub fn pattern(mut self, p: impl Into<String>) -> Self {
180        self.pattern = Some(p.into());
181        self
182    }
183    /// Fluent: set numeric `min`.
184    #[must_use]
185    pub fn min_value(mut self, v: f64) -> Self {
186        self.min_value = Some(v);
187        self
188    }
189    /// Fluent: set numeric `max`.
190    #[must_use]
191    pub fn max_value(mut self, v: f64) -> Self {
192        self.max_value = Some(v);
193        self
194    }
195    /// Fluent: set widget initial value.
196    #[must_use]
197    pub fn default_value(mut self, v: impl Into<String>) -> Self {
198        self.default_value = Some(v.into());
199        self
200    }
201    /// Fluent: narrow a snippet chooser to one library type.
202    #[must_use]
203    pub fn chooser_filter(mut self, type_name: impl Into<String>) -> Self {
204        self.chooser_filter = Some(type_name.into());
205        self
206    }
207}
208
209/// Per-block-type cardinality constraint on a [`BlockField::Stream`]
210/// (block counts). Empty (`None` / `None`) means
211/// "no constraint on this type". Independent of the stream-wide
212/// `min` / `max` already on the variant.
213#[derive(Debug, Clone, Copy, Default, Serialize)]
214pub struct BlockCountConstraint {
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub min: Option<u32>,
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub max: Option<u32>,
219}
220
221/// One declared field inside a block's structural shape. The four
222/// variants together cover struct, stream, list and static
223/// blocks — a single
224/// recursive enum, walked once, validated once, rendered once.
225#[derive(Debug, Clone, Serialize)]
226#[serde(tag = "kind", rename_all = "snake_case")]
227pub enum BlockField {
228    /// A scalar leaf. Pairs a name with one
229    /// rcms [`WidgetKind`] for the admin editor; the JSON value is
230    /// whatever shape that widget POSTs.
231    Widget {
232        name: String,
233        label: String,
234        widget: WidgetKind,
235        /// Choice-widget `(value, label)` pairs. Empty for non-choice
236        /// kinds. Matches the existing [`crate::widget::Widget::options`]
237        /// shape.
238        #[serde(default, skip_serializing_if = "Vec::is_empty")]
239        options: Vec<(String, String)>,
240        #[serde(default, skip_serializing_if = "Option::is_none")]
241        help: Option<String>,
242        #[serde(default)]
243        required: bool,
244        /// HTML5 / value validators (`min_length`, `max_length`,
245        /// `pattern`, `min_value`, `max_value`, `default_value`).
246        /// Default = no constraints; threaded into the rendered
247        /// `Widget` at editor render time.
248        #[serde(default, skip_serializing_if = "BlockFieldMeta::is_default")]
249        meta: BlockFieldMeta,
250    },
251
252    /// A read-only computed leaf — pure function of the block value.
253    /// Renders inline in the admin editor + on the public page. No
254    /// JSON column, no form input. Same idea as the
255    /// `DisplayField` shape.
256    Computed {
257        name: String,
258        label: String,
259        /// Pure function of the block's value. The default render
260        /// passes the *whole* block value (the `{name1: val1, …}`
261        /// dict) so computed fields can derive from siblings.
262        ///
263        /// Function pointer (not `Box<dyn Fn>`) so the variant stays
264        /// `Clone`-able cheaply and inventory-friendly.
265        #[serde(skip)]
266        render: fn(&Value, &BlockRenderCtx) -> String,
267        #[serde(default, skip_serializing_if = "Option::is_none")]
268        help: Option<String>,
269    },
270
271    /// Heterogeneous nested list. `allowed`
272    /// lists which registered block types may appear here. Boot-time
273    /// validation in [`validate_block_registry`] verifies every entry
274    /// resolves.
275    Stream {
276        name: String,
277        label: String,
278        allowed: Vec<String>,
279        #[serde(default, skip_serializing_if = "Option::is_none")]
280        min: Option<u32>,
281        #[serde(default, skip_serializing_if = "Option::is_none")]
282        max: Option<u32>,
283        /// Block counts — per-block-type cardinality
284        /// (e.g. `{"heading": BlockCountConstraint { min: Some(1),
285        /// max: Some(3) }}`). Independent of the stream-wide
286        /// `min` / `max`. Empty map = no per-type constraints.
287        #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
288        block_counts: std::collections::HashMap<String, BlockCountConstraint>,
289    },
290
291    /// Homogeneous nested list. Convenience
292    /// shorthand for `Stream { allowed: &[item_type] }` with the
293    /// admin editor showing a single "+ Add" button (no picker — only
294    /// one type is permitted).
295    Repeat {
296        name: String,
297        label: String,
298        item_type: String,
299        #[serde(default, skip_serializing_if = "Option::is_none")]
300        min: Option<u32>,
301        #[serde(default, skip_serializing_if = "Option::is_none")]
302        max: Option<u32>,
303    },
304}
305
306impl BlockField {
307    /// The wire-format `name` used as the dict key inside a block's
308    /// `value` object.
309    #[must_use]
310    pub fn name(&self) -> &str {
311        match self {
312            BlockField::Widget { name, .. } => name,
313            BlockField::Computed { name, .. } => name,
314            BlockField::Stream { name, .. } => name,
315            BlockField::Repeat { name, .. } => name,
316        }
317    }
318
319    /// Fluent constructor for a single-widget field.
320    #[must_use]
321    pub fn widget(name: impl Into<String>, label: impl Into<String>, widget: WidgetKind) -> Self {
322        BlockField::Widget {
323            name: name.into(),
324            label: label.into(),
325            widget,
326            options: Vec::new(),
327            help: None,
328            required: false,
329            meta: BlockFieldMeta::default(),
330        }
331    }
332
333    /// Fluent constructor for a stream field.
334    #[must_use]
335    pub fn stream<S: Into<String>>(
336        name: impl Into<String>,
337        label: impl Into<String>,
338        allowed: impl IntoIterator<Item = S>,
339    ) -> Self {
340        BlockField::Stream {
341            name: name.into(),
342            label: label.into(),
343            allowed: allowed.into_iter().map(Into::into).collect(),
344            min: None,
345            max: None,
346            block_counts: std::collections::HashMap::new(),
347        }
348    }
349
350    /// Fluent constructor for a repeat (single-type list) field.
351    #[must_use]
352    pub fn repeat(
353        name: impl Into<String>,
354        label: impl Into<String>,
355        item_type: impl Into<String>,
356    ) -> Self {
357        BlockField::Repeat {
358            name: name.into(),
359            label: label.into(),
360            item_type: item_type.into(),
361            min: None,
362            max: None,
363        }
364    }
365
366    /// Attach a validator pack ([`BlockFieldMeta`]) to a Widget
367    /// variant. No-op on the other variants. Built so authors can
368    /// chain: `BlockField::widget(...).with_meta(meta)`.
369    #[must_use]
370    pub fn with_meta(mut self, meta: BlockFieldMeta) -> Self {
371        if let BlockField::Widget {
372            meta: ref mut existing,
373            ..
374        } = self
375        {
376            *existing = meta;
377        }
378        self
379    }
380
381    /// Attach a per-block-type cardinality map to a Stream variant.
382    /// No-op on other variants.
383    #[must_use]
384    pub fn with_block_counts(
385        mut self,
386        counts: std::collections::HashMap<String, BlockCountConstraint>,
387    ) -> Self {
388        if let BlockField::Stream {
389            block_counts: ref mut existing,
390            ..
391        } = self
392        {
393            *existing = counts;
394        }
395        self
396    }
397
398    // ---- Fluent builder helpers — collapse the verbose match-arm
399    // syntax to one-liners for the common cases. All chain. ----
400
401    /// Mark a Widget field required (no-op on other variants).
402    #[must_use]
403    pub fn required(mut self) -> Self {
404        if let BlockField::Widget { required, .. } = &mut self {
405            *required = true;
406        }
407        self
408    }
409
410    /// Set helptext on a Widget field (no-op on other variants).
411    #[must_use]
412    pub fn with_help(mut self, h: impl Into<String>) -> Self {
413        if let BlockField::Widget { help, .. } = &mut self {
414            *help = Some(h.into());
415        }
416        self
417    }
418
419    /// Replace the choice-options on a Widget field
420    /// (no-op on other variants). Pairs are `(value, label)`.
421    #[must_use]
422    pub fn with_options<K, V, I>(mut self, opts: I) -> Self
423    where
424        K: Into<String>,
425        V: Into<String>,
426        I: IntoIterator<Item = (K, V)>,
427    {
428        if let BlockField::Widget { options, .. } = &mut self {
429            *options = opts
430                .into_iter()
431                .map(|(k, v)| (k.into(), v.into()))
432                .collect();
433        }
434        self
435    }
436
437    /// Set min cardinality on Stream / Repeat fields (no-op on Widget /
438    /// Computed). Cardinality below this is a validation error.
439    #[must_use]
440    pub fn with_min(mut self, n: u32) -> Self {
441        match &mut self {
442            BlockField::Stream { min, .. } | BlockField::Repeat { min, .. } => {
443                *min = Some(n);
444            }
445            _ => {}
446        }
447        self
448    }
449
450    /// Set max cardinality on Stream / Repeat fields (no-op on Widget /
451    /// Computed). Cardinality above this is a validation error.
452    #[must_use]
453    pub fn with_max(mut self, n: u32) -> Self {
454        match &mut self {
455            BlockField::Stream { max, .. } | BlockField::Repeat { max, .. } => {
456                *max = Some(n);
457            }
458            _ => {}
459        }
460        self
461    }
462
463    // ---- Per-WidgetKind shortcuts — for hand-rolled blocks the
464    // common cases collapse to one line. Defaults are intentionally
465    // minimal (not required, no validators); chain `.required()` /
466    // `.with_help(...)` / `.with_options(...)` to layer on detail.
467
468    /// Single-line text input.
469    #[must_use]
470    pub fn char(name: impl Into<String>, label: impl Into<String>) -> Self {
471        Self::widget(name, label, crate::widget::WidgetKind::Text)
472    }
473
474    /// Multi-line text input.
475    #[must_use]
476    pub fn text(name: impl Into<String>, label: impl Into<String>) -> Self {
477        Self::widget(name, label, crate::widget::WidgetKind::Textarea)
478    }
479
480    /// Markdown-source editor with the bundled toolbar.
481    #[must_use]
482    pub fn markdown(name: impl Into<String>, label: impl Into<String>) -> Self {
483        Self::widget(name, label, crate::widget::WidgetKind::Markdown)
484    }
485
486    /// HTML rich-text editor.
487    #[must_use]
488    pub fn richtext(name: impl Into<String>, label: impl Into<String>) -> Self {
489        Self::widget(name, label, crate::widget::WidgetKind::RichText)
490    }
491
492    /// `<input type="email">`.
493    #[must_use]
494    pub fn email(name: impl Into<String>, label: impl Into<String>) -> Self {
495        Self::widget(name, label, crate::widget::WidgetKind::Email)
496    }
497
498    /// `<input type="url">`.
499    #[must_use]
500    pub fn url(name: impl Into<String>, label: impl Into<String>) -> Self {
501        Self::widget(name, label, crate::widget::WidgetKind::Url)
502    }
503
504    /// `<input type="number" step="1">`.
505    #[must_use]
506    pub fn int(name: impl Into<String>, label: impl Into<String>) -> Self {
507        Self::widget(name, label, crate::widget::WidgetKind::Integer)
508    }
509
510    /// `<input type="number" step="any">` (free-form decimal).
511    #[must_use]
512    pub fn float(name: impl Into<String>, label: impl Into<String>) -> Self {
513        Self::widget(name, label, crate::widget::WidgetKind::Float)
514    }
515
516    /// `<input type="checkbox">`.
517    #[must_use]
518    pub fn boolean(name: impl Into<String>, label: impl Into<String>) -> Self {
519        Self::widget(name, label, crate::widget::WidgetKind::Boolean)
520    }
521
522    /// `<input type="date">`.
523    #[must_use]
524    pub fn date(name: impl Into<String>, label: impl Into<String>) -> Self {
525        Self::widget(name, label, crate::widget::WidgetKind::Date)
526    }
527
528    /// `<input type="datetime-local">`.
529    #[must_use]
530    pub fn datetime(name: impl Into<String>, label: impl Into<String>) -> Self {
531        Self::widget(name, label, crate::widget::WidgetKind::Datetime)
532    }
533
534    /// `<select>` dropdown with the given `(value, label)` choices.
535    /// Convenience around [`Self::widget`] + [`Self::with_options`].
536    #[must_use]
537    pub fn choice<K, V, I>(name: impl Into<String>, label: impl Into<String>, choices: I) -> Self
538    where
539        K: Into<String>,
540        V: Into<String>,
541        I: IntoIterator<Item = (K, V)>,
542    {
543        Self::widget(name, label, crate::widget::WidgetKind::Select).with_options(choices)
544    }
545
546    /// `MediaPicker` — pick an existing `cms_media` row.
547    #[must_use]
548    pub fn media(name: impl Into<String>, label: impl Into<String>) -> Self {
549        Self::widget(name, label, crate::widget::WidgetKind::MediaPicker)
550    }
551
552    /// `PageChooser` — pick a `cms_page` row via modal.
553    #[must_use]
554    pub fn page(name: impl Into<String>, label: impl Into<String>) -> Self {
555        Self::widget(name, label, crate::widget::WidgetKind::PageChooser)
556    }
557
558    /// `SnippetChooser` — pick a `cms_snippet` row via modal.
559    #[must_use]
560    pub fn snippet(name: impl Into<String>, label: impl Into<String>) -> Self {
561        Self::widget(name, label, crate::widget::WidgetKind::SnippetChooser)
562    }
563
564    /// `DocumentChooser` — pick a non-image `cms_media` row via modal.
565    #[must_use]
566    pub fn document(name: impl Into<String>, label: impl Into<String>) -> Self {
567        Self::widget(name, label, crate::widget::WidgetKind::DocumentChooser)
568    }
569}
570
571/// Context handed to [`Block::render`] + each computed field. Holds
572/// the Tera registry (for nested `block_render` recursion) and the
573/// trust-bag of pre-rendered child HTML the walker assembles bottom-up.
574///
575/// Sync-only — every render path is sync. Async data (translations,
576/// media URLs, snippet HTML) gets pre-fetched in the admin / public
577/// request handler before we start the render walk; this struct just
578/// carries already-loaded references.
579#[derive(Clone, Copy)]
580pub struct BlockRenderCtx<'a> {
581    /// Tera instance used for `tera.render(template, ctx)` calls.
582    /// Block templates can recursively call back into Tera via the
583    /// registered `block_render` / `stream_render` functions.
584    pub tera: &'a tera::Tera,
585    /// Per-request overlay of UI-defined block types (page-builder
586    /// dyn blocks). Checked before the inventory registry by every stream
587    /// walker. `None` = code blocks only (the default for all existing
588    /// call sites).
589    pub dyn_blocks: Option<&'a crate::page_builder::DynBlockSet>,
590}
591
592impl<'a> BlockRenderCtx<'a> {
593    #[must_use]
594    pub fn new(tera: &'a tera::Tera) -> Self {
595        Self {
596            tera,
597            dyn_blocks: None,
598        }
599    }
600
601    /// Attach the page-builder dyn-block overlay.
602    #[must_use]
603    pub fn with_dyn_blocks(mut self, set: &'a crate::page_builder::DynBlockSet) -> Self {
604        self.dyn_blocks = Some(set);
605        self
606    }
607}
608
609/// One type of node that can sit in a `WidgetKind::Stream` list.
610///
611/// Three required methods, four optional with defaults, and
612/// `render`/`migrate` have generic default impls. Implementors mostly
613/// just describe their shape and let the defaults do the heavy lifting.
614///
615/// ## Minimal impl
616///
617/// ```ignore
618/// use rustango_cms::{Block, BlockField};
619/// use rustango_cms::widget::WidgetKind;
620///
621/// pub struct HeadingBlock;
622///
623/// impl Block for HeadingBlock {
624///     fn type_name(&self) -> &'static str { "heading" }
625///     fn verbose_name(&self) -> &'static str { "Heading" }
626///     fn icon(&self) -> Option<&'static str> { Some("title") }
627///     fn fields(&self) -> Vec<BlockField> {
628///         vec![BlockField::widget("text", "Text", WidgetKind::Text)]
629///     }
630/// }
631///
632/// rustango_cms::register_block!(HeadingBlock);
633/// ```
634pub trait Block: Send + Sync + 'static {
635    /// Wire-format identifier — the `type` key in the JSON envelope
636    /// (e.g. `"heading"`). Must be globally unique across the process;
637    /// duplicate registrations panic at boot.
638    fn type_name(&self) -> &'static str;
639
640    /// Human-readable label shown in the admin picker + per-block
641    /// header chip.
642    fn verbose_name(&self) -> &'static str;
643
644    /// Structural shape. Each entry is rendered as one form input
645    /// (or sub-stream) in the admin editor and one entry in the
646    /// block's stored `value` dict.
647    fn fields(&self) -> Vec<BlockField>;
648
649    /// Material-symbols icon name shown next to the block's label in
650    /// the picker + the per-block header. `None` → generic "widgets"
651    /// glyph.
652    fn icon(&self) -> Option<&'static str> {
653        None
654    }
655
656    /// Picker grouping. Same string ⇒ same visual section in the
657    /// "+ Add block" popover. `None` ⇒ "Other" bucket.
658    fn group(&self) -> Option<&'static str> {
659        None
660    }
661
662    /// One-line description shown in the picker tile tooltip + the
663    /// "what does this block do" hint when the editor hovers over an
664    /// entry. `None` ⇒ no tooltip.
665    fn description(&self) -> Option<&'static str> {
666        None
667    }
668
669    /// Whether new instances of this block start collapsed in the
670    /// admin editor. Default `false` (expanded). Set `true` for
671    /// blocks whose default value already reads well in the
672    /// collapsed header so the editor scrolls less when the page
673    /// has many of them.
674    fn collapsed(&self) -> bool {
675        false
676    }
677
678    /// Initial value when a fresh instance of this block is inserted
679    /// into a stream. `None` ⇒ the editor opens a blank instance
680    /// (every field empty). Useful for blocks whose canonical entry
681    /// state isn't the all-empty shape (e.g. a Heading with `level=h2`
682    /// pre-selected).
683    ///
684    /// The returned JSON must match the block's [`Self::fields`]
685    /// shape — a dict keyed by field name. The admin editor merges
686    /// this dict with the empty defaults on insert.
687    fn default_value(&self) -> Option<Value> {
688        None
689    }
690
691    /// Schema version. Bump when this block's `fields()` changes in a
692    /// way that requires migrating stored JSON. Versions on disk that
693    /// differ from this trigger [`Self::migrate`] on every load.
694    fn version(&self) -> u32 {
695        1
696    }
697
698    /// Optional override of the default render template
699    /// (`blocks/<type_name>.html`). Useful for blocks that share a
700    /// template with another (e.g. multiple heading-level variants).
701    fn template(&self) -> Option<&'static str> {
702        None
703    }
704
705    /// Collapsed-state header template. When non-None, the admin
706    /// editor replaces the default static [`Self::verbose_name`]
707    /// label with this string, substituting `{field_name}` tokens
708    /// against the current block value. Useful so a Heading block
709    /// in its collapsed state shows the actual heading text instead
710    /// of just "Heading".
711    ///
712    /// Example: `Some("{text} (H{level})")` on a heading block
713    /// renders as `Welcome (H2)` when `value = {text: "Welcome",
714    /// level: "2"}`.
715    ///
716    /// The format string is also stamped onto the rendered block as
717    /// `data-label-format=` so the stream editor JS can live-update
718    /// the header when the author edits any field.
719    fn label_format(&self) -> Option<&'static str> {
720        None
721    }
722
723    /// Sample value used to render a preview thumbnail inside the
724    /// block-picker tile. When set, the admin pre-renders this block
725    /// with the sample value (via [`Self::preview_template`] or the
726    /// regular block template) and stashes the resulting HTML on
727    /// each [`PickerOption`](crate::block::admin::PickerOption). Editors get a "what does this look
728    /// like" glimpse before they insert the block.
729    fn preview_value(&self) -> Option<Value> {
730        None
731    }
732
733    /// Optional override of the template used for [`Self::preview_value`]
734    /// rendering. Defaults to [`Self::template`] (the same template
735    /// used for the public-side render). Useful when the block's real
736    /// template emits markup that needs heavy CSS / context to look
737    /// right but a tiny mock preview is enough.
738    fn preview_template(&self) -> Option<&'static str> {
739        None
740    }
741
742    /// Augments the Tera ctx
743    /// with derived values (e.g. a layout-string → grid-span map)
744    /// before the block's template renders. Default returns an
745    /// empty map. Keys cannot shadow the framework's own ctx
746    /// entries (`value`, `block_type`, `computed`) — those are
747    /// stamped last.
748    ///
749    /// Example:
750    ///
751    /// ```ignore
752    /// fn extra_context(&self, value: &Value, _: &BlockRenderCtx) -> serde_json::Map<String, Value> {
753    ///     let layout = value.get("layout").and_then(Value::as_str).unwrap_or("1");
754    ///     let spans = match layout {
755    ///         "2-1" => vec!["col-span-2", "col-span-1"],
756    ///         "1-2" => vec!["col-span-1", "col-span-2"],
757    ///         _ => vec!["col-span-1"],
758    ///     };
759    ///     serde_json::json!({ "spans": spans }).as_object().unwrap().clone()
760    /// }
761    /// ```
762    fn extra_context(
763        &self,
764        _value: &Value,
765        _ctx: &BlockRenderCtx<'_>,
766    ) -> serde_json::Map<String, Value> {
767        serde_json::Map::new()
768    }
769
770    /// Render this block's `value` to HTML. The default walks
771    /// [`Self::fields`], renders each into a Tera context map, and
772    /// renders the registered template. Override only for blocks
773    /// that bypass the field walker entirely.
774    ///
775    /// # Errors
776    /// Tera failures + shape mismatches surface as
777    /// [`BlockError::TemplateRender`] / [`BlockError::Shape`].
778    fn render(&self, value: &Value, ctx: &BlockRenderCtx<'_>) -> Result<String, BlockError> {
779        crate::block::render::default_render(self, value, ctx)
780    }
781
782    /// Migrate stored JSON from an older `version()` to the current
783    /// one. The registry calls this *stepwise* — once per integer
784    /// version between the stored value's version and `self.version()`
785    /// — so authors write single-version-step migrators only.
786    ///
787    /// The default is a no-op; blocks that change their schema
788    /// override this.
789    fn migrate(&self, _from: u32, value: Value) -> Result<Value, BlockError> {
790        Ok(value)
791    }
792}
793
794pub mod admin;
795pub mod builtin;
796pub mod enrich;
797pub mod migrate;
798pub mod render;
799pub mod tera_helpers;
800pub mod translate;
801
802#[cfg(test)]
803mod helper_tests {
804    use super::*;
805    use crate::widget::WidgetKind;
806
807    #[test]
808    fn char_helper_makes_text_widget() {
809        let f = BlockField::char("title", "Title");
810        match f {
811            BlockField::Widget {
812                name,
813                label,
814                widget,
815                required,
816                ..
817            } => {
818                assert_eq!(name, "title");
819                assert_eq!(label, "Title");
820                assert!(matches!(widget, WidgetKind::Text));
821                assert!(!required, "default = optional");
822            }
823            _ => panic!("expected Widget variant"),
824        }
825    }
826
827    #[test]
828    fn required_chain_flips_flag() {
829        let f = BlockField::int("count", "Count").required();
830        if let BlockField::Widget { required, .. } = f {
831            assert!(required);
832        } else {
833            panic!("expected Widget");
834        }
835    }
836
837    #[test]
838    fn choice_helper_carries_options() {
839        let f = BlockField::choice(
840            "level",
841            "Level",
842            vec![("2", "H2"), ("3", "H3"), ("4", "H4")],
843        );
844        if let BlockField::Widget {
845            widget, options, ..
846        } = f
847        {
848            assert!(matches!(widget, WidgetKind::Select));
849            assert_eq!(options.len(), 3);
850            assert_eq!(options[0], ("2".to_owned(), "H2".to_owned()));
851        } else {
852            panic!("expected Widget");
853        }
854    }
855
856    #[test]
857    fn with_help_on_widget_only() {
858        let f = BlockField::text("body", "Body").with_help("Markdown supported");
859        if let BlockField::Widget { help, .. } = f {
860            assert_eq!(help.as_deref(), Some("Markdown supported"));
861        }
862        // No-op on other variants.
863        let s = BlockField::stream("items", "Items", ["heading"]).with_help("hint");
864        if let BlockField::Stream { .. } = s {
865            // unchanged — no `help` field to set
866        }
867    }
868
869    #[test]
870    fn with_min_max_targets_stream_and_repeat() {
871        let s = BlockField::stream("items", "Items", ["heading"])
872            .with_min(1)
873            .with_max(5);
874        if let BlockField::Stream { min, max, .. } = s {
875            assert_eq!(min, Some(1));
876            assert_eq!(max, Some(5));
877        } else {
878            panic!("expected Stream");
879        }
880        let r = BlockField::repeat("rows", "Rows", "row").with_min(2);
881        if let BlockField::Repeat { min, .. } = r {
882            assert_eq!(min, Some(2));
883        } else {
884            panic!("expected Repeat");
885        }
886    }
887}