tablo-core 0.9.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
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
//! Conditions: a field or a layout block that shows only while another field posts one of the
//! values its condition names, and a field whose control is disabled while it does.
//!
//! The browser follows the watched field through one signal per condition, so the form needs no
//! rerun. A hidden field or block, and a disabled control, sit in a disabled fieldset, which the
//! browser neither validates nor submits. The server reads the same submission:
//! [`Schema::condition_hidden`] and [`Schema::condition_disabled`] name the fields they leave out,
//! and the panel drops their keys before parsing, so an edit keeps their stored values and a
//! create takes their blank answers, or a disabled field's default.

use std::collections::HashMap;

use topcoat::{
    context::Cx,
    runtime::{Event, Signal, signal},
    view::*,
};

use super::{
    Schema,
    fields::{ChoiceField, CustomField, Field, TextField},
    tree::Node,
};
use crate::{DeclarationErrorKind, topcoat_compat::async_page, values::FormValues};

/// A field a condition can watch: a text, choice or custom field of the form `F`, passed to
/// `visible_when` by reference.
///
/// A condition follows a toggle (`Field::toggle`, `Field::toggle_input`) through its checkbox, and
/// any other control through its `value`: an app's own checkbox control posts the same `value`
/// checked or not, so a condition cannot follow it.
pub trait Watched<F> {
    #[doc(hidden)]
    fn key(&self) -> &str;

    #[doc(hidden)]
    fn checkbox(&self) -> bool {
        false
    }
}

impl<F> Watched<F> for TextField<F> {
    fn key(&self) -> &str {
        self.name()
    }
}

impl<F> Watched<F> for ChoiceField<F> {
    fn key(&self) -> &str {
        self.name()
    }
}

impl<F> Watched<F> for CustomField<F> {
    fn key(&self) -> &str {
        self.name()
    }

    fn checkbox(&self) -> bool {
        self.is_checkbox()
    }
}

/// Shows a field or a block, or disables a field's control, while the field `watched` posts one
/// of `values`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Condition {
    watched: String,
    /// Whether the watched field is a checkbox, which renders unchecked with no value.
    checkbox: bool,
    values: Vec<String>,
    /// Whether a submission that hides what this guards still parses, as an embedded shared
    /// column's does: the codec reads that column only for the variants that declare it.
    parses_when_hidden: bool,
}

impl Condition {
    pub(crate) fn new<F>(
        watched: &impl Watched<F>,
        values: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            watched: watched.key().to_string(),
            checkbox: watched.checkbox(),
            values: values.into_iter().map(Into::into).collect(),
            parses_when_hidden: false,
        }
    }

    /// A condition watching the field named `key`, which posts a value rather than a checkbox's
    /// checked state.
    pub(crate) fn watching(
        key: impl Into<String>,
        values: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            watched: key.into(),
            checkbox: false,
            values: values.into_iter().map(Into::into).collect(),
            parses_when_hidden: true,
        }
    }

    /// Whether the submission `values` shows what the condition guards. A checkbox with no value
    /// reads as `false`, as it renders and posts.
    pub(crate) fn holds(&self, values: &FormValues) -> bool {
        let posted = match values.text(&self.watched) {
            Some(value) => value.trim(),
            None if self.checkbox => "false",
            None => "",
        };
        self.values.iter().any(|value| value == posted)
    }

    /// Renders `inner` in a fieldset the browser hides and disables while the condition fails, so
    /// a hidden required field never blocks the submit.
    pub(crate) fn guard<'a>(
        &self,
        cx: &'a Cx,
        scope: &str,
        values: &FormValues,
        inner: BoxView<'a>,
    ) -> BoxView<'a> {
        let condition = self.clone();
        let initial = self.holds(values);
        let scope = scope.to_string();
        async_page(async move {
            let shown = shown(cx, &scope, &condition, initial);
            let enabled = shown.clone();
            Ok(view! {
                <fieldset
                    class="contents"
                    :disabled=$(!enabled.get())
                    :hidden=$(!shown.get())
                >
                    (inner)
                </fieldset>
            })
        })
    }
}

