use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::sync::Arc;
use serde_json::Value;
use crate::form::FormInput;
use crate::policy::ActingUser;
use crate::runtime_resource::{FieldDef, Row};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Operation {
Create,
Edit,
}
impl Operation {
pub fn as_str(self) -> &'static str {
match self {
Operation::Create => "create",
Operation::Edit => "edit",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct FormContext<'a> {
operation: Operation,
record: Option<&'a Row>,
user: &'a ActingUser,
values: &'a FormInput,
parent: Option<&'a FormContext<'a>>,
}
impl<'a> FormContext<'a> {
pub fn new(
operation: Operation,
record: Option<&'a Row>,
user: &'a ActingUser,
values: &'a FormInput,
) -> Self {
FormContext {
operation,
record,
user,
values,
parent: None,
}
}
pub fn row(parent: &'a FormContext<'a>, values: &'a FormInput) -> Self {
FormContext {
operation: parent.operation,
record: parent.record,
user: parent.user,
values,
parent: Some(parent),
}
}
pub fn operation(&self) -> Operation {
self.operation
}
pub fn record(&self) -> Option<&'a Row> {
self.record
}
pub fn user(&self) -> &'a ActingUser {
self.user
}
pub fn get(&self, name: &str) -> Option<&'a str> {
match (name.strip_prefix("../../"), self.parent) {
(Some(outer), Some(parent)) => parent.get(outer),
_ => self.values.get(name),
}
}
pub fn checked(&self, name: &str) -> bool {
match (name.strip_prefix("../../"), self.parent) {
(Some(outer), Some(parent)) => parent.checked(outer),
_ => self.values.checkbox(name),
}
}
}
type Rule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;
type DefaultRule = Arc<dyn Fn(&FormContext<'_>) -> Value + Send + Sync>;
#[derive(Clone, Default)]
pub struct FieldConditions {
hidden: HashMap<String, Rule>,
visible: HashMap<String, Rule>,
live: BTreeSet<String>,
slugs: HashMap<String, String>,
slug_locks: HashMap<String, Rule>,
disabled: HashMap<String, Rule>,
defaults: HashMap<String, DefaultRule>,
}
impl fmt::Debug for FieldConditions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
f.debug_struct("FieldConditions")
.field("hidden", &names(&self.hidden))
.field("visible", &names(&self.visible))
.field("live", &self.live)
.field("slugs", &self.slugs)
.field("slug_locks", &names(&self.slug_locks))
.field("disabled", &names(&self.disabled))
.field(
"defaults",
&self.defaults.keys().cloned().collect::<BTreeSet<_>>(),
)
.finish()
}
}
impl FieldConditions {
pub fn new() -> Self {
FieldConditions::default()
}
pub fn visible(
mut self,
field: impl Into<String>,
rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
) -> Self {
self.visible.insert(field.into(), Arc::new(rule));
self
}
pub fn hidden(
mut self,
field: impl Into<String>,
rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
) -> Self {
self.hidden.insert(field.into(), Arc::new(rule));
self
}
pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
let operations = operations.to_vec();
self.visible(field, move |form| operations.contains(&form.operation()))
}
pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
let operations = operations.to_vec();
self.hidden(field, move |form| operations.contains(&form.operation()))
}
pub fn disabled(
mut self,
field: impl Into<String>,
rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
) -> Self {
self.disabled.insert(field.into(), Arc::new(rule));
self
}
pub fn disabled_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
let operations = operations.to_vec();
self.disabled(field, move |form| operations.contains(&form.operation()))
}
pub fn is_disabled(&self, field: &str, form: &FormContext<'_>) -> bool {
self.disabled.get(field).is_some_and(|rule| rule(form))
}
pub fn live(mut self, field: impl Into<String>) -> Self {
self.live.insert(field.into());
self
}
pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
self.slugs.insert(field.into(), source.into());
self
}
pub fn slug_locked_when(
mut self,
field: impl Into<String>,
rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
) -> Self {
self.slug_locks.insert(field.into(), Arc::new(rule));
self
}
pub fn is_slug_locked(&self, field: &str, form: &FormContext<'_>) -> bool {
let Some(rule) = self.slug_locks.get(field) else {
return false;
};
let stored = form
.record()
.and_then(|record| record.get(field))
.is_some_and(|value| match value {
Value::Null => false,
Value::String(text) => !text.trim().is_empty(),
_ => true,
});
form.operation() == Operation::Edit && stored && rule(form)
}
pub fn slug_source(&self, field: &str) -> Option<&str> {
self.slugs.get(field).map(String::as_str)
}
pub fn is_live(&self, field: &str) -> bool {
self.live.contains(field)
}
pub fn is_empty(&self) -> bool {
self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
}
pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
let visible = self.visible.get(field).is_none_or(|rule| rule(form));
!hidden && visible
}
pub fn hidden_fields(
&self,
fields: &[FieldDef],
operation: Operation,
record: Option<&Row>,
user: &ActingUser,
values: &FormInput,
) -> BTreeSet<String> {
let mut hidden = BTreeSet::new();
if self.hidden.is_empty() && self.visible.is_empty() {
return hidden;
}
for _ in 0..=fields.len() {
let state = stored_when_hidden(values, record, &hidden);
let form = FormContext::new(operation, record, user, &state);
let next: BTreeSet<String> = fields
.iter()
.filter(|field| !self.is_shown(&field.name, &form))
.map(|field| field.name.clone())
.collect();
if next == hidden {
break;
}
hidden = next;
}
hidden
}
pub fn default_value(self, field: impl Into<String>, value: impl Into<Value>) -> Self {
let value = value.into();
self.default_with(field, move |_| value.clone())
}
pub fn default_with(
mut self,
field: impl Into<String>,
rule: impl Fn(&FormContext<'_>) -> Value + Send + Sync + 'static,
) -> Self {
self.defaults.insert(field.into(), Arc::new(rule));
self
}
pub fn has_default(&self, field: &str) -> bool {
self.defaults.contains_key(field)
}
pub fn default_form(&self, fields: &[FieldDef], user: &ActingUser) -> FormInput {
self.fill_defaults(fields, user, &FormInput::default(), true)
}
pub fn with_defaults(
&self,
fields: &[FieldDef],
user: &ActingUser,
values: &FormInput,
) -> FormInput {
self.fill_defaults(fields, user, values, false)
}
fn fill_defaults(
&self,
fields: &[FieldDef],
user: &ActingUser,
values: &FormInput,
checkboxes: bool,
) -> FormInput {
let mut state = values.clone();
if self.defaults.is_empty() {
return state;
}
for field in fields {
let Some(rule) = self.defaults.get(&field.name) else {
continue;
};
if state.has(&field.name)
|| (!checkboxes && field.kind == crate::FieldKindDef::Checkbox)
{
continue;
}
let value = rule(&FormContext::new(Operation::Create, None, user, &state));
if let Some(text) = form_text(&value) {
state.insert(field.name.clone(), text);
}
}
state
}
pub fn hidden_sub_fields(
&self,
fields: &[FieldDef],
operation: Operation,
record: Option<&Row>,
user: &ActingUser,
values: &FormInput,
) -> BTreeSet<String> {
let mut hidden = BTreeSet::new();
if !self
.hidden
.keys()
.chain(self.visible.keys())
.any(|key| key.contains('.'))
{
return hidden;
}
let form = FormContext::new(operation, record, user, values);
for field in fields
.iter()
.filter(|f| crate::structure::is_structured(&f.kind))
{
let Some(value) = values
.get(&field.name)
.and_then(|text| serde_json::from_str::<Value>(text).ok())
else {
continue;
};
self.hidden_in(
&field.kind,
&field.name,
&field.name,
&value,
&form,
&mut hidden,
);
}
hidden
}
fn hidden_in(
&self,
kind: &crate::FieldKindDef,
path: &str,
schema: &str,
value: &Value,
form: &FormContext<'_>,
hidden: &mut BTreeSet<String>,
) {
use crate::FieldKindDef as Kind;
match kind {
Kind::Repeater(fields) => {
for (index, row) in value.as_array().into_iter().flatten().enumerate() {
if let Some(row) = row.as_object() {
let at = format!("{path}.{index}");
self.hidden_in_row(fields, row, &at, schema, form, hidden);
}
}
}
Kind::FlexibleContent(blocks) => {
for (index, row) in value.as_array().into_iter().flatten().enumerate() {
let block = row
.get("type")
.and_then(Value::as_str)
.and_then(|name| blocks.iter().find(|b| b.name == name));
let (Some(block), Some(data)) =
(block, row.get("data").and_then(Value::as_object))
else {
continue;
};
let at = format!("{path}.{index}.data");
let schema = format!("{schema}.{}", block.name);
self.hidden_in_row(&block.fields, data, &at, &schema, form, hidden);
}
}
Kind::Group(fields) | Kind::Clone(fields) => {
if let Some(values) = value.as_object() {
self.hidden_in_row(fields, values, path, schema, form, hidden);
}
}
_ => {}
}
}
fn hidden_in_row(
&self,
fields: &[FieldDef],
values: &serde_json::Map<String, Value>,
path: &str,
schema: &str,
form: &FormContext<'_>,
hidden: &mut BTreeSet<String>,
) {
let all = row_form(values);
let mut hidden_here: BTreeSet<String> = BTreeSet::new();
for _ in 0..=fields.len() {
let state = all.without(hidden_here.iter().map(String::as_str));
let row = FormContext::row(form, &state);
let next: BTreeSet<String> = fields
.iter()
.filter(|field| !self.is_shown(&format!("{schema}.{}", field.name), &row))
.map(|field| field.name.clone())
.collect();
if next == hidden_here {
break;
}
hidden_here = next;
}
let state = all.without(hidden_here.iter().map(String::as_str));
let row = FormContext::row(form, &state);
for field in fields {
let at = format!("{path}.{}", field.name);
if hidden_here.contains(&field.name) {
hidden.insert(at);
continue;
}
if let Some(value) = values.get(&field.name) {
let inner = format!("{schema}.{}", field.name);
self.hidden_in(&field.kind, &at, &inner, value, &row, hidden);
}
}
}
}
fn form_text(value: &Value) -> Option<String> {
match value {
Value::Null | Value::Bool(false) => None,
Value::Bool(true) => Some("on".to_string()),
Value::String(text) => Some(text.clone()),
other => Some(other.to_string()),
}
}
fn row_form(values: &serde_json::Map<String, Value>) -> FormInput {
FormInput::new(
values
.iter()
.filter_map(|(name, value)| form_text(value).map(|text| (name.clone(), text)))
.collect(),
)
}
fn stored_when_hidden(
values: &FormInput,
record: Option<&Row>,
hidden: &BTreeSet<String>,
) -> FormInput {
let mut state = values.without(hidden.iter().map(String::as_str));
for name in hidden {
let stored = match record.and_then(|record| record.get(name)) {
None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
Some(Value::Bool(true)) => "on".to_string(),
Some(Value::String(text)) => text.clone(),
Some(other) => other.to_string(),
};
state.insert(name.clone(), stored);
}
state
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime_resource::FieldKindDef;
fn field(name: &str) -> FieldDef {
FieldDef {
name: name.into(),
label: name.into(),
kind: FieldKindDef::Text,
required: true,
}
}
fn form(pairs: &[(&str, &str)]) -> FormInput {
FormInput::new(
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
)
}
fn user() -> ActingUser {
ActingUser::new(1, "Ada", "ada@example.test")
}
#[test]
fn a_field_with_no_condition_shows() {
let conditions = FieldConditions::new();
let user = user();
let values = form(&[]);
let context = FormContext::new(Operation::Create, None, &user, &values);
assert!(conditions.is_shown("title", &context));
assert!(conditions.is_empty());
}
#[test]
fn hidden_on_and_visible_on_follow_the_operation() {
let conditions = FieldConditions::new()
.hidden_on("slug", &[Operation::Create])
.visible_on("published_at", &[Operation::Edit]);
let fields = [field("slug"), field("published_at"), field("title")];
let user = user();
let values = form(&[]);
let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
assert_eq!(
on_create,
BTreeSet::from(["published_at".into(), "slug".into()])
);
let record = Row::new();
let on_edit =
conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
assert!(on_edit.is_empty());
}
#[test]
fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
let conditions = FieldConditions::new()
.hidden("note", |_| true)
.hidden_on("note", &[Operation::Create])
.visible("note", |form| form.user().can("notes.edit"));
let user = user();
let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
let values = form(&[]);
let record = Row::new();
let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
assert!(conditions.is_shown("note", &edit(&editor)));
let create = FormContext::new(Operation::Create, None, &editor, &values);
assert!(!conditions.is_shown("note", &create), "hidden on create");
}
#[test]
fn a_condition_reads_the_record_and_the_current_values() {
let conditions = FieldConditions::new()
.live("kind")
.visible("company", |form| form.get("kind") == Some("business"))
.visible("archived_note", |form| {
form.record()
.and_then(|record| record.get("status"))
.and_then(Value::as_str)
== Some("archived")
});
assert!(conditions.is_live("kind"));
assert!(!conditions.is_live("company"));
let fields = [field("kind"), field("company"), field("archived_note")];
let user = user();
let mut record = Row::new();
record.insert("status".into(), Value::from("archived"));
let hidden = conditions.hidden_fields(
&fields,
Operation::Edit,
Some(&record),
&user,
&form(&[("kind", "business")]),
);
assert!(hidden.is_empty(), "{hidden:?}");
let hidden = conditions.hidden_fields(
&fields,
Operation::Create,
None,
&user,
&form(&[("kind", "person")]),
);
assert_eq!(
hidden,
BTreeSet::from(["archived_note".into(), "company".into()])
);
}
#[test]
fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
let conditions = FieldConditions::new()
.visible("secret", |form| form.user().can("secret.edit"))
.visible("extra", |form| form.get("secret") == Some("yes"));
let fields = [field("secret"), field("extra")];
let user = user();
let sent = form(&[("secret", "yes"), ("extra", "changed")]);
let mut record = Row::new();
record.insert("secret".into(), Value::from("no"));
let hidden =
conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));
record.insert("secret".into(), Value::from("yes"));
let hidden =
conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
assert_eq!(hidden, BTreeSet::from(["secret".into()]));
}
#[test]
fn defaults_fill_the_create_form_in_order_and_skip_sent_fields() {
let conditions = FieldConditions::new()
.default_value("status", "draft")
.default_value("featured", true)
.default_with("summary", |form| {
Value::from(format!("{} post", form.get("status").unwrap_or("?")))
});
let mut featured = field("featured");
featured.kind = FieldKindDef::Checkbox;
let fields = [field("status"), featured, field("summary"), field("title")];
let user = user();
let shown = conditions.default_form(&fields, &user);
assert_eq!(shown.get("status"), Some("draft"));
assert!(shown.checkbox("featured"));
assert_eq!(shown.get("summary"), Some("draft post"));
assert!(!shown.has("title"));
let saved = conditions.with_defaults(&fields, &user, &form(&[("status", "publish")]));
assert_eq!(saved.get("summary"), Some("publish post"));
assert!(
!saved.has("featured"),
"an unticked checkbox stays unticked"
);
}
#[test]
fn a_row_condition_reads_its_row_and_the_form_around_it() {
let conditions = FieldConditions::new()
.visible("fields.choices", |row| row.get("type") == Some("select"))
.visible("fields.note", |row| row.get("../../mode") == Some("expert"));
let repeater = FieldDef {
name: "fields".into(),
label: "Fields".into(),
kind: FieldKindDef::Repeater(vec![field("type"), field("choices"), field("note")]),
required: false,
};
let user = user();
let values = form(&[
("mode", "simple"),
(
"fields",
r#"[{"type":"select"},{"type":"text","choices":"x"}]"#,
),
]);
let hidden = conditions.hidden_sub_fields(
std::slice::from_ref(&repeater),
Operation::Create,
None,
&user,
&values,
);
assert_eq!(
hidden,
BTreeSet::from([
"fields.0.note".into(),
"fields.1.choices".into(),
"fields.1.note".into()
])
);
let pruned = crate::structure::without_sub_fields(&[repeater], &values, &hidden);
assert_eq!(
pruned.get("fields"),
Some(r#"[{"type":"select"},{"type":"text"}]"#)
);
}
#[test]
fn a_block_condition_is_keyed_by_the_block_and_reads_the_block_row() {
let conditions =
FieldConditions::new().visible("content.hero.style", |row| row.checked("styled"));
let content = FieldDef {
name: "content".into(),
label: "Content".into(),
kind: FieldKindDef::FlexibleContent(vec![crate::runtime_resource::BlockDef {
name: "hero".into(),
label: "Hero".into(),
fields: vec![field("styled"), field("style")],
}]),
required: false,
};
let user = user();
let values = form(&[(
"content",
r#"[{"type":"hero","data":{"styled":true,"style":"a"}},{"type":"hero","data":{"style":"b"}}]"#,
)]);
let hidden = conditions.hidden_sub_fields(
std::slice::from_ref(&content),
Operation::Edit,
None,
&user,
&values,
);
assert_eq!(hidden, BTreeSet::from(["content.1.data.style".into()]));
let pruned = crate::structure::without_sub_fields(&[content], &values, &hidden);
let pruned: Value = serde_json::from_str(pruned.get("content").unwrap()).unwrap();
assert_eq!(
pruned,
serde_json::json!([
{"type": "hero", "data": {"styled": true, "style": "a"}},
{"type": "hero", "data": {}}
])
);
}
}