1use std::collections::{BTreeSet, HashMap};
38use std::fmt;
39use std::sync::Arc;
40
41use serde_json::Value;
42
43use crate::form::FormInput;
44use crate::policy::ActingUser;
45use crate::runtime_resource::{FieldDef, Row};
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub enum Operation {
50 Create,
52 Edit,
54}
55
56impl Operation {
57 pub fn as_str(self) -> &'static str {
59 match self {
60 Operation::Create => "create",
61 Operation::Edit => "edit",
62 }
63 }
64}
65
66#[derive(Debug, Clone, Copy)]
69pub struct FormContext<'a> {
70 operation: Operation,
71 record: Option<&'a Row>,
72 user: &'a ActingUser,
73 values: &'a FormInput,
74 parent: Option<&'a FormContext<'a>>,
76}
77
78impl<'a> FormContext<'a> {
79 pub fn new(
82 operation: Operation,
83 record: Option<&'a Row>,
84 user: &'a ActingUser,
85 values: &'a FormInput,
86 ) -> Self {
87 FormContext {
88 operation,
89 record,
90 user,
91 values,
92 parent: None,
93 }
94 }
95
96 pub fn row(parent: &'a FormContext<'a>, values: &'a FormInput) -> Self {
101 FormContext {
102 operation: parent.operation,
103 record: parent.record,
104 user: parent.user,
105 values,
106 parent: Some(parent),
107 }
108 }
109
110 pub fn operation(&self) -> Operation {
112 self.operation
113 }
114
115 pub fn record(&self) -> Option<&'a Row> {
118 self.record
119 }
120
121 pub fn user(&self) -> &'a ActingUser {
123 self.user
124 }
125
126 pub fn get(&self, name: &str) -> Option<&'a str> {
136 match (name.strip_prefix("../../"), self.parent) {
137 (Some(outer), Some(parent)) => parent.get(outer),
138 _ => self.values.get(name),
139 }
140 }
141
142 pub fn checked(&self, name: &str) -> bool {
145 match (name.strip_prefix("../../"), self.parent) {
146 (Some(outer), Some(parent)) => parent.checked(outer),
147 _ => self.values.checkbox(name),
148 }
149 }
150}
151
152type Rule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;
154
155type DefaultRule = Arc<dyn Fn(&FormContext<'_>) -> Value + Send + Sync>;
157
158#[derive(Clone, Default)]
167pub struct FieldConditions {
168 hidden: HashMap<String, Rule>,
169 visible: HashMap<String, Rule>,
170 live: BTreeSet<String>,
171 slugs: HashMap<String, String>,
173 slug_locks: HashMap<String, Rule>,
175 disabled: HashMap<String, Rule>,
177 defaults: HashMap<String, DefaultRule>,
179}
180
181impl fmt::Debug for FieldConditions {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
184 f.debug_struct("FieldConditions")
185 .field("hidden", &names(&self.hidden))
186 .field("visible", &names(&self.visible))
187 .field("live", &self.live)
188 .field("slugs", &self.slugs)
189 .field("slug_locks", &names(&self.slug_locks))
190 .field("disabled", &names(&self.disabled))
191 .field(
192 "defaults",
193 &self.defaults.keys().cloned().collect::<BTreeSet<_>>(),
194 )
195 .finish()
196 }
197}
198
199impl FieldConditions {
200 pub fn new() -> Self {
202 FieldConditions::default()
203 }
204
205 pub fn visible(
207 mut self,
208 field: impl Into<String>,
209 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
210 ) -> Self {
211 self.visible.insert(field.into(), Arc::new(rule));
212 self
213 }
214
215 pub fn hidden(
217 mut self,
218 field: impl Into<String>,
219 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
220 ) -> Self {
221 self.hidden.insert(field.into(), Arc::new(rule));
222 self
223 }
224
225 pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
227 let operations = operations.to_vec();
228 self.visible(field, move |form| operations.contains(&form.operation()))
229 }
230
231 pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
233 let operations = operations.to_vec();
234 self.hidden(field, move |form| operations.contains(&form.operation()))
235 }
236
237 pub fn disabled(
243 mut self,
244 field: impl Into<String>,
245 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
246 ) -> Self {
247 self.disabled.insert(field.into(), Arc::new(rule));
248 self
249 }
250
251 pub fn disabled_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
254 let operations = operations.to_vec();
255 self.disabled(field, move |form| operations.contains(&form.operation()))
256 }
257
258 pub fn is_disabled(&self, field: &str, form: &FormContext<'_>) -> bool {
260 self.disabled.get(field).is_some_and(|rule| rule(form))
261 }
262
263 pub fn live(mut self, field: impl Into<String>) -> Self {
269 self.live.insert(field.into());
270 self
271 }
272
273 pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
285 self.slugs.insert(field.into(), source.into());
286 self
287 }
288
289 pub fn slug_locked_when(
308 mut self,
309 field: impl Into<String>,
310 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
311 ) -> Self {
312 self.slug_locks.insert(field.into(), Arc::new(rule));
313 self
314 }
315
316 pub fn is_slug_locked(&self, field: &str, form: &FormContext<'_>) -> bool {
320 let Some(rule) = self.slug_locks.get(field) else {
321 return false;
322 };
323 let stored = form
324 .record()
325 .and_then(|record| record.get(field))
326 .is_some_and(|value| match value {
327 Value::Null => false,
328 Value::String(text) => !text.trim().is_empty(),
329 _ => true,
330 });
331 form.operation() == Operation::Edit && stored && rule(form)
332 }
333
334 pub fn slug_source(&self, field: &str) -> Option<&str> {
336 self.slugs.get(field).map(String::as_str)
337 }
338
339 pub fn is_live(&self, field: &str) -> bool {
341 self.live.contains(field)
342 }
343
344 pub fn is_empty(&self) -> bool {
346 self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
347 }
348
349 pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
352 let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
353 let visible = self.visible.get(field).is_none_or(|rule| rule(form));
354 !hidden && visible
355 }
356
357 pub fn hidden_fields(
364 &self,
365 fields: &[FieldDef],
366 operation: Operation,
367 record: Option<&Row>,
368 user: &ActingUser,
369 values: &FormInput,
370 ) -> BTreeSet<String> {
371 let mut hidden = BTreeSet::new();
372 if self.hidden.is_empty() && self.visible.is_empty() {
373 return hidden;
374 }
375 for _ in 0..=fields.len() {
376 let state = stored_when_hidden(values, record, &hidden);
377 let form = FormContext::new(operation, record, user, &state);
378 let next: BTreeSet<String> = fields
379 .iter()
380 .filter(|field| !self.is_shown(&field.name, &form))
381 .map(|field| field.name.clone())
382 .collect();
383 if next == hidden {
384 break;
385 }
386 hidden = next;
387 }
388 hidden
389 }
390
391 pub fn default_value(self, field: impl Into<String>, value: impl Into<Value>) -> Self {
404 let value = value.into();
405 self.default_with(field, move |_| value.clone())
406 }
407
408 pub fn default_with(
415 mut self,
416 field: impl Into<String>,
417 rule: impl Fn(&FormContext<'_>) -> Value + Send + Sync + 'static,
418 ) -> Self {
419 self.defaults.insert(field.into(), Arc::new(rule));
420 self
421 }
422
423 pub fn has_default(&self, field: &str) -> bool {
425 self.defaults.contains_key(field)
426 }
427
428 pub fn default_form(&self, fields: &[FieldDef], user: &ActingUser) -> FormInput {
431 self.fill_defaults(fields, user, &FormInput::default(), true)
432 }
433
434 pub fn with_defaults(
438 &self,
439 fields: &[FieldDef],
440 user: &ActingUser,
441 values: &FormInput,
442 ) -> FormInput {
443 self.fill_defaults(fields, user, values, false)
444 }
445
446 fn fill_defaults(
447 &self,
448 fields: &[FieldDef],
449 user: &ActingUser,
450 values: &FormInput,
451 checkboxes: bool,
452 ) -> FormInput {
453 let mut state = values.clone();
454 if self.defaults.is_empty() {
455 return state;
456 }
457 for field in fields {
458 let Some(rule) = self.defaults.get(&field.name) else {
459 continue;
460 };
461 if state.has(&field.name)
462 || (!checkboxes && field.kind == crate::FieldKindDef::Checkbox)
463 {
464 continue;
465 }
466 let value = rule(&FormContext::new(Operation::Create, None, user, &state));
467 if let Some(text) = form_text(&value) {
468 state.insert(field.name.clone(), text);
469 }
470 }
471 state
472 }
473
474 pub fn hidden_sub_fields(
483 &self,
484 fields: &[FieldDef],
485 operation: Operation,
486 record: Option<&Row>,
487 user: &ActingUser,
488 values: &FormInput,
489 ) -> BTreeSet<String> {
490 let mut hidden = BTreeSet::new();
491 if !self
492 .hidden
493 .keys()
494 .chain(self.visible.keys())
495 .any(|key| key.contains('.'))
496 {
497 return hidden;
498 }
499 let form = FormContext::new(operation, record, user, values);
500 for field in fields
501 .iter()
502 .filter(|f| crate::structure::is_structured(&f.kind))
503 {
504 let Some(value) = values
505 .get(&field.name)
506 .and_then(|text| serde_json::from_str::<Value>(text).ok())
507 else {
508 continue;
509 };
510 self.hidden_in(
511 &field.kind,
512 &field.name,
513 &field.name,
514 &value,
515 &form,
516 &mut hidden,
517 );
518 }
519 hidden
520 }
521
522 fn hidden_in(
525 &self,
526 kind: &crate::FieldKindDef,
527 path: &str,
528 schema: &str,
529 value: &Value,
530 form: &FormContext<'_>,
531 hidden: &mut BTreeSet<String>,
532 ) {
533 use crate::FieldKindDef as Kind;
534 match kind {
535 Kind::Repeater(fields) => {
536 for (index, row) in value.as_array().into_iter().flatten().enumerate() {
537 if let Some(row) = row.as_object() {
538 let at = format!("{path}.{index}");
539 self.hidden_in_row(fields, row, &at, schema, form, hidden);
540 }
541 }
542 }
543 Kind::FlexibleContent(blocks) => {
544 for (index, row) in value.as_array().into_iter().flatten().enumerate() {
545 let block = row
546 .get("type")
547 .and_then(Value::as_str)
548 .and_then(|name| blocks.iter().find(|b| b.name == name));
549 let (Some(block), Some(data)) =
550 (block, row.get("data").and_then(Value::as_object))
551 else {
552 continue;
553 };
554 let at = format!("{path}.{index}.data");
555 let schema = format!("{schema}.{}", block.name);
556 self.hidden_in_row(&block.fields, data, &at, &schema, form, hidden);
557 }
558 }
559 Kind::Group(fields) | Kind::Clone(fields) => {
560 if let Some(values) = value.as_object() {
561 self.hidden_in_row(fields, values, path, schema, form, hidden);
562 }
563 }
564 _ => {}
565 }
566 }
567
568 fn hidden_in_row(
570 &self,
571 fields: &[FieldDef],
572 values: &serde_json::Map<String, Value>,
573 path: &str,
574 schema: &str,
575 form: &FormContext<'_>,
576 hidden: &mut BTreeSet<String>,
577 ) {
578 let all = row_form(values);
579 let mut hidden_here: BTreeSet<String> = BTreeSet::new();
580 for _ in 0..=fields.len() {
581 let state = all.without(hidden_here.iter().map(String::as_str));
582 let row = FormContext::row(form, &state);
583 let next: BTreeSet<String> = fields
584 .iter()
585 .filter(|field| !self.is_shown(&format!("{schema}.{}", field.name), &row))
586 .map(|field| field.name.clone())
587 .collect();
588 if next == hidden_here {
589 break;
590 }
591 hidden_here = next;
592 }
593 let state = all.without(hidden_here.iter().map(String::as_str));
594 let row = FormContext::row(form, &state);
595 for field in fields {
596 let at = format!("{path}.{}", field.name);
597 if hidden_here.contains(&field.name) {
598 hidden.insert(at);
599 continue;
600 }
601 if let Some(value) = values.get(&field.name) {
602 let inner = format!("{schema}.{}", field.name);
603 self.hidden_in(&field.kind, &at, &inner, value, &row, hidden);
604 }
605 }
606 }
607}
608
609fn form_text(value: &Value) -> Option<String> {
612 match value {
613 Value::Null | Value::Bool(false) => None,
614 Value::Bool(true) => Some("on".to_string()),
615 Value::String(text) => Some(text.clone()),
616 other => Some(other.to_string()),
617 }
618}
619
620fn row_form(values: &serde_json::Map<String, Value>) -> FormInput {
622 FormInput::new(
623 values
624 .iter()
625 .filter_map(|(name, value)| form_text(value).map(|text| (name.clone(), text)))
626 .collect(),
627 )
628}
629
630fn stored_when_hidden(
633 values: &FormInput,
634 record: Option<&Row>,
635 hidden: &BTreeSet<String>,
636) -> FormInput {
637 let mut state = values.without(hidden.iter().map(String::as_str));
638 for name in hidden {
639 let stored = match record.and_then(|record| record.get(name)) {
640 None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
641 Some(Value::Bool(true)) => "on".to_string(),
642 Some(Value::String(text)) => text.clone(),
643 Some(other) => other.to_string(),
644 };
645 state.insert(name.clone(), stored);
646 }
647 state
648}
649
650#[cfg(test)]
651mod tests {
652 use super::*;
653 use crate::runtime_resource::FieldKindDef;
654
655 fn field(name: &str) -> FieldDef {
656 FieldDef {
657 name: name.into(),
658 label: name.into(),
659 kind: FieldKindDef::Text,
660 required: true,
661 }
662 }
663
664 fn form(pairs: &[(&str, &str)]) -> FormInput {
665 FormInput::new(
666 pairs
667 .iter()
668 .map(|(k, v)| (k.to_string(), v.to_string()))
669 .collect(),
670 )
671 }
672
673 fn user() -> ActingUser {
674 ActingUser::new(1, "Ada", "ada@example.test")
675 }
676
677 #[test]
678 fn a_field_with_no_condition_shows() {
679 let conditions = FieldConditions::new();
680 let user = user();
681 let values = form(&[]);
682 let context = FormContext::new(Operation::Create, None, &user, &values);
683 assert!(conditions.is_shown("title", &context));
684 assert!(conditions.is_empty());
685 }
686
687 #[test]
688 fn hidden_on_and_visible_on_follow_the_operation() {
689 let conditions = FieldConditions::new()
690 .hidden_on("slug", &[Operation::Create])
691 .visible_on("published_at", &[Operation::Edit]);
692 let fields = [field("slug"), field("published_at"), field("title")];
693 let user = user();
694 let values = form(&[]);
695 let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
696 assert_eq!(
697 on_create,
698 BTreeSet::from(["published_at".into(), "slug".into()])
699 );
700 let record = Row::new();
701 let on_edit =
702 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
703 assert!(on_edit.is_empty());
704 }
705
706 #[test]
707 fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
708 let conditions = FieldConditions::new()
709 .hidden("note", |_| true)
710 .hidden_on("note", &[Operation::Create])
711 .visible("note", |form| form.user().can("notes.edit"));
712 let user = user();
713 let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
714 let values = form(&[]);
715 let record = Row::new();
716 let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
717 assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
718 assert!(conditions.is_shown("note", &edit(&editor)));
719 let create = FormContext::new(Operation::Create, None, &editor, &values);
720 assert!(!conditions.is_shown("note", &create), "hidden on create");
721 }
722
723 #[test]
724 fn a_condition_reads_the_record_and_the_current_values() {
725 let conditions = FieldConditions::new()
726 .live("kind")
727 .visible("company", |form| form.get("kind") == Some("business"))
728 .visible("archived_note", |form| {
729 form.record()
730 .and_then(|record| record.get("status"))
731 .and_then(Value::as_str)
732 == Some("archived")
733 });
734 assert!(conditions.is_live("kind"));
735 assert!(!conditions.is_live("company"));
736 let fields = [field("kind"), field("company"), field("archived_note")];
737 let user = user();
738 let mut record = Row::new();
739 record.insert("status".into(), Value::from("archived"));
740 let hidden = conditions.hidden_fields(
741 &fields,
742 Operation::Edit,
743 Some(&record),
744 &user,
745 &form(&[("kind", "business")]),
746 );
747 assert!(hidden.is_empty(), "{hidden:?}");
748 let hidden = conditions.hidden_fields(
749 &fields,
750 Operation::Create,
751 None,
752 &user,
753 &form(&[("kind", "person")]),
754 );
755 assert_eq!(
756 hidden,
757 BTreeSet::from(["archived_note".into(), "company".into()])
758 );
759 }
760
761 #[test]
764 fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
765 let conditions = FieldConditions::new()
766 .visible("secret", |form| form.user().can("secret.edit"))
767 .visible("extra", |form| form.get("secret") == Some("yes"));
768 let fields = [field("secret"), field("extra")];
769 let user = user();
770 let sent = form(&[("secret", "yes"), ("extra", "changed")]);
771
772 let mut record = Row::new();
773 record.insert("secret".into(), Value::from("no"));
774 let hidden =
775 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
776 assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));
777
778 record.insert("secret".into(), Value::from("yes"));
779 let hidden =
780 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
781 assert_eq!(hidden, BTreeSet::from(["secret".into()]));
782 }
783
784 #[test]
785 fn defaults_fill_the_create_form_in_order_and_skip_sent_fields() {
786 let conditions = FieldConditions::new()
787 .default_value("status", "draft")
788 .default_value("featured", true)
789 .default_with("summary", |form| {
790 Value::from(format!("{} post", form.get("status").unwrap_or("?")))
791 });
792 let mut featured = field("featured");
793 featured.kind = FieldKindDef::Checkbox;
794 let fields = [field("status"), featured, field("summary"), field("title")];
795 let user = user();
796 let shown = conditions.default_form(&fields, &user);
797 assert_eq!(shown.get("status"), Some("draft"));
798 assert!(shown.checkbox("featured"));
799 assert_eq!(shown.get("summary"), Some("draft post"));
800 assert!(!shown.has("title"));
801 let saved = conditions.with_defaults(&fields, &user, &form(&[("status", "publish")]));
802 assert_eq!(saved.get("summary"), Some("publish post"));
803 assert!(
804 !saved.has("featured"),
805 "an unticked checkbox stays unticked"
806 );
807 }
808
809 #[test]
810 fn a_row_condition_reads_its_row_and_the_form_around_it() {
811 let conditions = FieldConditions::new()
812 .visible("fields.choices", |row| row.get("type") == Some("select"))
813 .visible("fields.note", |row| row.get("../../mode") == Some("expert"));
814 let repeater = FieldDef {
815 name: "fields".into(),
816 label: "Fields".into(),
817 kind: FieldKindDef::Repeater(vec![field("type"), field("choices"), field("note")]),
818 required: false,
819 };
820 let user = user();
821 let values = form(&[
822 ("mode", "simple"),
823 (
824 "fields",
825 r#"[{"type":"select"},{"type":"text","choices":"x"}]"#,
826 ),
827 ]);
828 let hidden = conditions.hidden_sub_fields(
829 std::slice::from_ref(&repeater),
830 Operation::Create,
831 None,
832 &user,
833 &values,
834 );
835 assert_eq!(
836 hidden,
837 BTreeSet::from([
838 "fields.0.note".into(),
839 "fields.1.choices".into(),
840 "fields.1.note".into()
841 ])
842 );
843 let pruned = crate::structure::without_sub_fields(&[repeater], &values, &hidden);
844 assert_eq!(
845 pruned.get("fields"),
846 Some(r#"[{"type":"select"},{"type":"text"}]"#)
847 );
848 }
849
850 #[test]
851 fn a_block_condition_is_keyed_by_the_block_and_reads_the_block_row() {
852 let conditions =
853 FieldConditions::new().visible("content.hero.style", |row| row.checked("styled"));
854 let content = FieldDef {
855 name: "content".into(),
856 label: "Content".into(),
857 kind: FieldKindDef::FlexibleContent(vec![crate::runtime_resource::BlockDef {
858 name: "hero".into(),
859 label: "Hero".into(),
860 fields: vec![field("styled"), field("style")],
861 }]),
862 required: false,
863 };
864 let user = user();
865 let values = form(&[(
866 "content",
867 r#"[{"type":"hero","data":{"styled":true,"style":"a"}},{"type":"hero","data":{"style":"b"}}]"#,
868 )]);
869 let hidden = conditions.hidden_sub_fields(
870 std::slice::from_ref(&content),
871 Operation::Edit,
872 None,
873 &user,
874 &values,
875 );
876 assert_eq!(hidden, BTreeSet::from(["content.1.data.style".into()]));
877 let pruned = crate::structure::without_sub_fields(&[content], &values, &hidden);
878 let pruned: Value = serde_json::from_str(pruned.get("content").unwrap()).unwrap();
879 assert_eq!(
880 pruned,
881 serde_json::json!([
882 {"type": "hero", "data": {"styled": true, "style": "a"}},
883 {"type": "hero", "data": {}}
884 ])
885 );
886 }
887}