/// Renders `inner` in a fieldset the browser disables while `condition` holds, so the control
/// neither validates nor posts.
pub(crate) fn disable<'a>(
    cx: &'a Cx,
    condition: &Condition,
    scope: &str,
    values: &FormValues,
    inner: BoxView<'a>,
) -> BoxView<'a> {
    let condition = condition.clone();
    let initial = condition.holds(values);
    let scope = scope.to_string();
    async_page(async move {
        let holds = shown(cx, &scope, &condition, initial);
        Ok(view! {
            <fieldset class="contents" :disabled=$(holds.get())>(inner)</fieldset>
        })
    })
}

/// The signal holding whether `condition` holds in the form `scope`, shared by its guard and its
/// watched field.
///
/// Keyed by the page's path: navigation carries the values of signals two pages share, and
/// another record's form starts from its own stored values. Keyed by the form's scope too: an
/// action's input in a dialog may watch a key the page's own form watches.
fn shown(cx: &Cx, scope: &str, condition: &Condition, initial: bool) -> Signal<bool> {
    let page = topcoat::context::try_context::<http::request::Parts>(cx)
        .map(|parts| parts.uri.path().to_string())
        .unwrap_or_default();
    signal(&cx.keyed(signal_key(&page, scope, condition)), move || {
        initial
    })
}

/// What names the signal of `condition` in the form `scope` on the page at `page`.
fn signal_key(
    page: &str,
    scope: &str,
    condition: &Condition,
) -> (&'static str, String, String, String, String) {
    (
        "tablo-condition",
        page.to_string(),
        scope.to_string(),
        condition.watched.clone(),
        condition.values.join("\u{1f}"),
    )
}

/// Renders the watched field `field`, posting under `posted`, inside one change handler per
/// condition reading it.
///
/// A handler reads only the event of the control posting the watched key: a searchable choice's
/// filter box or an app control's own inputs change inside the same wrapper. A runtime expression
/// has no `||`, so a condition naming several values stacks one handler per value: the innermost
/// sets the signal from the first value, and each outer one, run after it as the event bubbles,
/// sets it when its own value matches.
pub(crate) fn watch<'a>(
    cx: &'a Cx,
    field: &Field,
    posted: &str,
    conditions: &[Condition],
    scope: &str,
    values: &FormValues,
    control: BoxView<'a>,
) -> BoxView<'a> {
    let scope = scope.to_string();
    let conditions: Vec<(Condition, bool)> = conditions
        .iter()
        .map(|condition| (condition.clone(), condition.holds(values)))
        .collect();
    let checkbox = field.is_checkbox();
    let key = posted.to_string();
    async_page(async move {
        let mut view = control;
        for (condition, initial) in conditions {
            let shown = shown(cx, &scope, &condition, initial);
            if checkbox {
                // A checkbox posts `true` when checked and its hidden `false` otherwise.
                let on = condition.values.iter().any(|value| value == "true");
                let off = condition.values.iter().any(|value| value == "false");
                let name = key.clone();
                view = view! {
                    <div
                        class="contents"
                        @change=$(|e: Event| if e.target.name == name {
                            shown.set(if e.target.checked { on } else { off })
                        })
                    >
                        (view)
                    </div>
                }
                .boxed();
                continue;
            }
            let mut values = condition.values.into_iter();
            let Some(first) = values.next() else {
                continue;
            };
            let (set, name) = (shown.clone(), key.clone());
            view = view! {
                <div
                    class="contents"
                    @change=$(|e: Event| if e.target.name == name {
                        set.set(e.target.value.trim() == first)
                    })
                >
                    (view)
                </div>
            }
            .boxed();
            for value in values {
                let (set, name) = (shown.clone(), key.clone());
                view = view! {
                    <div
                        class="contents"
                        @change=$(|e: Event| if e.target.name == name {
                            if e.target.value.trim() == value {
                                set.set(true)
                            }
                        })
                    >
                        (view)
                    </div>
                }
                .boxed();
            }
        }
        Ok(view)
    })
}

