ignite-core 0.7.3

Core types for Ignite, the admin panel for Rocket.rs: resources, fields, forms and runtime resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! Fields that show only when a condition holds, as Filament's `visible()`, `hidden()`,
//! `visibleOn()`, `hiddenOn()` and `live()`, and fields shown but not editable, as its
//! `disabled()` and `disabledOn()`.
//!
//! A condition is a closure the server runs each time it builds or saves a form, given a
//! [`FormContext`]: the operation, the record being edited (none on create), the signed-in
//! user and the form's current values, as a Filament closure is given `$operation`, `$record`,
//! `auth()->user()` and `$get`. A field whose condition fails is hidden: the panel does not
//! render it, does not check it, and does not save it, so a request that sends it anyway
//! cannot change the stored value.
//!
//! A field marked [`live`](FieldConditions::live) re-renders the form when its value changes in
//! the browser: the panel's script sends the form to the server, which runs the conditions on
//! the new values and returns the fields to show.
//!
//! A condition on a sub-field of a repeater, group or flexible content field is keyed by the
//! sub-field's path without row numbers, such as `"fields.choices"` for the sub-field `choices`
//! of each row of the repeater `fields` (a flexible content block's sub-field adds the block's
//! name: `"content.hero.style"`). It runs once per row, and its [`FormContext::get`] reads the
//! row's own values, as Filament's `$get` is scoped to the repeater item; `get("../../name")`
//! reads the field `name` around the repeater, as Filament's `$get('../../name')`. A sub-field
//! that is hidden in its row is not rendered, not checked and not saved.
//!
//! A field can also have a default value on the create form, as Filament's `default()`: see
//! [`FieldConditions::default_value`].
//!
//! ```ignore
//! RuntimeResource::new("posts", "Posts", "Post", PostData)
//!     .field(kind_field)
//!     .field(company_field)
//!     .live("kind")
//!     .visible("company", |form| form.get("kind") == Some("business"))
//!     .hidden_on("slug", &[Operation::Create])
//!     .visible("featured", |form| form.user().can("posts.feature"));
//! ```

use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::sync::Arc;

use serde_json::Value;

use crate::form::FormInput;
use crate::policy::ActingUser;
use crate::runtime_resource::{FieldDef, Row};

/// What the form is for, as Filament's `$operation`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Operation {
    /// The new-record form and its save.
    Create,
    /// The edit form of a record and its save.
    Edit,
}

impl Operation {
    /// The operation's name as Filament spells it: `"create"` or `"edit"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Operation::Create => "create",
            Operation::Edit => "edit",
        }
    }
}

/// What a condition is given: the operation, the record, the signed-in user and the form's
/// current values.
#[derive(Debug, Clone, Copy)]
pub struct FormContext<'a> {
    operation: Operation,
    record: Option<&'a Row>,
    user: &'a ActingUser,
    values: &'a FormInput,
    /// The context around a repeater row or group whose sub-fields this context is for.
    parent: Option<&'a FormContext<'a>>,
}

impl<'a> FormContext<'a> {
    /// The context of a form for `operation`, editing `record` (none on create), for `user`,
    /// whose fields hold `values`. The panel builds it; an app builds one to test a condition.
    pub fn new(
        operation: Operation,
        record: Option<&'a Row>,
        user: &'a ActingUser,
        values: &'a FormInput,
    ) -> Self {
        FormContext {
            operation,
            record,
            user,
            values,
            parent: None,
        }
    }

    /// The context of the sub-fields of a repeater row, a flexible content block or a group,
    /// whose values are `values`, inside the context `parent`: the operation, the record and the
    /// user are `parent`'s, and [`get`](Self::get) reads `values`, as Filament's `$get` is
    /// scoped to the repeater item. `get("../../name")` reads `name` in `parent`.
    pub fn row(parent: &'a FormContext<'a>, values: &'a FormInput) -> Self {
        FormContext {
            operation: parent.operation,
            record: parent.record,
            user: parent.user,
            values,
            parent: Some(parent),
        }
    }

    /// Whether the form creates a record or edits one, as Filament's `$operation`.
    pub fn operation(&self) -> Operation {
        self.operation
    }

