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 rustango::sql::FetcherPool as _;
published_children_qs(pool, page)
.await
.order_by(&[("sort_order", false), ("id", false)])
.fetch(pool)
.await
}
async fn published_children_qs(
pool: &Pool,
page: &crate::page::Page,
) -> rustango::query::QuerySet<crate::page::Page> {
use crate::page::{Page, PageStatus};
use rustango::core::Column as _;
let id = page.id.get().copied().unwrap_or_default();
let now = chrono::Utc::now();
let not_expired = || Page::expire_at.is_null().or(Page::expire_at.gt(now));
let mut qs = Page::objects()
.where_(Page::parent_id.eq(id))
.where_(
Page::status
.eq(PageStatus::Published.as_str().to_owned())
.and(not_expired())
.or(Page::status
.eq(PageStatus::Scheduled.as_str().to_owned())
.and(Page::go_live_at.lte(now))
.and(not_expired())),
);
if let Some(tid) = crate::error_pages::error_page_type_id(pool).await {
qs = qs.where_(Page::page_type_id.ne(tid));
}
qs
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChildOrder {
#[default]
Position,
NewestFirst,
OldestFirst,
}
#[derive(Debug, Clone, Default)]
pub struct ChildrenPage {
pub pages: Vec<crate::page::Page>,
pub total: usize,
}
pub async fn published_children_page(
pool: &Pool,
page: &crate::page::Page,
order: ChildOrder,
limit: usize,
offset: usize,
) -> Result<ChildrenPage, ExecError> {
use rustango::core::NullsOrder;
use rustango::sql::{CounterPool as _, FetcherPool as _};
let qs = published_children_qs(pool, page).await;
let total = usize::try_from(qs.clone().count(pool).await?).unwrap_or_default();
let keys: &[(&'static str, bool, NullsOrder)] = match order {
ChildOrder::Position => &[
("sort_order", false, NullsOrder::Default),
("id", false, NullsOrder::Default),
],
ChildOrder::NewestFirst => &[
("published_at", true, NullsOrder::Last),
("id", true, NullsOrder::Default),
],
ChildOrder::OldestFirst => &[
("published_at", false, NullsOrder::Last),
("id", false, NullsOrder::Default),
],
};
let pages = qs
.order_by_with_nulls(keys)
.limit(i64::try_from(limit).unwrap_or(i64::MAX))
.offset(i64::try_from(offset).unwrap_or(i64::MAX))
.fetch(pool)
.await?;
Ok(ChildrenPage { pages, total })
}
#[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())
}
fn route_outcome(
&self,
_matched: &crate::routable::RouteMatch,
_route_ctx: &serde_json::Map<String, Value>,
) -> crate::routable::RouteOutcome {
crate::routable::RouteOutcome::Render
}
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())
}
async fn inline_panels(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<InlinePanelSpec>, ExecError> {
Ok(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 inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str) -> Result<Vec<InlineRowSummary>, ExecError> {
Ok(Vec::new())
}
async fn inline_row(
&self,
_pool: &Pool,
_page_id: i64,
_panel: &str,
_row_id: Option<i64>,
) -> Result<Option<serde_json::Map<String, Value>>, ExecError> {
Ok(None)
}
async fn save_inline_row(
&self,
_pool: &Pool,
_page_id: i64,
_panel: &str,
_row_id: Option<i64>,
_values: &serde_json::Map<String, Value>,
) -> Result<InlineRowSaved, ExecError> {
Ok(InlineRowSaved::Invalid(vec![crate::admin::cms_admin::FieldError::new("_form", "This panel can't be saved.")]))
}
async fn delete_inline_row(&self, _pool: &Pool, _page_id: i64, _panel: &str, _row_id: i64) -> Result<bool, ExecError> {
Ok(false)
}
async fn reorder_inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str, _ids: &[i64]) -> 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>,
#[serde(default)]
pub widgets: Vec<crate::widget::Widget>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tab: Option<String>,
#[serde(default)]
pub row_label: String,
#[serde(default = "yes")]
pub can_add: bool,
#[serde(default = "yes")]
pub can_delete: bool,
#[serde(default = "yes")]
pub can_order: bool,
#[serde(default)]
pub per_row: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InlineRowSummary {
pub id: i64,
pub title: String,
}
#[derive(Debug, Clone)]
pub enum InlineRowSaved {
Saved { id: i64, title: String },
Invalid(Vec<crate::admin::cms_admin::FieldError>),
}
fn yes() -> bool {
true
}
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,
widgets: Vec::new(),
tab: None,
row_label: String::new(),
can_add: true,
can_delete: true,
can_order: true,
per_row: false,
}
}
#[must_use]
pub fn per_row(mut self) -> Self {
self.per_row = true;
self
}
#[must_use]
pub fn with_widgets(
name: impl Into<String>,
label: impl Into<String>,
widgets: Vec<crate::widget::Widget>,
) -> Self {
let mut spec = Self::new(name, label, Vec::new());
spec.widgets = widgets;
spec
}
#[must_use]
pub fn in_tab(mut self, tab: impl Into<String>) -> Self {
self.tab = Some(tab.into());
self
}
#[must_use]
pub fn with_row_label(mut self, label: impl Into<String>) -> Self {
self.row_label = label.into();
self
}
#[must_use]
pub fn allow(mut self, add: bool, delete: bool, order: bool) -> Self {
self.can_add = add;
self.can_delete = delete;
self.can_order = order;
self
}
#[must_use]
pub fn row_widgets(&self) -> Vec<crate::widget::Widget> {
if self.widgets.is_empty() {
self.fields.iter().cloned().map(ExtensionField::into_widget).collect()
} else {
self.widgets.clone()
}
}
#[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())
}
fn route_outcome(
&self,
_matched: &crate::routable::RouteMatch,
_route_ctx: &serde_json::Map<String, Value>,
) -> crate::routable::RouteOutcome {
crate::routable::RouteOutcome::Render
}
async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
Ok(Vec::new())
}
async fn inline_panels(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<InlinePanelSpec>, ExecError> {
Ok(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 inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str) -> Result<Vec<InlineRowSummary>, ExecError> {
Ok(Vec::new())
}
async fn inline_row(
&self,
_pool: &Pool,
_page_id: i64,
_panel: &str,
_row_id: Option<i64>,
) -> Result<Option<serde_json::Map<String, Value>>, ExecError> {
Ok(None)
}
async fn save_inline_row(
&self,
_pool: &Pool,
_page_id: i64,
_panel: &str,
_row_id: Option<i64>,
_values: &serde_json::Map<String, Value>,
) -> Result<InlineRowSaved, ExecError> {
Ok(InlineRowSaved::Invalid(vec![crate::admin::cms_admin::FieldError::new("_form", "This panel can't be saved.")]))
}
async fn delete_inline_row(&self, _pool: &Pool, _page_id: i64, _panel: &str, _row_id: i64) -> Result<bool, ExecError> {
Ok(false)
}
async fn reorder_inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str, _ids: &[i64]) -> Result<(), ExecError> {
Ok(())
}
}
#[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 }));
}
}