impl Node {
    /// The condition on this node: a field's own, or a layout block's.
    fn condition<'s>(&'s self, fields: &'s [Field]) -> Option<&'s Condition> {
        match self {
            Node::Field(index) => fields[*index].condition(),
            Node::Section(s) => s.condition.as_ref(),
            Node::Group(g) => g.condition.as_ref(),
            Node::Grid(g) => g.condition.as_ref(),
            Node::Tabs(t) => t.condition.as_ref(),
            Node::Tab(t) => t.condition.as_ref(),
            Node::Wizard(w) => w.condition.as_ref(),
            Node::Step(s) => s.condition.as_ref(),
            Node::Embedded(_) => None,
        }
    }
}

/// Where a schema's conditions sit.
#[derive(Default)]
struct Scan<'s> {
    /// Each field slot with the conditions guarding it, outermost first and its own last.
    fields: Vec<(usize, Vec<&'s Condition>)>,
    /// Each condition with the conditions guarding the node it sits on.
    conditions: Vec<(&'s Condition, Vec<&'s Condition>)>,
    /// Each field slot a condition disables, with that condition.
    disabling: Vec<(usize, &'s Condition)>,
}

impl<'s> Scan<'s> {
    fn of(nodes: &'s [Node], fields: &'s [Field]) -> Self {
        let mut scan = Self::default();
        scan.walk(nodes, fields, &mut Vec::new());
        // A field's control sits inside every block guarding it, so its disabling condition
        // shows exactly while the field does.
        for (index, chain) in &scan.fields {
            if let Some(condition) = fields[*index].disabling() {
                scan.disabling.push((*index, condition));
                scan.conditions.push((condition, chain.clone()));
            }
        }
        scan
    }

    fn walk(&mut self, nodes: &'s [Node], fields: &'s [Field], chain: &mut Vec<&'s Condition>) {
        for node in nodes {
            let own = node.condition(fields);
            if let Some(condition) = own {
                self.conditions.push((condition, chain.clone()));
                chain.push(condition);
            }
            match node {
                Node::Field(index) => self.fields.push((*index, chain.clone())),
                Node::Embedded(embedded) => {
                    // An embedded value's leaves are placed by its node, and each carries its own
                    // condition as a top-level field does.
                    embedded.visit_fields(&mut |index| {
                        let own = fields[index].condition();
                        if let Some(condition) = own {
                            self.conditions.push((condition, chain.clone()));
                            chain.push(condition);
                        }
                        self.fields.push((index, chain.clone()));
                        if own.is_some() {
                            chain.pop();
                        }
                    });
                }
                node => self.walk(node.children().unwrap_or_default(), fields, chain),
            }
            if own.is_some() {
                chain.pop();
            }
        }
    }

    /// The conditions guarding the field named `key`, or `None` when the schema places none.
    fn guarding(&self, fields: &[Field], key: &str) -> Option<&[&'s Condition]> {
        self.fields
            .iter()
            .find(|(index, _)| fields[*index].name() == key)
            .map(|(_, chain)| chain.as_slice())
    }
}

impl<F> Schema<F> {
    /// The keys of the fields a condition hides in the submission `values`.
    pub(crate) fn condition_hidden(&self, values: &FormValues) -> Vec<String> {
        Scan::of(&self.nodes, &self.fields)
            .fields
            .into_iter()
            .filter(|(_, chain)| chain.iter().any(|condition| !condition.holds(values)))
            .map(|(index, _)| self.fields[index].name().to_string())
            .collect()
    }

    /// The keys of the fields a condition disables in the submission `values`, leaving out the
    /// ones a condition hides: those take the blank answer, not the `default`.
    pub(crate) fn condition_disabled(&self, values: &FormValues) -> Vec<String> {
        let scan = Scan::of(&self.nodes, &self.fields);
        let hidden: Vec<usize> = scan
            .fields
            .iter()
            .filter(|(_, chain)| chain.iter().any(|condition| !condition.holds(values)))
            .map(|(index, _)| *index)
            .collect();
        scan.disabling
            .into_iter()
            .filter(|(index, condition)| !hidden.contains(index) && condition.holds(values))
            .map(|(index, _)| self.fields[index].name().to_string())
            .collect()
    }

    /// Each key a condition watches, with the key of a field it guards or disables, or `None`
    /// when it guards none.
    pub(crate) fn condition_watchers(&self) -> Vec<(String, Option<String>)> {
        let scan = Scan::of(&self.nodes, &self.fields);
        let mut watchers = Vec::new();
        for (condition, _) in &scan.conditions {
            let disabled = scan
                .disabling
                .iter()
                .filter(|(_, c)| std::ptr::eq(*c, *condition))
                .map(|(index, _)| *index);
            let mut guards = scan
                .fields
                .iter()
                .filter(|(_, chain)| chain.iter().any(|c| std::ptr::eq(*c, *condition)))
                .map(|(index, _)| *index)
                .chain(disabled)
                .map(|index| self.fields[index].name().to_string())
                .peekable();
            if guards.peek().is_none() {
                watchers.push((condition.watched.clone(), None));
            }
            watchers.extend(guards.map(|key| (condition.watched.clone(), Some(key))));
        }
        watchers
    }

    /// The conditions each watched field's key drives, each once.
    pub(crate) fn watched(&self) -> HashMap<String, Vec<Condition>> {
        let mut out: HashMap<String, Vec<Condition>> = HashMap::new();
        for (condition, _) in Scan::of(&self.nodes, &self.fields).conditions {
            let driven = out.entry(condition.watched.clone()).or_default();
            if !driven.contains(condition) {
                driven.push(condition.clone());
            }
        }
        out
    }

    /// What is wrong with the schema's conditions: a watched field the schema does not place, one
    /// a condition hides while what it guards still shows, one a condition disables, a value the
    /// watched field never posts, and a hidden field with no blank answer, which a submission
    /// that hides it could not parse.
    pub(crate) fn condition_errors(&self) -> Vec<DeclarationErrorKind> {
        let scan = Scan::of(&self.nodes, &self.fields);
        let mut errors = Vec::new();
        for (condition, guarding) in &scan.conditions {
            let watched = condition.watched.clone();
            match scan.guarding(&self.fields, &condition.watched) {
                None => errors.push(DeclarationErrorKind::UnplacedWatchedField {
                    field: watched.clone(),
                }),
                // The browser follows the watched field's last change, the server its posted
                // value: they agree only while every condition hiding the watched field also
                // hides what it guards.
                Some(chain) if !chain.iter().all(|hiding| guarding.contains(hiding)) => {
                    errors.push(DeclarationErrorKind::HiddenWatchedField {
                        field: watched.clone(),
                    });
                }
                Some(_) => {}
            }
            if let Some(field) = self.fields.iter().find(|f| f.name() == condition.watched)
                && field.disabling().is_some()
            {
                errors.push(DeclarationErrorKind::DisabledWatchedField {
                    field: watched.clone(),
                });
            }
            if let Some(field) = self.fields.iter().find(|f| f.name() == condition.watched) {
                for value in &condition.values {
                    if field.can_post(value) == Some(false) {
                        errors.push(DeclarationErrorKind::UnpostedConditionValue {
                            field: watched.clone(),
                            value: value.clone(),
                        });
                    }
                }
            }
        }
        for (index, chain) in &scan.fields {
            let field = &self.fields[*index];
            // A condition hiding a field the codec reads nothing of there needs no blank answer.
            let hides_unparsed = chain.iter().any(|condition| !condition.parses_when_hidden);
            if hides_unparsed && field.is_required() {
                errors.push(DeclarationErrorKind::RequiredConditionalField {
                    field: field.name().to_string(),
                });
            }
        }
        errors
    }
}

#[cfg(test)]
mod tests;