Skip to main content

egui_pop_api/admin/
wizard.rs

1//! The wizard kit's surface (`docs/design/admin-forms.md`, section 5.3):
2//! a wizard declared in a manifest ([`egui_pop_model::admin::wizard`])
3//! fills the Settings app's page while it runs: the stepper on the left,
4//! the step's form, and a footer with Cancel, Back, Skip and Next (Finish
5//! on the summary).
6//!
7//! - Next is greyed while the step has a blocking problem, its reason in
8//!   the tooltip and beside it; each problem shows under its field.
9//! - The stepper goes back to any step, and ahead to a step whose steps
10//!   before it are valid; it says "Step 2 of 4, Destination" to
11//!   assistive technology.
12//! - Cancel (and Escape) asks first when anything was entered.
13//! - Keys: Enter (when no widget takes it first: a text field, an open
14//!   list, a focused control) and `Alt+N` go next or finish,
15//!   `Alt+B` back, Escape cancels.
16//! - Every gesture is a command an agent runs too: `admin.wizard.open`
17//!   (`{"id", "step", "values", "focus"}`), `admin.wizard.set` (`{"key", "value"}`
18//!   or `{"values"}`), `admin.wizard.next`, `admin.wizard.back`,
19//!   `admin.wizard.skip`, `admin.wizard.go` (`{"step"}`),
20//!   `admin.wizard.finish` and `admin.wizard.cancel` (`{"force"}`); each
21//!   answers the flow's state, which the `admin` collector shows too.
22//!
23//! Draft fields: a toggle, a number, a choice, a text, a path (with
24//! Browse when its input names a file to open or save: the files
25//! plugin's chooser, its choice written into the draft), and a multi (a
26//! tick box per choice; its value the choices ticked, `null` for every
27//! choice).
28//!
29//! A wizard opened as a focus screen ([`Admin::open_focus_wizard`],
30//! `"focus": true`) is drawn over the main window's whole page whatever
31//! the app's window setting, the shell's menus, status bar and centre
32//! hidden while it runs: a first-run setup, where nothing else is to be
33//! seen yet.
34//!
35//! Finishing runs the wizard's command with the draft as its arguments,
36//! then closes the wizard (and the Settings app, when the wizard opened
37//! it).
38
39use std::sync::Arc;
40use std::sync::atomic::{AtomicU64, Ordering};
41
42use egui::accesskit::Role;
43use egui::{Align, Key, Modifiers, Ui};
44use egui_pop_core::a11y;
45use egui_pop_core::lock;
46use egui_pop_core::note::Note;
47use egui_pop_core::strings::{self, Arg};
48use egui_pop_core::theme::Tokens;
49use egui_pop_core::ui::UiPop as _;
50use egui_pop_core::widgets;
51use egui_pop_model::admin::hooks::{Problem, Values};
52use egui_pop_model::admin::wizard::{Judge, SUMMARY};
53use egui_pop_model::admin::{
54    Check, Field, FieldKind, Flow, Item, Step, Tone, Wizard, cell_text, holds,
55};
56use egui_pop_model::commands::Origin;
57use egui_pop_model::ids::CommandId;
58use egui_pop_model::mount::ClaimKey;
59use serde_json::{Value as Json, json};
60
61use super::{ADMIN, Admin, shell};
62use crate::app::AppHandle;
63use crate::dialogs::CustomPass;
64use crate::strings as txt;
65
66/// Opens a wizard (`{"id", "step", "values"}`).
67pub const CMD_WIZARD_OPEN: CommandId = CommandId::from_static("admin.wizard.open");
68/// Sets draft values (`{"key", "value"}` or `{"values": {...}}`).
69pub const CMD_WIZARD_SET: CommandId = CommandId::from_static("admin.wizard.set");
70/// Goes to the next step, if the step shown is valid.
71pub const CMD_WIZARD_NEXT: CommandId = CommandId::from_static("admin.wizard.next");
72/// Goes back a step.
73pub const CMD_WIZARD_BACK: CommandId = CommandId::from_static("admin.wizard.back");
74/// Skips an optional step.
75pub const CMD_WIZARD_SKIP: CommandId = CommandId::from_static("admin.wizard.skip");
76/// Goes to a step (`{"step"}`, `summary` for the summary).
77pub const CMD_WIZARD_GO: CommandId = CommandId::from_static("admin.wizard.go");
78/// Runs the wizard's command with the draft, and closes it.
79pub const CMD_WIZARD_FINISH: CommandId = CommandId::from_static("admin.wizard.finish");
80/// Closes the wizard; asks first when anything was entered, unless
81/// `{"force": true}`.
82pub const CMD_WIZARD_CANCEL: CommandId = CommandId::from_static("admin.wizard.cancel");
83
84/// A wizard running.
85#[derive(Debug, Clone)]
86pub(super) struct Running {
87    pub flow: Flow,
88    /// The wizard opened the Settings app: its end closes it.
89    pub opened: bool,
90    /// Why the last Next, Go or Finish was refused; cleared by the next
91    /// gesture.
92    pub refused: Option<String>,
93    /// A focus screen: drawn over the main window's whole page, whatever
94    /// the app's window setting, the shell's bars and centre hidden.
95    pub focus: bool,
96    /// A sheet ([`Admin::open_sheet_wizard`]): the id of the custom dialog
97    /// it is drawn in, over the window it was opened from.
98    pub sheet: Option<u64>,
99}
100
101/// A field's own check, in words.
102fn check_text(ctx: &egui::Context, f: &Field, c: Check) -> String {
103    let field = [("field", f.meta.title.as_str())];
104    match c {
105        Check::Required => strings::tr_args(ctx, &txt::ADMIN_WIZARD_REQUIRED, &field),
106        Check::Below(min) => strings::tr_with(
107            ctx,
108            &txt::ADMIN_WIZARD_BELOW,
109            &[("field", Arg::Str(field[0].1)), ("min", min.into())],
110        ),
111        Check::Above(max) => strings::tr_with(
112            ctx,
113            &txt::ADMIN_WIZARD_ABOVE,
114            &[("field", Arg::Str(field[0].1)), ("max", max.into())],
115        ),
116        Check::NotAChoice => strings::tr_args(ctx, &txt::ADMIN_WIZARD_NOT_A_CHOICE, &field),
117    }
118}
119
120impl Admin {
121    /// Runs `f` with a judge: the application's keys, the hooks, the
122    /// checks' words.
123    fn judging<R>(&self, app: &AppHandle, f: impl FnOnce(&Judge<'_>) -> R) -> R {
124        let ctx = app.egui();
125        let say = move |field: &Field, c: Check| check_text(&ctx, field, c);
126        let hooks = self.hooks();
127        let j = Judge {
128            base: app.when_context(),
129            hooks: &hooks,
130            say: &say,
131        };
132        f(&j)
133    }
134
135    /// The wizard running, if any.
136    pub fn wizard_flow(&self) -> Option<Flow> {
137        lock(&self.wizard).as_ref().map(|r| r.flow.clone())
138    }
139
140    pub(super) fn running(&self) -> Option<Running> {
141        lock(&self.wizard).clone()
142    }
143
144    /// Opens a wizard declared in a manifest, on its first step (or on
145    /// `step`, if the steps before it are valid), its draft the defaults
146    /// with `values` over them. The Settings app opens with it.
147    pub fn open_wizard(
148        &self,
149        app: &AppHandle,
150        id: &str,
151        step: Option<&str>,
152        values: Values,
153    ) -> Result<Json, String> {
154        self.open_wizard_as(app, id, step, values, false)
155    }
156
157    /// Opens a wizard as [`Admin::open_wizard`] does, as a focus screen:
158    /// the main window's whole page, whatever the app's window setting
159    /// (`pop.admin.window`), with the shell's menus, status bar and centre
160    /// hidden until it ends; the title bar stays, to move or quit. For a
161    /// setup run before anything else (a first launch).
162    pub fn open_focus_wizard(
163        &self,
164        app: &AppHandle,
165        id: &str,
166        step: Option<&str>,
167        values: Values,
168    ) -> Result<Json, String> {
169        self.open_wizard_as(app, id, step, values, true)
170    }
171
172    /// Opens a wizard as [`Admin::open_wizard`] does, as a sheet: a
173    /// window-modal dialog over the window it is opened from (the window
174    /// drawn, or the one whose command opened it), which blocks that
175    /// window alone; the other windows keep working. For a short wizard of
176    /// one to three steps of form fields. The Settings app does not open.
177    /// Finishing runs the wizard's command, its answer to whatever opened
178    /// it, and closes the sheet; Cancel, Escape, or the window closing
179    /// end it with nothing run. Refused while another wizard runs.
180    pub fn open_sheet_wizard(
181        &self,
182        app: &AppHandle,
183        id: &str,
184        step: Option<&str>,
185        values: Values,
186    ) -> Result<Json, String> {
187        if let Some(r) = self.running() {
188            return Err(format!("the wizard `{}` is running", r.flow.wizard));
189        }
190        let me = app.service(&ADMIN).ok_or("no admin")?;
191        let dialogs = app
192            .service(&crate::dialogs::DIALOGS)
193            .ok_or("a sheet needs the dialogs plugin")?;
194        let tree = self.tree(app);
195        let w = tree.wizard(id).ok_or_else(|| format!("no wizard `{id}`"))?;
196        let (flow, refused) = self.judging(app, |j| {
197            let mut f = Flow::start(w, &j.base, values);
198            let refused = step.and_then(|s| f.go(w, j, s).err());
199            (f, refused)
200        });
201        let title = w.meta.title.clone();
202        *lock(&self.wizard) = Some(Running {
203            flow,
204            opened: false,
205            refused,
206            focus: false,
207            sheet: None,
208        });
209        let custom = crate::dialogs::Custom::closing(&title)
210            .own_footer()
211            .claims(&[ClaimKey::Escape])
212            .size(SHEET_SIZE[0], SHEET_SIZE[1]);
213        let guard = SheetGuard {
214            admin: me.clone(),
215            id: Arc::new(AtomicU64::new(0)),
216        };
217        let shared = guard.id.clone();
218        let opened = dialogs.open_custom(app, custom, move |ui, app, pass| {
219            sheet(ui, app, &guard.admin, pass);
220        });
221        let dialog = match opened {
222            Ok(d) => d,
223            Err(e) => {
224                lock(&self.wizard).take();
225                return Err(e);
226            }
227        };
228        shared.store(dialog, Ordering::Relaxed);
229        if let Some(r) = lock(&self.wizard).as_mut() {
230            r.sheet = Some(dialog);
231        }
232        Ok(self.wizard_state(app))
233    }
234
235    /// Whether a wizard opened as a focus screen is running.
236    pub fn focus_screen(&self) -> bool {
237        lock(&self.wizard).as_ref().is_some_and(|r| r.focus)
238    }
239
240    fn open_wizard_as(
241        &self,
242        app: &AppHandle,
243        id: &str,
244        step: Option<&str>,
245        values: Values,
246        focus: bool,
247    ) -> Result<Json, String> {
248        let tree = self.tree(app);
249        let w = tree.wizard(id).ok_or_else(|| format!("no wizard `{id}`"))?;
250        let (flow, refused) = self.judging(app, |j| {
251            let mut f = Flow::start(w, &j.base, values);
252            let refused = step.and_then(|s| f.go(w, j, s).err());
253            (f, refused)
254        });
255        let opened = !self.is_open();
256        *lock(&self.wizard) = Some(Running {
257            flow,
258            opened,
259            refused,
260            focus,
261            sheet: None,
262        });
263        lock(&self.state).open = true;
264        self.refresh();
265        // A focus screen takes it over the main window; another wizard
266        // opens in its window, in the window mode.
267        super::window::settle(app, self, false);
268        Ok(self.wizard_state(app))
269    }
270
271    /// Runs `f` on the flow running and its wizard; its refusal is kept
272    /// (shown beside Next) and returned.
273    fn on_flow<R>(
274        &self,
275        app: &AppHandle,
276        f: impl FnOnce(&Wizard, &mut Flow, &Judge<'_>) -> Result<R, String>,
277    ) -> Result<R, String> {
278        let tree = self.tree(app);
279        let mut guard = lock(&self.wizard);
280        let run = guard.as_mut().ok_or("no wizard is open")?;
281        let w = tree
282            .wizard(&run.flow.wizard)
283            .ok_or_else(|| format!("the wizard `{}` is gone", run.flow.wizard))?;
284        let r = self.judging(app, |j| f(w, &mut run.flow, j));
285        run.refused = r.as_ref().err().cloned();
286        r
287    }
288
289    /// Sets draft values.
290    pub fn wizard_set(&self, app: &AppHandle, values: Values) -> Result<Json, String> {
291        self.on_flow(app, |w, f, _| {
292            for (k, v) in values {
293                f.set(w, &k, v)?;
294            }
295            Ok(())
296        })?;
297        Ok(self.wizard_state(app))
298    }
299
300    /// Next: refused with the step's first blocking problem.
301    pub fn wizard_next(&self, app: &AppHandle) -> Result<Json, String> {
302        self.on_flow(app, |w, f, j| f.next(w, j))?;
303        Ok(self.wizard_state(app))
304    }
305
306    pub fn wizard_back(&self, app: &AppHandle) -> Result<Json, String> {
307        self.on_flow(app, |w, f, j| f.back(w, &j.base))?;
308        Ok(self.wizard_state(app))
309    }
310
311    pub fn wizard_skip(&self, app: &AppHandle) -> Result<Json, String> {
312        self.on_flow(app, |w, f, j| f.skip(w, &j.base))?;
313        Ok(self.wizard_state(app))
314    }
315
316    /// Goes to a step: lands on the first invalid one before it, if any,
317    /// and says why.
318    pub fn wizard_go(&self, app: &AppHandle, step: &str) -> Result<Json, String> {
319        self.on_flow(app, |w, f, j| f.go(w, j, step))?;
320        Ok(self.wizard_state(app))
321    }
322
323    /// Finishes: runs the wizard's command with the draft, then closes
324    /// it. Refused (and landed on the step) while a step is not valid.
325    pub fn wizard_finish(&self, app: &AppHandle) -> Result<Json, String> {
326        let (wizard, (command, args)) = self.on_flow(app, |w, f, j| {
327            f.finish(w, j)
328                .map(|r| (w.meta.id.clone(), r))
329                .map_err(|(step, reason)| {
330                    f.at = step;
331                    reason
332                })
333        })?;
334        let id = CommandId::new(&command).map_err(|e| format!("{e:?}"))?;
335        if app.command(&id).is_none() {
336            return Err(format!("no command `{command}`"));
337        }
338        // Its failure shows once the wizard closed (a toast by default).
339        app.run_reported(id, args.clone(), format!("settings/wizard/{wizard}"));
340        self.end_wizard(app, true);
341        let done = json!({ "finished": wizard, "command": command, "args": args });
342        *lock(&self.finished) = Some(done.clone());
343        Ok(done)
344    }
345
346    /// Cancels: asks first when anything was entered (unless `force`),
347    /// through the dialogs; without them, refused.
348    pub fn wizard_cancel(&self, app: &AppHandle, force: bool) -> Result<Json, String> {
349        let Some(run) = self.running() else {
350            return Err("no wizard is open".into());
351        };
352        if run.flow.dirty() && !force {
353            let tree = self.tree(app);
354            let ctx = app.egui();
355            let title = tree
356                .wizard(&run.flow.wizard)
357                .map_or(run.flow.wizard.clone(), |w| w.meta.title.clone());
358            let asked = tree.wizard(&run.flow.wizard).and_then(|w| w.cancel.clone());
359            let (title, text, verb) = match asked {
360                Some(c) => (c.title, c.text, c.verb),
361                None => (
362                    strings::tr_args(&ctx, &txt::ADMIN_WIZARD_CANCEL_TITLE, &[("wizard", &title)]),
363                    strings::tr(&ctx, &txt::ADMIN_WIZARD_CANCEL_TEXT),
364                    strings::tr(&ctx, &txt::ADMIN_WIZARD_CANCEL_VERB),
365                ),
366            };
367            let dialogs = app
368                .service(&crate::dialogs::DIALOGS)
369                .ok_or("something was entered: cancel with `force` to lose it")?;
370            let ask = crate::dialogs::Confirm::new(&title, &verb, CMD_WIZARD_CANCEL)
371                .detail(&text)
372                .args(json!({ "force": true }))
373                .danger();
374            // Over a sheet, in front of it: queued, it would wait behind
375            // the sheet it asks about.
376            if run.sheet.is_some() {
377                dialogs.open_now(ask);
378            } else {
379                dialogs.open(ask);
380            }
381            return Ok(json!({ "asked": true }));
382        }
383        self.end_wizard(app, false);
384        Ok(json!({ "cancelled": run.flow.wizard }))
385    }
386
387    /// Ends the wizard running; the Settings app closes when the wizard
388    /// opened it, a sheet's dialog is answered (accepted when `finished`).
389    fn end_wizard(&self, app: &AppHandle, finished: bool) {
390        let run = lock(&self.wizard).take();
391        if let Some(id) = run.as_ref().and_then(|r| r.sheet) {
392            if let Some(d) = app.service(&crate::dialogs::DIALOGS) {
393                let answer = if finished {
394                    crate::dialogs::Answer::Accept {
395                        values: Default::default(),
396                    }
397                } else {
398                    crate::dialogs::Answer::Cancel
399                };
400                d.give(id, answer, Origin::User);
401            }
402            return;
403        }
404        if run.is_some_and(|r| r.opened) {
405            self.close(app);
406        } else {
407            // A focus screen ended: back in its window, in the window mode.
408            super::window::settle(app, self, false);
409        }
410    }
411
412    /// The flow's state, for its commands' answers and the collector:
413    /// the step, the steps and their state, the draft, the problems.
414    pub fn wizard_state(&self, app: &AppHandle) -> Json {
415        let Some(run) = self.running() else {
416            return Json::Null;
417        };
418        let tree = self.tree(app);
419        let Some(w) = tree.wizard(&run.flow.wizard) else {
420            return Json::Null;
421        };
422        let f = &run.flow;
423        self.judging(app, |j| {
424            let shown = f.shown(w, &j.base);
425            let index = f.index(w, &j.base);
426            let blocked: Vec<bool> = shown.iter().map(|s| f.blocked(s, j).is_some()).collect();
427            let steps: Vec<Json> = shown
428                .iter()
429                .enumerate()
430                .map(|(i, s)| {
431                    json!({
432                        "id": s.meta.id,
433                        "title": s.meta.title,
434                        "state": step_state(f, &s.meta.id, i, index, &blocked),
435                        "optional": s.optional,
436                    })
437                })
438                .collect();
439            let here = w
440                .step_of(&f.at)
441                .map(|s| f.problems(s, j))
442                .unwrap_or_default();
443            let blocking = here.iter().find(|p| p.tone == Tone::Danger);
444            json!({
445                "wizard": w.meta.id,
446                "title": w.meta.title,
447                "step": f.at,
448                "index": index + 1,
449                "count": shown.len(),
450                "summary": w.summary,
451                "steps": steps,
452                "values": f.values,
453                "draft": f.draft(w, &j.base),
454                "problems": here,
455                "blocked": blocking.map(|p| p.message.clone()),
456                "refused": run.refused,
457                "dirty": f.dirty(),
458                "canFinish": f.first_blocked(w, j).is_none(),
459                "focus": run.focus,
460                "sheet": run.sheet,
461            })
462        })
463    }
464
465    /// What the last finish ran (the wizard, the command, its arguments).
466    pub fn last_finished(&self) -> Option<Json> {
467        lock(&self.finished).clone()
468    }
469}
470
471/// A step's state in the stepper: `current`, `done` (passed), `todo`
472/// (reachable), `later` (a step before it is not valid).
473fn step_state(f: &Flow, id: &str, i: usize, index: usize, blocked: &[bool]) -> &'static str {
474    if i == index {
475        "current"
476    } else if blocked[..i].iter().any(|b| *b) && i > index {
477        "later"
478    } else if f.passed.iter().any(|p| p == id) {
479        "done"
480    } else {
481        "todo"
482    }
483}
484
485/// The values a step's clauses and actions read: the draft.
486fn values(f: &Flow) -> Values {
487    f.values.clone()
488}
489
490/// The wizard's page in the Settings app, while it runs.
491pub(super) fn page(ui: &mut Ui, app: &AppHandle, admin: &Admin) {
492    let ctx = ui.ctx().clone();
493    let t = Tokens::of(&ctx);
494    let tree = admin.tree(app);
495    admin.browsed(app);
496    let Some(run) = admin.running() else {
497        return;
498    };
499    let Some(w) = tree.wizard(&run.flow.wizard) else {
500        admin.end_wizard(app, false);
501        return;
502    };
503    let f = &run.flow;
504    let base = app.when_context();
505    let ctx2 = ctx.clone();
506    let say = move |field: &Field, c: Check| check_text(&ctx2, field, c);
507    let hooks = admin.hooks();
508    let j = Judge {
509        base: base.clone(),
510        hooks: &hooks,
511        say: &say,
512    };
513    let shown = f.shown(w, &base);
514    let index = f.index(w, &base);
515    let blocked: Vec<bool> = shown.iter().map(|s| f.blocked(s, &j).is_some()).collect();
516    let step = w.step_of(&f.at);
517    let problems = step.map(|s| f.problems(s, &j)).unwrap_or_default();
518    let blocking = problems
519        .iter()
520        .find(|p| p.tone == Tone::Danger)
521        .map(|p| p.message.clone());
522    let can_finish = f.first_blocked(w, &j).is_none();
523    drop(hooks);
524    let last = !w.summary && index + 1 >= shown.len();
525    let finishing = f.on_summary() || last;
526    // The keys: with no dialog over the page and no key captured.
527    let free = app
528        .service(&crate::dialogs::DIALOGS)
529        .is_none_or(|d| d.current().is_none())
530        && !app.keys_captured();
531    if free {
532        keys(ui, app, index, finishing);
533    }
534    // The title, and where the flow stands.
535    let count = shown.len() + usize::from(w.summary);
536    let here = if f.on_summary() {
537        strings::tr(&ctx, &txt::ADMIN_WIZARD_SUMMARY)
538    } else {
539        step.map_or_else(String::new, |s| s.meta.title.clone())
540    };
541    let position = strings::tr_with(
542        &ctx,
543        &txt::ADMIN_WIZARD_STEP_OF,
544        &[
545            ("n", (index + 1).into()),
546            ("count", count.into()),
547            ("title", Arg::Str(&here)),
548        ],
549    );
550    ui.horizontal(|ui| {
551        ui.heading(&w.meta.title);
552        ui.with_layout(egui::Layout::right_to_left(Align::Center), |ui| {
553            ui.weak(&position);
554        });
555    });
556    if !w.meta.description.is_empty() {
557        ui.weak(&w.meta.description);
558    }
559    ui.separator();
560    let room = ui.spacing().interact_size.y + t.space.m * 2.0;
561    let body = (ui.available_height() - room).max(0.0);
562    let width = ui.available_width();
563    ui.allocate_ui_with_layout(
564        egui::vec2(width, body),
565        egui::Layout::left_to_right(Align::Min),
566        |ui| {
567            ui.set_min_height(body);
568            // The stepper.
569            let nav = ui
570                .vertical(|ui| {
571                    ui.set_width(220.0);
572                    for (i, s) in shown.iter().enumerate() {
573                        let state = step_state(f, &s.meta.id, i, index, &blocked);
574                        stepper_row(ui, app, i, count, &s.meta.title, &s.meta.id, state);
575                    }
576                    if w.summary {
577                        let state = if f.on_summary() {
578                            "current"
579                        } else if can_finish {
580                            "todo"
581                        } else {
582                            "later"
583                        };
584                        let title = strings::tr(&ctx, &txt::ADMIN_WIZARD_SUMMARY);
585                        stepper_row(ui, app, shown.len(), count, &title, SUMMARY, state);
586                    }
587                })
588                .response;
589            a11y::name(
590                &nav,
591                Role::List,
592                &strings::tr(&ctx, &txt::ADMIN_WIZARD_STEPS),
593            );
594            ui.separator();
595            let width = ui.available_width();
596            egui::ScrollArea::vertical()
597                .id_salt(("egui_pop.admin.wizard", &w.meta.id, &f.at))
598                .auto_shrink([false, false])
599                .max_height(body)
600                .show(ui, |ui| {
601                    let width = (width - ui.spacing().scroll.allocated_width()).max(0.0);
602                    ui.set_max_width(width);
603                    ui.vertical(|ui| {
604                        ui.set_max_width(width);
605                        match step {
606                            Some(s) => step_page(ui, app, admin, w, f, s, &problems),
607                            None => summary_page(ui, app, w, f, &base),
608                        }
609                    });
610                });
611        },
612    );
613    ui.separator();
614    // The footer: Cancel on the left; Next or Finish, Skip, Back on the
615    // right, the reason Next is greyed beside it. Toasts keep off it:
616    // Finish sits in their default corner, and one over it takes its
617    // click.
618    let row = footer(
619        ui,
620        app,
621        Footer {
622            w,
623            refused: run.refused.as_deref(),
624            optional: step.is_some_and(|s| s.optional),
625            index,
626            finishing,
627            can_finish,
628            blocking: blocking.as_deref(),
629        },
630    );
631    crate::toasts::keep_clear(&ctx, row.rect);
632}
633
634/// A wizard's keys: Enter (Next's, the default button, as in a dialog,
635/// unless a text edit takes it or a list is open) and `Alt+N` go next or
636/// finish, `Alt+B` back, Escape cancels. Whether Escape was pressed.
637fn keys(ui: &mut Ui, app: &AppHandle, index: usize, finishing: bool) -> bool {
638    let ctx = ui.ctx().clone();
639    let enter = !egui::Popup::is_any_open(&ctx)
640        && ctx
641            .memory(|m| m.focused())
642            .is_none_or(|id| egui::text_edit::TextEditState::load(&ctx, id).is_none());
643    let (cancel, next, back) = ui.input_mut(|i| {
644        (
645            i.consume_key(Modifiers::NONE, Key::Escape),
646            i.consume_key(Modifiers::ALT, Key::N)
647                || (enter && i.consume_key(Modifiers::NONE, Key::Enter)),
648            i.consume_key(Modifiers::ALT, Key::B),
649        )
650    });
651    if cancel {
652        app.run(CMD_WIZARD_CANCEL, json!({}));
653    } else if next {
654        app.run(
655            if finishing {
656                CMD_WIZARD_FINISH
657            } else {
658                CMD_WIZARD_NEXT
659            },
660            json!({}),
661        );
662    } else if back && index > 0 {
663        app.run(CMD_WIZARD_BACK, json!({}));
664    }
665    cancel
666}
667
668/// A sheet's size, in points (capped to its window).
669const SHEET_SIZE: [f32; 2] = [520.0, 340.0];
670
671/// Held by a sheet's body: when the body goes (its dialog answered,
672/// cancelled, or its window closed), the wizard it draws ends with it.
673struct SheetGuard {
674    admin: Arc<Admin>,
675    /// The sheet's dialog id (0 until it is known).
676    id: Arc<AtomicU64>,
677}
678
679impl Drop for SheetGuard {
680    fn drop(&mut self) {
681        let id = self.id.load(Ordering::Relaxed);
682        let mut run = lock(&self.admin.wizard);
683        if run.as_ref().is_some_and(|r| r.sheet == Some(id)) {
684            run.take();
685        }
686    }
687}
688
689/// A wizard run as a sheet ([`Admin::open_sheet_wizard`]), in its
690/// dialog: where the flow stands ("Step 2 of 3, Destination", announced
691/// as it changes), the step's form, then the footer. Escape is the
692/// wizard's Cancel (it asks first when anything was entered).
693fn sheet(ui: &mut Ui, app: &AppHandle, admin: &Admin, pass: &mut CustomPass) {
694    let ctx = ui.ctx().clone();
695    let tree = admin.tree(app);
696    admin.browsed(app);
697    let Some(run) = admin.running().filter(|r| r.sheet.is_some()) else {
698        return;
699    };
700    let Some(w) = tree.wizard(&run.flow.wizard) else {
701        admin.end_wizard(app, false);
702        return;
703    };
704    let f = &run.flow;
705    let base = app.when_context();
706    let ctx2 = ctx.clone();
707    let say = move |field: &Field, c: Check| check_text(&ctx2, field, c);
708    let hooks = admin.hooks();
709    let j = Judge {
710        base: base.clone(),
711        hooks: &hooks,
712        say: &say,
713    };
714    let shown = f.shown(w, &base);
715    let index = f.index(w, &base);
716    let step = w.step_of(&f.at);
717    let problems = step.map(|s| f.problems(s, &j)).unwrap_or_default();
718    let blocking = problems
719        .iter()
720        .find(|p| p.tone == Tone::Danger)
721        .map(|p| p.message.clone());
722    let can_finish = f.first_blocked(w, &j).is_none();
723    drop(hooks);
724    let last = !w.summary && index + 1 >= shown.len();
725    let finishing = f.on_summary() || last;
726    if !app.keys_captured() && keys(ui, app, index, finishing) {
727        // Escape is the wizard's: it may ask before cancelling.
728        pass.claim_escape();
729    }
730    let count = shown.len() + usize::from(w.summary);
731    let here = if f.on_summary() {
732        strings::tr(&ctx, &txt::ADMIN_WIZARD_SUMMARY)
733    } else {
734        step.map_or_else(String::new, |s| s.meta.title.clone())
735    };
736    let position = strings::tr_with(
737        &ctx,
738        &txt::ADMIN_WIZARD_STEP_OF,
739        &[
740            ("n", (index + 1).into()),
741            ("count", count.into()),
742            ("title", Arg::Str(&here)),
743        ],
744    );
745    // Said to assistive technology as the step changes.
746    let said = egui::Id::unique(("egui_pop.admin.sheet.step", &w.meta.id));
747    if ctx.data(|d| d.get_temp::<String>(said)).as_deref() != Some(position.as_str()) {
748        ctx.data_mut(|d| d.insert_temp(said, position.clone()));
749        a11y::announce(&ctx, position.clone(), a11y::Politeness::Polite);
750    }
751    ui.weak(&position);
752    if index == 0 && !w.meta.description.is_empty() {
753        ui.weak(&w.meta.description);
754    }
755    ui.separator();
756    let room = ui.spacing().interact_size.y + Tokens::of(&ctx).space.m * 2.0;
757    let body = (ui.available_height() - room).max(0.0);
758    egui::ScrollArea::vertical()
759        .id_salt(("egui_pop.admin.sheet", &w.meta.id, &f.at))
760        .auto_shrink([false, false])
761        .max_height(body)
762        .show(ui, |ui| match step {
763            Some(s) => step_page(ui, app, admin, w, f, s, &problems),
764            None => summary_page(ui, app, w, f, &base),
765        });
766    ui.separator();
767    footer(
768        ui,
769        app,
770        Footer {
771            w,
772            refused: run.refused.as_deref(),
773            optional: step.is_some_and(|s| s.optional),
774            index,
775            finishing,
776            can_finish,
777            blocking: blocking.as_deref(),
778        },
779    );
780    pass.describe(admin.wizard_state(app));
781}
782
783/// What a wizard's footer shows.
784struct Footer<'a> {
785    w: &'a Wizard,
786    /// Why the last gesture was refused.
787    refused: Option<&'a str>,
788    /// The step shown can be skipped.
789    optional: bool,
790    /// The step shown, from 0.
791    index: usize,
792    /// Its primary button finishes.
793    finishing: bool,
794    can_finish: bool,
795    /// The step's blocking problem, which greys Next.
796    blocking: Option<&'a str>,
797}
798
799/// A wizard's footer: Cancel on the left; Next or Finish, Skip, Back on
800/// the right, the reason Next is greyed beside it. Each button runs its
801/// command.
802fn footer(ui: &mut Ui, app: &AppHandle, f: Footer<'_>) -> egui::Response {
803    let ctx = ui.ctx().clone();
804    let Footer {
805        w,
806        refused,
807        optional,
808        index,
809        finishing,
810        can_finish,
811        blocking,
812    } = f;
813    ui.horizontal(|ui| {
814        let r = ui.button(strings::tr(&ctx, &txt::ADMIN_WIZARD_CANCEL));
815        if r.clicked() {
816            app.run(CMD_WIZARD_CANCEL, json!({}));
817        }
818        ui.with_layout(egui::Layout::right_to_left(Align::Center), |ui| {
819            let (label, go, on) = if finishing {
820                let verb = if w.finish.verb.is_empty() {
821                    strings::tr(&ctx, &txt::ADMIN_WIZARD_FINISH)
822                } else {
823                    w.finish.verb.clone()
824                };
825                (verb, CMD_WIZARD_FINISH, can_finish)
826            } else {
827                (
828                    strings::tr(&ctx, &txt::ADMIN_WIZARD_NEXT),
829                    CMD_WIZARD_NEXT,
830                    blocking.is_none(),
831                )
832            };
833            let r = ui.add_enabled(on, egui::Button::new(&label).selected(true));
834            if r.clicked() {
835                app.run(go, json!({}));
836            }
837            let reason = blocking.or(refused);
838            if !on && let Some(reason) = reason {
839                r.on_disabled_hover_text(reason);
840            }
841            if optional {
842                let r = ui.button(strings::tr(&ctx, &txt::ADMIN_WIZARD_SKIP));
843                if r.clicked() {
844                    app.run(CMD_WIZARD_SKIP, json!({}));
845                }
846            }
847            if index > 0 {
848                let r = ui.button(strings::tr(&ctx, &txt::ADMIN_WIZARD_BACK));
849                if r.clicked() {
850                    app.run(CMD_WIZARD_BACK, json!({}));
851                }
852            }
853            if let Some(reason) = reason {
854                Note::error(reason).compact().show(ui);
855            }
856        });
857    })
858    .response
859}
860
861/// A step in the stepper: its number and title, selected while shown,
862/// greyed while a step before it is not valid; said "Step 2 of 4,
863/// Destination, done".
864fn stepper_row(
865    ui: &mut Ui,
866    app: &AppHandle,
867    i: usize,
868    count: usize,
869    title: &str,
870    id: &str,
871    state: &str,
872) {
873    let ctx = ui.ctx().clone();
874    let t = Tokens::of(&ctx);
875    let text = format!("{}. {title}", i + 1);
876    let rich = match state {
877        "done" => egui::RichText::new(text).color(t.status.success),
878        _ => egui::RichText::new(text),
879    };
880    let r = ui.add_enabled(
881        state != "later",
882        widgets::SelectableRow::new(state == "current", rich),
883    );
884    let mut name = strings::tr_with(
885        &ctx,
886        &txt::ADMIN_WIZARD_STEP_OF,
887        &[
888            ("n", (i + 1).into()),
889            ("count", count.into()),
890            ("title", Arg::Str(title)),
891        ],
892    );
893    match state {
894        "done" => name = format!("{name}, {}", strings::tr(&ctx, &txt::ADMIN_WIZARD_DONE)),
895        "later" => name = format!("{name}, {}", strings::tr(&ctx, &txt::ADMIN_WIZARD_LATER)),
896        _ => {}
897    }
898    let selected = state == "current";
899    let enabled = state != "later";
900    r.widget_info(move || {
901        let mut info = egui::WidgetInfo::labeled(Role::ListItem, enabled, &name);
902        info.selected = Some(selected);
903        info
904    });
905    if r.clicked() && state != "current" {
906        app.run(CMD_WIZARD_GO, json!({ "step": id }));
907    }
908}
909
910/// A step's page: its title and description, its groups in inset boxes,
911/// its draft fields with their problems under them, the step's own
912/// problems at the end.
913#[allow(
914    clippy::too_many_arguments,
915    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
916)]
917fn step_page(
918    ui: &mut Ui,
919    app: &AppHandle,
920    admin: &Admin,
921    w: &Wizard,
922    f: &Flow,
923    s: &Step,
924    problems: &[Problem],
925) {
926    let ctx = ui.ctx().clone();
927    let t = Tokens::of(&ctx);
928    ui.horizontal(|ui| {
929        ui.heading(&s.meta.title);
930        if s.optional {
931            ui.weak(strings::tr(&ctx, &txt::ADMIN_WIZARD_OPTIONAL));
932        }
933    });
934    if !s.meta.description.is_empty() {
935        ui.weak(&s.meta.description);
936    }
937    ui.add_space(t.space.s);
938    let entries = app.settings();
939    let values = values(f);
940    let cx = f.context(&app.when_context());
941    let mut changed = Values::new();
942    for g in &s.groups {
943        if !holds(g.meta.when.as_deref(), &cx) {
944            continue;
945        }
946        if !g.meta.title.is_empty() {
947            ui.strong(&g.meta.title);
948        }
949        shell::inset(ui, |ui| {
950            for item in &g.items {
951                let meta = item.meta();
952                if !holds(meta.when.as_deref(), &cx) {
953                    continue;
954                }
955                let on = holds(meta.enabled.as_deref(), &cx);
956                let r = ui
957                    .add_enabled_ui(on, |ui| match item {
958                        Item::Field(field) if field.draft_key().is_some() => {
959                            let key = field.draft_key().unwrap_or_default();
960                            let v = f.values.get(key).cloned().unwrap_or(Json::Null);
961                            if let Some(new) = draft_row(ui, app, admin, w, field, &v) {
962                                changed.insert(key.to_string(), new);
963                            }
964                            for p in problems.iter().filter(|p| p.field == key) {
965                                problem(ui, p);
966                            }
967                        }
968                        other => shell::item_row(ui, app, admin, &entries, other, &values),
969                    })
970                    .response;
971                if !on && let Some(reason) = &meta.reason {
972                    r.on_disabled_hover_text(reason);
973                }
974            }
975        });
976        ui.add_space(t.space.m);
977    }
978    // The step's own problems (from its hook, or on no field shown here).
979    let keys: Vec<&str> = s.fields().filter_map(Field::draft_key).collect();
980    for p in problems
981        .iter()
982        .filter(|p| !keys.contains(&p.field.as_str()))
983    {
984        problem(ui, p);
985    }
986    if !changed.is_empty() {
987        let _ = admin.wizard_set(app, changed);
988    }
989}
990
991/// A problem, under its field or at the end of the step.
992fn problem(ui: &mut Ui, p: &Problem) {
993    Note::new(shell::severity_of(p.tone), p.message.clone())
994        .copyable(false)
995        .show(ui);
996}
997
998/// A draft field's row: its label and control (a toggle, a number, a
999/// choice, a text), its help under it. The new value when it changed.
1000fn draft_row(
1001    ui: &mut Ui,
1002    app: &AppHandle,
1003    admin: &Admin,
1004    w: &Wizard,
1005    f: &Field,
1006    value: &Json,
1007) -> Option<Json> {
1008    let title = f.meta.title.as_str();
1009    let id = egui::Id::unique(("egui_pop.admin.wizard.field", &w.meta.id, &f.meta.id));
1010    let kind = f.kind.unwrap_or(FieldKind::Text);
1011    let mut out = None;
1012    if kind == FieldKind::Note {
1013        note_row(ui, f, value);
1014        return None;
1015    }
1016    if kind == FieldKind::Multi {
1017        out = multi_row(ui, f, value);
1018        if !f.help.is_empty() {
1019            ui.weak(&f.help);
1020        }
1021        return out;
1022    }
1023    ui.horizontal_wrapped(|ui| match kind {
1024        FieldKind::Toggle => {
1025            let mut on = value.as_bool().unwrap_or(false);
1026            if widgets::checkbox(ui, &mut on, title).changed() {
1027                out = Some(Json::Bool(on));
1028            }
1029        }
1030        FieldKind::Number => {
1031            ui.label(title);
1032            let before = value.as_f64().unwrap_or(0.0);
1033            let mut n = before;
1034            // A value out of range stays as it is (its problem says so),
1035            // never clamped behind the person's back.
1036            let mut drag = egui::DragValue::new(&mut n).clamp_existing_to_range(false);
1037            if let (Some(min), Some(max)) = (f.input.min, f.input.max) {
1038                drag = drag.range(min..=max);
1039            }
1040            let r = ui.add(drag);
1041            a11y::name(&r, Role::SpinButton, title);
1042            if r.changed() && n != before {
1043                out = Some(if n.fract() == 0.0 && n.abs() < 1e15 {
1044                    json!(n as i64)
1045                } else {
1046                    json!(n)
1047                });
1048            }
1049        }
1050        FieldKind::Choice => {
1051            ui.label(title);
1052            let now = f.shown(value);
1053            let mut picked = None;
1054            let r = ui
1055                .combo_box(widgets::combo_box(id).selected_text(now), |ui| {
1056                    for c in &f.input.choices {
1057                        if ui
1058                            .add(widgets::SelectableRow::new(c.value == *value, &c.label))
1059                            .clicked()
1060                        {
1061                            picked = Some(c.value.clone());
1062                        }
1063                    }
1064                })
1065                .response;
1066            a11y::name(&r, Role::ComboBox, title);
1067            out = picked.filter(|p| p != value);
1068        }
1069        FieldKind::Path => {
1070            ui.label(title);
1071            let mut text = cell_text(value);
1072            let r = ui.add(
1073                egui::TextEdit::singleline(&mut text)
1074                    .id(id)
1075                    .desired_width(320.0),
1076            );
1077            a11y::name(&r, Role::TextInput, title);
1078            if r.changed() {
1079                out = Some(Json::String(text.clone()));
1080            }
1081            if let Some(file) = &f.input.file {
1082                let r = ui.button(strings::tr(ui.ctx(), &txt::DIALOG_BROWSE));
1083                if r.clicked() {
1084                    admin.browse(app, f, file, &text);
1085                }
1086            }
1087        }
1088        _ => {
1089            ui.label(title);
1090            let mut text = cell_text(value);
1091            let edit = if kind == FieldKind::LongText {
1092                egui::TextEdit::multiline(&mut text)
1093            } else {
1094                egui::TextEdit::singleline(&mut text)
1095            };
1096            let r = ui.add(edit.id(id).desired_width(260.0));
1097            a11y::name(&r, Role::TextInput, title);
1098            if r.changed() {
1099                out = Some(Json::String(text));
1100            }
1101        }
1102    });
1103    if !f.help.is_empty() {
1104        ui.weak(&f.help);
1105    }
1106    out
1107}
1108
1109/// A note's row: its icon when it has one, then its words (its draft
1110/// value, else its title), read-only; screen readers read it as a label.
1111pub(super) fn note_row(ui: &mut Ui, f: &Field, value: &Json) {
1112    let text = f.note_text(value);
1113    ui.horizontal_wrapped(|ui| {
1114        if let Some(icon) = &f.meta.icon {
1115            use egui_pop_core::icon::{IconWidget, Size, Source, registry};
1116            let surface = format!("admin note {}", f.meta.id);
1117            registry::record(ui.ctx(), &surface, &text, icon);
1118            ui.add(
1119                IconWidget::new(Source::named(icon, &surface))
1120                    .size(Size::Inline)
1121                    .label(&text),
1122            );
1123        }
1124        let r = ui.label(&text);
1125        a11y::name(&r, Role::Label, &text);
1126    });
1127    if !f.help.is_empty() {
1128        ui.weak(&f.help);
1129    }
1130}
1131
1132/// A multi's row: its title, then a tick box per choice. Its value is the
1133/// choices ticked; `null` is every choice (a list the draft does not know
1134/// yet starts all ticked), and ticking or unticking one writes the list.
1135fn multi_row(ui: &mut Ui, f: &Field, value: &Json) -> Option<Json> {
1136    let mut out = None;
1137    let all: Vec<&Json> = f.input.choices.iter().map(|c| &c.value).collect();
1138    let ticked = |v: &Json| match value {
1139        Json::Array(a) => a.contains(v),
1140        _ => true,
1141    };
1142    ui.label(&f.meta.title);
1143    if f.input.choices.is_empty() {
1144        ui.weak(strings::tr(ui.ctx(), &txt::ADMIN_WIZARD_NO_CHOICES));
1145    }
1146    for c in &f.input.choices {
1147        let mut on = ticked(&c.value);
1148        if widgets::checkbox(ui, &mut on, &c.label).changed() {
1149            let next = all
1150                .iter()
1151                .filter(|v| if ***v == c.value { on } else { ticked(v) })
1152                .map(|v| (*v).clone())
1153                .collect();
1154            out = Some(Json::Array(next));
1155        }
1156    }
1157    out
1158}
1159
1160impl Admin {
1161    /// A path field's Browse: the files plugin's chooser, its choice
1162    /// written into the draft when it comes (see [`Admin::browsed`]).
1163    fn browse(
1164        &self,
1165        app: &AppHandle,
1166        f: &Field,
1167        file: &egui_pop_model::admin::FileInput,
1168        value: &str,
1169    ) {
1170        use crate::files::{FILES, FileRequest};
1171        let Some(key) = f.draft_key() else {
1172            return;
1173        };
1174        let Some(files) = app.service(&FILES) else {
1175            return;
1176        };
1177        let title = if file.title.is_empty() {
1178            f.meta.title.as_str()
1179        } else {
1180            file.title.as_str()
1181        };
1182        let purpose = if file.purpose.is_empty() {
1183            format!("egui_pop.admin.{key}")
1184        } else {
1185            file.purpose.clone()
1186        };
1187        let mut request = if file.folder {
1188            FileRequest::folder(title)
1189        } else if file.save {
1190            let name = std::path::Path::new(value)
1191                .file_name()
1192                .and_then(|n| n.to_str())
1193                .unwrap_or(&file.name);
1194            FileRequest::save(title, name)
1195        } else {
1196            FileRequest::open(title)
1197        }
1198        .purpose(&purpose);
1199        let value = std::path::Path::new(value);
1200        let start = if file.folder && value.is_dir() {
1201            Some(value)
1202        } else {
1203            value.parent().filter(|d| d.is_dir())
1204        };
1205        if let Some(dir) = start {
1206            request = request.directory(dir);
1207        }
1208        if !file.extensions.is_empty() && !file.folder {
1209            let exts: Vec<&str> = file.extensions.iter().map(String::as_str).collect();
1210            let name = if file.filter_name.is_empty() {
1211                exts.join(", ")
1212            } else {
1213                file.filter_name.clone()
1214            };
1215            request = request.filter(&name, &exts);
1216        }
1217        let pending = files.choose(app, request);
1218        *lock(&self.browsing) = Some((key.to_string(), pending));
1219    }
1220
1221    /// Writes a finished Browse's choice into the draft.
1222    fn browsed(&self, app: &AppHandle) {
1223        let done = {
1224            let b = lock(&self.browsing);
1225            b.as_ref()
1226                .and_then(|(k, p)| p.take().map(|r| (k.clone(), r)))
1227        };
1228        let Some((key, result)) = done else {
1229            return;
1230        };
1231        lock(&self.browsing).take();
1232        if let Ok(crate::files::Chosen::Paths(paths)) = crate::files::chosen(&result)
1233            && let Some(p) = paths.first()
1234        {
1235            let _ = self.wizard_set(app, [(key, Json::String(p.display().to_string()))].into());
1236        }
1237    }
1238}
1239
1240/// The summary: each step's fields with their values as shown, and
1241/// "Change" going back to the step.
1242fn summary_page(
1243    ui: &mut Ui,
1244    app: &AppHandle,
1245    w: &Wizard,
1246    f: &Flow,
1247    base: &egui_pop_model::when::WhenContext,
1248) {
1249    let ctx = ui.ctx().clone();
1250    let t = Tokens::of(&ctx);
1251    ui.heading(strings::tr(&ctx, &txt::ADMIN_WIZARD_SUMMARY));
1252    ui.weak(strings::tr(&ctx, &txt::ADMIN_WIZARD_SUMMARY_ABOUT));
1253    ui.add_space(t.space.s);
1254    for (s, rows) in f.summary(w, base) {
1255        ui.horizontal(|ui| {
1256            ui.strong(&s.meta.title);
1257            let r = ui.small_button(strings::tr(&ctx, &txt::ADMIN_WIZARD_CHANGE));
1258            a11y::name(
1259                &r,
1260                Role::Button,
1261                &strings::tr_args(
1262                    &ctx,
1263                    &txt::ADMIN_WIZARD_CHANGE_NAME,
1264                    &[("step", &s.meta.title)],
1265                ),
1266            );
1267            if r.clicked() {
1268                app.run(CMD_WIZARD_GO, json!({ "step": s.meta.id }));
1269            }
1270        });
1271        shell::inset(ui, |ui| {
1272            if rows.is_empty() {
1273                ui.weak(strings::tr(&ctx, &txt::ADMIN_WIZARD_NOT_SET));
1274            }
1275            for (field, v) in rows {
1276                let shown = match v {
1277                    Json::Null if field.kind == Some(FieldKind::Multi) => {
1278                        strings::tr(&ctx, &txt::ADMIN_WIZARD_ALL)
1279                    }
1280                    Json::Array(ref a) if a.is_empty() => {
1281                        strings::tr(&ctx, &txt::ADMIN_WIZARD_NOT_SET)
1282                    }
1283                    Json::Bool(true) => strings::tr(&ctx, &txt::ADMIN_WIZARD_YES),
1284                    Json::Bool(false) => strings::tr(&ctx, &txt::ADMIN_WIZARD_NO),
1285                    Json::Null => strings::tr(&ctx, &txt::ADMIN_WIZARD_NOT_SET),
1286                    Json::String(ref s) if s.trim().is_empty() => {
1287                        strings::tr(&ctx, &txt::ADMIN_WIZARD_NOT_SET)
1288                    }
1289                    ref other => field.shown(other),
1290                };
1291                let r = ui
1292                    .horizontal_wrapped(|ui| {
1293                        ui.label(&field.meta.title);
1294                        ui.with_layout(egui::Layout::right_to_left(Align::Center), |ui| {
1295                            ui.strong(&shown);
1296                        });
1297                    })
1298                    .response;
1299                a11y::name(&r, Role::Group, &format!("{}: {shown}", field.meta.title));
1300            }
1301        });
1302        ui.add_space(t.space.m);
1303    }
1304}
1305
1306/// The commands: open, set, next, back, skip, go, finish, cancel.
1307pub(super) fn commands(ctx: &mut crate::Ctx<'_>) -> Result<(), crate::PluginError> {
1308    use egui_pop_model::commands::CommandSpec;
1309    fn admin(call: &crate::app::Call<'_>) -> Result<std::sync::Arc<Admin>, String> {
1310        call.app.service(&ADMIN).ok_or_else(|| "no admin".into())
1311    }
1312    fn values_arg(args: &Json) -> Values {
1313        let mut v: Values = args
1314            .get("values")
1315            .and_then(Json::as_object)
1316            .map(|o| o.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
1317            .unwrap_or_default();
1318        if let Some(key) = args.get("key").and_then(Json::as_str) {
1319            v.insert(key.into(), args.get("value").cloned().unwrap_or(Json::Null));
1320        }
1321        v
1322    }
1323    ctx.command(
1324        CommandSpec::new(CMD_WIZARD_OPEN, "Open a wizard", "File")
1325            .hidden()
1326            .args(json!({ "id": "", "step": "", "values": {}, "focus": false, "sheet": false })),
1327        |call| {
1328            let id = call
1329                .args
1330                .get("id")
1331                .and_then(Json::as_str)
1332                .ok_or("`id` is missing")?;
1333            let step = call
1334                .args
1335                .get("step")
1336                .and_then(Json::as_str)
1337                .filter(|s| !s.is_empty());
1338            let focus = call.args.get("focus").and_then(Json::as_bool) == Some(true);
1339            let a = admin(call)?;
1340            if call.args.get("sheet").and_then(Json::as_bool) == Some(true) {
1341                return a.open_sheet_wizard(call.app, id, step, values_arg(call.args));
1342            }
1343            a.open_wizard_as(call.app, id, step, values_arg(call.args), focus)
1344        },
1345    )?;
1346    ctx.command(
1347        CommandSpec::new(CMD_WIZARD_SET, "Set a wizard's values", "File")
1348            .hidden()
1349            .args(json!({ "key": "", "value": null, "values": {} })),
1350        |call| admin(call)?.wizard_set(call.app, values_arg(call.args)),
1351    )?;
1352    ctx.command(
1353        CommandSpec::new(CMD_WIZARD_NEXT, "Wizard: next step", "File").hidden(),
1354        |call| admin(call)?.wizard_next(call.app),
1355    )?;
1356    ctx.command(
1357        CommandSpec::new(CMD_WIZARD_BACK, "Wizard: previous step", "File").hidden(),
1358        |call| admin(call)?.wizard_back(call.app),
1359    )?;
1360    ctx.command(
1361        CommandSpec::new(CMD_WIZARD_SKIP, "Wizard: skip this step", "File").hidden(),
1362        |call| admin(call)?.wizard_skip(call.app),
1363    )?;
1364    ctx.command(
1365        CommandSpec::new(CMD_WIZARD_GO, "Wizard: go to a step", "File")
1366            .hidden()
1367            .args(json!({ "step": "" })),
1368        |call| {
1369            let step = call
1370                .args
1371                .get("step")
1372                .and_then(Json::as_str)
1373                .ok_or("`step` is missing")?;
1374            admin(call)?.wizard_go(call.app, step)
1375        },
1376    )?;
1377    ctx.command(
1378        CommandSpec::new(CMD_WIZARD_FINISH, "Wizard: finish", "File").hidden(),
1379        |call| admin(call)?.wizard_finish(call.app),
1380    )?;
1381    ctx.command(
1382        CommandSpec::new(CMD_WIZARD_CANCEL, "Wizard: cancel", "File")
1383            .hidden()
1384            .args(json!({ "force": false })),
1385        |call| {
1386            let force = call
1387                .args
1388                .get("force")
1389                .and_then(Json::as_bool)
1390                .unwrap_or(false);
1391            admin(call)?.wizard_cancel(call.app, force)
1392        },
1393    )?;
1394    Ok(())
1395}