1use std::collections::{BTreeSet, HashMap};
27use std::fmt;
28use std::sync::Arc;
29
30use serde_json::Value;
31
32use crate::form::FormInput;
33use crate::policy::ActingUser;
34use crate::runtime_resource::{FieldDef, Row};
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum Operation {
39 Create,
41 Edit,
43}
44
45impl Operation {
46 pub fn as_str(self) -> &'static str {
48 match self {
49 Operation::Create => "create",
50 Operation::Edit => "edit",
51 }
52 }
53}
54
55#[derive(Debug, Clone, Copy)]
58pub struct FormContext<'a> {
59 operation: Operation,
60 record: Option<&'a Row>,
61 user: &'a ActingUser,
62 values: &'a FormInput,
63}
64
65impl<'a> FormContext<'a> {
66 pub fn new(
69 operation: Operation,
70 record: Option<&'a Row>,
71 user: &'a ActingUser,
72 values: &'a FormInput,
73 ) -> Self {
74 FormContext {
75 operation,
76 record,
77 user,
78 values,
79 }
80 }
81
82 pub fn operation(&self) -> Operation {
84 self.operation
85 }
86
87 pub fn record(&self) -> Option<&'a Row> {
90 self.record
91 }
92
93 pub fn user(&self) -> &'a ActingUser {
95 self.user
96 }
97
98 pub fn get(&self, name: &str) -> Option<&'a str> {
103 self.values.get(name)
104 }
105
106 pub fn checked(&self, name: &str) -> bool {
108 self.values.checkbox(name)
109 }
110}
111
112type Rule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;
114
115#[derive(Clone, Default)]
124pub struct FieldConditions {
125 hidden: HashMap<String, Rule>,
126 visible: HashMap<String, Rule>,
127 live: BTreeSet<String>,
128 slugs: HashMap<String, String>,
130 slug_locks: HashMap<String, Rule>,
132 disabled: HashMap<String, Rule>,
134}
135
136impl fmt::Debug for FieldConditions {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
139 f.debug_struct("FieldConditions")
140 .field("hidden", &names(&self.hidden))
141 .field("visible", &names(&self.visible))
142 .field("live", &self.live)
143 .field("slugs", &self.slugs)
144 .field("slug_locks", &names(&self.slug_locks))
145 .field("disabled", &names(&self.disabled))
146 .finish()
147 }
148}
149
150impl FieldConditions {
151 pub fn new() -> Self {
153 FieldConditions::default()
154 }
155
156 pub fn visible(
158 mut self,
159 field: impl Into<String>,
160 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
161 ) -> Self {
162 self.visible.insert(field.into(), Arc::new(rule));
163 self
164 }
165
166 pub fn hidden(
168 mut self,
169 field: impl Into<String>,
170 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
171 ) -> Self {
172 self.hidden.insert(field.into(), Arc::new(rule));
173 self
174 }
175
176 pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
178 let operations = operations.to_vec();
179 self.visible(field, move |form| operations.contains(&form.operation()))
180 }
181
182 pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
184 let operations = operations.to_vec();
185 self.hidden(field, move |form| operations.contains(&form.operation()))
186 }
187
188 pub fn disabled(
194 mut self,
195 field: impl Into<String>,
196 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
197 ) -> Self {
198 self.disabled.insert(field.into(), Arc::new(rule));
199 self
200 }
201
202 pub fn disabled_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
205 let operations = operations.to_vec();
206 self.disabled(field, move |form| operations.contains(&form.operation()))
207 }
208
209 pub fn is_disabled(&self, field: &str, form: &FormContext<'_>) -> bool {
211 self.disabled.get(field).is_some_and(|rule| rule(form))
212 }
213
214 pub fn live(mut self, field: impl Into<String>) -> Self {
220 self.live.insert(field.into());
221 self
222 }
223
224 pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
236 self.slugs.insert(field.into(), source.into());
237 self
238 }
239
240 pub fn slug_locked_when(
259 mut self,
260 field: impl Into<String>,
261 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
262 ) -> Self {
263 self.slug_locks.insert(field.into(), Arc::new(rule));
264 self
265 }
266
267 pub fn is_slug_locked(&self, field: &str, form: &FormContext<'_>) -> bool {
271 let Some(rule) = self.slug_locks.get(field) else {
272 return false;
273 };
274 let stored = form
275 .record()
276 .and_then(|record| record.get(field))
277 .is_some_and(|value| match value {
278 Value::Null => false,
279 Value::String(text) => !text.trim().is_empty(),
280 _ => true,
281 });
282 form.operation() == Operation::Edit && stored && rule(form)
283 }
284
285 pub fn slug_source(&self, field: &str) -> Option<&str> {
287 self.slugs.get(field).map(String::as_str)
288 }
289
290 pub fn is_live(&self, field: &str) -> bool {
292 self.live.contains(field)
293 }
294
295 pub fn is_empty(&self) -> bool {
297 self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
298 }
299
300 pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
303 let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
304 let visible = self.visible.get(field).is_none_or(|rule| rule(form));
305 !hidden && visible
306 }
307
308 pub fn hidden_fields(
315 &self,
316 fields: &[FieldDef],
317 operation: Operation,
318 record: Option<&Row>,
319 user: &ActingUser,
320 values: &FormInput,
321 ) -> BTreeSet<String> {
322 let mut hidden = BTreeSet::new();
323 if self.hidden.is_empty() && self.visible.is_empty() {
324 return hidden;
325 }
326 for _ in 0..=fields.len() {
327 let state = stored_when_hidden(values, record, &hidden);
328 let form = FormContext::new(operation, record, user, &state);
329 let next: BTreeSet<String> = fields
330 .iter()
331 .filter(|field| !self.is_shown(&field.name, &form))
332 .map(|field| field.name.clone())
333 .collect();
334 if next == hidden {
335 break;
336 }
337 hidden = next;
338 }
339 hidden
340 }
341}
342
343fn stored_when_hidden(
346 values: &FormInput,
347 record: Option<&Row>,
348 hidden: &BTreeSet<String>,
349) -> FormInput {
350 let mut state = values.without(hidden.iter().map(String::as_str));
351 for name in hidden {
352 let stored = match record.and_then(|record| record.get(name)) {
353 None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
354 Some(Value::Bool(true)) => "on".to_string(),
355 Some(Value::String(text)) => text.clone(),
356 Some(other) => other.to_string(),
357 };
358 state.insert(name.clone(), stored);
359 }
360 state
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366 use crate::runtime_resource::FieldKindDef;
367
368 fn field(name: &str) -> FieldDef {
369 FieldDef {
370 name: name.into(),
371 label: name.into(),
372 kind: FieldKindDef::Text,
373 required: true,
374 }
375 }
376
377 fn form(pairs: &[(&str, &str)]) -> FormInput {
378 FormInput::new(
379 pairs
380 .iter()
381 .map(|(k, v)| (k.to_string(), v.to_string()))
382 .collect(),
383 )
384 }
385
386 fn user() -> ActingUser {
387 ActingUser::new(1, "Ada", "ada@example.test")
388 }
389
390 #[test]
391 fn a_field_with_no_condition_shows() {
392 let conditions = FieldConditions::new();
393 let user = user();
394 let values = form(&[]);
395 let context = FormContext::new(Operation::Create, None, &user, &values);
396 assert!(conditions.is_shown("title", &context));
397 assert!(conditions.is_empty());
398 }
399
400 #[test]
401 fn hidden_on_and_visible_on_follow_the_operation() {
402 let conditions = FieldConditions::new()
403 .hidden_on("slug", &[Operation::Create])
404 .visible_on("published_at", &[Operation::Edit]);
405 let fields = [field("slug"), field("published_at"), field("title")];
406 let user = user();
407 let values = form(&[]);
408 let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
409 assert_eq!(
410 on_create,
411 BTreeSet::from(["published_at".into(), "slug".into()])
412 );
413 let record = Row::new();
414 let on_edit =
415 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
416 assert!(on_edit.is_empty());
417 }
418
419 #[test]
420 fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
421 let conditions = FieldConditions::new()
422 .hidden("note", |_| true)
423 .hidden_on("note", &[Operation::Create])
424 .visible("note", |form| form.user().can("notes.edit"));
425 let user = user();
426 let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
427 let values = form(&[]);
428 let record = Row::new();
429 let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
430 assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
431 assert!(conditions.is_shown("note", &edit(&editor)));
432 let create = FormContext::new(Operation::Create, None, &editor, &values);
433 assert!(!conditions.is_shown("note", &create), "hidden on create");
434 }
435
436 #[test]
437 fn a_condition_reads_the_record_and_the_current_values() {
438 let conditions = FieldConditions::new()
439 .live("kind")
440 .visible("company", |form| form.get("kind") == Some("business"))
441 .visible("archived_note", |form| {
442 form.record()
443 .and_then(|record| record.get("status"))
444 .and_then(Value::as_str)
445 == Some("archived")
446 });
447 assert!(conditions.is_live("kind"));
448 assert!(!conditions.is_live("company"));
449 let fields = [field("kind"), field("company"), field("archived_note")];
450 let user = user();
451 let mut record = Row::new();
452 record.insert("status".into(), Value::from("archived"));
453 let hidden = conditions.hidden_fields(
454 &fields,
455 Operation::Edit,
456 Some(&record),
457 &user,
458 &form(&[("kind", "business")]),
459 );
460 assert!(hidden.is_empty(), "{hidden:?}");
461 let hidden = conditions.hidden_fields(
462 &fields,
463 Operation::Create,
464 None,
465 &user,
466 &form(&[("kind", "person")]),
467 );
468 assert_eq!(
469 hidden,
470 BTreeSet::from(["archived_note".into(), "company".into()])
471 );
472 }
473
474 #[test]
477 fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
478 let conditions = FieldConditions::new()
479 .visible("secret", |form| form.user().can("secret.edit"))
480 .visible("extra", |form| form.get("secret") == Some("yes"));
481 let fields = [field("secret"), field("extra")];
482 let user = user();
483 let sent = form(&[("secret", "yes"), ("extra", "changed")]);
484
485 let mut record = Row::new();
486 record.insert("secret".into(), Value::from("no"));
487 let hidden =
488 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
489 assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));
490
491 record.insert("secret".into(), Value::from("yes"));
492 let hidden =
493 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
494 assert_eq!(hidden, BTreeSet::from(["secret".into()]));
495 }
496}