    /// The record being edited, as stored, as Filament's `$record`: a runtime resource's
    /// [`Row`], or a static resource's record serialized to JSON. `None` on create.
    pub fn record(&self) -> Option<&'a Row> {
        self.record
    }

    /// The signed-in user, as `auth()->user()` in a Filament closure.
    pub fn user(&self) -> &'a ActingUser {
        self.user
    }

    /// The current value of the field `name`, as Filament's `$get('name')`: the value the
    /// user has typed or chosen, or `None` when it is blank. When the form is first shown it
    /// is the stored value. A field that is itself hidden gives its stored value, never one a
    /// request sent for it. The value is not checked.
    ///
    /// In the context of a repeater row (see [`row`](Self::row)), `name` is a sibling in the
    /// row, and a sibling hidden in its row reads as blank; `"../../name"` reads `name` around
    /// the repeater, as Filament's `$get('../../name')`. A structured field's value is its JSON
    /// text.
    pub fn get(&self, name: &str) -> Option<&'a str> {
        match (name.strip_prefix("../../"), self.parent) {
            (Some(outer), Some(parent)) => parent.get(outer),
            _ => self.values.get(name),
        }
    }

    /// Whether the checkbox `name` is ticked. See [`FormInput::checkbox`]. `"../../name"`
    /// reads around a repeater row, as [`get`](Self::get) does.
    pub fn checked(&self, name: &str) -> bool {
        match (name.strip_prefix("../../"), self.parent) {
            (Some(outer), Some(parent)) => parent.checked(outer),
            _ => self.values.checkbox(name),
        }
    }
}

/// A condition on a field.
type Rule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;

/// A field's default value on the create form, from the form's state.
type DefaultRule = Arc<dyn Fn(&FormContext<'_>) -> Value + Send + Sync>;

/// The conditions of a form's fields, by field name, and the fields that are live. Each
/// method takes the field's name and returns the conditions, so they chain.
///
/// As in Filament, a field has one `hidden` condition and one `visible` condition, and shows
/// only when its `hidden` condition fails and its `visible` condition holds. A later
/// [`hidden`](Self::hidden) or [`hidden_on`](Self::hidden_on) for the same field replaces the
/// earlier one, and so does a later [`visible`](Self::visible) or
/// [`visible_on`](Self::visible_on). A field with no condition always shows.
#[derive(Clone, Default)]
pub struct FieldConditions {
    hidden: HashMap<String, Rule>,
    visible: HashMap<String, Rule>,
    live: BTreeSet<String>,
    /// The field each slug field is filled from, by slug field name.
    slugs: HashMap<String, String>,
    /// When each slug field stops following its source, by slug field name.
    slug_locks: HashMap<String, Rule>,
    /// When each field is shown but not editable, by field name.
    disabled: HashMap<String, Rule>,
    /// The default value of each field on the create form, by field name.
    defaults: HashMap<String, DefaultRule>,
}

impl fmt::Debug for FieldConditions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
        f.debug_struct("FieldConditions")
            .field("hidden", &names(&self.hidden))
            .field("visible", &names(&self.visible))
            .field("live", &self.live)
            .field("slugs", &self.slugs)
            .field("slug_locks", &names(&self.slug_locks))
            .field("disabled", &names(&self.disabled))
            .field(
                "defaults",
                &self.defaults.keys().cloned().collect::<BTreeSet<_>>(),
            )
            .finish()
    }
}

impl FieldConditions {
    /// No conditions: every field shows, and none is live.
    pub fn new() -> Self {
        FieldConditions::default()
    }

    /// Shows `field` only when `rule` holds, as Filament's `->visible(fn () => ...)`.
    pub fn visible(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.visible.insert(field.into(), Arc::new(rule));
        self
    }

    /// Hides `field` when `rule` holds, as Filament's `->hidden(fn () => ...)`.
    pub fn hidden(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.hidden.insert(field.into(), Arc::new(rule));
        self
    }

