Skip to main content

egui_pop_model/admin/
wizard.rs

1//! The wizard kit (`docs/design/admin-forms.md`, section 5.3): a
2//! multi-step flow declared as data, each step a form built with the same
3//! groups and items as a section's page, its values a **draft** handed to
4//! a command on finish.
5//!
6//! - **Steps**: declared in order; a step whose `when` does not hold
7//!   (read against the draft as `form.<key>`) does not exist for now, and
8//!   its values are not handed on.
9//! - **Validation per step**: each field's own checks ([`Field::check`]:
10//!   required, range, choices), its `validate` hook, then the step's; a
11//!   problem of the danger tone blocks Next with its message, a warning
12//!   is shown and lets through.
13//! - **Navigation**: Next, Back, Skip (an optional step: its values go
14//!   back to their defaults), and going to any step whose steps before it
15//!   are valid; one that is not lands on the first invalid one, with its
16//!   reason.
17//! - **Summary**: after the last step (unless declared without), every
18//!   step's fields with their values as shown.
19//! - **Finish**: the command, with the template filled from the draft
20//!   (or the draft itself when the wizard declares no arguments).
21//!
22//! [`Flow`] is the state of a wizard being filled: pure, no egui, so an
23//! agent and a test drive it as the shell does.
24
25use serde::{Deserialize, Serialize};
26use serde_json::{Map, Value as Json};
27
28use super::hooks::{Hooks, Problem, Values};
29use super::{
30    Confirmation, Field, FieldKind, Group, Item, Meta, Section, SectionBuilder, Tone, bad_clauses,
31    form_context, holds, template, unknown_node,
32};
33use crate::diagnostics::Diagnostics;
34use crate::when::{When, WhenContext};
35
36/// Where a flow stands after its last step: the summary.
37pub const SUMMARY: &str = "summary";
38
39/// What a field's own checks found ([`Field::check`]); the shell words
40/// it in the interface's language.
41#[derive(Clone, Copy, Debug, PartialEq)]
42pub enum Check {
43    /// Required and left empty.
44    Required,
45    /// Below its minimum.
46    Below(f64),
47    /// Above its maximum.
48    Above(f64),
49    /// Not one of its choices.
50    NotAChoice,
51}
52
53/// A step: a form (groups of fields, statuses, callouts, records), its
54/// `validate` hook, whether it may be skipped.
55#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
56pub struct Step {
57    #[serde(flatten)]
58    pub meta: Meta,
59    #[serde(default)]
60    pub groups: Vec<Group>,
61    /// A `validate` hook run over the draft when the step is left.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub validate: Option<String>,
64    /// Skip is offered.
65    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
66    pub optional: bool,
67}
68
69impl Step {
70    /// Its fields, every group's.
71    pub fn fields(&self) -> impl Iterator<Item = &Field> {
72        self.groups
73            .iter()
74            .flat_map(|g| &g.items)
75            .filter_map(|i| match i {
76                Item::Field(f) => Some(f),
77                _ => None,
78            })
79    }
80
81    /// Its fields shown for these values: in a group and with a `when`
82    /// that hold.
83    pub fn shown_fields(&self, cx: &WhenContext) -> Vec<&Field> {
84        self.groups
85            .iter()
86            .filter(|g| holds(g.meta.when.as_deref(), cx))
87            .flat_map(|g| &g.items)
88            .filter_map(|i| match i {
89                Item::Field(f) if holds(f.meta.when.as_deref(), cx) => Some(f),
90                _ => None,
91            })
92            .collect()
93    }
94}
95
96/// What finishing runs: a command, its arguments' template (`${key}`;
97/// `null`: the draft itself, as an object), and the button's verb.
98#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
99pub struct Finish {
100    pub command: String,
101    #[serde(default, skip_serializing_if = "Json::is_null")]
102    pub args: Json,
103    #[serde(default, skip_serializing_if = "String::is_empty")]
104    pub verb: String,
105}
106
107fn yes() -> bool {
108    true
109}
110
111fn is_true(b: &bool) -> bool {
112    *b
113}
114
115/// A wizard: its steps, its summary, what finishing runs, and what
116/// cancelling asks when something was entered.
117#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
118pub struct Wizard {
119    #[serde(flatten)]
120    pub meta: Meta,
121    pub steps: Vec<Step>,
122    /// A summary step after the last one.
123    #[serde(default = "yes", skip_serializing_if = "is_true")]
124    pub summary: bool,
125    pub finish: Finish,
126    /// What cancelling asks once something was entered (the shell's own
127    /// words otherwise).
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub cancel: Option<Confirmation>,
130}
131
132impl Wizard {
133    /// A wizard whose finish runs `command`.
134    pub fn new(id: &str, title: &str, command: &str) -> Wizard {
135        Wizard {
136            meta: Meta::new(id, title),
137            steps: Vec::new(),
138            summary: true,
139            finish: Finish {
140                command: command.into(),
141                args: Json::Null,
142                verb: String::new(),
143            },
144            cancel: None,
145        }
146    }
147
148    pub fn description(mut self, text: &str) -> Wizard {
149        self.meta.description = text.into();
150        self
151    }
152
153    pub fn icon(mut self, icon: &str) -> Wizard {
154        self.meta.icon = Some(icon.into());
155        self
156    }
157
158    /// A step, built as a section is (groups, fields, statuses...): its
159    /// draft fields are [`Field::draft`]s of this wizard.
160    pub fn step(
161        mut self,
162        id: &str,
163        title: &str,
164        build: impl FnOnce(&mut SectionBuilder<'_>),
165    ) -> Wizard {
166        let mut section = Section {
167            meta: Meta {
168                order: self.steps.len() as i32,
169                ..Meta::new(id, title)
170            },
171            scope: self.meta.id.clone(),
172            ..Section::default()
173        };
174        build(&mut SectionBuilder {
175            section: &mut section,
176        });
177        self.steps.push(Step {
178            meta: section.meta,
179            groups: section.groups,
180            validate: None,
181            optional: false,
182        });
183        self
184    }
185
186    /// The last step's `validate` hook.
187    pub fn validate(mut self, hook: &str) -> Wizard {
188        if let Some(s) = self.steps.last_mut() {
189            s.validate = Some(hook.into());
190        }
191        self
192    }
193
194    /// The last step exists only when the clause holds.
195    pub fn when(mut self, clause: &str) -> Wizard {
196        if let Some(s) = self.steps.last_mut() {
197            s.meta.when = Some(clause.into());
198        }
199        self
200    }
201
202    /// The last step may be skipped.
203    pub fn optional(mut self) -> Wizard {
204        if let Some(s) = self.steps.last_mut() {
205            s.optional = true;
206        }
207        self
208    }
209
210    /// The finish's arguments: a template over the draft (`${key}`).
211    pub fn args(mut self, args: Json) -> Wizard {
212        self.finish.args = args;
213        self
214    }
215
216    /// The finish button's verb ("Set up backups").
217    pub fn verb(mut self, verb: &str) -> Wizard {
218        self.finish.verb = verb.into();
219        self
220    }
221
222    /// No summary: the last step finishes.
223    pub fn no_summary(mut self) -> Wizard {
224        self.summary = false;
225        self
226    }
227
228    /// What cancelling asks once something was entered.
229    pub fn cancel(mut self, confirmation: Confirmation) -> Wizard {
230        self.cancel = Some(confirmation);
231        self
232    }
233
234    pub fn step_of(&self, id: &str) -> Option<&Step> {
235        self.steps.iter().find(|s| s.meta.id == id)
236    }
237
238    /// Every draft field, by key, with its step.
239    pub fn fields(&self) -> impl Iterator<Item = (&Step, &Field)> {
240        self.steps
241            .iter()
242            .flat_map(|s| s.fields().map(move |f| (s, f)))
243            .filter(|(_, f)| f.draft_key().is_some())
244    }
245
246    /// The draft at the start: each draft field's default.
247    pub fn defaults(&self) -> Values {
248        self.fields()
249            .filter_map(|(_, f)| {
250                f.draft_key()
251                    .map(|k| (k.to_string(), f.input.default.clone()))
252            })
253            .collect()
254    }
255
256    /// Checks it: steps there, their ids unique, their clauses parse, the
257    /// settings its fields bind exist. What fails is reported and left
258    /// out.
259    pub(crate) fn check(&mut self, d: &mut Diagnostics, setting_exists: &dyn Fn(&str) -> bool) {
260        let at = format!("wizard/{}", self.meta.id);
261        let mut ids: Vec<String> = Vec::new();
262        self.steps.retain_mut(|s| {
263            if s.meta.id == SUMMARY || ids.contains(&s.meta.id) {
264                d.warn(
265                    "admin-duplicate",
266                    None,
267                    format!("{at}/{}", s.meta.id),
268                    "a step with this id is already declared (or is `summary`): left out",
269                );
270                return false;
271            }
272            ids.push(s.meta.id.clone());
273            bad_clauses(d, &at, &mut s.meta);
274            for g in &mut s.groups {
275                bad_clauses(d, &at, &mut g.meta);
276                g.items.retain(|item| {
277                    if unknown_node(d, &format!("{at}/{}", s.meta.id), item) {
278                        return false;
279                    }
280                    for clause in [&item.meta().when, &item.meta().enabled]
281                        .into_iter()
282                        .flatten()
283                    {
284                        if let Err(e) = When::parse(clause) {
285                            d.warn(
286                                "admin-bad-clause",
287                                None,
288                                format!("{at}/{}", s.meta.id),
289                                format!("`{clause}` does not parse ({e}): it always holds"),
290                            );
291                        }
292                    }
293                    if let Item::Field(f) = item
294                        && let Some(setting) = f.setting_id()
295                        && !setting_exists(setting)
296                    {
297                        d.warn(
298                            "admin-no-setting",
299                            None,
300                            format!("{at}/{}", s.meta.id),
301                            format!("no setting `{setting}`: left out"),
302                        );
303                        return false;
304                    }
305                    true
306                });
307            }
308            true
309        });
310        if self.steps.is_empty() {
311            d.warn("admin-wizard-empty", None, &at, "a wizard with no step");
312        }
313    }
314}
315
316/// What a flow needs to judge its steps: the application's context keys,
317/// the hooks, and the words of a field's own checks.
318pub struct Judge<'a> {
319    pub base: WhenContext,
320    pub hooks: &'a Hooks,
321    pub say: &'a dyn Fn(&Field, Check) -> String,
322}
323
324impl std::fmt::Debug for Judge<'_> {
325    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
326        f.debug_struct("Judge")
327            .field("base", &self.base)
328            .finish_non_exhaustive()
329    }
330}
331
332/// A wizard being filled: the step shown, the draft, the steps passed.
333#[derive(Clone, Debug, PartialEq, Serialize)]
334pub struct Flow {
335    pub wizard: String,
336    /// A step's id, or [`SUMMARY`].
337    pub at: String,
338    pub values: Values,
339    /// The draft at the start: what Cancel compares with.
340    pub initial: Values,
341    /// The steps left by Next or Skip (the stepper marks them done).
342    pub passed: Vec<String>,
343}
344
345impl Flow {
346    /// A flow at its first step, its draft the defaults with `values`
347    /// over them.
348    pub fn start(w: &Wizard, base: &WhenContext, values: Values) -> Flow {
349        let mut initial = w.defaults();
350        initial.extend(values);
351        let mut f = Flow {
352            wizard: w.meta.id.clone(),
353            at: String::new(),
354            values: initial.clone(),
355            initial,
356            passed: Vec::new(),
357        };
358        f.at = f
359            .shown(w, base)
360            .first()
361            .map_or_else(|| SUMMARY.to_string(), |s| s.meta.id.clone());
362        f
363    }
364
365    /// The context its clauses read: the application's, and the draft as
366    /// `form.<key>`.
367    pub fn context(&self, base: &WhenContext) -> WhenContext {
368        form_context(base.clone(), &self.values)
369    }
370
371    /// The steps that exist for the draft as it stands.
372    pub fn shown<'a>(&self, w: &'a Wizard, base: &WhenContext) -> Vec<&'a Step> {
373        let cx = self.context(base);
374        w.steps
375            .iter()
376            .filter(|s| holds(s.meta.when.as_deref(), &cx))
377            .collect()
378    }
379
380    /// Where it stands among the steps shown (the summary after them).
381    pub fn index(&self, w: &Wizard, base: &WhenContext) -> usize {
382        let shown = self.shown(w, base);
383        shown
384            .iter()
385            .position(|s| s.meta.id == self.at)
386            .unwrap_or(shown.len())
387    }
388
389    pub fn on_summary(&self) -> bool {
390        self.at == SUMMARY
391    }
392
393    /// Whether anything was entered.
394    pub fn dirty(&self) -> bool {
395        self.values != self.initial
396    }
397
398    /// Sets a draft value; refused for a key no field of the wizard has.
399    pub fn set(&mut self, w: &Wizard, key: &str, value: Json) -> Result<(), String> {
400        if !w.fields().any(|(_, f)| f.draft_key() == Some(key)) {
401            return Err(format!("no field `{key}` in the wizard `{}`", w.meta.id));
402        }
403        self.values.insert(key.into(), value);
404        Ok(())
405    }
406
407    /// A step's problems for the draft as it stands: its fields' own
408    /// checks and hooks, then the step's hook.
409    pub fn problems(&self, step: &Step, j: &Judge<'_>) -> Vec<Problem> {
410        let cx = self.context(&j.base);
411        let mut out = Vec::new();
412        for f in step.shown_fields(&cx) {
413            let Some(key) = f.draft_key() else {
414                continue;
415            };
416            let v = self.values.get(key).cloned().unwrap_or(Json::Null);
417            if let Some(c) = f.check(&v) {
418                out.push(Problem {
419                    field: key.into(),
420                    tone: Tone::Danger,
421                    message: (j.say)(f, c),
422                });
423            }
424            if let Some(h) = &f.hooks.validate {
425                out.extend(j.hooks.validate(h, &self.values));
426            }
427        }
428        if let Some(h) = &step.validate {
429            out.extend(j.hooks.validate(h, &self.values));
430        }
431        out
432    }
433
434    /// The first problem that blocks a step (danger), if any.
435    pub fn blocked(&self, step: &Step, j: &Judge<'_>) -> Option<Problem> {
436        self.problems(step, j)
437            .into_iter()
438            .find(|p| p.tone == Tone::Danger)
439    }
440
441    fn pass(&mut self, id: &str) {
442        if !self.passed.iter().any(|p| p == id) {
443            self.passed.push(id.into());
444        }
445    }
446
447    /// The step after the one shown, or the summary; `None` past the last
448    /// step of a wizard with no summary.
449    fn after(&self, w: &Wizard, base: &WhenContext) -> Option<String> {
450        let shown = self.shown(w, base);
451        let i = shown.iter().position(|s| s.meta.id == self.at)?;
452        match shown.get(i + 1) {
453            Some(s) => Some(s.meta.id.clone()),
454            None => w.summary.then(|| SUMMARY.to_string()),
455        }
456    }
457
458    /// Next: the step shown checked, then the one after it. Refused with
459    /// the first blocking problem's message, or on the last step.
460    pub fn next(&mut self, w: &Wizard, j: &Judge<'_>) -> Result<(), String> {
461        if self.on_summary() {
462            return Err("this is the summary: finish".into());
463        }
464        let step = w
465            .step_of(&self.at)
466            .ok_or_else(|| format!("no step `{}`", self.at))?;
467        if let Some(p) = self.blocked(step, j) {
468            return Err(p.message);
469        }
470        let to = self
471            .after(w, &j.base)
472            .ok_or("this is the last step: finish")?;
473        let at = self.at.clone();
474        self.pass(&at);
475        self.at = to;
476        Ok(())
477    }
478
479    /// Skip: an optional step's values back to their defaults, then the
480    /// step after it.
481    pub fn skip(&mut self, w: &Wizard, base: &WhenContext) -> Result<(), String> {
482        let step = w
483            .step_of(&self.at)
484            .filter(|s| s.optional)
485            .ok_or("this step may not be skipped")?;
486        let defaults = w.defaults();
487        for f in step.fields() {
488            if let Some(k) = f.draft_key() {
489                match self.initial.get(k).or_else(|| defaults.get(k)) {
490                    Some(v) => self.values.insert(k.into(), v.clone()),
491                    None => self.values.remove(k),
492                };
493            }
494        }
495        let to = self.after(w, base).ok_or("this is the last step: finish")?;
496        let at = self.at.clone();
497        self.pass(&at);
498        self.at = to;
499        Ok(())
500    }
501
502    /// Back: the step before (the last one from the summary).
503    pub fn back(&mut self, w: &Wizard, base: &WhenContext) -> Result<(), String> {
504        let shown = self.shown(w, base);
505        let i = self.index(w, base);
506        if i == 0 {
507            return Err("this is the first step".into());
508        }
509        self.at = shown[i - 1].meta.id.clone();
510        Ok(())
511    }
512
513    /// Goes to a step (or the summary): every step before it must be
514    /// valid, else it lands on the first one that is not and says why.
515    pub fn go(&mut self, w: &Wizard, j: &Judge<'_>, to: &str) -> Result<(), String> {
516        let shown = self.shown(w, &j.base);
517        let end = if to == SUMMARY {
518            if !w.summary {
519                return Err("this wizard has no summary".into());
520            }
521            shown.len()
522        } else {
523            shown
524                .iter()
525                .position(|s| s.meta.id == to)
526                .ok_or_else(|| format!("no step `{to}` now"))?
527        };
528        for s in &shown[..end] {
529            if let Some(p) = self.blocked(s, j) {
530                self.at = s.meta.id.clone();
531                return Err(p.message);
532            }
533        }
534        for s in &shown[..end] {
535            self.pass(&s.meta.id);
536        }
537        self.at = to.into();
538        Ok(())
539    }
540
541    /// Whether every step shown is valid: the summary may be reached and
542    /// the wizard finished.
543    pub fn first_blocked(&self, w: &Wizard, j: &Judge<'_>) -> Option<(String, Problem)> {
544        self.shown(w, &j.base)
545            .into_iter()
546            .find_map(|s| self.blocked(s, j).map(|p| (s.meta.id.clone(), p)))
547    }
548
549    /// The draft handed on: the values of the fields shown in the steps
550    /// shown (a step or field whose `when` does not hold hands nothing).
551    pub fn draft(&self, w: &Wizard, base: &WhenContext) -> Values {
552        let cx = self.context(base);
553        self.shown(w, base)
554            .into_iter()
555            .flat_map(|s| s.shown_fields(&cx))
556            .filter_map(|f| f.draft_key())
557            .filter_map(|k| self.values.get(k).map(|v| (k.to_string(), v.clone())))
558            .collect()
559    }
560
561    /// Finishing: the command and its arguments, once every step shown is
562    /// valid; else the first invalid step and its reason. In the
563    /// arguments' template, a field of a step not shown is `null`.
564    pub fn finish(&self, w: &Wizard, j: &Judge<'_>) -> Result<(String, Json), (String, String)> {
565        if let Some((step, p)) = self.first_blocked(w, j) {
566            return Err((step, p.message));
567        }
568        let draft = self.draft(w, &j.base);
569        let args = if w.finish.args.is_null() {
570            Json::Object(draft.into_iter().collect::<Map<String, Json>>())
571        } else {
572            // A field of a step not shown is null, not its `${key}`.
573            let mut all = draft;
574            for (_, f) in w.fields() {
575                if let Some(k) = f.draft_key() {
576                    all.entry(k.to_string()).or_insert(Json::Null);
577                }
578            }
579            template::expand(&w.finish.args, &all).0
580        };
581        Ok((w.finish.command.clone(), args))
582    }
583
584    /// The summary: each step shown, its fields shown and their values.
585    pub fn summary<'a>(
586        &self,
587        w: &'a Wizard,
588        base: &WhenContext,
589    ) -> Vec<(&'a Step, Vec<(&'a Field, Json)>)> {
590        let cx = self.context(base);
591        self.shown(w, base)
592            .into_iter()
593            .map(|s| {
594                let rows = s
595                    .shown_fields(&cx)
596                    .into_iter()
597                    // A note asks nothing: the summary lists answers.
598                    .filter(|f| f.kind != Some(FieldKind::Note))
599                    .filter_map(|f| {
600                        f.draft_key()
601                            .map(|k| (f, self.values.get(k).cloned().unwrap_or(Json::Null)))
602                    })
603                    .collect();
604                (s, rows)
605            })
606            .collect()
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use super::super::hooks::Hook;
613    use super::super::{FORMAT, FieldKind, Manifest};
614    use super::*;
615    use serde_json::json;
616
617    fn trip() -> Wizard {
618        Wizard::new("trip", "Plan a trip", "trip.book")
619            .step("where", "Where", |s| {
620                s.field(
621                    Field::draft("trip", "city", "City", FieldKind::Text)
622                        .required()
623                        .default_value(json!("")),
624                )
625                .field(
626                    Field::draft("trip", "abroad", "Abroad", FieldKind::Toggle)
627                        .default_value(json!(false)),
628                );
629            })
630            .step("passport", "Passport", |s| {
631                s.field(
632                    Field::draft("trip", "passport", "Passport number", FieldKind::Text).required(),
633                );
634            })
635            .when("form.abroad")
636            .step("nights", "Nights", |s| {
637                s.field(
638                    Field::draft("trip", "nights", "Nights", FieldKind::Number)
639                        .range(1.0, 30.0)
640                        .default_value(json!(2)),
641                );
642            })
643            .validate("trip.long")
644            .step("extras", "Extras", |s| {
645                s.field(
646                    Field::draft("trip", "room", "Room", FieldKind::Choice)
647                        .choice(json!("single"), "Single room")
648                        .choice(json!("double"), "Double room")
649                        .default_value(json!("single")),
650                );
651            })
652            .optional()
653            .args(json!({ "to": "${city}", "nights": "${nights}", "room": "${room}" }))
654            .verb("Book")
655    }
656
657    fn hooks() -> Hooks {
658        let mut h = Hooks::new();
659        h.register(
660            "trip.long",
661            Hook::Validate(Box::new(|v| {
662                let n = v.get("nights").and_then(Json::as_f64).unwrap_or(0.0);
663                if n > 14.0 {
664                    vec![Problem {
665                        field: "nights".into(),
666                        tone: Tone::Warning,
667                        message: "A long trip.".into(),
668                    }]
669                } else {
670                    Vec::new()
671                }
672            })),
673        );
674        h
675    }
676
677    fn say(f: &Field, c: Check) -> String {
678        format!("{}: {c:?}", f.meta.title)
679    }
680
681    #[test]
682    fn a_wizard_round_trips_through_a_manifest() {
683        let m = Manifest::new(FORMAT).wizard(trip());
684        let json = m.to_json();
685        assert_eq!(json["wizards"][0]["steps"][1]["when"], "form.abroad");
686        assert_eq!(json["wizards"][0]["steps"][3]["optional"], true);
687        assert_eq!(Manifest::from_json(&json).unwrap(), m);
688    }
689
690    #[test]
691    fn next_is_blocked_with_the_reason_and_conditional_steps_come_and_go() {
692        let w = trip();
693        let h = hooks();
694        let j = Judge {
695            base: WhenContext::new(),
696            hooks: &h,
697            say: &say,
698        };
699        let mut f = Flow::start(&w, &j.base, Values::new());
700        assert_eq!(f.at, "where");
701        assert!(!f.dirty());
702        // The city is required: Next is refused with its reason.
703        assert_eq!(f.next(&w, &j).unwrap_err(), "City: Required");
704        f.set(&w, "city", json!("Lyon")).unwrap();
705        assert!(f.set(&w, "nowhere", json!(1)).is_err());
706        assert!(f.dirty());
707        // Not abroad: no passport step.
708        assert_eq!(f.shown(&w, &j.base).len(), 3);
709        f.next(&w, &j).unwrap();
710        assert_eq!(f.at, "nights");
711        f.back(&w, &j.base).unwrap();
712        f.set(&w, "abroad", json!(true)).unwrap();
713        assert_eq!(f.shown(&w, &j.base).len(), 4);
714        f.next(&w, &j).unwrap();
715        assert_eq!(f.at, "passport");
716        // Going ahead lands on the first invalid step, with its reason.
717        let e = f.go(&w, &j, SUMMARY).unwrap_err();
718        assert_eq!(
719            (f.at.as_str(), e.as_str()),
720            ("passport", "Passport number: Required")
721        );
722        f.set(&w, "passport", json!("X1")).unwrap();
723        f.next(&w, &j).unwrap();
724        // A range, then a warning that lets through.
725        f.set(&w, "nights", json!(40)).unwrap();
726        assert_eq!(f.next(&w, &j).unwrap_err(), "Nights: Above(30.0)");
727        f.set(&w, "nights", json!(20)).unwrap();
728        let s = w.step_of("nights").unwrap();
729        assert_eq!(f.problems(s, &j)[0].tone, Tone::Warning);
730        f.next(&w, &j).unwrap();
731        assert_eq!(f.at, "extras");
732        // Skipping an optional step takes its values back.
733        f.set(&w, "room", json!("double")).unwrap();
734        f.skip(&w, &j.base).unwrap();
735        assert!(f.on_summary());
736        assert_eq!(f.values["room"], json!("single"));
737        let summary = f.summary(&w, &j.base);
738        assert_eq!(summary.len(), 4);
739        assert_eq!(summary[3].1[0].0.shown(&summary[3].1[0].1), "Single room");
740        let (cmd, args) = f.finish(&w, &j).unwrap();
741        assert_eq!(cmd, "trip.book");
742        assert_eq!(
743            args,
744            json!({ "to": "Lyon", "nights": 20, "room": "single" })
745        );
746        // Back from the summary: the last step.
747        f.back(&w, &j.base).unwrap();
748        assert_eq!(f.at, "extras");
749        assert_eq!(f.passed, ["where", "passport", "nights", "extras"]);
750    }
751
752    #[test]
753    fn a_hidden_step_hands_nothing_on_and_the_draft_is_the_default_args() {
754        let mut w = trip();
755        w.finish.args = Json::Null;
756        let h = Hooks::new();
757        let j = Judge {
758            base: WhenContext::new(),
759            hooks: &h,
760            say: &say,
761        };
762        let mut f = Flow::start(&w, &j.base, [("city".to_string(), json!("Oslo"))].into());
763        assert!(!f.dirty(), "values given at the start are not an entry");
764        f.values.insert("passport".into(), json!("kept out"));
765        let (_, args) = f.finish(&w, &j).unwrap();
766        assert_eq!(
767            args,
768            json!({ "city": "Oslo", "abroad": false, "nights": 2, "room": "single" })
769        );
770        w.finish.args = json!({ "passport": "${passport}" });
771        let (_, args) = f.finish(&w, &j).unwrap();
772        assert_eq!(args, json!({ "passport": null }), "its step is not shown");
773    }
774
775    #[test]
776    fn the_check_reports_bad_steps() {
777        let mut m = Manifest::new(FORMAT)
778            .wizard(
779                Wizard::new("w", "W", "x")
780                    .step("a", "A", |s| {
781                        s.field(Field::setting("missing"));
782                    })
783                    .step("a", "Again", |_| {})
784                    .step("b", "B", |_| {})
785                    .when("(("),
786            )
787            .wizard(Wizard::new("w", "Twice", "x"));
788        let d = m.check(&[], &|_| false);
789        let codes: Vec<&str> = d.all().iter().map(|x| x.code).collect();
790        assert_eq!(
791            codes,
792            [
793                "admin-no-setting",
794                "admin-duplicate",
795                "admin-bad-clause",
796                "admin-duplicate"
797            ]
798        );
799        assert_eq!(m.wizards.len(), 1);
800        assert_eq!(m.wizards[0].steps.len(), 2);
801        assert!(m.wizards[0].steps[1].meta.when.is_none());
802    }
803}