use serde::Serialize;
use serde_json::Value;
use thiserror::Error;
use crate::widget::WidgetKind;
pub mod registry;
pub use registry::{find_block, registered_blocks, validate_block_registry, BlockRegistration};
#[derive(Debug, Error)]
pub enum BlockError {
#[error("block `{block_type}` at `{path}`: {reason}")]
Shape {
block_type: String,
path: String,
reason: String,
},
#[error("unknown block type `{0}` (not registered via `register_block!`)")]
UnknownType(String),
#[error("block `{owner}` references unregistered type `{referred}`")]
DanglingReference {
owner: &'static str,
referred: &'static str,
},
#[error("block `{block_type}` migrate {from}→{to} failed: {reason}")]
MigrateFailed {
block_type: String,
from: u32,
to: u32,
reason: String,
},
#[error("block `{block_type}` template `{template}` render failed: {source}")]
TemplateRender {
block_type: String,
template: String,
#[source]
source: tera::Error,
},
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct BlockFieldMeta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min_length: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_length: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min_value: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_value: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub chooser_filter: Option<String>,
}
impl BlockFieldMeta {
#[must_use]
pub fn none() -> Self {
Self::default()
}
#[must_use]
pub fn is_default(&self) -> bool {
self.min_length.is_none()
&& self.max_length.is_none()
&& self.pattern.is_none()
&& self.min_value.is_none()
&& self.max_value.is_none()
&& self.default_value.is_none()
&& self.chooser_filter.is_none()
}
#[must_use]
pub fn min_length(mut self, n: u32) -> Self {
self.min_length = Some(n);
self
}
#[must_use]
pub fn max_length(mut self, n: u32) -> Self {
self.max_length = Some(n);
self
}
#[must_use]
pub fn pattern(mut self, p: impl Into<String>) -> Self {
self.pattern = Some(p.into());
self
}
#[must_use]
pub fn min_value(mut self, v: f64) -> Self {
self.min_value = Some(v);
self
}
#[must_use]
pub fn max_value(mut self, v: f64) -> Self {
self.max_value = Some(v);
self
}
#[must_use]
pub fn default_value(mut self, v: impl Into<String>) -> Self {
self.default_value = Some(v.into());
self
}
#[must_use]
pub fn chooser_filter(mut self, type_name: impl Into<String>) -> Self {
self.chooser_filter = Some(type_name.into());
self
}
}
#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct BlockCountConstraint {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max: Option<u32>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum BlockField {
Widget {
name: String,
label: String,
widget: WidgetKind,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
options: Vec<(String, String)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
help: Option<String>,
#[serde(default)]
required: bool,
#[serde(default, skip_serializing_if = "BlockFieldMeta::is_default")]
meta: BlockFieldMeta,
},
Computed {
name: String,
label: String,
#[serde(skip)]
render: fn(&Value, &BlockRenderCtx) -> String,
#[serde(default, skip_serializing_if = "Option::is_none")]
help: Option<String>,
},
Stream {
name: String,
label: String,
allowed: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
min: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
max: Option<u32>,
#[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
block_counts: std::collections::HashMap<String, BlockCountConstraint>,
},
Repeat {
name: String,
label: String,
item_type: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
min: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
max: Option<u32>,
},
}
impl BlockField {
#[must_use]
pub fn name(&self) -> &str {
match self {
BlockField::Widget { name, .. } => name,
BlockField::Computed { name, .. } => name,
BlockField::Stream { name, .. } => name,
BlockField::Repeat { name, .. } => name,
}
}
#[must_use]
pub fn widget(name: impl Into<String>, label: impl Into<String>, widget: WidgetKind) -> Self {
BlockField::Widget {
name: name.into(),
label: label.into(),
widget,
options: Vec::new(),
help: None,
required: false,
meta: BlockFieldMeta::default(),
}
}
#[must_use]
pub fn stream<S: Into<String>>(
name: impl Into<String>,
label: impl Into<String>,
allowed: impl IntoIterator<Item = S>,
) -> Self {
BlockField::Stream {
name: name.into(),
label: label.into(),
allowed: allowed.into_iter().map(Into::into).collect(),
min: None,
max: None,
block_counts: std::collections::HashMap::new(),
}
}
#[must_use]
pub fn repeat(
name: impl Into<String>,
label: impl Into<String>,
item_type: impl Into<String>,
) -> Self {
BlockField::Repeat {
name: name.into(),
label: label.into(),
item_type: item_type.into(),
min: None,
max: None,
}
}
#[must_use]
pub fn with_meta(mut self, meta: BlockFieldMeta) -> Self {
if let BlockField::Widget {
meta: ref mut existing,
..
} = self
{
*existing = meta;
}
self
}
#[must_use]
pub fn with_block_counts(
mut self,
counts: std::collections::HashMap<String, BlockCountConstraint>,
) -> Self {
if let BlockField::Stream {
block_counts: ref mut existing,
..
} = self
{
*existing = counts;
}
self
}
#[must_use]
pub fn required(mut self) -> Self {
if let BlockField::Widget { required, .. } = &mut self {
*required = true;
}
self
}
#[must_use]
pub fn with_help(mut self, h: impl Into<String>) -> Self {
if let BlockField::Widget { help, .. } = &mut self {
*help = Some(h.into());
}
self
}
#[must_use]
pub fn with_options<K, V, I>(mut self, opts: I) -> Self
where
K: Into<String>,
V: Into<String>,
I: IntoIterator<Item = (K, V)>,
{
if let BlockField::Widget { options, .. } = &mut self {
*options = opts
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
}
self
}
#[must_use]
pub fn with_min(mut self, n: u32) -> Self {
match &mut self {
BlockField::Stream { min, .. } | BlockField::Repeat { min, .. } => {
*min = Some(n);
}
_ => {}
}
self
}
#[must_use]
pub fn with_max(mut self, n: u32) -> Self {
match &mut self {
BlockField::Stream { max, .. } | BlockField::Repeat { max, .. } => {
*max = Some(n);
}
_ => {}
}
self
}
#[must_use]
pub fn char(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Text)
}
#[must_use]
pub fn text(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Textarea)
}
#[must_use]
pub fn markdown(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Markdown)
}
#[must_use]
pub fn richtext(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::RichText)
}
#[must_use]
pub fn email(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Email)
}
#[must_use]
pub fn url(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Url)
}
#[must_use]
pub fn int(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Integer)
}
#[must_use]
pub fn float(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Float)
}
#[must_use]
pub fn boolean(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Boolean)
}
#[must_use]
pub fn date(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Date)
}
#[must_use]
pub fn datetime(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::Datetime)
}
#[must_use]
pub fn choice<K, V, I>(name: impl Into<String>, label: impl Into<String>, choices: I) -> Self
where
K: Into<String>,
V: Into<String>,
I: IntoIterator<Item = (K, V)>,
{
Self::widget(name, label, crate::widget::WidgetKind::Select).with_options(choices)
}
#[must_use]
pub fn media(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::MediaPicker)
}
#[must_use]
pub fn page(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::PageChooser)
}
#[must_use]
pub fn snippet(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::SnippetChooser)
}
#[must_use]
pub fn document(name: impl Into<String>, label: impl Into<String>) -> Self {
Self::widget(name, label, crate::widget::WidgetKind::DocumentChooser)
}
}
#[derive(Clone, Copy)]
pub struct BlockRenderCtx<'a> {
pub tera: &'a tera::Tera,
pub dyn_blocks: Option<&'a crate::page_builder::DynBlockSet>,
}
impl<'a> BlockRenderCtx<'a> {
#[must_use]
pub fn new(tera: &'a tera::Tera) -> Self {
Self {
tera,
dyn_blocks: None,
}
}
#[must_use]
pub fn with_dyn_blocks(mut self, set: &'a crate::page_builder::DynBlockSet) -> Self {
self.dyn_blocks = Some(set);
self
}
}
pub trait Block: Send + Sync + 'static {
fn type_name(&self) -> &'static str;
fn verbose_name(&self) -> &'static str;
fn fields(&self) -> Vec<BlockField>;
fn icon(&self) -> Option<&'static str> {
None
}
fn group(&self) -> Option<&'static str> {
None
}
fn description(&self) -> Option<&'static str> {
None
}
fn collapsed(&self) -> bool {
false
}
fn default_value(&self) -> Option<Value> {
None
}
fn version(&self) -> u32 {
1
}
fn template(&self) -> Option<&'static str> {
None
}
fn label_format(&self) -> Option<&'static str> {
None
}
fn preview_value(&self) -> Option<Value> {
None
}
fn preview_template(&self) -> Option<&'static str> {
None
}
fn extra_context(
&self,
_value: &Value,
_ctx: &BlockRenderCtx<'_>,
) -> serde_json::Map<String, Value> {
serde_json::Map::new()
}
fn render(&self, value: &Value, ctx: &BlockRenderCtx<'_>) -> Result<String, BlockError> {
crate::block::render::default_render(self, value, ctx)
}
fn migrate(&self, _from: u32, value: Value) -> Result<Value, BlockError> {
Ok(value)
}
}
pub mod admin;
pub mod builtin;
pub mod enrich;
pub mod layout;
pub mod migrate;
pub mod render;
pub mod tera_helpers;
pub mod translate;
#[cfg(test)]
mod helper_tests {
use super::*;
use crate::widget::WidgetKind;
#[test]
fn char_helper_makes_text_widget() {
let f = BlockField::char("title", "Title");
match f {
BlockField::Widget {
name,
label,
widget,
required,
..
} => {
assert_eq!(name, "title");
assert_eq!(label, "Title");
assert!(matches!(widget, WidgetKind::Text));
assert!(!required, "default = optional");
}
_ => panic!("expected Widget variant"),
}
}
#[test]
fn required_chain_flips_flag() {
let f = BlockField::int("count", "Count").required();
if let BlockField::Widget { required, .. } = f {
assert!(required);
} else {
panic!("expected Widget");
}
}
#[test]
fn choice_helper_carries_options() {
let f = BlockField::choice(
"level",
"Level",
vec![("2", "H2"), ("3", "H3"), ("4", "H4")],
);
if let BlockField::Widget {
widget, options, ..
} = f
{
assert!(matches!(widget, WidgetKind::Select));
assert_eq!(options.len(), 3);
assert_eq!(options[0], ("2".to_owned(), "H2".to_owned()));
} else {
panic!("expected Widget");
}
}
#[test]
fn with_help_on_widget_only() {
let f = BlockField::text("body", "Body").with_help("Markdown supported");
if let BlockField::Widget { help, .. } = f {
assert_eq!(help.as_deref(), Some("Markdown supported"));
}
let s = BlockField::stream("items", "Items", ["heading"]).with_help("hint");
if let BlockField::Stream { .. } = s {
}
}
#[test]
fn with_min_max_targets_stream_and_repeat() {
let s = BlockField::stream("items", "Items", ["heading"])
.with_min(1)
.with_max(5);
if let BlockField::Stream { min, max, .. } = s {
assert_eq!(min, Some(1));
assert_eq!(max, Some(5));
} else {
panic!("expected Stream");
}
let r = BlockField::repeat("rows", "Rows", "row").with_min(2);
if let BlockField::Repeat { min, .. } = r {
assert_eq!(min, Some(2));
} else {
panic!("expected Repeat");
}
}
}