1use std::collections::{BTreeSet, HashMap};
26use std::fmt;
27use std::sync::Arc;
28
29use serde_json::Value;
30
31use crate::form::FormInput;
32use crate::policy::ActingUser;
33use crate::runtime_resource::{FieldDef, Row};
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37pub enum Operation {
38 Create,
40 Edit,
42}
43
44impl Operation {
45 pub fn as_str(self) -> &'static str {
47 match self {
48 Operation::Create => "create",
49 Operation::Edit => "edit",
50 }
51 }
52}
53
54#[derive(Debug, Clone, Copy)]
57pub struct FormContext<'a> {
58 operation: Operation,
59 record: Option<&'a Row>,
60 user: &'a ActingUser,
61 values: &'a FormInput,
62}
63
64impl<'a> FormContext<'a> {
65 pub fn new(
68 operation: Operation,
69 record: Option<&'a Row>,
70 user: &'a ActingUser,
71 values: &'a FormInput,
72 ) -> Self {
73 FormContext {
74 operation,
75 record,
76 user,
77 values,
78 }
79 }
80
81 pub fn operation(&self) -> Operation {
83 self.operation
84 }
85
86 pub fn record(&self) -> Option<&'a Row> {
89 self.record
90 }
91
92 pub fn user(&self) -> &'a ActingUser {
94 self.user
95 }
96
97 pub fn get(&self, name: &str) -> Option<&'a str> {
102 self.values.get(name)
103 }
104
105 pub fn checked(&self, name: &str) -> bool {
107 self.values.checkbox(name)
108 }
109}
110
111type Rule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;
113
114#[derive(Clone, Default)]
123pub struct FieldConditions {
124 hidden: HashMap<String, Rule>,
125 visible: HashMap<String, Rule>,
126 live: BTreeSet<String>,
127 slugs: HashMap<String, String>,
129 slug_locks: HashMap<String, Rule>,
131}
132
133impl fmt::Debug for FieldConditions {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
136 f.debug_struct("FieldConditions")
137 .field("hidden", &names(&self.hidden))
138 .field("visible", &names(&self.visible))
139 .field("live", &self.live)
140 .field("slugs", &self.slugs)
141 .field("slug_locks", &names(&self.slug_locks))
142 .finish()
143 }
144}
145
146impl FieldConditions {
147 pub fn new() -> Self {
149 FieldConditions::default()
150 }
151
152 pub fn visible(
154 mut self,
155 field: impl Into<String>,
156 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
157 ) -> Self {
158 self.visible.insert(field.into(), Arc::new(rule));
159 self
160 }
161
162 pub fn hidden(
164 mut self,
165 field: impl Into<String>,
166 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
167 ) -> Self {
168 self.hidden.insert(field.into(), Arc::new(rule));
169 self
170 }
171
172 pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
174 let operations = operations.to_vec();
175 self.visible(field, move |form| operations.contains(&form.operation()))
176 }
177
178 pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
180 let operations = operations.to_vec();
181 self.hidden(field, move |form| operations.contains(&form.operation()))
182 }
183
184 pub fn live(mut self, field: impl Into<String>) -> Self {
190 self.live.insert(field.into());
191 self
192 }
193
194 pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
206 self.slugs.insert(field.into(), source.into());
207 self
208 }
209
210 pub fn slug_locked_when(
229 mut self,
230 field: impl Into<String>,
231 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
232 ) -> Self {
233 self.slug_locks.insert(field.into(), Arc::new(rule));
234 self
235 }
236
237 pub fn is_slug_locked(&self, field: &str, form: &FormContext<'_>) -> bool {
241 let Some(rule) = self.slug_locks.get(field) else {
242 return false;
243 };
244 let stored = form
245 .record()
246 .and_then(|record| record.get(field))
247 .is_some_and(|value| match value {
248 Value::Null => false,
249 Value::String(text) => !text.trim().is_empty(),
250 _ => true,
251 });
252 form.operation() == Operation::Edit && stored && rule(form)
253 }
254
255 pub fn slug_source(&self, field: &str) -> Option<&str> {
257 self.slugs.get(field).map(String::as_str)
258 }
259
260 pub fn is_live(&self, field: &str) -> bool {
262 self.live.contains(field)
263 }
264
265 pub fn is_empty(&self) -> bool {
267 self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
268 }
269
270 pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
273 let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
274 let visible = self.visible.get(field).is_none_or(|rule| rule(form));
275 !hidden && visible
276 }
277
278 pub fn hidden_fields(
285 &self,
286 fields: &[FieldDef],
287 operation: Operation,
288 record: Option<&Row>,
289 user: &ActingUser,
290 values: &FormInput,
291 ) -> BTreeSet<String> {
292 let mut hidden = BTreeSet::new();
293 if self.hidden.is_empty() && self.visible.is_empty() {
294 return hidden;
295 }
296 for _ in 0..=fields.len() {
297 let state = stored_when_hidden(values, record, &hidden);
298 let form = FormContext::new(operation, record, user, &state);
299 let next: BTreeSet<String> = fields
300 .iter()
301 .filter(|field| !self.is_shown(&field.name, &form))
302 .map(|field| field.name.clone())
303 .collect();
304 if next == hidden {
305 break;
306 }
307 hidden = next;
308 }
309 hidden
310 }
311}
312
313fn stored_when_hidden(
316 values: &FormInput,
317 record: Option<&Row>,
318 hidden: &BTreeSet<String>,
319) -> FormInput {
320 let mut state = values.without(hidden.iter().map(String::as_str));
321 for name in hidden {
322 let stored = match record.and_then(|record| record.get(name)) {
323 None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
324 Some(Value::Bool(true)) => "on".to_string(),
325 Some(Value::String(text)) => text.clone(),
326 Some(other) => other.to_string(),
327 };
328 state.insert(name.clone(), stored);
329 }
330 state
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336 use crate::runtime_resource::FieldKindDef;
337
338 fn field(name: &str) -> FieldDef {
339 FieldDef {
340 name: name.into(),
341 label: name.into(),
342 kind: FieldKindDef::Text,
343 required: true,
344 }
345 }
346
347 fn form(pairs: &[(&str, &str)]) -> FormInput {
348 FormInput::new(
349 pairs
350 .iter()
351 .map(|(k, v)| (k.to_string(), v.to_string()))
352 .collect(),
353 )
354 }
355
356 fn user() -> ActingUser {
357 ActingUser::new(1, "Ada", "ada@example.test")
358 }
359
360 #[test]
361 fn a_field_with_no_condition_shows() {
362 let conditions = FieldConditions::new();
363 let user = user();
364 let values = form(&[]);
365 let context = FormContext::new(Operation::Create, None, &user, &values);
366 assert!(conditions.is_shown("title", &context));
367 assert!(conditions.is_empty());
368 }
369
370 #[test]
371 fn hidden_on_and_visible_on_follow_the_operation() {
372 let conditions = FieldConditions::new()
373 .hidden_on("slug", &[Operation::Create])
374 .visible_on("published_at", &[Operation::Edit]);
375 let fields = [field("slug"), field("published_at"), field("title")];
376 let user = user();
377 let values = form(&[]);
378 let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
379 assert_eq!(
380 on_create,
381 BTreeSet::from(["published_at".into(), "slug".into()])
382 );
383 let record = Row::new();
384 let on_edit =
385 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
386 assert!(on_edit.is_empty());
387 }
388
389 #[test]
390 fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
391 let conditions = FieldConditions::new()
392 .hidden("note", |_| true)
393 .hidden_on("note", &[Operation::Create])
394 .visible("note", |form| form.user().can("notes.edit"));
395 let user = user();
396 let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
397 let values = form(&[]);
398 let record = Row::new();
399 let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
400 assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
401 assert!(conditions.is_shown("note", &edit(&editor)));
402 let create = FormContext::new(Operation::Create, None, &editor, &values);
403 assert!(!conditions.is_shown("note", &create), "hidden on create");
404 }
405
406 #[test]
407 fn a_condition_reads_the_record_and_the_current_values() {
408 let conditions = FieldConditions::new()
409 .live("kind")
410 .visible("company", |form| form.get("kind") == Some("business"))
411 .visible("archived_note", |form| {
412 form.record()
413 .and_then(|record| record.get("status"))
414 .and_then(Value::as_str)
415 == Some("archived")
416 });
417 assert!(conditions.is_live("kind"));
418 assert!(!conditions.is_live("company"));
419 let fields = [field("kind"), field("company"), field("archived_note")];
420 let user = user();
421 let mut record = Row::new();
422 record.insert("status".into(), Value::from("archived"));
423 let hidden = conditions.hidden_fields(
424 &fields,
425 Operation::Edit,
426 Some(&record),
427 &user,
428 &form(&[("kind", "business")]),
429 );
430 assert!(hidden.is_empty(), "{hidden:?}");
431 let hidden = conditions.hidden_fields(
432 &fields,
433 Operation::Create,
434 None,
435 &user,
436 &form(&[("kind", "person")]),
437 );
438 assert_eq!(
439 hidden,
440 BTreeSet::from(["archived_note".into(), "company".into()])
441 );
442 }
443
444 #[test]
447 fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
448 let conditions = FieldConditions::new()
449 .visible("secret", |form| form.user().can("secret.edit"))
450 .visible("extra", |form| form.get("secret") == Some("yes"));
451 let fields = [field("secret"), field("extra")];
452 let user = user();
453 let sent = form(&[("secret", "yes"), ("extra", "changed")]);
454
455 let mut record = Row::new();
456 record.insert("secret".into(), Value::from("no"));
457 let hidden =
458 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
459 assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));
460
461 record.insert("secret".into(), Value::from("yes"));
462 let hidden =
463 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
464 assert_eq!(hidden, BTreeSet::from(["secret".into()]));
465 }
466}