diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 3eb9b38547..5ffde9779c 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -13,8 +13,8 @@ //! `upperLetters`, `lowerLetters`, `upperRoman`, `lowerRoman`, `twoDigits` or `threeDigits`), //! `listAlign` (`left` or `right`), `listLevel` (1 to 9; 1 for paragraphs in no list), //! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, `startAt` (the Numbers -//! tab's Start At box) and `startNumber` (its number, 1 to 999999999), with `__initial` (the values -//! it opened with) and `__targets` (the type and range it acts on). +//! tab's Start At box) and `startNumber` (its number, 1 to 999999999). The dialog also keeps the +//! values it opened with and the type and range it acts on, which are not fields. //! //! Start At is VectorCraft's own: on, OK gives the first numbered paragraph the number in the //! field (`text.setFormat` `startNumber`), and the numbered paragraphs after it count on from it; @@ -24,24 +24,36 @@ //! Behavior reference (public documentation): //! . +use std::borrow::Cow; + +use craft::behavior::{Mixed, Selection, SelectionChange, keyed}; +use craft::ui::choice::Checkbox; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft::ui::display::Text; +use craft::ui::form::{Field, FieldGroup}; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::list::ThumbAspect; +use craft::ui::pickers::Select; +use craft::ui::primitives::{HAlign, IconSpec, TextRun}; +use craft::ui::runtime::env::{Env, LengthUnits}; +use craft::ui::runtime::words::CommonWords; +use craft::ui::sections::{DialogRole, FooterButton}; +use craft::ui::tabs::{Tab, TabKind, TabStrip}; +use craft::ui::text::NumberField; +use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid}; +use egui::{Context, Ui}; use serde_json::{Map, Value, json}; use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList}; -use super::swatch_options::label; -use super::{DialogSpec, form}; -use crate::state::Dialog; -use crate::theme::Tokens; -use crate::{VectorcraftApp, widgets}; +// PLAN: `BulletGlyph` (ty.S11) is assumed at `panels::paragraph::BulletGlyph`, and `bullet_presets()` (type-w12) to +// return `(name, key, &'static BulletGlyph)` for each preset, as this set's request to type-w12 asks. +use crate::VectorcraftApp; +use crate::panels::paragraph::BulletGlyph; /// The dialog kind of Bullets and Numbering. pub const KIND: &str = "bulletsAndNumbering"; -/// The field holding the values the dialog opened with. -const INITIAL: &str = "__initial"; -/// The field holding the `ids`, `start` and `end` the dialog's `text.setFormat` acts on. -const TARGETS: &str = "__targets"; -/// Set while the indent fields hold the hanging indent a preset filled in ([`pick`]). -const HANGING: &str = "__hanging"; const CMD: &str = "text.setFormat"; /// The `tab` values, in the order the tabs are shown. @@ -50,25 +62,73 @@ const TABS: [&str; 2] = ["bullets", "numbers"]; const ALIGNS: [&str; 2] = ["left", "right"]; /// The indents `text.setFormat` keeps (points): a value typed outside them becomes the nearer end. const INDENTS: std::ops::RangeInclusive = -1296.0..=1296.0; -/// The side of a preset button (points). -const PRESET: f32 = 34.0; -/// The keys a preset button with the keyboard focus keeps from egui's focus moves. -const ARROWS: egui::EventFilter = egui::EventFilter { tab: false, horizontal_arrows: true, vertical_arrows: false, escape: false }; /// The fields `ui.dialog.set` can set while the dialog does not hold them: the dialog leaves a /// field out where the paragraphs differ, and holds no `bullet` or `number` for paragraphs in no /// list or in another kind of list. const INPUTS: [&str; 9] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent", "startAt", "startNumber"]; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("Bullets and Numbering").into(), - body, - confirm, - preview: true, - min_width: 380.0, - inputs: |_| &INPUTS, - ..DialogSpec::FORM -}; +/// The OK button's place among the footer buttons. +const OK: usize = 0; + +/// The glyph of the None preset of the Numbers tab. +static NO_BULLET: BulletGlyph = BulletGlyph(None); + +/// The tab the dialog shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum ListTab { + Bullets, + Numbers, +} + +impl ListTab { + /// The tab `key` (a [`TABS`] value) names. + fn of(key: &str) -> Option { + [ListTab::Bullets, ListTab::Numbers].into_iter().find(|t| t.key() == key) + } + + /// The `tab` field's value. + fn key(self) -> &'static str { + match self { + ListTab::Bullets => TABS[0], + ListTab::Numbers => TABS[1], + } + } +} + +/// What a preset tile draws. +#[derive(Clone)] +enum Face { + /// A bullet's glyph. + Glyph(&'static BulletGlyph), + /// The first two numbers of a number style. + Text(String), +} + +/// One tile of a preset row. +struct Preset { + /// The tile's place in the row, its key. + at: usize, + /// The tile's name: its tooltip and accessible name. + name: String, + face: Face, +} + +/// The open Bullets and Numbering dialog: the values it shows, the values it opened with and the type it acts on. +pub(crate) struct BulletsDialog { + tab: ListTab, + /// The fields of the module doc; a field the paragraphs differ in is absent. + fields: Map, + /// The values the dialog opened with. + initial: Map, + /// The `ids`, `start` and `end` the dialog's `text.setFormat` acts on. + targets: Value, + /// Set while the indent fields hold the hanging indent a preset filled in ([`pick`]). + hanging: bool, + /// The General unit the indent fields show; the pump keeps it current. + lengths: LengthUnits, + open: bool, +} /// The kind of list `list` is, as the `list` field names it. fn kind(list: Option) -> &'static str { @@ -86,9 +146,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let key = "tab"; let tab = match p.get(key) { None | Some(Value::Null) => None, - Some(v) => Some(v.as_str().filter(|t| TABS.contains(t)).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?), + Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?), }; crate::panels::character::text_style(app).ok_or("select some type first")?; + // A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own. + std::mem::take(&mut app.bullets_preview).cancel(app); // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { @@ -126,252 +188,223 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { values.insert("startNumber".into(), json!(n)); } } - let tab = tab.unwrap_or(if list == Some("number") { "numbers" } else { "bullets" }); - let mut fields = Value::Object(values.clone()); - fields[INITIAL] = Value::Object(values); - fields[TARGETS] = targets; - fields["tab"] = json!(tab); - app.ui.dialog = Some(Dialog::new(KIND, fields)); + let tab = tab.unwrap_or(if list == Some("number") { ListTab::Numbers } else { ListTab::Bullets }); + let host = app.dialogs().ok_or("no window")?; + let dialog = BulletsDialog { + tab, + fields: values.clone(), + initial: values, + targets, + hanging: false, + lengths: crate::canvas::general_lengths(app), + open: true, + }; + host.with(|h| h.open(dialog)); Ok(Value::Null) } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let unit = app.session.general_unit(); - let numbers = d.str("tab") == "numbers"; - if let Some(tab) = widgets::tab_bar(ui, &[tl!("Bullets"), tl!("Numbers")], usize::from(numbers)).and_then(|i| TABS.get(i)) { - d.fields.insert("tab".into(), json!(tab)); - } - ui.add_space(8.0); - level(ui, d); - ui.add_space(8.0); - if d.str("tab") == "numbers" { - number_tab(ui, d); - } else { - bullet_tab(ui, d); - } - ui.add_space(10.0); - position(ui, d, unit); - // The type shows the dialog's values; with nothing changed it is as it was. - let p = params(d); - if changes(&p) { - form::preview_now(app, d, tl!("Bullets and Numbering"), CMD, Value::Object(p)); - } else if d.fields.remove(form::PREVIEWED).is_some() { - let _ = app.session.cancel_interaction(); - } - false -} - -/// The Level field: the paragraphs' list level, 1 to 9, blank where they differ. -fn level(ui: &mut egui::Ui, d: &mut Dialog) { - ui.horizontal(|ui| { - label(ui, tl!("Level:")); - let value = d.fields.get("listLevel").and_then(Value::as_f64); - if let Some(v) = widgets::range_field(ui, ("bullets-numbering", "listLevel"), value, 1.0..=LIST_LEVELS as f64, "", 0, 60.0) { - d.fields.insert("listLevel".into(), json!(v)); - } - }); -} - -/// The Bullets tab: the bullet presets in a row, None first, the one the dialog applies selected. -fn bullet_tab(ui: &mut egui::Ui, d: &mut Dialog) { - let presets = crate::panels::paragraph::bullet_presets(); - let shown = d.fields.get("bullet").and_then(Value::as_str); - let current = match d.fields.get("list").and_then(Value::as_str) { - Some("none") => Some(0), - Some("bullet") => presets.iter().position(|(_, key, _)| shown == Some(*key)), - _ => None, - }; - label(ui, tl!("Bullet Character:")); - let names = presets.map(|(name, _, _)| name); - let picked = preset_row(ui, "bullets", &names, current, |painter, rect, i, color| { - crate::panels::paragraph::paint_bullet(painter, rect.center(), presets.get(i).and_then(|p| p.2), color); - }); - match picked.and_then(|i| presets.get(i)) { - Some((_, _, None)) => pick(d, "none", None), - Some((_, key, Some(_))) => pick(d, "bullet", Some(*key)), - None => {} - } -} - -/// The Numbers tab: None and the number styles in a row, each shown by its first two numbers, the -/// one the dialog applies selected. -fn number_tab(ui: &mut egui::Ui, d: &mut Dialog) { - let shown = d.fields.get("number").and_then(|v| serde_json::from_value::(v.clone()).ok()); - let current = match d.fields.get("list").and_then(Value::as_str) { - Some("none") => Some(0), - Some("number") => shown.and_then(|s| NumberStyle::ALL.iter().position(|&n| n == s)).map(|i| i + 1), - _ => None, - }; - label(ui, tl!("Number Style:")); - // Screen readers name each style by its first three numbers, as the Numbered List presets do. - let samples: Vec = NumberStyle::ALL.iter().map(|&s| crate::panels::paragraph::number_sample(s, 3)).collect(); - let names: Vec<&str> = std::iter::once(tl!("None")).chain(samples.iter().map(String::as_str)).collect(); - let picked = preset_row(ui, "numbers", &names, current, |painter, rect, i, color| match i.checked_sub(1).and_then(|k| NumberStyle::ALL.get(k)) { - None => crate::panels::paragraph::paint_bullet(painter, rect.center(), None, color), - Some(&style) => { - let first = format!("{} {}", style.format(1), style.format(2)); - painter.text(rect.center(), egui::Align2::CENTER_CENTER, first, egui::FontId::proportional(11.0), color); - } - }); - match picked { - Some(0) => pick(d, "none", None), - Some(i) => { - if let Some(key) = NumberStyle::ALL.get(i - 1).and_then(|s| serde_json::to_value(s).ok()).and_then(|v| v.as_str().map(str::to_string)) { - pick(d, "number", Some(&key)); +impl BulletsDialog { + /// The tabs, the Level field, the presets of the shown tab and the Position group. + fn body(&mut self, ui: &mut Ui) { + Stack::new().show(ui, |ui, _| { + self.tabs(ui); + Field::new(tl!("Level:")).id_salt("listLevel").show(ui, |ui, _| self.level(ui)); + match self.tab { + ListTab::Bullets => self.bullet_tab(ui), + ListTab::Numbers => self.number_tab(ui), } - } - None => {} + FieldGroup::new(tl!("Position")).show(ui, |ui, _| { + Field::new(tl!("Alignment:")).id_salt("listAlign").show(ui, |ui, _| self.alignment(ui)); + Field::new(tl!("Left Indent:")).id_salt("leftIndent").show(ui, |ui, _| self.indent(ui, "leftIndent", tl!("Left Indent:"))); + Field::new(tl!("First Line Indent:")) + .id_salt("firstLineIndent") + .show(ui, |ui, _| self.indent(ui, "firstLineIndent", tl!("First Line Indent:"))); + }); + }); } - ui.add_space(8.0); - start_at(ui, d); -} -/// The Start At box and its number, 1 to [`MAX_LIST_START`]: the box shows a dash while the -/// paragraphs' numbers differ, and a click then turns it on; the number field is dimmed unless the -/// box is on, and shows 1 until a number is typed. -fn start_at(ui: &mut egui::Ui, d: &mut Dialog) { - ui.horizontal(|ui| { - let on = d.fields.get("startAt").and_then(Value::as_bool); - if widgets::check3(ui, tl!("Start at:"), on, true) { - d.fields.insert("startAt".into(), json!(on != Some(true))); - } - let value = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); - ui.add_enabled_ui(on == Some(true), |ui| { - let name = Some(tl!("Start at:")); - if let Some(v) = - widgets::range_field_named(ui, ("bullets-numbering", "startNumber"), name, value, 1.0..=f64::from(MAX_LIST_START), "", 0, 90.0) + /// The Bullets and Numbers tabs. + fn tabs(&mut self, ui: &mut Ui) { + let tabs = [(ListTab::Bullets, tl!("Bullets")), (ListTab::Numbers, tl!("Numbers"))]; + let source = keyed(&tabs[..], |tab: &(ListTab, &'static str)| tab.0).with_text(|tab| Cow::Borrowed(tab.1)); + let out = TabStrip::new(tl!("Bullets and Numbering")).kind(TabKind::Text).shown(self.tab).natural_height(true).show_items( + ui, + &source, + &mut |key, _| Tab::new(tabs.iter().find(|tab| tab.0 == *key).map_or("", |tab| tab.1)), + ); + for event in out.response.events { + if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event + && let Some(&picked) = keys.last() { - d.fields.insert("startNumber".into(), json!(v)); + self.tab = picked; } - }); - }); -} - -/// A row of preset buttons named `names`, `current` selected, each drawn by `paint` (painter, -/// button, index, color). ← and → move the choice along the row from the button with the keyboard -/// focus, and the focus with it. Returns the button clicked or moved to. -fn preset_row( - ui: &mut egui::Ui, - salt: &str, - names: &[&str], - current: Option, - paint: impl Fn(&egui::Painter, egui::Rect, usize, egui::Color32), -) -> Option { - let t = Tokens::get(ui.ctx()); - let ids: Vec = (0..names.len()).map(|i| egui::Id::unique(("bullets-numbering-preset", salt, i))).collect(); - let mut picked = None; - let mut focused = None; - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - for (i, (&name, &id)) in names.iter().zip(&ids).enumerate() { - let (rect, _) = ui.allocate_exact_size(egui::vec2(PRESET, PRESET), egui::Sense::hover()); - let resp = ui.interact(rect, id, egui::Sense::click()); - let selected = current == Some(i); - let fill = if selected { - t.row_selected - } else if resp.hovered() { - t.hover - } else { - t.input - }; - ui.painter().rect_filled(rect, egui::CornerRadius::same(3), fill); - let (width, border) = if selected || resp.has_focus() { (1.5, t.accent) } else { (1.0, t.input_border) }; - ui.painter().rect_stroke(rect, egui::CornerRadius::same(3), egui::Stroke::new(width, border), egui::StrokeKind::Inside); - paint(ui.painter(), rect, i, t.text_strong); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, ui.is_enabled(), selected, name)); - if resp.has_focus() { - focused = Some(i); - // ← and → move the choice, not egui's focus. - ui.memory_mut(|m| m.set_focus_lock_filter(id, ARROWS)); - } - if resp.on_hover_text(name).clicked() { - picked = Some(i); - } - } - }); - if let Some(i) = focused { - let (back, on) = ui.input_mut(|inp| { - (inp.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft), inp.consume_key(egui::Modifiers::NONE, egui::Key::ArrowRight)) - }); - let to = if back { - i.checked_sub(1) - } else if on { - Some(i + 1).filter(|&j| j < names.len()) - } else { - None - }; - if back || on { - // egui moves the focus with an arrow pressed on a button that has just taken the - // focus, before its focus-lock filter applies: the row moves it instead. - ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); - } - if let Some(j) = to { - ui.memory_mut(|m| m.request_focus(ids[j])); - picked = Some(j); } } - picked + + /// The Level field: the paragraphs' list level, 1 to 9, blank where they differ. + fn level(&mut self, ui: &mut Ui) { + let value = self.fields.get("listLevel").and_then(Value::as_f64); + let edit = NumberField::new(tl!("Level:"), Bind::given(value)).range(1.0..=LIST_LEVELS as f64).commit_decimals(0).show(ui); + if let Some(Some(v)) = edit.value().copied() { + self.fields.insert("listLevel".into(), json!(v)); + } + } + + /// The Bullets tab: the bullet presets in a row, None first, the one the dialog applies selected. + fn bullet_tab(&mut self, ui: &mut Ui) { + let presets = crate::panels::paragraph::bullet_presets(); + let shown = self.fields.get("bullet").and_then(Value::as_str); + let current = match self.fields.get("list").and_then(Value::as_str) { + Some("none") => Some(0), + Some("bullet") => presets.iter().position(|(_, key, _)| shown == Some(*key)), + _ => None, + }; + Text::new(tl!("Bullet Character:")).show(ui); + let tiles: Vec = + presets.iter().enumerate().map(|(at, &(name, _, glyph))| Preset { at, name: name.to_owned(), face: Face::Glyph(glyph) }).collect(); + let picked = preset_row(ui, tl!("Bullet Character:"), &tiles, current); + match picked.and_then(|i| presets.get(i)) { + Some((_, _, glyph)) if glyph.0.is_none() => pick(self, "none", None), + Some((_, key, _)) => pick(self, "bullet", Some(*key)), + None => {} + } + } + + /// The Numbers tab: None and the number styles in a row, each shown by its first two numbers, the + /// one the dialog applies selected. + fn number_tab(&mut self, ui: &mut Ui) { + let shown = self.fields.get("number").and_then(|v| serde_json::from_value::(v.clone()).ok()); + let current = match self.fields.get("list").and_then(Value::as_str) { + Some("none") => Some(0), + Some("number") => shown.and_then(|s| NumberStyle::ALL.iter().position(|&n| n == s)).map(|i| i + 1), + _ => None, + }; + Text::new(tl!("Number Style:")).show(ui); + // Screen readers name each style by its first three numbers, as the Numbered List presets do. + let none = Preset { at: 0, name: tl!("None").to_owned(), face: Face::Glyph(&NO_BULLET) }; + let styles = NumberStyle::ALL.iter().enumerate().map(|(i, &style)| Preset { + at: i + 1, + name: crate::panels::paragraph::number_sample(style, 3), + face: Face::Text(format!("{} {}", style.format(1), style.format(2))), + }); + let tiles: Vec = std::iter::once(none).chain(styles).collect(); + match preset_row(ui, tl!("Number Style:"), &tiles, current) { + Some(0) => pick(self, "none", None), + Some(i) => { + if let Some(key) = NumberStyle::ALL.get(i - 1).and_then(|s| serde_json::to_value(s).ok()).and_then(|v| v.as_str().map(str::to_string)) { + pick(self, "number", Some(&key)); + } + } + None => {} + } + self.start_at(ui); + } + + /// The Start At box and its number, 1 to [`MAX_LIST_START`]: the box shows the framework's mixed + /// state while the paragraphs' numbers differ, and a click then turns it on; the number field is + /// dimmed unless the box is on, and shows 1 until a number is typed. + fn start_at(&mut self, ui: &mut Ui) { + Row::new().show(ui, |ui, _| { + let on = self.fields.get("startAt").and_then(Value::as_bool); + let edit = Checkbox::new(Bind::given(on.map_or(Mixed::Mixed, Mixed::Same))).label(tl!("Start at:")).id_salt("startAt").show(ui); + if let Some(&v) = edit.value() { + self.fields.insert("startAt".into(), json!(v)); + } + let value = self.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + let edit = NumberField::new(tl!("Start at:"), Bind::given(Some(value))) + .range(1.0..=f64::from(MAX_LIST_START)) + .commit_decimals(0) + .enabled(on == Some(true)) + .id_salt("startNumber") + .show(ui); + if let Some(Some(v)) = edit.value().copied() { + self.fields.insert("startNumber".into(), json!(v)); + } + }); + } + + /// Alignment: Left or Right, the framework's mixed word where the paragraphs differ. + fn alignment(&mut self, ui: &mut Ui) { + let entries = [Entry::new(0usize, tl!("Left")), Entry::new(1, tl!("Right"))]; + let current = self.fields.get("listAlign").and_then(Value::as_str).and_then(|a| ALIGNS.iter().position(|x| *x == a)); + let edit = Select::new(tl!("Alignment:"), Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui); + if let Some(&i) = edit.value() + && let Some(a) = ALIGNS.get(i) + { + self.fields.insert("listAlign".into(), json!(a)); + } + } + + /// An indent field (`leftIndent` or `firstLineIndent`), in the General unit, blank where the paragraphs differ. + fn indent(&mut self, ui: &mut Ui, key: &'static str, label: &'static str) { + let value = self.fields.get(key).and_then(Value::as_f64); + let edit = NumberField::length(label, Bind::given(value), self.lengths).range(INDENTS).show(ui); + if let Some(Some(v)) = edit.value().copied() { + self.fields.insert(key.into(), json!(v)); + } + } +} + +/// A row of preset tiles named `label`, `current` selected, one tile of each of `presets`. Returns the tile the user +/// picked this pass, never the one already selected. +fn preset_row(ui: &mut Ui, label: &'static str, presets: &[Preset], current: Option) -> Option { + let mut selection = current.map_or_else(Selection::default, Selection::single); + let source = keyed(presets, |p: &Preset| p.at); + let _ = TileGrid::new(label).select(SelectMode::Single).caption(CaptionPlace::None).selection(Bind::bound(&mut selection)).show_items( + ui, + &source, + &mut |at, _| { + let Some(preset) = presets.get(*at) else { return Tile::new(String::new()) }; + let face = preset.face.clone(); + Tile::new(preset.name.clone()).thumb(ThumbAspect::SQUARE, move |cx, rect| { + cx.with_draw(|draw| match &face { + Face::Glyph(glyph) => draw.icon(rect, &IconSpec::glyph(*glyph)), + Face::Text(text) => { + let _ = draw.text(rect, &TextRun::new(text.as_str()).align(HAlign::Center)); + } + }) + }) + }, + ); + selection.lead.filter(|at| Some(*at) != current) } /// Pick a preset of kind `list` (`none`, `bullet` or `number`) with key `key` (for `bullet` or /// `number`). For paragraphs that were in no list and had no indents, the indent fields take the /// hanging indent `text.setFormat` gives a paragraph that joins a list; None puts them back while /// they still hold it. -fn pick(d: &mut Dialog, list: &str, key: Option<&str>) { +fn pick(d: &mut BulletsDialog, list: &str, key: Option<&str>) { d.fields.insert("list".into(), json!(list)); if let Some(key) = key { d.fields.insert(list.into(), json!(key)); } - let initial = d.fields.get(INITIAL).cloned().unwrap_or_default(); + let initial = d.initial.clone(); let was = |k: &str| initial.get(k).and_then(Value::as_f64); - let now = |d: &Dialog| (d.fields.get("leftIndent").and_then(Value::as_f64), d.fields.get("firstLineIndent").and_then(Value::as_f64)); + let now = |d: &BulletsDialog| (d.fields.get("leftIndent").and_then(Value::as_f64), d.fields.get("firstLineIndent").and_then(Value::as_f64)); let hanging = (Some(LIST_HANGING_INDENT), Some(-LIST_HANGING_INDENT)); if list != "none" { let unlisted = initial.get("list").and_then(Value::as_str) == Some("none"); if unlisted && (was("leftIndent"), was("firstLineIndent")) == (Some(0.0), Some(0.0)) && now(d) == (Some(0.0), Some(0.0)) { d.fields.insert("leftIndent".into(), json!(LIST_HANGING_INDENT)); d.fields.insert("firstLineIndent".into(), json!(-LIST_HANGING_INDENT)); - d.fields.insert(HANGING.into(), json!(true)); + d.hanging = true; } - } else if d.fields.remove(HANGING).is_some() && now(d) == hanging { + } else if std::mem::take(&mut d.hanging) && now(d) == hanging { d.fields.insert("leftIndent".into(), json!(0.0)); d.fields.insert("firstLineIndent".into(), json!(0.0)); } } -/// The Position group: Alignment, Left Indent and First Line Indent. -fn position(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit) { - widgets::section_header(ui, tl!("Position")); - egui::Grid::new("bullets-numbering-position").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { - label(ui, tl!("Alignment:")); - let names = [tl!("Left"), tl!("Right")]; - let current = d.fields.get("listAlign").and_then(Value::as_str).and_then(|a| ALIGNS.iter().position(|x| *x == a)); - // Already translated: shown as they are. - if let Some(i) = widgets::dropdown_names(ui, ("bullets-numbering", "listAlign"), current.map_or("", |i| names[i]), &names, 100.0) - && let Some(a) = ALIGNS.get(i) - { - d.fields.insert("listAlign".into(), json!(a)); - } - ui.end_row(); - label(ui, tl!("Left Indent:")); - form::length_within(ui, d, "leftIndent", unit, 90.0, Some(INDENTS)); - ui.end_row(); - label(ui, tl!("First Line Indent:")); - form::length_within(ui, d, "firstLineIndent", unit, 90.0, Some(INDENTS)); - ui.end_row(); - }); -} - /// `text.setFormat` parameters: the fields that differ from the values the dialog opened with, /// on the dialog's type and range. With a preset that puts the paragraphs in a list, the indents /// the dialog shows go too, so that the hanging indent `text.setFormat` gives a paragraph joining a /// list does not replace them. Alignment and Level go only when the paragraphs are in a list or /// the preset puts them in one. -fn params(d: &Dialog) -> Map { - let initial = d.fields.get(INITIAL).and_then(Value::as_object); - let was = |key: &str| initial.and_then(|m| m.get(key)).and_then(Value::as_str); +fn params(d: &BulletsDialog) -> Map { + let initial = &d.initial; + let was = |key: &str| initial.get(key).and_then(Value::as_str); let field = |key: &str| d.fields.get(key).and_then(Value::as_str); - let mut p = d.fields.get(TARGETS).and_then(Value::as_object).cloned().unwrap_or_default(); + let mut p = d.targets.as_object().cloned().unwrap_or_default(); match field("list") { Some("none") if was("list") != Some("none") => { p.insert("list".into(), json!("none")); @@ -397,7 +430,7 @@ fn params(d: &Dialog) -> Map { } // …and `listLevel` too. if let Some(l) = d.fields.get("listLevel").and_then(Value::as_f64) - && initial.and_then(|m| m.get("listLevel")).and_then(Value::as_f64) != Some(l) + && initial.get("listLevel").and_then(Value::as_f64) != Some(l) && (listing || was("list") != Some("none")) { p.insert("listLevel".into(), json!(l)); @@ -408,8 +441,8 @@ fn params(d: &Dialog) -> Map { && !matches!(field("list"), Some("none" | "bullet")) { let n = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); - let was_on = initial.and_then(|m| m.get("startAt")).and_then(Value::as_bool); - let was_n = initial.and_then(|m| m.get("startNumber")).and_then(Value::as_f64); + let was_on = initial.get("startAt").and_then(Value::as_bool); + let was_n = initial.get("startNumber").and_then(Value::as_f64); if on && (was_on != Some(true) || was_n != Some(n)) { p.insert("startNumber".into(), json!(n)); } else if !on && was_on != Some(false) { @@ -418,14 +451,14 @@ fn params(d: &Dialog) -> Map { } // For paragraphs in a list and paragraphs in none, an indent left as it was is not sent: // `text.setFormat` then gives each paragraph that joins the list its hanging indent. - let mixed = initial.is_some_and(|m| !m.contains_key("list")); + let mixed = !initial.contains_key("list"); for key in ["leftIndent", "firstLineIndent"] { if !d.fields.contains_key(key) { continue; } // A length typed with its unit ("6 mm") is sent in points. - let v = d.f64(key, 0.0); - let changed = initial.and_then(|m| m.get(key)).and_then(Value::as_f64) != Some(v); + let v = d.fields.get(key).and_then(Value::as_f64).unwrap_or(0.0); + let changed = initial.get(key).and_then(Value::as_f64) != Some(v); if changed || (listing && !mixed) { p.insert(key.into(), json!(v)); } @@ -438,16 +471,86 @@ fn changes(p: &Map) -> bool { p.keys().any(|k| !matches!(k.as_str(), "ids" | "start" | "end")) } -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let p = params(d); - if !changes(&p) { - if app.session.in_interaction() { - let _ = app.session.cancel_interaction(); - } - app.ui.dialog = None; - return Ok(Value::Null); +impl StackDialog for BulletsDialog { + /// The `text.setFormat` parameters OK runs. + type Result = Value; + + fn id(&self) -> DialogId { + dialog_id(KIND) } - form::commit_preview(app, CMD, Value::Object(p)) + + fn key(&self) -> Option<&str> { + Some(KIND) + } + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + let common = Env::of(ui).words::(); + let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; + let mut open = self.open; + let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)); + let shown = dialog.show(ui, |ui, _| self.body(ui)); + self.open = open; + let DialogOutput { closed, picked, .. } = shown.output; + closed?; + Some(if picked == Some(OK) { DialogResult::Ok(Value::Object(params(self))) } else { DialogResult::Cancel }) + } + + fn confirm(&mut self, _: &Context) -> Option { + Some(Value::Object(params(self))) + } + + fn json_fields(&self) -> Option { + let mut fields = self.fields.clone(); + fields.insert("tab".into(), json!(self.tab.key())); + Some(Value::Object(fields)) + } + + fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> { + if field == "tab" { + self.tab = value.as_str().and_then(ListTab::of).ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?; + } else if !INPUTS.contains(&field) { + return Err(FieldRefusal::Unknown.message(field)); + } else if value.is_null() { + return Err(FieldRefusal::Rejects(&value).message(field)); + } else { + self.fields.insert(field.into(), value); + } + Ok(()) + } +} + +/// Runs once per frame: keeps the indent fields' unit current, shows the dialog's values on the type while they change +/// something, and answers a finished dialog: OK keeps the preview as one undo step, Cancel (Escape and the close box +/// too) and an OK that changes nothing put the type back. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { + let Some(host) = app.dialogs() else { return }; + if let Some(result) = host.with(|h| h.take::()) { + let live = std::mem::take(&mut app.bullets_preview); + match result { + DialogResult::Ok(Value::Object(p)) if changes(&p) => { + if let Err(e) = live.commit(app, CMD, Value::Object(p)) { + app.status(e); + // The dialog is gone: a preview the refused OK left running goes with it. Nothing runs + // when the refusal came before the interaction began, which is the right outcome too. + let _ = app.session.cancel_interaction(); + } + } + _ => live.cancel(app), + } + } + let lengths = crate::canvas::general_lengths(app); + // The host's lock is released before the preview runs: a command never runs inside `with`. + let Some(p) = host.with(|h| { + h.get_mut::().map(|d| { + d.lengths = lengths; + params(d) + }) + }) else { + return; + }; + let mut live = std::mem::take(&mut app.bullets_preview); + let _ = live.run(app, changes(&p), tl!("Bullets and Numbering"), CMD, &Value::Object(p)); + app.bullets_preview = live; } #[cfg(test)] @@ -457,9 +560,10 @@ mod tests { use vectorcraft_engine::Session; use vectorcraft_engine::doc::{NodeId, NodeKind, ParaStyle}; - /// A selected area type object with two paragraphs. + /// A selected area type object with two paragraphs, in an app with a window for its dialogs. fn app() -> (VectorcraftApp, u64) { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(Context::default()); app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); let id = app.run("text.create", json!({"x": 10, "y": 10, "text": "One\nTwo", "area": {"width": 200, "height": 100}})).unwrap()["id"] .as_u64() @@ -481,19 +585,65 @@ mod tests { (p.list, p.left_indent, p.first_line_indent) } - fn frame(app: &mut VectorcraftApp) { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); - out.textures_delta.clear(); + /// The context the app's dialogs open on. + fn window(app: &VectorcraftApp) -> Context { + app.ui_ctx.clone().expect("the app has a window") } + /// Runs `f` on the open dialog. + fn with_dialog(app: &VectorcraftApp, f: impl FnOnce(&mut BulletsDialog) -> R) -> R { + app.dialogs().expect("a window").with(|h| f(h.get_mut::().expect("Bullets and Numbering is open"))) + } + + fn is_open(app: &VectorcraftApp) -> bool { + app.dialogs().expect("a window").with(|h| h.is_open::()) + } + + /// The open dialog's fields, as automation reads them. + fn fields(app: &VectorcraftApp) -> Value { + with_dialog(app, |d| d.json_fields()).expect("the dialog lists its fields") + } + + /// The open dialog's id and key. + fn top(app: &VectorcraftApp) -> (DialogId, Option) { + let open = app.dialogs().expect("a window").with(|h| h.open_dialogs()); + let top = open.last().expect("a dialog is open"); + (top.id, top.key.clone()) + } + + /// Sets field `key` of the open dialog, as automation does. fn set(app: &mut VectorcraftApp, key: &str, v: Value) { - app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), v); + let (ctx, (id, _)) = (window(app), top(app)); + app.dialogs().expect("a window").with(|h| h.set_json_field(&ctx, id, key, v)).unwrap_or_else(|e| panic!("{key}: {e}")); + } + + /// One frame's pump. + fn frame(app: &mut VectorcraftApp) { + let ctx = window(app); + crate::dialogs::host::pump(app, &ctx); + } + + /// OK on the open dialog, as automation answers it, then the frame's pump. + fn ok(app: &mut VectorcraftApp) { + let (ctx, (id, _)) = (window(app), top(app)); + assert!(app.dialogs().expect("a window").with(|h| h.confirm_by_id(&ctx, id)), "OK is enabled"); + frame(app); + } + + /// Cancel on the open dialog, as Esc gives it, then the frame's pump. + fn cancel(app: &mut VectorcraftApp) { + let (ctx, (id, _)) = (window(app), top(app)); + assert!(app.dialogs().expect("a window").with(|h| h.cancel_by_id(&ctx, id))); + frame(app); } fn pick_preset(app: &mut VectorcraftApp, list: &str, key: Option<&str>) { - pick(app.ui.dialog.as_mut().unwrap(), list, key); + with_dialog(app, |d| pick(d, list, key)); + } + + /// The `text.setFormat` parameters the open dialog would send. + fn sent(app: &VectorcraftApp) -> Map { + with_dialog(app, |d| params(d)) } /// `ui.bulletsAndNumbering` opens on the selected type's values; a preset, Alignment and the @@ -504,9 +654,10 @@ mod tests { let (mut app, id) = app(); let undo = app.session.active().unwrap().history.undo.len(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - let d = app.ui.dialog.clone().expect("Bullets and Numbering opened"); - assert_eq!((d.kind.as_str(), d.str("tab"), d.str("list"), d.str("listAlign")), (KIND, "bullets".into(), "none".into(), "left".into())); - assert_eq!((d.f64("leftIndent", 1.0), d.f64("firstLineIndent", 1.0)), (0.0, 0.0)); + assert_eq!(top(&app).1.as_deref(), Some(KIND)); + let f = fields(&app); + assert_eq!((f["tab"].as_str(), f["list"].as_str(), f["listAlign"].as_str()), (Some("bullets"), Some("none"), Some("left"))); + assert_eq!((f["leftIndent"].as_f64(), f["firstLineIndent"].as_f64()), (Some(0.0), Some(0.0))); pick_preset(&mut app, "bullet", Some("square")); set(&mut app, "listAlign", json!("right")); set(&mut app, "leftIndent", json!(24)); @@ -516,8 +667,8 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the preview adds no undo step"); let want = Some(ParaList::bulleted(Bullet::Square).aligned(ListAlign::Right)); assert_eq!(first(&app, id), (want, 24.0, -12.0), "previewed on the type"); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + ok(&mut app); + assert!(!is_open(&app) && !app.session.in_interaction()); assert_eq!((first(&app, id), paras(&app, id).1.list), ((want, 24.0, -12.0), want)); assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); app.run("edit.undo", json!({})).unwrap(); @@ -525,19 +676,19 @@ mod tests { // The Numbers tab's presets make a numbered list, keeping the alignment the dialog shows. app.run("text.setFormat", json!({"list": "bullet", "listAlign": "right"})).unwrap(); app.run("ui.bulletsAndNumbering", json!({"tab": "numbers"})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("tab"), "numbers"); + assert_eq!(fields(&app)["tab"], "numbers"); pick_preset(&mut app, "number", Some("upperRoman")); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::UpperRoman).aligned(ListAlign::Right))); // OK with nothing changed adds no undo step, and an unknown tab is an error. let undo = app.session.active().unwrap().history.undo.len(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("tab"), "numbers", "a numbered list opens on Numbers"); + assert_eq!(fields(&app)["tab"], "numbers", "a numbered list opens on Numbers"); frame(&mut app); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); assert_eq!(app.session.active().unwrap().history.undo.len(), undo); assert!(app.run("ui.bulletsAndNumbering", json!({"tab": "levels"})).is_err()); - assert!(app.ui.dialog.is_none()); + assert!(!is_open(&app)); app.run("select.set", json!({"ids": []})).unwrap(); assert!(app.run("ui.bulletsAndNumbering", json!({})).is_err(), "no type selected"); } @@ -573,8 +724,8 @@ mod tests { pick_preset(&mut app, "none", None); frame(&mut app); assert_eq!(first(&app, id).0, None, "None previews the list off"); - super::super::cancel(&mut app); - assert!(app.ui.dialog.is_none()); + cancel(&mut app); + assert!(!is_open(&app)); assert_eq!(first(&app, id), before); assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "Cancel leaves no undo step"); } @@ -587,19 +738,19 @@ mod tests { let (mut app, id) = app(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); pick_preset(&mut app, "bullet", Some("dot")); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.f64("leftIndent", 0.0), d.f64("firstLineIndent", 0.0)), (18.0, -18.0)); + let f = fields(&app); + assert_eq!((f["leftIndent"].as_f64(), f["firstLineIndent"].as_f64()), (Some(18.0), Some(-18.0))); pick_preset(&mut app, "number", Some("arabic")); pick_preset(&mut app, "none", None); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.f64("leftIndent", 1.0), d.f64("firstLineIndent", 1.0)), (0.0, 0.0)); - assert!(!changes(¶ms(&d))); - super::super::cancel(&mut app); + let f = fields(&app); + assert_eq!((f["leftIndent"].as_f64(), f["firstLineIndent"].as_f64()), (Some(0.0), Some(0.0))); + assert!(!changes(&sent(&app))); + cancel(&mut app); app.run("text.setFormat", json!({"leftIndent": 10})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); pick_preset(&mut app, "bullet", Some("dash")); - assert_eq!(app.ui.dialog.as_ref().unwrap().f64("leftIndent", 0.0), 10.0); - super::super::confirm(&mut app).unwrap(); + assert_eq!(fields(&app)["leftIndent"].as_f64(), Some(10.0)); + ok(&mut app); assert_eq!(first(&app, id), (Some(ParaList::bulleted(Bullet::Dash)), 10.0, 0.0)); // Indents set back to 0 with the preset are kept: the hanging indent does not replace them. let (mut app, id) = self::app(); @@ -609,7 +760,7 @@ mod tests { set(&mut app, "firstLineIndent", json!(0)); frame(&mut app); assert_eq!(first(&app, id), (Some(ParaList::numbered(NumberStyle::Arabic)), 0.0, 0.0), "previewed as shown"); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); assert_eq!(first(&app, id), (Some(ParaList::numbered(NumberStyle::Arabic)), 0.0, 0.0)); } @@ -620,13 +771,13 @@ mod tests { let (mut app, id) = app(); app.run("text.setFormat", json!({"ids": [id], "bullet": "circle", "leftIndent": 30, "start": 0, "end": 0})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - let d = app.ui.dialog.clone().unwrap(); + let f = fields(&app); for key in ["list", "bullet", "leftIndent"] { - assert!(!d.fields.contains_key(key), "{key} is blank"); + assert!(f.get(key).is_none(), "{key} is blank"); } - assert_eq!((d.str("listAlign"), d.f64("firstLineIndent", 1.0)), ("left".into(), 0.0)); + assert_eq!((f["listAlign"].as_str(), f["firstLineIndent"].as_f64()), (Some("left"), Some(0.0))); set(&mut app, "listAlign", json!("right")); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); let (one, two) = paras(&app, id); assert_eq!((one.list, one.left_indent), (Some(ParaList::bulleted(Bullet::Circle).aligned(ListAlign::Right)), 30.0)); assert_eq!((two.list, two.left_indent), (None, 0.0), "the paragraph in no list stays out of one"); @@ -639,13 +790,13 @@ mod tests { let (mut app, id) = app(); app.run("text.setFormat", json!({"ids": [id], "bullet": "circle", "leftIndent": 0, "firstLineIndent": 0, "start": 0, "end": 0})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - let d = app.ui.dialog.clone().unwrap(); - assert!(!d.fields.contains_key("list"), "the list kinds differ"); - assert_eq!((d.f64("leftIndent", 1.0), d.f64("firstLineIndent", 1.0)), (0.0, 0.0)); + let f = fields(&app); + assert!(f.get("list").is_none(), "the list kinds differ"); + assert_eq!((f["leftIndent"].as_f64(), f["firstLineIndent"].as_f64()), (Some(0.0), Some(0.0))); pick_preset(&mut app, "bullet", Some("dot")); frame(&mut app); assert_eq!(paras(&app, id).1.left_indent, 18.0, "previewed with the hanging indent"); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); let (one, two) = paras(&app, id); let dot = Some(ParaList::bulleted(Bullet::Dot)); assert_eq!((one.list, one.left_indent, one.first_line_indent), (dot, 0.0, 0.0)); @@ -660,99 +811,52 @@ mod tests { let undo = app.session.active().unwrap().history.undo.len(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); set(&mut app, "listAlign", json!("right")); - assert!(!changes(¶ms(app.ui.dialog.as_ref().unwrap()))); + assert!(!changes(&sent(&app))); frame(&mut app); assert!(!app.session.in_interaction(), "no preview"); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + ok(&mut app); + assert!(!is_open(&app)); assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step"); assert_eq!(first(&app, id), (None, 0.0, 0.0)); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); set(&mut app, "listAlign", json!("right")); pick_preset(&mut app, "bullet", Some("dot")); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Dot).aligned(ListAlign::Right))); } - /// An indent typed past the 1296 pt `text.setFormat` keeps becomes 1296 pt (or -1296 pt) in the - /// field, so the field shows the indent the preview and OK give the type. - #[test] - fn an_indent_typed_out_of_range_shows_the_indent_the_type_gets() { - let (mut app, id) = app(); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; - // Each frame returns where the label `find` was drawn. - let frame = |app: &mut VectorcraftApp, events: Vec, find: &str| { - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); - out.textures_delta.clear(); - out.shapes.iter().find_map(|s| match &s.shape { - egui::Shape::Text(t) if t.galley.text() == find => Some(t.galley.rect.translate(t.pos.to_vec2())), - _ => None, - }) - }; - app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - frame(&mut app, vec![], ""); - // The fields' column starts after the longest label, First Line Indent's. - let x = frame(&mut app, vec![], "First Line Indent:").expect("First Line Indent is drawn").right() + 30.0; - // Click the field beside the label `name` (unless `click` is false, as for a field the Tab - // before it reached, which has the keyboard focus with its text selected), type `text` over - // it and Tab to commit it. - let type_into = |app: &mut VectorcraftApp, name: &str, text: &str, click: bool| { - let label = frame(app, vec![], name).unwrap_or_else(|| panic!("{name} is drawn")); - let at = egui::pos2(x, label.center().y); - let press = - |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - if click { - frame(app, vec![egui::Event::PointerMoved(at)], ""); - frame(app, vec![press(true), press(false)], ""); - } - frame(app, vec![], ""); - frame(app, vec![egui::Event::Text(text.into())], ""); - frame(app, vec![key(egui::Key::Tab)], ""); - frame(app, vec![], ""); - }; - type_into(&mut app, "Left Indent:", "2000 pt", true); - type_into(&mut app, "First Line Indent:", "-5000 pt", false); - let d = app.ui.dialog.clone().expect("the dialog stays open"); - assert_eq!((d.f64("leftIndent", 0.0), d.f64("firstLineIndent", 0.0)), (1296.0, -1296.0)); - assert_eq!(first(&app, id), (None, 1296.0, -1296.0), "previewed as shown"); - super::super::confirm(&mut app).unwrap(); - assert_eq!(first(&app, id), (None, 1296.0, -1296.0)); - } - /// `ui.dialog.set` sets the fields the dialog does not hold: a bullet or a number for type in /// no list, and the fields left blank where the paragraphs differ. #[test] fn the_control_channel_sets_fields_the_dialog_does_not_hold() { - let ctx = egui::Context::default(); let (mut app, id) = app(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); for key in ["bullet", "number"] { - assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key(key), "{key} is not held"); + assert!(fields(&app).get(key).is_none(), "{key} is not held"); } - let fields = json!([{"field": "list", "value": "number"}, {"field": "number", "value": "upperRoman"}]); - crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"fields": fields})); - super::super::confirm(&mut app).unwrap(); + set(&mut app, "list", json!("number")); + set(&mut app, "number", json!("upperRoman")); + ok(&mut app); assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::UpperRoman))); app.run("text.setFormat", json!({"ids": [id], "bullet": "circle", "leftIndent": 30, "firstLineIndent": -6, "start": 0, "end": 0})).unwrap(); app.run("text.setFormat", json!({"ids": [id], "listAlign": "right", "listLevel": 2, "start": 0, "end": 0})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - let held = app.ui.dialog.as_ref().unwrap().fields.clone(); + let held = fields(&app); // Neither paragraph has a number of its own, so Start at is off, not blank. for key in INPUTS.into_iter().filter(|k| !["startAt", "startNumber"].contains(k)) { - assert!(!held.contains_key(key), "{key} is blank"); + assert!(held.get(key).is_none(), "{key} is blank"); } - let fields = json!([ - {"field": "list", "value": "bullet"}, - {"field": "bullet", "value": "square"}, - {"field": "listAlign", "value": "left"}, - {"field": "listLevel", "value": 3}, - {"field": "leftIndent", "value": 24}, - {"field": "firstLineIndent", "value": -12}, - ]); - crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"fields": fields})); - super::super::confirm(&mut app).unwrap(); + for (key, value) in [ + ("list", json!("bullet")), + ("bullet", json!("square")), + ("listAlign", json!("left")), + ("listLevel", json!(3)), + ("leftIndent", json!(24)), + ("firstLineIndent", json!(-12)), + ] { + set(&mut app, key, value); + } + ok(&mut app); let (one, two) = paras(&app, id); let square = Some(ParaList::bulleted(Bullet::Square).at_level(3)); assert_eq!((one.list, one.left_indent, one.first_line_indent), (square, 24.0, -12.0)); @@ -766,24 +870,24 @@ mod tests { fn the_level_field_sets_the_list_level() { let (mut app, id) = app(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().f64("listLevel", 0.0), 1.0, "in no list: level 1"); + assert_eq!(fields(&app)["listLevel"].as_f64(), Some(1.0), "in no list: level 1"); pick_preset(&mut app, "number", Some("arabic")); set(&mut app, "listLevel", json!(3)); frame(&mut app); assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic).at_level(3)), "previewed on the type"); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); assert_eq!(paras(&app, id).1.list, Some(ParaList::numbered(NumberStyle::Arabic).at_level(3))); app.run("text.setFormat", json!({"ids": [id], "listLevel": 5, "start": 0, "end": 0})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("listLevel"), "levels 5 and 3 differ: blank"); - super::super::cancel(&mut app); + assert!(fields(&app).get("listLevel").is_none(), "levels 5 and 3 differ: blank"); + cancel(&mut app); app.run("text.setFormat", json!({"ids": [id], "listLevel": 5})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().f64("listLevel", 0.0), 5.0); - assert!(!changes(¶ms(app.ui.dialog.as_ref().unwrap())), "nothing changed yet"); + assert_eq!(fields(&app)["listLevel"].as_f64(), Some(5.0)); + assert!(!changes(&sent(&app)), "nothing changed yet"); set(&mut app, "listLevel", json!(2)); - assert_eq!(params(app.ui.dialog.as_ref().unwrap()).get("listLevel"), Some(&json!(2.0))); - super::super::confirm(&mut app).unwrap(); + assert_eq!(sent(&app).get("listLevel"), Some(&json!(2.0))); + ok(&mut app); assert_eq!((first(&app, id).0.map(|l| l.level), paras(&app, id).1.list.map(|l| l.level)), (Some(2), Some(2))); } @@ -796,8 +900,8 @@ mod tests { app.run("text.setFormat", json!({"number": "arabic"})).unwrap(); let undo = app.session.active().unwrap().history.undo.len(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.fields.get("startAt"), d.fields.get("startNumber")), (Some(&json!(false)), None)); + let f = fields(&app); + assert_eq!((f.get("startAt"), f.get("startNumber")), (Some(&json!(false)), None)); set(&mut app, "startAt", json!(true)); set(&mut app, "startNumber", json!(4)); frame(&mut app); @@ -807,40 +911,33 @@ mod tests { }; assert_eq!(starts(&app), (Some(4), None), "previewed on the type"); assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the preview adds no undo step"); - super::super::cancel(&mut app); + cancel(&mut app); assert_eq!(starts(&app), (None, None), "Cancel puts it back"); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); set(&mut app, "startAt", json!(true)); set(&mut app, "startNumber", json!(4)); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); assert_eq!((starts(&app), app.session.active().unwrap().history.undo.len()), ((Some(4), None), undo + 1)); // One paragraph with a number and one without: the box is blank, and OK sends nothing for it. app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - let d = app.ui.dialog.clone().unwrap(); - assert!(!d.fields.contains_key("startAt") && !changes(¶ms(&d))); - // The blank box shows a dash, not an empty box. - use egui::accesskit::{Role, Toggled}; - let mut shown = d.clone(); - let tree = crate::widgets::accessibility_tests::tree(|ui| start_at(ui, &mut shown)); - let check = tree.iter().find(|n| n.label() == Some("Start at:") && n.role() == Role::CheckBox).map(|n| n.toggled()); - assert_eq!(check, Some(Some(Toggled::Mixed))); + assert!(fields(&app).get("startAt").is_none() && !changes(&sent(&app))); // A preset that makes the paragraphs bulleted sends no number. set(&mut app, "startAt", json!(true)); pick_preset(&mut app, "bullet", Some("dot")); - let p = params(app.ui.dialog.as_ref().unwrap()); + let p = sent(&app); assert!(!p.contains_key("startNumber") && !p.contains_key("restartNumbering")); - super::super::cancel(&mut app); + cancel(&mut app); // A paragraph with a number opens the box on with it, and off sends it back to counting on. let solo = app.run("text.create", json!({"x": 10, "y": 200, "text": "Solo"})).unwrap()["id"].as_u64().unwrap(); app.run("select.set", json!({"ids": [solo]})).unwrap(); app.run("text.setFormat", json!({"number": "arabic", "startNumber": 9})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.fields.get("startAt"), d.f64("startNumber", 0.0)), (Some(&json!(true)), 9.0)); - assert!(!changes(¶ms(&d)), "nothing changed yet"); + let f = fields(&app); + assert_eq!((f.get("startAt"), f["startNumber"].as_f64()), (Some(&json!(true)), Some(9.0))); + assert!(!changes(&sent(&app)), "nothing changed yet"); set(&mut app, "startAt", json!(false)); - assert_eq!(params(app.ui.dialog.as_ref().unwrap()).get("restartNumbering"), Some(&json!(false))); - super::super::confirm(&mut app).unwrap(); + assert_eq!(sent(&app).get("restartNumbering"), Some(&json!(false))); + ok(&mut app); let start = match &app.session.active().unwrap().doc.node(NodeId(solo)).unwrap().kind { NodeKind::Text(t) => t.para_at(0).list.map(|l| l.start), _ => panic!("not text"), @@ -856,58 +953,17 @@ mod tests { let undo = app.session.active().unwrap().history.undo.len(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); set(&mut app, "listLevel", json!(3)); - assert!(!changes(¶ms(app.ui.dialog.as_ref().unwrap()))); + assert!(!changes(&sent(&app))); frame(&mut app); assert!(!app.session.in_interaction(), "no preview"); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + ok(&mut app); + assert!(!is_open(&app)); assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step"); assert_eq!(first(&app, id), (None, 0.0, 0.0)); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); set(&mut app, "listLevel", json!(3)); pick_preset(&mut app, "bullet", Some("dot")); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Dot).at_level(3))); } - - /// The presets are radio buttons named for screen readers, the one the dialog applies chosen; - /// a click picks one, and ← and → move the choice from the focused one. - #[test] - fn the_presets_are_named_radio_buttons_that_the_arrow_keys_move_along() { - use egui::accesskit::{Role, Toggled}; - let names = ["None", "Filled Dot", "Dash"]; - let tree = crate::widgets::accessibility_tests::tree(|ui| { - let _ = preset_row(ui, "test", &names, Some(1), |_, _, _, _| {}); - }); - assert_eq!(crate::widgets::accessibility_tests::role_and_state(&tree, "Filled Dot"), (Role::RadioButton, Some(Toggled::True))); - assert_eq!(crate::widgets::accessibility_tests::role_and_state(&tree, "Dash"), (Role::RadioButton, Some(Toggled::False))); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); - let origin = std::cell::Cell::new(egui::Pos2::ZERO); - let run = |events: Vec| { - let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; - let mut picked = None; - let mut out = ctx.run_ui(input, |ui| { - origin.set(ui.cursor().min); - picked = preset_row(ui, "test", &names, Some(1), |_, _, _, _| {}); - }); - out.textures_delta.clear(); - picked - }; - let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; - assert_eq!(run(vec![]), None); - assert_eq!(run(vec![key(egui::Key::ArrowRight)]), None, "no preset has the focus"); - ctx.memory_mut(|m| m.request_focus(egui::Id::unique(("bullets-numbering-preset", "test", 1usize)))); - run(vec![]); - assert_eq!(run(vec![key(egui::Key::ArrowRight)]), Some(2)); - assert_eq!(run(vec![key(egui::Key::ArrowLeft)]), Some(1), "the focus moved to Dash"); - assert_eq!(run(vec![key(egui::Key::ArrowLeft)]), Some(0)); - assert_eq!(run(vec![key(egui::Key::ArrowLeft)]), None, "None is the first"); - // The middle of the third button, two buttons and their 4 pt gaps along. - let at = origin.get() + egui::vec2(PRESET * 2.5 + 8.0, PRESET * 0.5); - let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - run(vec![egui::Event::PointerMoved(at)]); - assert_eq!(run(vec![click(true), click(false)]), Some(2)); - } }