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}
130
131impl fmt::Debug for FieldConditions {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
134 f.debug_struct("FieldConditions")
135 .field("hidden", &names(&self.hidden))
136 .field("visible", &names(&self.visible))
137 .field("live", &self.live)
138 .field("slugs", &self.slugs)
139 .finish()
140 }
141}
142
143impl FieldConditions {
144 pub fn new() -> Self {
146 FieldConditions::default()
147 }
148
149 pub fn visible(
151 mut self,
152 field: impl Into<String>,
153 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
154 ) -> Self {
155 self.visible.insert(field.into(), Arc::new(rule));
156 self
157 }
158
159 pub fn hidden(
161 mut self,
162 field: impl Into<String>,
163 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
164 ) -> Self {
165 self.hidden.insert(field.into(), Arc::new(rule));
166 self
167 }
168
169 pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
171 let operations = operations.to_vec();
172 self.visible(field, move |form| operations.contains(&form.operation()))
173 }
174
175 pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
177 let operations = operations.to_vec();
178 self.hidden(field, move |form| operations.contains(&form.operation()))
179 }
180
181 pub fn live(mut self, field: impl Into<String>) -> Self {
187 self.live.insert(field.into());
188 self
189 }
190
191 pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
202 self.slugs.insert(field.into(), source.into());
203 self
204 }
205
206 pub fn slug_source(&self, field: &str) -> Option<&str> {
208 self.slugs.get(field).map(String::as_str)
209 }
210
211 pub fn is_live(&self, field: &str) -> bool {
213 self.live.contains(field)
214 }
215
216 pub fn is_empty(&self) -> bool {
218 self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
219 }
220
221 pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
224 let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
225 let visible = self.visible.get(field).is_none_or(|rule| rule(form));
226 !hidden && visible
227 }
228
229 pub fn hidden_fields(
236 &self,
237 fields: &[FieldDef],
238 operation: Operation,
239 record: Option<&Row>,
240 user: &ActingUser,
241 values: &FormInput,
242 ) -> BTreeSet<String> {
243 let mut hidden = BTreeSet::new();
244 if self.hidden.is_empty() && self.visible.is_empty() {
245 return hidden;
246 }
247 for _ in 0..=fields.len() {
248 let state = stored_when_hidden(values, record, &hidden);
249 let form = FormContext::new(operation, record, user, &state);
250 let next: BTreeSet<String> = fields
251 .iter()
252 .filter(|field| !self.is_shown(&field.name, &form))
253 .map(|field| field.name.clone())
254 .collect();
255 if next == hidden {
256 break;
257 }
258 hidden = next;
259 }
260 hidden
261 }
262}
263
264fn stored_when_hidden(
267 values: &FormInput,
268 record: Option<&Row>,
269 hidden: &BTreeSet<String>,
270) -> FormInput {
271 let mut state = values.without(hidden.iter().map(String::as_str));
272 for name in hidden {
273 let stored = match record.and_then(|record| record.get(name)) {
274 None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
275 Some(Value::Bool(true)) => "on".to_string(),
276 Some(Value::String(text)) => text.clone(),
277 Some(other) => other.to_string(),
278 };
279 state.insert(name.clone(), stored);
280 }
281 state
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287 use crate::runtime_resource::FieldKindDef;
288
289 fn field(name: &str) -> FieldDef {
290 FieldDef {
291 name: name.into(),
292 label: name.into(),
293 kind: FieldKindDef::Text,
294 required: true,
295 }
296 }
297
298 fn form(pairs: &[(&str, &str)]) -> FormInput {
299 FormInput::new(
300 pairs
301 .iter()
302 .map(|(k, v)| (k.to_string(), v.to_string()))
303 .collect(),
304 )
305 }
306
307 fn user() -> ActingUser {
308 ActingUser::new(1, "Ada", "ada@example.test")
309 }
310
311 #[test]
312 fn a_field_with_no_condition_shows() {
313 let conditions = FieldConditions::new();
314 let user = user();
315 let values = form(&[]);
316 let context = FormContext::new(Operation::Create, None, &user, &values);
317 assert!(conditions.is_shown("title", &context));
318 assert!(conditions.is_empty());
319 }
320
321 #[test]
322 fn hidden_on_and_visible_on_follow_the_operation() {
323 let conditions = FieldConditions::new()
324 .hidden_on("slug", &[Operation::Create])
325 .visible_on("published_at", &[Operation::Edit]);
326 let fields = [field("slug"), field("published_at"), field("title")];
327 let user = user();
328 let values = form(&[]);
329 let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
330 assert_eq!(
331 on_create,
332 BTreeSet::from(["published_at".into(), "slug".into()])
333 );
334 let record = Row::new();
335 let on_edit =
336 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
337 assert!(on_edit.is_empty());
338 }
339
340 #[test]
341 fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
342 let conditions = FieldConditions::new()
343 .hidden("note", |_| true)
344 .hidden_on("note", &[Operation::Create])
345 .visible("note", |form| form.user().can("notes.edit"));
346 let user = user();
347 let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
348 let values = form(&[]);
349 let record = Row::new();
350 let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
351 assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
352 assert!(conditions.is_shown("note", &edit(&editor)));
353 let create = FormContext::new(Operation::Create, None, &editor, &values);
354 assert!(!conditions.is_shown("note", &create), "hidden on create");
355 }
356
357 #[test]
358 fn a_condition_reads_the_record_and_the_current_values() {
359 let conditions = FieldConditions::new()
360 .live("kind")
361 .visible("company", |form| form.get("kind") == Some("business"))
362 .visible("archived_note", |form| {
363 form.record()
364 .and_then(|record| record.get("status"))
365 .and_then(Value::as_str)
366 == Some("archived")
367 });
368 assert!(conditions.is_live("kind"));
369 assert!(!conditions.is_live("company"));
370 let fields = [field("kind"), field("company"), field("archived_note")];
371 let user = user();
372 let mut record = Row::new();
373 record.insert("status".into(), Value::from("archived"));
374 let hidden = conditions.hidden_fields(
375 &fields,
376 Operation::Edit,
377 Some(&record),
378 &user,
379 &form(&[("kind", "business")]),
380 );
381 assert!(hidden.is_empty(), "{hidden:?}");
382 let hidden = conditions.hidden_fields(
383 &fields,
384 Operation::Create,
385 None,
386 &user,
387 &form(&[("kind", "person")]),
388 );
389 assert_eq!(
390 hidden,
391 BTreeSet::from(["archived_note".into(), "company".into()])
392 );
393 }
394
395 #[test]
398 fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
399 let conditions = FieldConditions::new()
400 .visible("secret", |form| form.user().can("secret.edit"))
401 .visible("extra", |form| form.get("secret") == Some("yes"));
402 let fields = [field("secret"), field("extra")];
403 let user = user();
404 let sent = form(&[("secret", "yes"), ("extra", "changed")]);
405
406 let mut record = Row::new();
407 record.insert("secret".into(), Value::from("no"));
408 let hidden =
409 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
410 assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));
411
412 record.insert("secret".into(), Value::from("yes"));
413 let hidden =
414 conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
415 assert_eq!(hidden, BTreeSet::from(["secret".into()]));
416 }
417}