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