use std::future::Future;
use std::pin::Pin;
use axum::http::HeaderMap;
use axum::response::Response;
use futures_util::FutureExt as _;
use rustango::sql::Pool;
use crate::page::Page;
pub type HookFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[derive(Clone, Copy)]
#[non_exhaustive]
pub struct HookCtx<'a> {
pub pool: &'a Pool,
pub tenant: &'a str,
pub user_id: Option<i64>,
}
impl<'a> HookCtx<'a> {
#[must_use]
pub fn new(pool: &'a Pool, tenant: &'a str, user_id: Option<i64>) -> Self {
Self { pool, tenant, user_id }
}
}
pub const HOOK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
async fn guarded<T>(hook: &str, fut: HookFuture<'_, T>) -> Option<T> {
let caught = std::panic::AssertUnwindSafe(fut).catch_unwind();
match rustango::__private_runtime::tokio::time::timeout(HOOK_TIMEOUT, caught).await {
Ok(Ok(v)) => Some(v),
Ok(Err(e)) => {
tracing::warn!(target: "rustango_cms::hooks", hook, error = ?e, "hook panicked (continuing)");
None
}
Err(_) => {
tracing::warn!(target: "rustango_cms::hooks", hook, "hook timed out after {HOOK_TIMEOUT:?} (continuing)");
None
}
}
}
#[derive(Clone, Copy)]
pub struct AfterPublishPage(pub for<'a> fn(HookCtx<'a>, &'a Page) -> HookFuture<'a, ()>);
inventory::collect!(AfterPublishPage);
#[macro_export]
macro_rules! register_after_publish_page {
($f:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::AfterPublishPage($f)
}
};
}
pub async fn fire_after_publish_page(ctx: HookCtx<'_>, page: &Page) {
for hook in inventory::iter::<AfterPublishPage>() {
guarded("after_publish_page", (hook.0)(ctx, page)).await;
}
}
#[derive(Clone, Copy)]
pub struct BeforeServePage(
pub for<'a> fn(HookCtx<'a>, &'a Page, &'a HeaderMap) -> HookFuture<'a, Option<Response>>,
);
inventory::collect!(BeforeServePage);
#[macro_export]
macro_rules! register_before_serve_page {
($f:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::BeforeServePage($f)
}
};
}
pub async fn fire_before_serve_page(ctx: HookCtx<'_>, page: &Page, headers: &HeaderMap) -> Option<Response> {
for hook in inventory::iter::<BeforeServePage>() {
if let Some(Some(resp)) = guarded("before_serve_page", (hook.0)(ctx, page, headers)).await {
return Some(resp);
}
}
None
}
#[derive(Debug, Clone, Copy)]
pub struct AdminMenuItem {
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub href: &'static str,
}
inventory::collect!(AdminMenuItem);
#[macro_export]
macro_rules! register_admin_menu_item {
($key:expr, $label:expr, $icon:expr, $href:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::AdminMenuItem {
key: $key,
label: $label,
icon: $icon,
href: $href,
}
}
};
}
#[must_use]
pub fn admin_menu_items() -> Vec<&'static AdminMenuItem> {
let mut items: Vec<&'static AdminMenuItem> = inventory::iter::<AdminMenuItem>().collect();
items.sort_by_key(|i| i.key);
items
}
#[derive(Debug, Clone, Copy)]
pub struct HelpMenuItem {
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub href: &'static str,
}
inventory::collect!(HelpMenuItem);
#[macro_export]
macro_rules! register_help_menu_item {
($key:expr, $label:expr, $icon:expr, $href:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::HelpMenuItem {
key: $key,
label: $label,
icon: $icon,
href: $href,
}
}
};
}
#[must_use]
pub fn help_menu_items() -> Vec<&'static HelpMenuItem> {
let mut items: Vec<&'static HelpMenuItem> = inventory::iter::<HelpMenuItem>().collect();
items.sort_by_key(|i| i.key);
items
}
#[derive(Debug, Clone, Copy)]
pub struct AccountSettingsPanel {
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub html: &'static str,
}
inventory::collect!(AccountSettingsPanel);
#[macro_export]
macro_rules! register_account_settings_panel {
($key:expr, $label:expr, $icon:expr, $html:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::AccountSettingsPanel {
key: $key,
label: $label,
icon: $icon,
html: $html,
}
}
};
}
#[derive(Debug, Clone, Copy)]
pub struct UserbarItem {
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub href_template: &'static str,
}
inventory::collect!(UserbarItem);
#[macro_export]
macro_rules! register_userbar_item {
($key:expr, $label:expr, $icon:expr, $href:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::UserbarItem {
key: $key,
label: $label,
icon: $icon,
href_template: $href,
}
}
};
}
#[must_use]
pub fn userbar_items() -> Vec<&'static UserbarItem> {
let mut items: Vec<&'static UserbarItem> = inventory::iter::<UserbarItem>().collect();
items.sort_by_key(|i| i.key);
items
}
#[derive(Clone, Copy)]
pub struct DashboardWidget {
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub render: for<'a> fn(HookCtx<'a>) -> HookFuture<'a, String>,
}
inventory::collect!(DashboardWidget);
#[macro_export]
macro_rules! register_dashboard_widget {
($key:expr, $label:expr, $icon:expr, $render:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::DashboardWidget {
key: $key,
label: $label,
icon: $icon,
render: $render,
}
}
};
}
#[must_use]
pub fn dashboard_widgets() -> Vec<&'static DashboardWidget> {
let mut items: Vec<&'static DashboardWidget> = inventory::iter::<DashboardWidget>().collect();
items.sort_by_key(|i| i.key);
items
}
pub async fn render_dashboard_widgets(ctx: HookCtx<'_>) -> Vec<(&'static DashboardWidget, String)> {
let mut out = Vec::new();
for w in dashboard_widgets() {
if let Some(html) = guarded("dashboard_widget", (w.render)(ctx)).await {
out.push((w, html));
}
}
out
}
#[must_use]
pub fn account_settings_panels() -> Vec<&'static AccountSettingsPanel> {
let mut items: Vec<&'static AccountSettingsPanel> =
inventory::iter::<AccountSettingsPanel>().collect();
items.sort_by_key(|i| i.key);
items
}
#[derive(Debug, Clone, Copy)]
pub struct BulkActionSpec {
pub resource: &'static str,
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub danger: bool,
pub confirm_message: &'static str,
pub action_url: &'static str,
}
inventory::collect!(BulkActionSpec);
#[macro_export]
macro_rules! register_bulk_action {
(
resource = $resource:expr,
key = $key:expr,
label = $label:expr,
icon = $icon:expr,
danger = $danger:expr,
confirm = $confirm:expr,
action_url = $action_url:expr $(,)?
) => {
::rustango_cms::inventory::submit! {
$crate::hooks::BulkActionSpec {
resource: $resource,
key: $key,
label: $label,
icon: $icon,
danger: $danger,
confirm_message: $confirm,
action_url: $action_url,
}
}
};
}
#[must_use]
pub fn bulk_actions_for(resource: &str) -> Vec<&'static BulkActionSpec> {
let mut items: Vec<&'static BulkActionSpec> = inventory::iter::<BulkActionSpec>()
.filter(|a| a.resource == resource)
.collect();
items.sort_by_key(|i| i.key);
items
}
inventory::submit! {
HelpMenuItem {
key: "docs",
label: "Documentation",
icon: "menu_book",
href: "/cms-admin/help",
}
}
inventory::submit! {
HelpMenuItem {
key: "keyboard-shortcuts",
label: "Keyboard shortcuts",
icon: "keyboard",
href: "#kbd-cheatsheet",
}
}
inventory::submit! {
HelpMenuItem {
key: "styleguide",
label: "Styleguide",
icon: "palette",
href: "/cms-admin/styleguide",
}
}
#[derive(Debug, Clone, Copy)]
pub struct PageActionMenuItem {
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub href_template: &'static str,
}
inventory::collect!(PageActionMenuItem);
#[macro_export]
macro_rules! register_page_action_menu_item {
($key:expr, $label:expr, $icon:expr, $href:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::PageActionMenuItem {
key: $key,
label: $label,
icon: $icon,
href_template: $href,
}
}
};
}
#[must_use]
pub fn page_action_menu_items(page_id: i64) -> Vec<serde_json::Value> {
let mut items: Vec<&'static PageActionMenuItem> =
inventory::iter::<PageActionMenuItem>().collect();
items.sort_by_key(|i| i.key);
items
.into_iter()
.map(|i| {
serde_json::json!({
"key": i.key,
"label": i.label,
"icon": i.icon,
"href": i.href_template.replace("{page_id}", &page_id.to_string()),
})
})
.collect()
}
#[derive(Debug, Clone, Copy)]
pub struct PageListingButton {
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub href_template: &'static str,
}
inventory::collect!(PageListingButton);
#[macro_export]
macro_rules! register_page_listing_button {
($key:expr, $label:expr, $icon:expr, $href:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::PageListingButton {
key: $key,
label: $label,
icon: $icon,
href_template: $href,
}
}
};
}
#[must_use]
pub fn page_listing_buttons(page_id: i64) -> Vec<serde_json::Value> {
let mut items: Vec<&'static PageListingButton> =
inventory::iter::<PageListingButton>().collect();
items.sort_by_key(|i| i.key);
items
.into_iter()
.map(|i| {
serde_json::json!({
"key": i.key,
"label": i.label,
"icon": i.icon,
"href": i.href_template.replace("{page_id}", &page_id.to_string()),
})
})
.collect()
}
#[derive(Debug, Clone, Copy)]
pub struct PageHeaderButton {
pub key: &'static str,
pub label: &'static str,
pub icon: &'static str,
pub href_template: &'static str,
pub style: &'static str,
}
inventory::collect!(PageHeaderButton);
#[macro_export]
macro_rules! register_page_header_button {
(
key = $key:expr,
label = $label:expr,
icon = $icon:expr,
href = $href:expr,
style = $style:expr $(,)?
) => {
::rustango_cms::inventory::submit! {
$crate::hooks::PageHeaderButton {
key: $key,
label: $label,
icon: $icon,
href_template: $href,
style: $style,
}
}
};
}
#[must_use]
pub fn page_header_buttons(page_id: i64) -> Vec<serde_json::Value> {
let mut items: Vec<&'static PageHeaderButton> = inventory::iter::<PageHeaderButton>().collect();
items.sort_by_key(|i| i.key);
items
.into_iter()
.map(|i| {
serde_json::json!({
"key": i.key,
"label": i.label,
"icon": i.icon,
"style": i.style,
"href": i.href_template.replace("{page_id}", &page_id.to_string()),
})
})
.collect()
}
#[must_use]
pub fn page_listing_buttons_raw() -> Vec<serde_json::Value> {
let mut items: Vec<&'static PageListingButton> =
inventory::iter::<PageListingButton>().collect();
items.sort_by_key(|i| i.key);
items
.into_iter()
.map(|i| {
serde_json::json!({
"key": i.key,
"label": i.label,
"icon": i.icon,
"href_template": i.href_template,
})
})
.collect()
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct AdminSearchHit {
pub label: String,
pub href: String,
pub subtitle: String,
}
#[derive(Clone, Copy)]
pub struct AdminSearchArea {
pub key: &'static str,
pub label: &'static str,
pub search: for<'a> fn(HookCtx<'a>, &'a str) -> HookFuture<'a, Vec<AdminSearchHit>>,
}
inventory::collect!(AdminSearchArea);
#[macro_export]
macro_rules! register_admin_search_area {
($key:expr, $label:expr, $search:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::AdminSearchArea {
key: $key,
label: $label,
search: $search,
}
}
};
}
#[must_use]
pub async fn run_admin_search_areas(ctx: HookCtx<'_>, query: &str) -> Vec<(&'static str, Vec<AdminSearchHit>)> {
let mut out = Vec::new();
for area in inventory::iter::<AdminSearchArea>() {
let hits = guarded("admin_search_area", (area.search)(ctx, query)).await.unwrap_or_default();
if !hits.is_empty() {
out.push((area.label, hits));
}
}
out
}
#[derive(Debug, Clone, Copy)]
pub struct AdminCss(pub &'static str);
inventory::collect!(AdminCss);
#[macro_export]
macro_rules! register_admin_css {
($css:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::AdminCss($css)
}
};
}
#[must_use]
pub fn admin_css() -> Vec<&'static str> {
inventory::iter::<AdminCss>().map(|c| c.0).collect()
}
#[derive(Debug, Clone, Copy)]
pub struct AdminJs(pub &'static str);
inventory::collect!(AdminJs);
#[macro_export]
macro_rules! register_admin_js {
($js:expr) => {
::rustango_cms::inventory::submit! {
$crate::hooks::AdminJs($js)
}
};
}
#[must_use]
pub fn admin_js() -> Vec<&'static str> {
inventory::iter::<AdminJs>().map(|j| j.0).collect()
}
#[cfg(test)]
mod tests {
use super::*;
inventory::submit! { AdminCss(".rcms-admin-css-marker{display:none}") }
inventory::submit! { AdminJs("/* rcms-admin-js-marker */") }
#[test]
fn admin_css_and_js_collect_registered_blobs() {
assert!(
admin_css()
.iter()
.any(|c| c.contains("rcms-admin-css-marker")),
"registered CSS blob is collected"
);
assert!(
admin_js()
.iter()
.any(|j| j.contains("rcms-admin-js-marker")),
"registered JS blob is collected"
);
}
#[test]
fn page_action_href_template_substitutes_page_id() {
let raw = PageActionMenuItem {
key: "x",
label: "X",
icon: "extension",
href_template: "/cms-admin/x/plugin?page={page_id}",
};
let rendered = raw.href_template.replace("{page_id}", "42");
assert_eq!(rendered, "/cms-admin/x/plugin?page=42");
}
#[test]
fn bulk_action_spec_fields_round_trip() {
let spec = BulkActionSpec {
resource: "cms_page",
key: "archive_old",
label: "Archive old",
icon: "archive",
danger: false,
confirm_message: "Archive every selected old page?",
action_url: "/plugin/archive",
};
assert_eq!(spec.resource, "cms_page");
assert!(!spec.danger);
assert!(spec.confirm_message.contains("Archive"));
}
#[test]
fn page_listing_button_href_template_substitutes_page_id() {
let raw = PageListingButton {
key: "x",
label: "X",
icon: "extension",
href_template: "/plugin/{page_id}/do",
};
let rendered = raw.href_template.replace("{page_id}", "7");
assert_eq!(rendered, "/plugin/7/do");
}
}