use std::fmt;
use std::sync::Arc;
use orbit_orm::Database;
use serde_json::Value;
use crate::list::{BadgeColor, ListFilter};
use crate::policy::ActingUser;
use crate::runtime_resource::{Row, RuntimeFuture};
pub type ActionResult = Result<(), String>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ActionAbility {
#[default]
Update,
Delete,
}
pub const DEFAULT_CONFIRMATION: &str = "Are you sure you would like to do this?";
type Handler = Arc<
dyn for<'a> Fn(&'a Database, &'a ActingUser, i64, &'a Row) -> RuntimeFuture<'a, ActionResult>
+ Send
+ Sync,
>;
type Rule = Arc<dyn Fn(&Row) -> bool + Send + Sync>;
#[derive(Clone)]
pub struct RowAction {
name: String,
label: Option<String>,
url: Option<String>,
handler: Option<Handler>,
confirmation: Option<String>,
rules: Vec<Rule>,
color: Option<BadgeColor>,
ability: ActionAbility,
success: Option<String>,
}
impl fmt::Debug for RowAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RowAction")
.field("name", &self.name)
.field("label", &self.label)
.field("url", &self.url)
.field("posts", &self.handler.is_some())
.field("confirmation", &self.confirmation)
.field("rules", &self.rules.len())
.field("color", &self.color)
.field("ability", &self.ability)
.field("success", &self.success)
.finish()
}
}
impl RowAction {
pub fn make(name: impl Into<String>) -> Self {
RowAction {
name: name.into(),
label: None,
url: None,
handler: None,
confirmation: None,
rules: Vec::new(),
color: None,
ability: ActionAbility::Update,
success: None,
}
}
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
pub fn url(mut self, template: impl Into<String>) -> Self {
self.url = Some(template.into());
self
}
pub fn action<F>(mut self, handler: F) -> Self
where
F: for<'a> Fn(
&'a Database,
&'a ActingUser,
i64,
&'a Row,
) -> RuntimeFuture<'a, ActionResult>
+ Send
+ Sync
+ 'static,
{
self.handler = Some(Arc::new(handler));
self
}
pub fn requires_confirmation(mut self) -> Self {
if self.confirmation.is_none() {
self.confirmation = Some(DEFAULT_CONFIRMATION.to_string());
}
self
}
pub fn modal_description(mut self, text: impl Into<String>) -> Self {
self.confirmation = Some(text.into());
self
}
pub fn visible(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
self.rules.push(Arc::new(rule));
self
}
pub fn hidden(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
self.rules.push(Arc::new(move |row: &Row| !rule(row)));
self
}
pub fn visible_when(self, filter: ListFilter) -> Self {
self.visible(move |row| filter.matches(row))
}
pub fn color(mut self, color: BadgeColor) -> Self {
self.color = Some(color);
self
}
pub fn authorize(mut self, ability: ActionAbility) -> Self {
self.ability = ability;
self
}
pub fn success_notification_title(mut self, title: impl Into<String>) -> Self {
self.success = Some(title.into());
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn get_label(&self) -> String {
match &self.label {
Some(label) => label.clone(),
None => {
let words = self.name.replace(['_', '-'], " ");
let mut chars = words.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
}
}
pub fn is_post(&self) -> bool {
self.handler.is_some()
}
pub fn url_for(&self, record: &Row) -> Option<String> {
self.url.as_deref().map(|template| fill(template, record))
}
pub fn confirmation(&self) -> Option<&str> {
self.confirmation.as_deref()
}
pub fn is_visible(&self, record: &Row) -> bool {
self.rules.iter().all(|rule| rule(record))
}
pub fn get_color(&self) -> Option<BadgeColor> {
self.color
}
pub fn ability(&self) -> ActionAbility {
self.ability
}
pub fn success_message(&self) -> Option<&str> {
self.success.as_deref()
}
pub async fn run(
&self,
db: &Database,
user: &ActingUser,
id: i64,
record: &Row,
) -> Result<ActionResult, orbit_orm::Error> {
match &self.handler {
Some(handler) => handler(db, user, id, record).await,
None => Ok(Err("This action is a link.".to_string())),
}
}
}
#[derive(Clone)]
pub struct BulkAction {
name: String,
label: Option<String>,
handler: Option<Handler>,
rules: Vec<Rule>,
ability: ActionAbility,
success: Option<String>,
}
impl fmt::Debug for BulkAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BulkAction")
.field("name", &self.name)
.field("label", &self.label)
.field("posts", &self.handler.is_some())
.field("rules", &self.rules.len())
.field("ability", &self.ability)
.field("success", &self.success)
.finish()
}
}
impl BulkAction {
pub fn make(name: impl Into<String>) -> Self {
BulkAction {
name: name.into(),
label: None,
handler: None,
rules: Vec::new(),
ability: ActionAbility::Update,
success: None,
}
}
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
pub fn action<F>(mut self, handler: F) -> Self
where
F: for<'a> Fn(
&'a Database,
&'a ActingUser,
i64,
&'a Row,
) -> RuntimeFuture<'a, ActionResult>
+ Send
+ Sync
+ 'static,
{
self.handler = Some(Arc::new(handler));
self
}
pub fn visible(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
self.rules.push(Arc::new(rule));
self
}
pub fn hidden(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
self.rules.push(Arc::new(move |row: &Row| !rule(row)));
self
}
pub fn authorize(mut self, ability: ActionAbility) -> Self {
self.ability = ability;
self
}
pub fn success_notification_title(mut self, title: impl Into<String>) -> Self {
self.success = Some(title.into());
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn get_label(&self) -> String {
match &self.label {
Some(label) => label.clone(),
None => RowAction::make(self.name.clone()).get_label(),
}
}
pub fn is_runnable(&self) -> bool {
self.handler.is_some()
}
pub fn ability(&self) -> ActionAbility {
self.ability
}
pub fn is_visible(&self, record: &Row) -> bool {
self.rules.iter().all(|rule| rule(record))
}
pub fn success_message(&self, count: usize) -> Option<String> {
self.success
.as_ref()
.map(|title| title.replace(":count", &count.to_string()))
}
pub async fn run(
&self,
db: &Database,
user: &ActingUser,
id: i64,
record: &Row,
) -> Result<ActionResult, orbit_orm::Error> {
match &self.handler {
Some(handler) => handler(db, user, id, record).await,
None => Ok(Err("This action has no handler.".to_string())),
}
}
}
fn fill(template: &str, record: &Row) -> String {
let mut out = String::with_capacity(template.len());
let mut rest = template;
while let Some(open) = rest.find('{') {
let Some(close) = rest[open..].find('}') else {
break;
};
out.push_str(&rest[..open]);
let key = &rest[open + 1..open + close];
let value = match record.get(key) {
Some(Value::String(text)) => text.clone(),
Some(Value::Null) | None => String::new(),
Some(other) => other.to_string(),
};
for byte in value.bytes() {
if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
out.push(byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
rest = &rest[open + close + 1..];
}
out.push_str(rest);
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn row(value: Value) -> Row {
value.as_object().unwrap().clone()
}
#[test]
fn the_label_defaults_to_the_name_made_readable() {
assert_eq!(
RowAction::make("delete_permanently").get_label(),
"Delete permanently"
);
assert_eq!(
RowAction::make("move-to-trash").get_label(),
"Move to trash"
);
assert_eq!(RowAction::make("x").label("Restore").get_label(), "Restore");
}
#[test]
fn a_url_fills_the_record_values_encoded() {
let action = RowAction::make("view").url("/blog/{slug}?id={id}&none={missing}");
let record = row(json!({"id": 7, "slug": "a b&c"}));
assert_eq!(
action.url_for(&record).unwrap(),
"/blog/a%20b%26c?id=7&none="
);
assert!(!action.is_post());
}
#[test]
fn visibility_rules_all_hold() {
let action = RowAction::make("restore")
.visible_when(ListFilter::new().where_eq("status", "trash"))
.hidden(|row| row.get("locked") == Some(&json!(true)));
assert!(action.is_visible(&row(json!({"status": "trash"}))));
assert!(!action.is_visible(&row(json!({"status": "publish"}))));
assert!(!action.is_visible(&row(json!({"status": "trash", "locked": true}))));
}
#[test]
fn a_bulk_action_has_a_label_a_rule_and_a_count_message() {
let action = BulkAction::make("move_to_trash")
.hidden(|row| row.get("status") == Some(&json!("trash")))
.success_notification_title("Moved :count posts.");
assert_eq!(action.get_label(), "Move to trash");
assert_eq!(BulkAction::make("x").label("Trash").get_label(), "Trash");
assert!(action.is_visible(&row(json!({"status": "draft"}))));
assert!(!action.is_visible(&row(json!({"status": "trash"}))));
assert_eq!(action.success_message(3).as_deref(), Some("Moved 3 posts."));
assert_eq!(BulkAction::make("x").success_message(3), None);
assert!(!action.is_runnable());
}
#[test]
fn confirmation_defaults_to_filaments_text() {
let action = RowAction::make("trash").requires_confirmation();
assert_eq!(action.confirmation(), Some(DEFAULT_CONFIRMATION));
let action = RowAction::make("trash").modal_description("Sure?");
assert_eq!(action.confirmation(), Some("Sure?"));
assert_eq!(RowAction::make("trash").confirmation(), None);
}
}