1use 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
36pub const SUMMARY: &str = "summary";
38
39#[derive(Clone, Copy, Debug, PartialEq)]
42pub enum Check {
43 Required,
45 Below(f64),
47 Above(f64),
49 NotAChoice,
51}
52
53#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
63 pub validate: Option<String>,
64 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
66 pub optional: bool,
67}
68
69impl Step {
70 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 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#[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
118pub struct Wizard {
119 #[serde(flatten)]
120 pub meta: Meta,
121 pub steps: Vec<Step>,
122 #[serde(default = "yes", skip_serializing_if = "is_true")]
124 pub summary: bool,
125 pub finish: Finish,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub cancel: Option<Confirmation>,
130}
131
132impl Wizard {
133 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 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 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 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 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 pub fn args(mut self, args: Json) -> Wizard {
212 self.finish.args = args;
213 self
214 }
215
216 pub fn verb(mut self, verb: &str) -> Wizard {
218 self.finish.verb = verb.into();
219 self
220 }
221
222 pub fn no_summary(mut self) -> Wizard {
224 self.summary = false;
225 self
226 }
227
228 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 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 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 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
316pub 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#[derive(Clone, Debug, PartialEq, Serialize)]
334pub struct Flow {
335 pub wizard: String,
336 pub at: String,
338 pub values: Values,
339 pub initial: Values,
341 pub passed: Vec<String>,
343}
344
345impl Flow {
346 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 pub fn context(&self, base: &WhenContext) -> WhenContext {
368 form_context(base.clone(), &self.values)
369 }
370
371 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 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 pub fn dirty(&self) -> bool {
395 self.values != self.initial
396 }
397
398 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 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 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 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 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 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 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 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 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 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 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 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 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 .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 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 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 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 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 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 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}