use async_trait::async_trait;
use rustango::sql::{ExecError, Pool};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionField {
pub name: String,
pub label: String,
pub kind: ExtensionFieldKind,
pub value: String,
pub help: String,
pub max_length: Option<u32>,
}
impl ExtensionField {
#[must_use]
pub fn into_widget(self) -> crate::Widget {
crate::Widget {
name: self.name,
kind: self.kind.into(),
custom_name: String::new(),
custom_html: String::new(),
label: self.label,
value: self.value,
options: Vec::new(),
help: self.help,
placeholder: String::new(),
required: false,
min: None,
max: None,
step: None,
max_length: self.max_length,
min_length: None,
pattern: String::new(),
read_only: false,
allowed: Vec::new(),
variant: String::new(),
}
}
#[must_use]
pub fn from_widget(w: crate::Widget) -> Self {
let kind = ExtensionFieldKind::from_widget_kind(w.kind);
Self {
name: w.name,
label: w.label,
kind,
value: w.value,
help: w.help,
max_length: w.max_length,
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExtensionFieldKind {
Text,
Textarea,
Markdown,
MediaPicker,
Number,
Url,
}
impl ExtensionFieldKind {
#[must_use]
pub fn from_widget_kind(k: crate::WidgetKind) -> Self {
use crate::WidgetKind as WK;
match k {
WK::Text => Self::Text,
WK::Textarea => Self::Textarea,
WK::Markdown => Self::Markdown,
WK::MediaPicker => Self::MediaPicker,
WK::Number | WK::Integer | WK::Float => Self::Number,
WK::Url => Self::Url,
_ => Self::Text,
}
}
}
impl From<ExtensionFieldKind> for crate::WidgetKind {
fn from(k: ExtensionFieldKind) -> Self {
match k {
ExtensionFieldKind::Text => Self::Text,
ExtensionFieldKind::Textarea => Self::Textarea,
ExtensionFieldKind::Markdown => Self::Markdown,
ExtensionFieldKind::MediaPicker => Self::MediaPicker,
ExtensionFieldKind::Number => Self::Number,
ExtensionFieldKind::Url => Self::Url,
}
}
}
pub async fn default_children(
pool: &Pool,
page: &crate::page::Page,
) -> Result<Vec<crate::page::Page>, ExecError> {
published_children(pool, page).await
}
pub async fn all_children(
pool: &Pool,
page: &crate::page::Page,
) -> Result<Vec<crate::page::Page>, ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let id = page.id.get().copied().unwrap_or_default();
crate::page::Page::objects()
.where_(crate::page::Page::parent_id.eq(id))
.order_by(&[("sort_order", false), ("id", false)])
.fetch(pool)
.await
}
pub async fn published_children(
pool: &Pool,
page: &crate::page::Page,
) -> Result<Vec<crate::page::Page>, ExecError> {
use crate::page::PageStatus;
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let id = page.id.get().copied().unwrap_or_default();
let now = chrono::Utc::now();
let rows = crate::page::Page::objects()
.where_(crate::page::Page::parent_id.eq(id))
.where_(crate::page::Page::status.is_in([
PageStatus::Published.as_str().to_owned(),
PageStatus::Scheduled.as_str().to_owned(),
]))
.order_by(&[("sort_order", false), ("id", false)])
.fetch(pool)
.await?;
let error_tid = crate::error_pages::error_page_type_id(pool).await;
Ok(rows
.into_iter()
.filter(|p| crate::resolver::visible_now(p, now))
.filter(|p| error_tid.map_or(true, |tid| p.page_type_id != tid))
.collect())
}
#[async_trait]
pub trait PageTypeHandler: Send + Sync + 'static {
fn app_label(&self) -> &'static str;
fn type_name(&self) -> &'static str;
fn verbose_name(&self) -> &'static str;
fn default_template(&self) -> &'static str;
fn allowed_parent_types(&self) -> &'static [&'static str] {
&[]
}
fn allowed_child_types(&self) -> &'static [&'static str] {
&[]
}
fn is_leaf(&self) -> bool {
false
}
fn is_creatable(&self) -> bool {
true
}
fn icon(&self) -> Option<&'static str> {
None
}
fn description(&self) -> Option<&'static str> {
None
}
fn feed_kind(&self) -> Option<&'static str> {
None
}
fn workflow_slug(&self) -> Option<&'static str> {
None
}
fn view_restriction(&self) -> Option<crate::view_restriction::TypeViewRestriction> {
None
}
fn view_mode(&self) -> crate::page_view::PageViewMode {
crate::page_view::PageViewMode::Auto
}
async fn load_extension(&self, _pool: &Pool, _page_id: i64) -> Result<Value, ExecError> {
Ok(Value::Null)
}
fn routes(&self) -> Vec<crate::routable::RouteSpec> {
Vec::new()
}
async fn route_context(
&self,
_pool: &Pool,
_page: &crate::page::Page,
_matched: &crate::routable::RouteMatch,
) -> Result<serde_json::Map<String, Value>, ExecError> {
Ok(serde_json::Map::new())
}
async fn public_context(
&self,
_pool: &Pool,
_page: &crate::page::Page,
) -> Result<serde_json::Map<String, Value>, ExecError> {
Ok(serde_json::Map::new())
}
async fn children_query(
&self,
pool: &Pool,
page: &crate::page::Page,
) -> Result<Vec<crate::page::Page>, ExecError> {
default_children(pool, page).await
}
async fn extension_fields(
&self,
_pool: &Pool,
_page_id: i64,
) -> Result<Vec<ExtensionField>, ExecError> {
Ok(Vec::new())
}
async fn widgets(&self, pool: &Pool, page_id: i64) -> Result<Vec<crate::Widget>, ExecError> {
Ok(self
.extension_fields(pool, page_id)
.await?
.into_iter()
.map(ExtensionField::into_widget)
.collect())
}
fn snippet_m2m_relations(&self) -> Vec<(&'static str, &'static str)> {
Vec::new()
}
async fn preview_extension(
&self,
pool: &Pool,
page_id: i64,
form: &std::collections::HashMap<String, String>,
) -> Result<Value, ExecError> {
let widgets = self.widgets(pool, page_id).await.unwrap_or_default();
let mut map = serde_json::Map::new();
for w in widgets {
let raw = form.get(&w.name).map(String::as_str).unwrap_or_default();
let val = crate::page_builder::values::coerce(w.kind, raw);
map.insert(w.name, val);
}
Ok(Value::Object(map))
}
async fn save_extension(
&self,
_pool: &Pool,
_page_id: i64,
_form: &std::collections::HashMap<String, String>,
) -> Result<(), ExecError> {
Ok(())
}
async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
Ok(Vec::new())
}
fn inline_panels(&self) -> Vec<InlinePanelSpec> {
Vec::new()
}
async fn load_inline_panel(
&self,
_pool: &Pool,
_page_id: i64,
_panel_name: &str,
) -> Result<Vec<serde_json::Map<String, Value>>, ExecError> {
Ok(Vec::new())
}
async fn save_inline_panel(
&self,
_pool: &Pool,
_page_id: i64,
_panel_name: &str,
_rows: &[serde_json::Map<String, Value>],
) -> Result<(), ExecError> {
Ok(())
}
async fn display_fields(
&self,
_pool: &Pool,
_page_id: i64,
) -> Result<Vec<DisplayField>, ExecError> {
Ok(Vec::new())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisplayField {
pub label: String,
pub html: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub help: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
impl DisplayField {
#[must_use]
pub fn new(label: impl Into<String>, html: impl Into<String>) -> Self {
Self {
label: label.into(),
html: html.into(),
help: String::new(),
icon: None,
}
}
#[must_use]
pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
#[must_use]
pub fn with_help(mut self, help: impl Into<String>) -> Self {
self.help = help.into();
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TabBody {
Html(String),
Template {
path: String,
#[serde(default)]
context: serde_json::Map<String, serde_json::Value>,
},
Widgets(Vec<crate::widget::Widget>),
Group {
heading: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
help: String,
#[serde(default)]
layout: PanelLayout,
widgets: Vec<crate::widget::Widget>,
},
Help {
content: String,
},
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PanelLayout {
#[default]
Column,
Row,
}
impl PanelLayout {
#[must_use]
pub fn class_suffix(self) -> &'static str {
match self {
Self::Column => "column",
Self::Row => "row",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InlinePanelSpec {
pub name: String,
pub label: String,
pub fields: Vec<ExtensionField>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min_num: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_num: Option<usize>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub help: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
impl InlinePanelSpec {
#[must_use]
pub fn new(
name: impl Into<String>,
label: impl Into<String>,
fields: Vec<ExtensionField>,
) -> Self {
Self {
name: name.into(),
label: label.into(),
fields,
min_num: None,
max_num: None,
help: String::new(),
icon: None,
}
}
#[must_use]
pub fn with_min(mut self, min: usize) -> Self {
self.min_num = Some(min);
self
}
#[must_use]
pub fn with_max(mut self, max: usize) -> Self {
self.max_num = Some(max);
self
}
#[must_use]
pub fn with_help(mut self, help: impl Into<String>) -> Self {
self.help = help.into();
self
}
#[must_use]
pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabSpec {
pub name: String,
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub badge: Option<String>,
pub body: TabBody,
}
impl TabSpec {
#[must_use]
pub fn new(name: impl Into<String>, label: impl Into<String>, html: impl Into<String>) -> Self {
Self {
name: name.into(),
label: label.into(),
icon: None,
badge: None,
body: TabBody::Html(html.into()),
}
}
#[must_use]
pub fn template(
name: impl Into<String>,
label: impl Into<String>,
path: impl Into<String>,
) -> Self {
Self {
name: name.into(),
label: label.into(),
icon: None,
badge: None,
body: TabBody::Template {
path: path.into(),
context: serde_json::Map::new(),
},
}
}
#[must_use]
pub fn widgets(
name: impl Into<String>,
label: impl Into<String>,
widgets: Vec<crate::widget::Widget>,
) -> Self {
Self {
name: name.into(),
label: label.into(),
icon: None,
badge: None,
body: TabBody::Widgets(widgets),
}
}
#[must_use]
pub fn group(
name: impl Into<String>,
label: impl Into<String>,
heading: impl Into<String>,
widgets: Vec<crate::widget::Widget>,
) -> Self {
Self {
name: name.into(),
label: label.into(),
icon: None,
badge: None,
body: TabBody::Group {
heading: heading.into(),
help: String::new(),
layout: PanelLayout::Column,
widgets,
},
}
}
#[must_use]
pub fn help(
name: impl Into<String>,
label: impl Into<String>,
content: impl Into<String>,
) -> Self {
Self {
name: name.into(),
label: label.into(),
icon: None,
badge: None,
body: TabBody::Help {
content: content.into(),
},
}
}
#[must_use]
pub fn with_layout(mut self, layout: PanelLayout) -> Self {
if let TabBody::Group {
layout: ref mut existing,
..
} = self.body
{
*existing = layout;
}
self
}
#[must_use]
pub fn with_help(mut self, help: impl Into<String>) -> Self {
if let TabBody::Group {
help: ref mut existing,
..
} = self.body
{
*existing = help.into();
}
self
}
#[must_use]
pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
#[must_use]
pub fn with_badge(mut self, badge: impl Into<String>) -> Self {
self.badge = Some(badge.into());
self
}
#[must_use]
pub fn with_context_value(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
if let TabBody::Template { context, .. } = &mut self.body {
context.insert(key.into(), value);
}
self
}
}
pub struct PageTypeHandlerRegistration {
pub factory: fn() -> Box<dyn PageTypeHandler>,
}
inventory::collect!(PageTypeHandlerRegistration);
pub fn registered_handlers() -> impl Iterator<Item = Box<dyn PageTypeHandler>> {
inventory::iter::<PageTypeHandlerRegistration>
.into_iter()
.map(|r| (r.factory)())
}
pub fn find_handler(type_name: &str) -> Option<Box<dyn PageTypeHandler>> {
registered_handlers().find(|p| p.type_name() == type_name)
}
#[must_use]
pub fn any_type_view_restriction() -> bool {
static CACHED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*CACHED.get_or_init(|| registered_handlers().any(|h| h.view_restriction().is_some()))
}
#[async_trait]
pub trait PageTypeOverrides: Send + Sync + 'static {
fn allowed_parent_types(&self) -> &'static [&'static str] {
&[]
}
fn allowed_child_types(&self) -> &'static [&'static str] {
&[]
}
fn is_creatable(&self) -> bool {
true
}
fn feed_kind(&self) -> Option<&'static str> {
None
}
fn workflow_slug(&self) -> Option<&'static str> {
None
}
fn view_restriction(&self) -> Option<crate::view_restriction::TypeViewRestriction> {
None
}
fn view_mode(&self) -> crate::page_view::PageViewMode {
crate::page_view::PageViewMode::Auto
}
async fn display_fields(
&self,
_pool: &Pool,
_page_id: i64,
) -> Result<Vec<DisplayField>, ExecError> {
Ok(Vec::new())
}
async fn public_context(
&self,
_pool: &Pool,
_page: &crate::page::Page,
) -> Result<serde_json::Map<String, Value>, ExecError> {
Ok(serde_json::Map::new())
}
async fn children_query(
&self,
_pool: &Pool,
_page: &crate::page::Page,
) -> Result<Option<Vec<crate::page::Page>>, ExecError> {
Ok(None)
}
fn routes(&self) -> Vec<crate::routable::RouteSpec> {
Vec::new()
}
async fn route_context(
&self,
_pool: &Pool,
_page: &crate::page::Page,
_matched: &crate::routable::RouteMatch,
) -> Result<serde_json::Map<String, Value>, ExecError> {
Ok(serde_json::Map::new())
}
async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
Ok(Vec::new())
}
}
#[cfg(all(test, feature = "sqlite"))]
mod preview_tests {
use super::*;
use crate::widget::{Widget, WidgetKind};
struct Choosers;
#[async_trait]
impl PageTypeHandler for Choosers {
fn app_label(&self) -> &'static str {
"cms"
}
fn type_name(&self) -> &'static str {
"Choosers"
}
fn verbose_name(&self) -> &'static str {
"Choosers"
}
fn default_template(&self) -> &'static str {
"c.html"
}
async fn widgets(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<Widget>, ExecError> {
Ok(vec![
Widget::new(WidgetKind::PageChooser, "related", "Related"),
Widget::new(WidgetKind::SnippetChooser, "cta", "CTA"),
Widget::new(WidgetKind::DocumentChooser, "doc", "Doc"),
])
}
}
#[tokio::test]
async fn preview_types_chooser_ids_like_the_saved_value() {
let pool = Pool::connect("sqlite::memory:").await.expect("pool");
let form = std::collections::HashMap::from([
("related".to_owned(), "7".to_owned()),
("cta".to_owned(), "3".to_owned()),
("doc".to_owned(), String::new()),
]);
let v = Choosers.preview_extension(&pool, 1, &form).await.expect("preview");
assert_eq!(v, serde_json::json!({ "related": 7, "cta": 3, "doc": null }));
}
}