    /// Shows `field` only on the forms of `operations`, as Filament's `->visibleOn('edit')`.
    pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
        let operations = operations.to_vec();
        self.visible(field, move |form| operations.contains(&form.operation()))
    }

    /// Hides `field` on the forms of `operations`, as Filament's `->hiddenOn('edit')`.
    pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
        let operations = operations.to_vec();
        self.hidden(field, move |form| operations.contains(&form.operation()))
    }

    /// Shows `field` but does not let the user change it when `rule` holds, as Filament's
    /// `->disabled(fn () => ...)`: its input is disabled and, as in Filament, a disabled field
    /// is not saved, so its stored value is kept whatever a request sends. A later
    /// [`disabled`](Self::disabled) or [`disabled_on`](Self::disabled_on) for the field
    /// replaces the earlier one.
    pub fn disabled(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.disabled.insert(field.into(), Arc::new(rule));
        self
    }

    /// Disables `field` on the forms of `operations`, as Filament's `->disabledOn('edit')`:
    /// such as a key that is set when the record is created and locked after its first save.
    pub fn disabled_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
        let operations = operations.to_vec();
        self.disabled(field, move |form| operations.contains(&form.operation()))
    }

    /// Whether `field` is disabled on `form`.
    pub fn is_disabled(&self, field: &str, form: &FormContext<'_>) -> bool {
        self.disabled.get(field).is_some_and(|rule| rule(form))
    }

    /// Makes `field` live, as Filament's `->live()`: when its value changes in the browser,
    /// the form's fields are shown again for the new value, so a field whose condition reads
    /// it with [`FormContext::get`] appears or disappears. The browser sends the change when
    /// the input fires `change`: at once for a select, a checkbox or a radio, and when a text
    /// input loses focus.
    pub fn live(mut self, field: impl Into<String>) -> Self {
        self.live.insert(field.into());
        self
    }

    /// Fills the field `field` with the slug of the field `source` as the user types, until the
    /// user edits `field` by hand, as Filament's documented slug pattern:
    /// `->afterStateUpdated(...)` on the title sets `slug` to `Str::slug($state)` unless the slug
    /// no longer matches `Str::slug($old)`. Filament writes that with a closure on the server;
    /// the panel's script does it in the browser, so it needs no round trip. The slug is the
    /// text in lowercase ASCII, accents removed, with each run of other characters turned into
    /// one `-`, as `Str::slug` gives it. The value is not checked: `validate` still checks it.
    ///
    /// On the edit form, a slug that is not the slug of the stored title counts as edited by
    /// hand, so it is not replaced. [`slug_locked_when`](Self::slug_locked_when) stops it from
    /// following the title at all, such as once the record is published.
    pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
        self.slugs.insert(field.into(), source.into());
        self
    }

    /// Stops the slug field `field` from following its source on the edit form of a record
    /// whose stored slug is not blank, when `rule` holds, such as when the stored record is
    /// published: the slug of a published post's URL then stays as it is when the title
    /// changes. On the create form, and while `rule` fails (such as for a draft), the slug
    /// follows the title as [`slug_from`](Self::slug_from) says. The user can still edit the
    /// slug by hand. The input is marked `data-ignite-slug-locked`, which the panel's script
    /// reads.
    ///
    /// Filament's slug example has no such rule: it stops when the user has edited the slug.
    /// Ignite keeps that, and adds this one.
    ///
    /// ```ignore
    /// conditions
    ///     .slug_from("slug", "title")
    ///     .slug_locked_when("slug", |form| {
    ///         form.record().and_then(|r| r.get("status")).and_then(|s| s.as_str()) == Some("publish")
    ///     })
    /// ```
    pub fn slug_locked_when(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.slug_locks.insert(field.into(), Arc::new(rule));
        self
    }

    /// Whether the slug field `field` no longer follows its source on `form`: the form edits a
    /// record whose stored `field` is not blank, and the rule of
    /// [`slug_locked_when`](Self::slug_locked_when) holds.
    pub fn is_slug_locked(&self, field: &str, form: &FormContext<'_>) -> bool {
        let Some(rule) = self.slug_locks.get(field) else {
            return false;
        };
        let stored = form
            .record()
            .and_then(|record| record.get(field))
            .is_some_and(|value| match value {
                Value::Null => false,
                Value::String(text) => !text.trim().is_empty(),
                _ => true,
            });
        form.operation() == Operation::Edit && stored && rule(form)
    }

    /// The field `field` is filled from by [`slug_from`](Self::slug_from), if any.
    pub fn slug_source(&self, field: &str) -> Option<&str> {
        self.slugs.get(field).map(String::as_str)
    }

    /// Whether `field` is live.
    pub fn is_live(&self, field: &str) -> bool {
        self.live.contains(field)
    }

    /// Whether no field has a condition or is live.
    pub fn is_empty(&self) -> bool {
        self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
    }

    /// Whether `field` shows in `form`: its `hidden` condition, if any, fails and its
    /// `visible` condition, if any, holds.
    pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
        let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
        let visible = self.visible.get(field).is_none_or(|rule| rule(form));
        !hidden && visible
    }

    /// The names of the `fields` that are hidden on the form for `operation`, editing
    /// `record`, for `user`, whose fields hold `values`.
    ///
    /// A condition that reads a hidden field gets the field's stored value, not the one in
    /// `values`, so a request cannot show a field by sending a value for a field it may not
    /// see. The conditions run again until the hidden fields settle.
    pub fn hidden_fields(
        &self,
        fields: &[FieldDef],
        operation: Operation,
        record: Option<&Row>,
        user: &ActingUser,
        values: &FormInput,
    ) -> BTreeSet<String> {
        let mut hidden = BTreeSet::new();
        if self.hidden.is_empty() && self.visible.is_empty() {
            return hidden;
        }
        for _ in 0..=fields.len() {
            let state = stored_when_hidden(values, record, &hidden);
            let form = FormContext::new(operation, record, user, &state);
            let next: BTreeSet<String> = fields
                .iter()
                .filter(|field| !self.is_shown(&field.name, &form))
                .map(|field| field.name.clone())
                .collect();
            if next == hidden {
                break;
            }
            hidden = next;
        }
        hidden
    }

    /// Gives `field` the default value `value` on the create form, as Filament's
    /// `->default(...)`: the create form shows it (a checkbox is ticked by `true`, a select has
    /// the value chosen, a checkbox list or a repeater takes JSON such as `["a","b"]`), and a
    /// create whose request does not send the field saves it, as Laravel's
    /// `$request->input('name', $default)`. The edit form always shows the stored value, as
    /// Filament uses defaults on the Create page only. A field with no default shows blank, as
    /// before.
    ///
    /// An unticked checkbox sends nothing, so a checkbox default only ticks the box on the
    /// create form: a create that does not send the checkbox saves `false`, as Laravel's
    /// `$request->boolean()`. A field hidden or disabled on the create form is not saved,
    /// default or not. A later default for the same field replaces the earlier one.
    pub fn default_value(self, field: impl Into<String>, value: impl Into<Value>) -> Self {
        let value = value.into();
        self.default_with(field, move |_| value.clone())
    }

    /// Gives `field` a default computed from the create form's state, as Filament's
    /// `->default(fn (Get $get) => ...)`: `rule` is given the create form's [`FormContext`]
    /// (no record, the signed-in user, and the form's values so far: on the form shown, the
    /// defaults of the fields before `field` in the form's order; on a save, the values the
    /// request sent and those defaults). Otherwise as
    /// [`default_value`](Self::default_value).
    pub fn default_with(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> Value + Send + Sync + 'static,
    ) -> Self {
        self.defaults.insert(field.into(), Arc::new(rule));
        self
    }

    /// Whether `field` has a default value on the create form.
    pub fn has_default(&self, field: &str) -> bool {
        self.defaults.contains_key(field)
    }

    /// The values the create form shows for `user` before anything is typed: the default of
    /// each field of `fields` that has one, in the fields' order, as form text.
    pub fn default_form(&self, fields: &[FieldDef], user: &ActingUser) -> FormInput {
        self.fill_defaults(fields, user, &FormInput::default(), true)
    }

    /// `values`, a submitted create form, with the default of each field the request did not
    /// send ([`FormInput::has`] is false), except a checkbox: an unticked checkbox sends
    /// nothing, so it stays unticked. The panel calls it before it checks a create.
    pub fn with_defaults(
        &self,
        fields: &[FieldDef],
        user: &ActingUser,
        values: &FormInput,
    ) -> FormInput {
        self.fill_defaults(fields, user, values, false)
    }

    fn fill_defaults(
        &self,
        fields: &[FieldDef],
        user: &ActingUser,
        values: &FormInput,
        checkboxes: bool,
    ) -> FormInput {
        let mut state = values.clone();
        if self.defaults.is_empty() {
            return state;
        }
        for field in fields {
            let Some(rule) = self.defaults.get(&field.name) else {
                continue;
            };
            if state.has(&field.name)
                || (!checkboxes && field.kind == crate::FieldKindDef::Checkbox)
            {
                continue;
            }
            let value = rule(&FormContext::new(Operation::Create, None, user, &state));
            if let Some(text) = form_text(&value) {
                state.insert(field.name.clone(), text);
            }
        }
        state
    }

    /// The sub-fields of the repeaters, groups and flexible content of `fields` that their
    /// conditions hide in their own row, by the dotted path of their value, such as
    /// `fields.0.choices` (a block's: `content.0.data.style`), on the form for `operation`,
    /// editing `record`, for `user`, whose fields hold `values` (a structured field's value as
    /// JSON text). A condition is keyed by the sub-field's path without row numbers
    /// (`fields.choices`) and reads its row's values (see [`FormContext::row`]); a sibling the
    /// row hides reads as blank. The panel leaves these sub-fields out of the form and out of
    /// the saved value.
    pub fn hidden_sub_fields(
        &self,
        fields: &[FieldDef],
        operation: Operation,
        record: Option<&Row>,
        user: &ActingUser,
        values: &FormInput,
    ) -> BTreeSet<String> {
        let mut hidden = BTreeSet::new();
        if !self
            .hidden
            .keys()
            .chain(self.visible.keys())
            .any(|key| key.contains('.'))
        {
            return hidden;
        }
        let form = FormContext::new(operation, record, user, values);
        for field in fields
            .iter()
            .filter(|f| crate::structure::is_structured(&f.kind))
        {
            let Some(value) = values
                .get(&field.name)
                .and_then(|text| serde_json::from_str::<Value>(text).ok())
            else {
                continue;
            };
            self.hidden_in(
                &field.kind,
                &field.name,
                &field.name,
                &value,
                &form,
                &mut hidden,
            );
        }
        hidden
    }

    /// Adds to `hidden` the hidden sub-fields inside `value`, a value of `kind` at the dotted
    /// path `path`, whose conditions are keyed under `schema`.
    fn hidden_in(
        &self,
        kind: &crate::FieldKindDef,
        path: &str,
        schema: &str,
        value: &Value,
        form: &FormContext<'_>,
        hidden: &mut BTreeSet<String>,
    ) {
        use crate::FieldKindDef as Kind;
        match kind {
            Kind::Repeater(fields) => {
                for (index, row) in value.as_array().into_iter().flatten().enumerate() {
                    if let Some(row) = row.as_object() {
                        let at = format!("{path}.{index}");
                        self.hidden_in_row(fields, row, &at, schema, form, hidden);
                    }
                }
            }
            Kind::FlexibleContent(blocks) => {
                for (index, row) in value.as_array().into_iter().flatten().enumerate() {
                    let block = row
                        .get("type")
                        .and_then(Value::as_str)
                        .and_then(|name| blocks.iter().find(|b| b.name == name));
                    let (Some(block), Some(data)) =
                        (block, row.get("data").and_then(Value::as_object))
                    else {
                        continue;
                    };
                    let at = format!("{path}.{index}.data");
                    let schema = format!("{schema}.{}", block.name);
                    self.hidden_in_row(&block.fields, data, &at, &schema, form, hidden);
                }
            }
            Kind::Group(fields) | Kind::Clone(fields) => {
                if let Some(values) = value.as_object() {
                    self.hidden_in_row(fields, values, path, schema, form, hidden);
                }
            }
            _ => {}
        }
    }

    /// Adds to `hidden` the sub-fields of one row (or group), holding `values`, at `path`.
    fn hidden_in_row(
        &self,
        fields: &[FieldDef],
        values: &serde_json::Map<String, Value>,
        path: &str,
        schema: &str,
        form: &FormContext<'_>,
        hidden: &mut BTreeSet<String>,
    ) {
        let all = row_form(values);
        let mut hidden_here: BTreeSet<String> = BTreeSet::new();
        for _ in 0..=fields.len() {
            let state = all.without(hidden_here.iter().map(String::as_str));
            let row = FormContext::row(form, &state);
            let next: BTreeSet<String> = fields
                .iter()
                .filter(|field| !self.is_shown(&format!("{schema}.{}", field.name), &row))
                .map(|field| field.name.clone())
                .collect();
            if next == hidden_here {
                break;
            }
            hidden_here = next;
        }
        let state = all.without(hidden_here.iter().map(String::as_str));
        let row = FormContext::row(form, &state);
        for field in fields {
            let at = format!("{path}.{}", field.name);
            if hidden_here.contains(&field.name) {
                hidden.insert(at);
                continue;
            }
            if let Some(value) = values.get(&field.name) {
                let inner = format!("{schema}.{}", field.name);
                self.hidden_in(&field.kind, &at, &inner, value, &row, hidden);
            }
        }
    }
}

