diff --git a/crates/ui-egui/src/dialogs/accessibility.rs b/crates/ui-egui/src/dialogs/accessibility.rs index f830519f2..f6907f12c 100644 --- a/crates/ui-egui/src/dialogs/accessibility.rs +++ b/crates/ui-egui/src/dialogs/accessibility.rs @@ -1,18 +1,94 @@ -/// Opens this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w16): dl.A10 -pub(crate) fn open( - app: &mut crate::SlideApp, - ctx: &egui::Context, - host: &mut craft::ui::dialog::DialogHost, - params: &serde_json::Value, -) -> Result, String> { - let _ = (app, ctx, host, params); - todo!("dl.A10") +use crate::SlideApp; +use craft::ui::contract::{CollectionEvent, ShowCollection as _, WordSetCx as _}; +use craft::ui::dialog::{DialogHost, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, Severity}; +use craft::ui::patterns::form_dialogs::{FormButtons, FormDialog}; +use egui::{Context, Ui}; +use serde_json::{Value, json}; + +/// Accessibility findings and the document locations their activations reveal. +struct AccessibilityDialog { + findings: Vec, + targets: Vec<(u64, Option)>, + go_to: Option, } -/// Advances this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w16): dl.A10 -pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) { - let _ = (app, ctx, host); - todo!("dl.A10") +impl AccessibilityDialog { + fn set_findings(&mut self, findings: Vec, targets: Vec<(u64, Option)>) { + self.findings = findings; + self.targets = targets; + } + + fn take_go_to(&mut self) -> Option<(u64, Option)> { + self.go_to.take().and_then(|at| self.targets.get(at).copied()) + } +} + +impl StackDialog for AccessibilityDialog { + type Result = (); + + fn id(&self) -> DialogId { + dialog_id("accessibility") + } + + fn key(&self) -> Option<&str> { + Some("accessibility") + } + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + let shown = FormDialog::::own("Accessibility Checker").buttons(FormButtons::Close).show(ui, |ui, _, _| { + let source = Findings::new(&self.findings); + let events = FindingsList::new("Accessibility issues") + .empty("No accessibility issues found. People with disabilities should not have difficulty reading this document.") + .max_rows(12) + .show_items(ui, &source, &mut |key, icx| self.findings[*key as usize].row(&icx.words::())) + .events; + for event in events { + if let CollectionEvent::Activate(id) = event { + self.go_to = Some(id as usize); + } + } + true + }); + shown.closed.map(|_| DialogResult::Ok(())) + } +} + +fn findings(app: &mut SlideApp) -> (Vec, Vec<(u64, Option)>) { + let result = app.session.execute("review.accessibility", &json!({})).unwrap_or_default(); + let mut findings = Vec::new(); + let mut targets = Vec::new(); + for item in result.as_array().into_iter().flatten() { + let slide = item.get("slide").and_then(Value::as_u64).unwrap_or(0); + let issue = item.get("issue").and_then(Value::as_str).unwrap_or(""); + let name = item.get("name").and_then(Value::as_str).map(|name| format!(" — {name}")).unwrap_or_default(); + // The row id and its target share one ordering; only the displayed slide is one-based. + findings.push(Finding::new(targets.len() as u64, Severity::Warning, format!("Slide {}: {issue}{name}", slide + 1))); + targets.push((slide, item.get("shape").and_then(Value::as_u64))); + } + (findings, targets) +} + +/// Opens the checker with the active presentation's findings. +pub(crate) fn open(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost, _params: &Value) -> Result, String> { + let (findings, targets) = findings(app); + Ok(Some(host.open(AccessibilityDialog { findings, targets, go_to: None }))) +} + +/// Reveals activated findings and refreshes the checker while it is open. +pub(crate) fn pump(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost) { + let _ = host.take::(); + let Some(dialog) = host.get_mut::() else { return }; + // FindingsList emits Activate from this pass's input; taking it prevents replay in another pass. + // Resolve against the shown targets before a refresh can reorder the rows. + if let Some((slide, shape)) = dialog.take_go_to() { + let _ = app.run("slide.go", json!({"index": slide})); + if let Some(shape) = shape { + let _ = app.run("edit.select", json!({"ids": [shape]})); + } + } + let (findings, targets) = findings(app); + if dialog.findings != findings || dialog.targets != targets { + dialog.set_findings(findings, targets); + } } diff --git a/crates/ui-egui/src/dialogs/find.rs b/crates/ui-egui/src/dialogs/find.rs index 353db23d3..d240560df 100644 --- a/crates/ui-egui/src/dialogs/find.rs +++ b/crates/ui-egui/src/dialogs/find.rs @@ -1,118 +1,91 @@ -use super::{Dialog, SlideApp, Ui, Value, check, field, json, vec2}; +// PLAN: shell-w11 must enable craft's text-find feature in crates/ui-egui/Cargo.toml; both find imports below require it, and the reported inference errors follow from their absence. +use crate::SlideApp; +use craft::text::find::FindOptions; +use craft::text::ui::find::{FindReplaceDialog, FindRequest, FindTab}; +use craft::ui::dialog::{DialogHost, DialogId, StackDialog as _}; +use egui::Context; +use serde_json::{Value, json}; -/// Home › Find / Replace: step through matches (slide text, table cells, notes) or replace them. -pub(super) fn find_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool { - let replace_mode = d.get("replace", "0") == "1"; - // "Find what:" has the keyboard when the dialog opens, so Ctrl+F and typing finds (#951). - let mut what = d.get("text", ""); - ui.horizontal(|ui| { - ui.add_sized(vec2(120.0, 20.0), egui::Label::new("Find what:")); - let r = ui.add(egui::TextEdit::singleline(&mut what).desired_width(180.0)); - // Enter finds the next match and leaves the keyboard here, so the search can be changed. - if !d.fields.contains_key("focused") || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) { - r.request_focus(); - d.fields.insert("focused".into(), "1".into()); - } - }); - d.fields.insert("text".into(), what); - if replace_mode { - field(ui, d, "Replace with:", "with", ""); - } - let case = check(ui, d, "Match case", "matchCase", false); - let whole = check(ui, d, "Find whole words only", "wholeWords", false); - let text = d.get("text", ""); - let q = json!({"text": text, "matchCase": case, "wholeWords": whole}); - let mut close = false; - let mut find_next = false; - ui.add_space(6.0); - ui.horizontal(|ui| { - let has = !text.is_empty(); - if ui.add_enabled(has, egui::Button::new("Find Next")).clicked() || (has && ui.input(|i| i.key_pressed(egui::Key::Enter))) { - find_next = true; - } - if replace_mode { - if ui.add_enabled(has, egui::Button::new("Replace")).clicked() { - let cur: Option = serde_json::from_str(&d.get("cur", "")).ok(); - if let Some(at) = cur { - let mut p = q.clone(); - p["with"] = json!(d.get("with", "")); - p["at"] = at; - if app.session.execute("text.replace", &p).is_ok() { - let n = d.get("next", "1").parse::().unwrap_or(1); - d.fields.insert("next".into(), n.saturating_sub(1).to_string()); - } - } - find_next = true; - } - if ui.add_enabled(has, egui::Button::new("Replace All")).clicked() { - let mut p = q.clone(); - p["with"] = json!(d.get("with", "")); - let msg = match app.session.execute("text.replace", &p) { - Ok(v) => format!("Replaced {} occurrence(s).", v.get("replaced").and_then(Value::as_u64).unwrap_or(0)), - Err(_) => format!("DeckCraft can't find “{text}”."), - }; - d.fields.insert("status".into(), msg); - d.fields.remove("cur"); - } - } else if ui.button("Replace…").clicked() { - d.fields.insert("replace".into(), "1".into()); - } - if ui.button("Close").clicked() { - close = true; - } - }); - if find_next { - let list = app.session.execute("text.find", &q).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default(); - if list.is_empty() { - d.fields.insert("status".into(), format!("DeckCraft can't find “{text}”.")); - d.fields.remove("cur"); - } else { - let n = d.get("next", "0").parse::().unwrap_or(0) % list.len(); - let m = &list[n]; - let _ = app.run("slide.go", json!({"index": m.get("slide").cloned().unwrap_or_default()})); - if let Some(id) = m.get("shape").filter(|v| !v.is_null()) { - let _ = app.run("edit.select", json!({"ids": [id]})); - } - d.fields.insert("cur".into(), m.to_string()); - d.fields.insert("next".into(), (n + 1).to_string()); - let where_ = if m.get("shape").is_some_and(Value::is_null) { " (notes)" } else { "" }; - d.fields.insert( - "status".into(), - format!("Match {} of {} on slide {}{where_}.", n + 1, list.len(), m.get("slide").and_then(Value::as_u64).unwrap_or(0) + 1), - ); - } - } - let status = d.get("status", ""); - if !status.is_empty() { - ui.add_space(4.0); - ui.label(status); - } - close -} - -/// Opens this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w16): dl.A10 -pub(crate) fn open( - app: &mut crate::SlideApp, - ctx: &egui::Context, - host: &mut craft::ui::dialog::DialogHost, - params: &serde_json::Value, -) -> Result, String> { - let _ = (app, ctx, host, params); - todo!("dl.A10") -} - -/// Advances this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w16): dl.A10 -pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) { - let _ = (app, ctx, host); - todo!("dl.A10") -} - -/// The next and current find results. -#[allow(dead_code)] // P3(dialogs-w16): dl.A13 +/// The next result to visit and the match available for replacement. #[derive(Default)] pub(crate) struct FindProgress { + /// The next result's index before wrapping through the current matches. pub(crate) next: usize, - pub(crate) current: Option, + /// The engine match that the dialog last revealed. + pub(crate) current: Option, +} + +/// Opens Find or Replace, keeping an already open dialog's query and options. +pub(crate) fn open(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost, params: &Value) -> Result, String> { + let tab = if params.get("replace").and_then(Value::as_bool).unwrap_or(false) { FindTab::Replace } else { FindTab::Find }; + app.dialogs.find = FindProgress::default(); + let id = if let Some(dialog) = host.get_mut::() { + dialog.show_tab(tab, None); + dialog.id() + } else { + host.open(FindReplaceDialog::new("", tab).word(false)) + }; + Ok(Some(id)) +} + +/// Applies the dialog's pending search or replacement once and reports its result. +pub(crate) fn pump(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost) { + let _ = host.take::(); + // FindReplaceDialog::show files input requests; taking clears them before another pass. + let Some(request) = host.get_mut::().and_then(FindReplaceDialog::take_request) else { return }; + let message = match request { + FindRequest::FindNext { query, options, .. } => find_next(app, &query, options), + FindRequest::Replace { query, with, options, find_next: true, .. } => { + if let Some(at) = app.dialogs.find.current.clone() { + let mut params = query_params(&query, options); + params["with"] = json!(with); + params["at"] = at; + if app.session.execute("text.replace", ¶ms).is_ok() { + app.dialogs.find.next = app.dialogs.find.next.saturating_sub(1); + } + } + find_next(app, &query, options) + } + FindRequest::ReplaceAll { query, with, options, .. } => { + let mut params = query_params(&query, options); + params["with"] = json!(with); + let message = match app.session.execute("text.replace", ¶ms) { + Ok(value) => format!("Replaced {} occurrence(s).", value.get("replaced").and_then(Value::as_u64).unwrap_or(0)), + Err(_) => not_found(&query), + }; + app.dialogs.find.current = None; + message + } + _ => return, + }; + if let Some(dialog) = host.get_mut::() { + dialog.set_message(message); + } +} + +fn query_params(query: &str, options: FindOptions) -> Value { + json!({"text": query, "matchCase": options.match_case, "wholeWords": options.whole_word}) +} + +fn not_found(query: &str) -> String { + format!("DeckCraft can't find “{query}”.") +} + +fn find_next(app: &mut SlideApp, query: &str, options: FindOptions) -> String { + let matches = + app.session.execute("text.find", &query_params(query, options)).ok().and_then(|value| value.as_array().cloned()).unwrap_or_default(); + if matches.is_empty() { + app.dialogs.find.current = None; + return not_found(query); + } + let n = app.dialogs.find.next % matches.len(); + let found = &matches[n]; + let _ = app.run("slide.go", json!({"index": found.get("slide").cloned().unwrap_or_default()})); + if let Some(shape) = found.get("shape").filter(|shape| !shape.is_null()) { + let _ = app.run("edit.select", json!({"ids": [shape]})); + } + app.dialogs.find.current = Some(found.clone()); + app.dialogs.find.next = n + 1; + let notes = if found.get("shape").is_some_and(Value::is_null) { " (notes)" } else { "" }; + format!("Match {} of {} on slide {}{notes}.", n + 1, matches.len(), found.get("slide").and_then(Value::as_u64).unwrap_or(0) + 1) } diff --git a/crates/ui-egui/src/find_dialog_tests.rs b/crates/ui-egui/src/find_dialog_tests.rs deleted file mode 100644 index 3c46e3ff0..000000000 --- a/crates/ui-egui/src/find_dialog_tests.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! Home › Find (Ctrl+F): "Find what:" has the keyboard as soon as the dialog opens (#951). - -use deckcraft_engine::Session; -use egui_kittest::Harness; -use serde_json::json; - -use crate::{Services, SlideApp}; - -#[test] -fn ctrl_f_puts_the_caret_in_find_what() { - let mut s = Session::with_new(); - s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); - s.execute("insert.textBox", &json!({"rect": [40, 40, 400, 80], "text": "Hello there"})).unwrap(); - s.execute("text.exit", &json!({})).unwrap(); - s.doc_mut().unwrap().selection.shapes.clear(); - // P3(dialogs-w16): sh.A2 - let app = SlideApp::new_base(s, Services::default()); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); - h.run_steps(3); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::F); - h.run_steps(3); - assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("find")); - // Typing right away goes into the field, without clicking it first. - h.event(egui::Event::Text("there".into())); - h.run_steps(3); - let typed = h.state().dialog.as_ref().and_then(|d| d.fields.get("text").cloned()); - assert_eq!(typed.as_deref(), Some("there")); - // Enter finds it. - h.key_press(egui::Key::Enter); - h.run_steps(3); - let status = h.state().dialog.as_ref().and_then(|d| d.fields.get("status").cloned()); - assert!(status.as_deref().is_some_and(|m| m.starts_with("Match 1 of 1")), "Enter didn't find the text: {status:?}"); - // The keyboard stays in the field afterwards: more typing adds to it. - h.event(egui::Event::Text("!".into())); - h.run_steps(3); - let typed = h.state().dialog.as_ref().and_then(|d| d.fields.get("text").cloned()); - assert_eq!(typed.as_deref(), Some("there!")); -}