/// A JSON value as a form sends it: `true` as `on`, text as it is, a number or a structured
/// value as JSON text. `null` and `false` are not sent.
fn form_text(value: &Value) -> Option<String> {
    match value {
        Value::Null | Value::Bool(false) => None,
        Value::Bool(true) => Some("on".to_string()),
        Value::String(text) => Some(text.clone()),
        other => Some(other.to_string()),
    }
}

/// The values of a repeater row or group as form values, for its sub-fields' conditions.
fn row_form(values: &serde_json::Map<String, Value>) -> FormInput {
    FormInput::new(
        values
            .iter()
            .filter_map(|(name, value)| form_text(value).map(|text| (name.clone(), text)))
            .collect(),
    )
}

/// `values`, with each field of `hidden` holding its stored value in `record` instead, or no
/// value when there is none.
fn stored_when_hidden(
    values: &FormInput,
    record: Option<&Row>,
    hidden: &BTreeSet<String>,
) -> FormInput {
    let mut state = values.without(hidden.iter().map(String::as_str));
    for name in hidden {
        let stored = match record.and_then(|record| record.get(name)) {
            None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
            Some(Value::Bool(true)) => "on".to_string(),
            Some(Value::String(text)) => text.clone(),
            Some(other) => other.to_string(),
        };
        state.insert(name.clone(), stored);
    }
    state
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime_resource::FieldKindDef;

    fn field(name: &str) -> FieldDef {
        FieldDef {
            name: name.into(),
            label: name.into(),
            kind: FieldKindDef::Text,
            required: true,
        }
    }

    fn form(pairs: &[(&str, &str)]) -> FormInput {
        FormInput::new(
            pairs
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        )
    }

    fn user() -> ActingUser {
        ActingUser::new(1, "Ada", "ada@example.test")
    }

    #[test]
    fn a_field_with_no_condition_shows() {
        let conditions = FieldConditions::new();
        let user = user();
        let values = form(&[]);
        let context = FormContext::new(Operation::Create, None, &user, &values);
        assert!(conditions.is_shown("title", &context));
        assert!(conditions.is_empty());
    }

    #[test]
    fn hidden_on_and_visible_on_follow_the_operation() {
        let conditions = FieldConditions::new()
            .hidden_on("slug", &[Operation::Create])
            .visible_on("published_at", &[Operation::Edit]);
        let fields = [field("slug"), field("published_at"), field("title")];
        let user = user();
        let values = form(&[]);
        let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
        assert_eq!(
            on_create,
            BTreeSet::from(["published_at".into(), "slug".into()])
        );
        let record = Row::new();
        let on_edit =
            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
        assert!(on_edit.is_empty());
    }

    #[test]
    fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
        let conditions = FieldConditions::new()
            .hidden("note", |_| true)
            .hidden_on("note", &[Operation::Create])
            .visible("note", |form| form.user().can("notes.edit"));
        let user = user();
        let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
        let values = form(&[]);
        let record = Row::new();
        let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
        assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
        assert!(conditions.is_shown("note", &edit(&editor)));
        let create = FormContext::new(Operation::Create, None, &editor, &values);
        assert!(!conditions.is_shown("note", &create), "hidden on create");
    }

    #[test]
    fn a_condition_reads_the_record_and_the_current_values() {
        let conditions = FieldConditions::new()
            .live("kind")
            .visible("company", |form| form.get("kind") == Some("business"))
            .visible("archived_note", |form| {
                form.record()
                    .and_then(|record| record.get("status"))
                    .and_then(Value::as_str)
                    == Some("archived")
            });
        assert!(conditions.is_live("kind"));
        assert!(!conditions.is_live("company"));
        let fields = [field("kind"), field("company"), field("archived_note")];
        let user = user();
        let mut record = Row::new();
        record.insert("status".into(), Value::from("archived"));
        let hidden = conditions.hidden_fields(
            &fields,
            Operation::Edit,
            Some(&record),
            &user,
            &form(&[("kind", "business")]),
        );
        assert!(hidden.is_empty(), "{hidden:?}");
        let hidden = conditions.hidden_fields(
            &fields,
            Operation::Create,
            None,
            &user,
            &form(&[("kind", "person")]),
        );
        assert_eq!(
            hidden,
            BTreeSet::from(["archived_note".into(), "company".into()])
        );
    }

    // `secret` is hidden from this user, and `extra` shows when `secret` is "yes". A request
    // that sends `secret=yes` must not show `extra`: the condition reads the stored value.
    #[test]
    fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
        let conditions = FieldConditions::new()
            .visible("secret", |form| form.user().can("secret.edit"))
            .visible("extra", |form| form.get("secret") == Some("yes"));
        let fields = [field("secret"), field("extra")];
        let user = user();
        let sent = form(&[("secret", "yes"), ("extra", "changed")]);

        let mut record = Row::new();
        record.insert("secret".into(), Value::from("no"));
        let hidden =
            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
        assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));

        record.insert("secret".into(), Value::from("yes"));
        let hidden =
            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
        assert_eq!(hidden, BTreeSet::from(["secret".into()]));
    }

    #[test]
    fn defaults_fill_the_create_form_in_order_and_skip_sent_fields() {
        let conditions = FieldConditions::new()
            .default_value("status", "draft")
            .default_value("featured", true)
            .default_with("summary", |form| {
                Value::from(format!("{} post", form.get("status").unwrap_or("?")))
            });
        let mut featured = field("featured");
        featured.kind = FieldKindDef::Checkbox;
        let fields = [field("status"), featured, field("summary"), field("title")];
        let user = user();
        let shown = conditions.default_form(&fields, &user);
        assert_eq!(shown.get("status"), Some("draft"));
        assert!(shown.checkbox("featured"));
        assert_eq!(shown.get("summary"), Some("draft post"));
        assert!(!shown.has("title"));
        let saved = conditions.with_defaults(&fields, &user, &form(&[("status", "publish")]));
        assert_eq!(saved.get("summary"), Some("publish post"));
        assert!(
            !saved.has("featured"),
            "an unticked checkbox stays unticked"
        );
    }

    #[test]
    fn a_row_condition_reads_its_row_and_the_form_around_it() {
        let conditions = FieldConditions::new()
            .visible("fields.choices", |row| row.get("type") == Some("select"))
            .visible("fields.note", |row| row.get("../../mode") == Some("expert"));
        let repeater = FieldDef {
            name: "fields".into(),
            label: "Fields".into(),
            kind: FieldKindDef::Repeater(vec![field("type"), field("choices"), field("note")]),
            required: false,
        };
        let user = user();
        let values = form(&[
            ("mode", "simple"),
            (
                "fields",
                r#"[{"type":"select"},{"type":"text","choices":"x"}]"#,
            ),
        ]);
        let hidden = conditions.hidden_sub_fields(
            std::slice::from_ref(&repeater),
            Operation::Create,
            None,
            &user,
            &values,
        );
        assert_eq!(
            hidden,
            BTreeSet::from([
                "fields.0.note".into(),
                "fields.1.choices".into(),
                "fields.1.note".into()
            ])
        );
        let pruned = crate::structure::without_sub_fields(&[repeater], &values, &hidden);
        assert_eq!(
            pruned.get("fields"),
            Some(r#"[{"type":"select"},{"type":"text"}]"#)
        );
    }

    #[test]
    fn a_block_condition_is_keyed_by_the_block_and_reads_the_block_row() {
        let conditions =
            FieldConditions::new().visible("content.hero.style", |row| row.checked("styled"));
        let content = FieldDef {
            name: "content".into(),
            label: "Content".into(),
            kind: FieldKindDef::FlexibleContent(vec![crate::runtime_resource::BlockDef {
                name: "hero".into(),
                label: "Hero".into(),
                fields: vec![field("styled"), field("style")],
            }]),
            required: false,
        };
        let user = user();
        let values = form(&[(
            "content",
            r#"[{"type":"hero","data":{"styled":true,"style":"a"}},{"type":"hero","data":{"style":"b"}}]"#,
        )]);
        let hidden = conditions.hidden_sub_fields(
            std::slice::from_ref(&content),
            Operation::Edit,
            None,
            &user,
            &values,
        );
        assert_eq!(hidden, BTreeSet::from(["content.1.data.style".into()]));
        let pruned = crate::structure::without_sub_fields(&[content], &values, &hidden);
        let pruned: Value = serde_json::from_str(pruned.get("content").unwrap()).unwrap();
        assert_eq!(
            pruned,
            serde_json::json!([
                {"type": "hero", "data": {"styled": true, "style": "a"}},
                {"type": "hero", "data": {}}
            ])
        );
    }
}