From c968881b8e79387b2b0df8c211b6d3b4dbda3c8f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 05:31:30 -0500 Subject: [PATCH] pdf-dialogs-w2: net change of 2 commits - pdf-dialogs-w2: finished by an agent - pdf-dialogs-w2: review fixes (review-1) --- crates/ui-panels/src/dialog/prompt.rs | 18 ++ crates/ui-panels/src/dialog/prompt/stories.rs | 26 +- crates/ui-panels/src/dialog/prompts.rs | 100 +++++--- crates/ui-panels/src/dialog/recovery.rs | 4 +- crates/ui-panels/src/dialog/trials.rs | 89 ++++++- crates/ui-panels/src/dialog/unsaved.rs | 17 +- .../src/patterns/form_dialogs/password.rs | 233 +++++++++++------- .../patterns/form_dialogs/password/stories.rs | 36 ++- .../src/patterns/form_dialogs/preview.rs | 59 ++++- .../patterns/form_dialogs/preview/stories.rs | 45 +++- .../tests/it/form_dialogs/password.rs | 31 ++- crates/ui-widgets/src/display/text.rs | 19 +- migration/api-map/form-dialogs-option.toml | 29 ++- 13 files changed, 543 insertions(+), 163 deletions(-) diff --git a/crates/ui-panels/src/dialog/prompt.rs b/crates/ui-panels/src/dialog/prompt.rs index 7def4e717..04312ce01 100644 --- a/crates/ui-panels/src/dialog/prompt.rs +++ b/crates/ui-panels/src/dialog/prompt.rs @@ -2,6 +2,7 @@ use super::frame::DialogOutput; use super::modal::Dialog; +use crate::choice::Checkbox; use crate::contract::{Bind, NoValue, Outcome, Props as _, Show as _, ShowContainer as _}; use crate::display::Text; use crate::layout_components::Stack; @@ -10,6 +11,7 @@ use crate::runtime::env::{Env, Label}; use crate::runtime::focus::Initial; use crate::runtime::overlay::CloseReason; use crate::sections::{DialogRole, FooterButton, Section}; +use craft_behavior::Mixed; use craft_keymap::{Chord, mnemonic}; use craft_theme::variant::Tone; use egui::{Response, Ui}; @@ -81,6 +83,22 @@ pub(super) fn buttons(env: &Env, replies: Vec) -> Vec { .collect() } +/// Adds the "Apply to All" box (`label`) under `prompt`'s message while `remaining`, the documents still asked about +/// this one included, is above one. `hosted` is the dialog's own field on the dialog host; without one the box keeps +/// its state in memory. `ticked` starts at the hosted state and holds the box's state once the prompt is shown. +pub(super) fn apply_to_all<'a>(prompt: Prompt<'a>, label: Label, remaining: usize, hosted: Option<&'a mut bool>, ticked: &'a mut bool) -> Prompt<'a> { + if remaining <= 1 { + return prompt; + } + let mut hosted = hosted; + prompt.extras(move |ui| { + let bind = hosted.as_mut().map_or_else(Bind::kept, |value| Bind::bound(&mut **value)); + if let Some(Mixed::Same(shown)) = Checkbox::new(bind).label(label.clone()).show(ui).shown { + *ticked = *shown; + } + }) +} + /// What a prompt reports: its response, how it closed in this pass and the answer given. #[derive(Debug)] #[non_exhaustive] diff --git a/crates/ui-panels/src/dialog/prompt/stories.rs b/crates/ui-panels/src/dialog/prompt/stories.rs index aec09ee52..8f9cf3cc8 100644 --- a/crates/ui-panels/src/dialog/prompt/stories.rs +++ b/crates/ui-panels/src/dialog/prompt/stories.rs @@ -2,7 +2,8 @@ use super::super::stories::hosted; use super::super::{ - Alert, DialogHost, HostedAlert, Prompt, RecoveredDocument, RecoveryDialog, StackDialog as _, StandardPrompt, UnsavedChangesDialog, + Alert, DialogHost, HostedAlert, Prompt, PromptChoice, RecoveredDocument, RecoveryDialog, StackDialog as _, StandardPrompt, + UnsavedChangesDialog, }; use crate::choice::Checkbox; use crate::contract::{Bind, Props as _, Show as _}; @@ -99,6 +100,23 @@ fn standard_prompt_without_apply(ui: &mut Ui, data: &mut StoryData) -> StoryOutp StandardPrompt::trash_mask().can_apply(!alternate_form).show(ui).into() } +/// A link prompt whose safe answer is the default: Enter cancels. +#[story(StandardPrompt, covers = [], drive = Drive::Never)] +fn standard_prompt_default_cancel(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + StandardPrompt::custom("Open the link “https://example.com/report”?") + .title("Open Link") + .button(PromptChoice::Proceed, "Open") + .button(PromptChoice::Cancel, "Cancel") + .default_choice(PromptChoice::Cancel) + .show(ui) + .into() +} + +#[story(StandardPrompt, covers = [], drive = Drive::Never)] +fn standard_prompt_changed_on_disk(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + StandardPrompt::changed_on_disk("poster.pdf").show(ui).into() +} + #[story(UnsavedChangesDialog, covers = [], drive = Drive::Never)] fn unsaved_changes_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let remaining = if *data.value("several_documents", true) { 3 } else { 1 }; @@ -109,6 +127,10 @@ fn unsaved_changes_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn recovery_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let age = *data.choice("age", AGES[1].1, &AGES); let blocked = *data.value("recover_blocked", false); + let remaining = if *data.value("several_documents", false) { 3 } else { 1 }; + let protected = *data.value("protected", false); let document = RecoveredDocument::new("poster", "poster.psd", age); - RecoveryDialog::new(if blocked { document.blocked("Stop recording first") } else { document }).show(ui).into() + let document = if blocked { document.blocked("Stop recording first") } else { document }; + let document = if protected { document.protected() } else { document }; + RecoveryDialog::new(document).remaining(remaining).show(ui).into() } diff --git a/crates/ui-panels/src/dialog/prompts.rs b/crates/ui-panels/src/dialog/prompts.rs index 4f48c4bae..e9a89ff1a 100644 --- a/crates/ui-panels/src/dialog/prompts.rs +++ b/crates/ui-panels/src/dialog/prompts.rs @@ -38,8 +38,8 @@ pub enum PromptKind { /// The file's name. name: String, }, - /// The document's own file changed on disk since it was opened or saved: Replace or Cancel (Save As keeps both; - /// the message says so). + /// The document's own file changed on disk since it was opened or saved: Replace (Proceed), Save As… (the + /// Alternate, which keeps both files) or Cancel. #[non_exhaustive] ChangedOnDisk { /// The document's file name. @@ -67,9 +67,10 @@ pub enum PromptKind { #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum PromptChoice { - /// The default button: Delete, Open Anyway, Replace, Apply. + /// The main action, and the default button unless `StandardPrompt::default_choice` names another: Delete, Open + /// Anyway, Replace, Apply. Proceed, - /// The Alternate button where the prompt has one (Trash mask's Delete). + /// The Alternate button where the prompt has one (Trash mask's Delete, changed on disk's Save As…). Alternate, /// Dismiss without acting. Cancel, @@ -85,13 +86,15 @@ impl PromptChoice { } } -/// What a `StandardPrompt` answers with: the choice, whether "Don't show again" was ticked with Proceed, and the -/// `tag` the app gave the prompt, so a result says which question it answers (the document, the path, the layers). +/// What a `StandardPrompt` answers with: the choice, whether "Don't show again" was ticked with an answer other than +/// Cancel, and the `tag` the app gave the prompt, so a result says which question it answers (the document, the path, +/// the layers). #[non_exhaustive] pub struct PromptAnswer { /// The button the user pressed. pub choice: PromptChoice, - /// "Don't show again" was ticked and the choice is Proceed: the app stores it and skips the prompt next time. + /// "Don't show again" was ticked and the choice is not Cancel: the app stores the choice and gives it next time + /// without asking. A cancelled prompt is asked again. pub skip: bool, tag: Option>, } @@ -131,7 +134,7 @@ pub struct StandardPromptOutput { /// The answer given in this pass; `None` while the prompt stays open. pub answer: Option, /// The "Don't show again" box is ticked. Storing it is the app's: it skips the prompt next time when the answer - /// is Proceed. + /// is not Cancel. pub skipped: bool, } @@ -160,8 +163,11 @@ pub struct StandardPrompt { skip_box: bool, skip: bool, open: bool, - /// What a programmatic OK answers. - chosen: PromptChoice, + /// What a programmatic OK answers; the default answer until `set_choice` names another. + chosen: Option, + /// The button drawn as default and answered by Enter; kept apart from `chosen`, so automation setting the answer + /// does not move the default the user sees. + default: PromptChoice, /// Carries a typed tag back in the `PromptAnswer` (a document id with the layer ids); read it with /// `PromptAnswer::tag` or `PromptAnswer::take_tag`. #[prop(boxed)] @@ -211,7 +217,8 @@ impl StandardPrompt { skip_box: false, skip: false, open: true, - chosen: PromptChoice::Proceed, + chosen: None, + default: PromptChoice::Proceed, tag: None, escape: PromptChoice::Cancel, noun: None, @@ -237,10 +244,11 @@ impl StandardPrompt { self } - /// The answer a host-side `confirm` gives, as pressing that button would; Proceed (the default button) until - /// set. A choice the prompt has no enabled button for gives none. + /// The answer a host-side `confirm` gives, as pressing that button would; the default choice until set. A choice + /// the prompt has no enabled button for gives none. The button drawn as default stays where `default_choice` put + /// it. pub fn set_choice(&mut self, choice: PromptChoice) { - self.chosen = choice; + self.chosen = Some(choice); } /// The choice Escape and the close action answer, when the prompt has a button that takes it; `None` otherwise. @@ -276,11 +284,22 @@ impl StandardPrompt { } /// The answer Enter gives and the button drawn as default: Proceed unless set. A choice with no button leaves - /// Proceed. + /// Proceed. It is also the answer a host-side `confirm` gives until `set_choice` names another. #[must_use] - pub fn default_choice(self, choice: PromptChoice) -> Self { - let _ = choice; - todo!("DG-C16") + pub fn default_choice(mut self, choice: PromptChoice) -> Self { + self.default = choice; + self + } + + /// What a programmatic OK answers: the choice `set_choice` named, else the default answer. + fn chosen_answer(&self) -> PromptChoice { + self.chosen.unwrap_or_else(|| self.default_answer()) + } + + /// The choice the default button answers: the one `default_choice` set when it has a button that takes a press, + /// else Proceed. + fn default_answer(&self) -> PromptChoice { + if self.takes(self.default) { self.default } else { PromptChoice::Proceed } } /// Adds a paragraph after the message, a label of its own. @@ -291,7 +310,8 @@ impl StandardPrompt { } /// Adds a button with the app's label; its letter comes from the translated labels of the prompt. The first call - /// replaces the kind's own buttons. `PromptChoice::Proceed` is the default button (Enter), `PromptChoice::Cancel` + /// replaces the kind's own buttons. `PromptChoice::Proceed` is the default button (Enter) unless `default_choice` + /// names another, `PromptChoice::Cancel` /// answers Escape and the close action unless `escape` names another choice, and `PromptChoice::Alternate` is a /// third answer; each is listed once. #[must_use] @@ -348,17 +368,31 @@ impl StandardPrompt { if let Some(own) = &self.message { message = own.clone(); } + let alternate = match self.kind { + PromptKind::ChangedOnDisk { .. } => &words.save_as, + _ => &words.discard, + }; + // `Prompt` and the footer take the first Accept answer as the default (Enter and the default stop), so the + // default choice's reply is the Accept one and an Accept Proceed that is not the default steps back to Other. + // A Destructive Proceed keeps its look. + let default = self.default_answer(); let answers = self .offered() .into_iter() .map(|(choice, enabled)| { - let own = self.buttons.iter().find(|(button, _)| *button == choice).map(|(_, label)| Reply::new(label.clone(), choice.role())); - let reply = own.unwrap_or_else(|| match choice { - PromptChoice::Proceed => Reply::new(proceed.clone(), role), - PromptChoice::Alternate => Reply::new(words.discard.clone(), DialogRole::Other), - PromptChoice::Cancel => Reply::new(common.cancel.clone(), DialogRole::Cancel), + let own = self.buttons.iter().find(|(button, _)| *button == choice).map(|(_, label)| (label.clone(), choice.role())); + let (label, role) = own.unwrap_or_else(|| match choice { + PromptChoice::Proceed => (proceed.clone(), role), + PromptChoice::Alternate => (alternate.clone(), DialogRole::Other), + PromptChoice::Cancel => (common.cancel.clone(), DialogRole::Cancel), }); - (choice, reply.enabled(enabled, None)) + let role = match role { + _ if default == PromptChoice::Proceed => role, + _ if choice == default => DialogRole::Accept, + DialogRole::Accept => DialogRole::Other, + role => role, + }; + (choice, Reply::new(label, role).enabled(enabled, None)) }) .collect(); if title.as_str().is_empty() { @@ -376,6 +410,7 @@ impl StandardPrompt { match self.kind { PromptKind::Custom => Vec::new(), PromptKind::TrashMask => vec![(PromptChoice::Proceed, self.can_apply), (PromptChoice::Alternate, true), (PromptChoice::Cancel, true)], + PromptKind::ChangedOnDisk { .. } => vec![(PromptChoice::Proceed, true), (PromptChoice::Alternate, true), (PromptChoice::Cancel, true)], _ => vec![(PromptChoice::Proceed, true), (PromptChoice::Cancel, true)], } } @@ -429,9 +464,9 @@ impl StandardPrompt { } } - /// The answer of `choice`; Proceed reports the skip box when it is `ticked`. + /// The answer of `choice`; every choice but Cancel reports the skip box when it is `ticked`. fn answer(&mut self, choice: PromptChoice, ticked: bool) -> PromptAnswer { - PromptAnswer { choice, skip: choice == PromptChoice::Proceed && self.skip_box && ticked, tag: self.tag.take() } + PromptAnswer { choice, skip: choice != PromptChoice::Cancel && self.skip_box && ticked, tag: self.tag.take() } } /// Shows the prompt; `hosted` holds the open state and the box in the prompt's own fields, else in memory. @@ -449,6 +484,12 @@ impl StandardPrompt { .and_then(|choice| choices.iter().position(|listed| *listed == choice)) .and_then(|at| footer.get(at)) .map(|button| button.role()); + // After the default remap a Proceed can share Other with the Alternate; Escape finds its answer by role, so a + // shared role would answer whichever comes first. No prompt is built that way: this keeps it so. + debug_assert!( + escape.is_none_or(|role| footer.iter().filter(|button| button.role() == role).count() == 1), + "the escape answer's role names one button" + ); let mut prompt = Prompt::new(title, message).answers(footer); if let Some(role) = escape { prompt = prompt.escape(role); @@ -510,13 +551,14 @@ impl StackDialog for StandardPrompt { /// The answer set with `set_choice`: the default button's, Proceed, unless set. None while that answer's /// button is missing or disabled. fn confirm(&mut self, _: &Context) -> Option { - self.takes(self.chosen).then(|| self.answer(self.chosen, self.skip)) + let chosen = self.chosen_answer(); + self.takes(chosen).then(|| self.answer(chosen, self.skip)) } /// `choice`, the answer a programmatic OK gives, and `skip`, the "Don't show again" box where the prompt has /// one. fn json_fields(&self) -> Option { - let mut fields = json!({ "choice": self.chosen }); + let mut fields = json!({ "choice": self.chosen_answer() }); if self.skip_box { fields["skip"] = Value::Bool(self.skip); } diff --git a/crates/ui-panels/src/dialog/recovery.rs b/crates/ui-panels/src/dialog/recovery.rs index 7a0d67a8d..dc20da875 100644 --- a/crates/ui-panels/src/dialog/recovery.rs +++ b/crates/ui-panels/src/dialog/recovery.rs @@ -178,7 +178,9 @@ impl RecoveryDialog { (Some(CloseReason::Activated | CloseReason::Enter), Some(_)) => Some(RecoveryAnswer::Recover), _ => None, }; - let answer = answer.map(|answer| self.choice(answer, ticked)); + // P3(pdf-shell-w5): SH-C34: the Apply to All box is not shown yet. + + let answer = answer.map(|answer| RecoveryChoice { answer, apply_to_all: false }); RecoveryOutput { response: shown.response, closed: shown.closed, answer } } diff --git a/crates/ui-panels/src/dialog/trials.rs b/crates/ui-panels/src/dialog/trials.rs index a72b5db1f..c7b076ec3 100644 --- a/crates/ui-panels/src/dialog/trials.rs +++ b/crates/ui-panels/src/dialog/trials.rs @@ -1,7 +1,11 @@ -//! Trials of the dialog shells' layer behaviour: initial focus, Escape and a closed dialog's keys. +//! Trials of the dialog shells' layer behaviour: initial focus, Escape and a closed dialog's keys; and of the prompts +//! on the dialog host: the default answer and the Apply to All box. #![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] -use super::{BlockingOverlay, Dialog}; +use super::{ + BlockingOverlay, Dialog, DialogHost, DialogResult, PromptChoice, RecoveredDocument, RecoveryAnswer, RecoveryDialog, StackDialog, + StandardPrompt, UnsavedChangesDialog, +}; use crate::buttons::Button; use crate::choice::Checkbox; use crate::contract::{Bind, Props as _, Role, Show as _, ShowContainer as _}; @@ -13,8 +17,11 @@ use crate::testing::input::key_press; use crate::testing::relations::{apart_above, grows_with, inside, off_foot, same_column}; use crate::testing::{Fixture, Frames, trial}; use crate::text::TextField; +use craft_quit::{CloseAnswer, CloseScope}; use egui::{Key, Modifiers, Rect, Ui}; -use std::cell::Cell; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::time::Duration; #[trial] fn escape_closes_a_cancellable_overlay_with_nothing_to_focus() { @@ -248,6 +255,82 @@ fn a_dialog_opens_on_its_first_field_else_its_default_button() { assert_eq!(focus_on_open(false, false), None, "without either nothing takes it"); } +/// A dialog host showing `dialog` in a fixture, once the dialog settled. +fn hosted(dialog: D) -> (Rc>, Fixture) { + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + host.borrow_mut().open(dialog); + fixture.idle(30); + (host, fixture) +} + +/// The choice a hosted `prompt` answers to `key`; Cancel when the host reports the dialog cancelled. +fn prompt_answer_to(prompt: StandardPrompt, key: Key) -> Option { + let (host, mut fixture) = hosted(prompt); + fixture.key(key, Modifiers::NONE).idle(2); + let result = host.borrow_mut().take::(); + result.map(|result| match result { + DialogResult::Ok(answer) => answer.choice, + DialogResult::Cancel => PromptChoice::Cancel, + }) +} + +/// A prompt asking to open a link: Open (Proceed) and Cancel. +fn link_prompt() -> StandardPrompt { + StandardPrompt::custom("Open the link “https://example.com”?").button(PromptChoice::Proceed, "Open").button(PromptChoice::Cancel, "Cancel") +} + +#[trial] +fn enter_answers_a_prompts_chosen_default() { + let safe = || link_prompt().default_choice(PromptChoice::Cancel); + assert_eq!(prompt_answer_to(safe(), Key::Enter), Some(PromptChoice::Cancel), "Enter answers the chosen default, so it opens no link"); + assert_eq!(prompt_answer_to(safe(), Key::Escape), Some(PromptChoice::Cancel), "Escape still cancels"); + assert_eq!(prompt_answer_to(link_prompt(), Key::Enter), Some(PromptChoice::Proceed), "without a chosen default Enter proceeds"); + let missing = link_prompt().default_choice(PromptChoice::Alternate); + assert_eq!(prompt_answer_to(missing, Key::Enter), Some(PromptChoice::Proceed), "a default with no button leaves Proceed the default"); +} + +/// Shows `dialog` on a dialog host, ticks its "Apply to All" box when `tick` and the box shows, and presses the first +/// button of `accept` that is shown. Whether the box showed, and the host's result. +fn ticked_and_accepted(dialog: D, tick: bool, accept: &[&str]) -> (bool, Option>) { + let (host, mut fixture) = hosted(dialog); + let offered = fixture.by_label("Apply to All"); + if let (true, Some(apply)) = (tick, &offered) { + fixture.click(apply).idle(2); + } + let button = accept.iter().find_map(|label| fixture.by_label(label)).expect("the accepting button is shown"); + fixture.click(&button).idle(2); + let result = host.borrow_mut().take::(); + (offered.is_some(), result) +} + +#[trial] +fn apply_to_all_shows_only_with_several_documents_and_rides_the_answer() { + // Save on macOS, Yes elsewhere. + let save = ["Save", "Yes"]; + let unsaved = |remaining: usize, tick: bool| { + let (offered, result) = ticked_and_accepted(UnsavedChangesDialog::new(CloseScope::Close, "poster.pdf").remaining(remaining), tick, &save); + match result { + Some(DialogResult::Ok(answer)) => (offered, answer.answer, answer.apply_to_all), + other => panic!("the dialog answers Save: {other:?}"), + } + }; + assert_eq!(unsaved(1, true), (false, CloseAnswer::Save, false), "one document: no box, and the answer applies to it alone"); + assert_eq!(unsaved(3, true), (true, CloseAnswer::Save, true), "several documents: the ticked box rides the answer"); + assert_eq!(unsaved(3, false), (true, CloseAnswer::Save, false), "an unticked box leaves the answer to this document"); + let recovery = |remaining: usize, tick: bool| { + let document = RecoveredDocument::new("poster", "poster.pdf", Duration::from_secs(300)); + let (offered, result) = ticked_and_accepted(RecoveryDialog::new(document).remaining(remaining), tick, &["Recover"]); + match result { + Some(DialogResult::Ok(choice)) => (offered, choice.answer, choice.apply_to_all), + other => panic!("the dialog answers Recover: {other:?}"), + } + }; + assert_eq!(recovery(1, true), (false, RecoveryAnswer::Recover, false), "one document: no box"); + assert_eq!(recovery(3, true), (true, RecoveryAnswer::Recover, true), "several documents: the ticked box rides the answer"); +} + /// A progress overlay shows a spinner beside its message on its card, is named by the message, and its Cancel makes /// Escape close it. #[trial] diff --git a/crates/ui-panels/src/dialog/unsaved.rs b/crates/ui-panels/src/dialog/unsaved.rs index 5196a3bf1..8755fa0ec 100644 --- a/crates/ui-panels/src/dialog/unsaved.rs +++ b/crates/ui-panels/src/dialog/unsaved.rs @@ -2,16 +2,14 @@ //! `Prompt`. use super::host::{DialogResult, FieldRefusal, StackDialog}; -use super::prompt::{Prompt, Reply, buttons}; +use super::prompt::{Prompt, Reply, apply_to_all, buttons}; use super::stack::{DialogId, DialogStack, dialog_id}; use super::words::DialogWords; -use crate::choice::Checkbox; -use crate::contract::{Bind, NoValue, Outcome, Props as _, Show as _}; +use crate::contract::{Bind, NoValue, Outcome}; use crate::runtime::env::{Env, Label}; use crate::runtime::overlay::CloseReason; use crate::runtime::words::CommonWords; use crate::sections::DialogRole; -use craft_behavior::Mixed; use craft_host::target::Os; use craft_keymap::{Chord, Key, Mods}; use craft_quit::{CloseAnswer, CloseScope}; @@ -148,16 +146,7 @@ impl UnsavedChangesDialog { let mut prompt = Prompt::new(words.unsaved_title.clone(), message).answers(buttons(&env, replies)); let mut ticked = hosted && self.apply_to_all; if self.offers_apply_to_all() { - let label = words.unsaved_apply_to_all.clone(); - let tick = &mut ticked; - let mut value = hosted.then_some(&mut self.apply_to_all); - prompt = prompt.extras(move |ui| { - if let Some(Mixed::Same(shown)) = - Checkbox::new(value.as_mut().map_or_else(Bind::kept, |value| Bind::bound(&mut **value))).label(label.clone()).show(ui).shown - { - *tick = *shown; - } - }); + prompt = apply_to_all(prompt, words.unsaved_apply_to_all.clone(), self.remaining, hosted.then_some(&mut self.apply_to_all), &mut ticked); } if hosted { prompt = prompt.opened(Bind::bound(&mut self.open)); diff --git a/crates/ui-patterns/src/patterns/form_dialogs/password.rs b/crates/ui-patterns/src/patterns/form_dialogs/password.rs index 0fec3c3ae..439d29bf0 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/password.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/password.rs @@ -1,9 +1,9 @@ //! `PasswordDialog`: the password for a protected file, a permissions password, or a new password with its strength. use crate::buttons::ToggleButton; -use crate::contract::{Bind, NoValue, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; +use crate::contract::{Bind, BodyCx, NoValue, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; use crate::dialog::{Dialog, DialogOutput}; -use crate::display::{Icon, Progress, Text}; +use crate::display::{Icon, Progress, Shade, Text}; use crate::form::{Field, FieldGroup, Help}; use crate::layout_components::{Row, Stack}; use crate::primitives::IconSpec; @@ -49,6 +49,11 @@ craft_ui::words! { medium: "passwordDialog.medium" = "Medium"; strong: "passwordDialog.strong" = "Strong"; wrong: "passwordDialog.wrong" = "That password is not correct."; + open_several: count "passwordDialog.openSeveral" = + "{n} file is protected. Enter a password to open it." | "{n} files are protected. Enter a password to open them."; + permissions_several: count "passwordDialog.permissionsSeveral" = + "{n} file has security restrictions. Enter its permissions password to lift them." + | "{n} files have security restrictions. Enter their permissions password to lift them."; } } @@ -167,14 +172,12 @@ impl PasswordPurpose { /// The purpose of opening `count` files with one password. pub fn open_several(count: usize) -> Self { - let _ = count; - todo!("WF-W13") + PasswordPurpose::Open { files: PasswordFiles::Several(count) } } /// The purpose of lifting the restrictions of `count` files with one password. pub fn permissions_several(count: usize) -> Self { - let _ = count; - todo!("WF-W13") + PasswordPurpose::Permissions { files: PasswordFiles::Several(count) } } } @@ -240,6 +243,14 @@ pub struct PasswordFieldsOutput { pub valid: bool, } +impl Outcome for PasswordFieldsOutput { + type Value = NoValue; + + fn response(&self) -> &Response { + &self.response + } +} + /// The password fields: the masked field with the reveal toggle that hands the focus back, the Re-type field with the /// mismatch help, the strength help and meter, and an error line. #[must_use = "show the fields with `show`"] @@ -271,27 +282,104 @@ impl<'a> PasswordFields<'a> { self } - /// Shows the fields. + /// Shows the fields. With a confirmation field the first one takes the strength help once something is typed, + /// else the error line; without one, the error line. pub fn show(self, ui: &mut Ui) -> PasswordFieldsOutput { - let PasswordFields { label, input, confirm, error } = self; - let _ = (ui, label, input, confirm, error); - todo!("DG-C15") + let PasswordFields { label, mut input, mut confirm, error } = self; + let env = Env::of(ui); + let words = env.words::(); + let mut valid = false; + let shown = Stack::new().show(ui, |ui, cx| { + let mut revealed = cx.memory::().0; + let typed = bound_text(&mut input, cx); + let retyped = confirm.as_mut().map(|confirm| bound_text(confirm, cx)); + let strength = (retyped.is_some() && !typed.is_empty()).then(|| PasswordStrength::of(&typed)); + FieldGroup::new(words.fields.clone()).show(ui, |ui, _| { + let mut field = Field::new(label.clone()); + if let Some(strength) = strength { + let (word, tone) = match strength { + PasswordStrength::Weak => (&words.weak, Tone::Bad), + PasswordStrength::Medium => (&words.medium, Tone::Warn), + PasswordStrength::Strong => (&words.strong, Tone::Good), + }; + field = field.help(Help::Status(tone, Label::from(words.strength.fill(&[("strength", word.as_str())])))); + } else if let Some(error) = &error { + field = field.help(Help::Status(Tone::Bad, error.clone())); + } + field.show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + let mut text = TextField::new(label.clone(), input.reborrowed()); + if !revealed { + text = text.masked(); + } + let text = text.show(ui); + let name = if revealed { words.hide.clone() } else { words.show.clone() }; + let reveal = ToggleButton::new(name, Bind::bound(&mut revealed)) + .icon(IconId::new("eye")) + .on_icon(IconId::new("eye_off")) + .icon_only() + .show(ui); + // Typing goes on in the field: the reveal button hands the focus back, as does a press that left + // nothing focused. + if clicked(reveal.response()) || focus::focused_rec(ui.ctx()).is_none() { + focus::request(ui.ctx(), FocusTarget::Id(text.response().id)); + } + }); + }); + if let (Some(confirm), Some(retyped)) = (confirm.as_mut(), &retyped) { + let mismatch = (!retyped.is_empty() && typed != *retyped).then(|| words.mismatch.clone()); + let mut field = Field::new(words.retype_password.clone()); + if let Some(mismatch) = mismatch { + field = field.help(Help::Status(Tone::Bad, mismatch)); + } + field.show(ui, |ui, _| { + let mut text = TextField::new(words.retype_password.clone(), confirm.reborrowed()); + if !revealed { + text = text.masked(); + } + text.show(ui); + }); + } + }); + if let Some(strength) = strength { + let (filled, variant) = match strength { + PasswordStrength::Weak => (1.0 / 3.0, Variant::DANGER), + PasswordStrength::Medium => (2.0 / 3.0, Variant::look(Emphasis::Solid, Tone::Warn)), + PasswordStrength::Strong => (1.0, Variant::look(Emphasis::Solid, Tone::Good)), + }; + Progress::new(filled).variant(variant).label(words.strength_meter.clone()).show(ui); + } + // The entries after this pass's edits: a bound or kept entry holds them now. + let typed = bound_text(&mut input, cx); + let retyped = confirm.as_mut().map(|confirm| bound_text(confirm, cx)); + valid = entries_valid(&typed, retyped.as_deref()); + *cx.memory::() = Revealed(revealed); + }); + PasswordFieldsOutput { response: shown.output, valid } } } -/// What the dialog keeps while it is open: the entries and whether they show as text. +/// Whether the fields show their text, kept per [`PasswordFields`]. +#[derive(Clone, Copy, Default)] +struct Revealed(bool); + +/// The text `bind` holds this pass; empty while a kept binding holds nothing. +fn bound_text(bind: &mut Bind<'_, String>, cx: &mut BodyCx<'_>) -> String { + bind.reborrow().read(cx).and_then(|value| value.same().cloned()).unwrap_or_default() +} + +/// Whether password entries may be accepted: with a confirmation, a non-empty entry that the confirmation repeats. +fn entries_valid(input: &str, confirm: Option<&str>) -> bool { + confirm.is_none_or(|confirm| !input.is_empty() && input == confirm) +} + +/// What the dialog keeps while it is open: the entries and whether the fields found them valid after the last pass. #[derive(Clone, Default)] struct Entries { input: String, confirm: String, - reveal: bool, -} - -impl Entries { - /// Whether OK may be pressed: a new password needs a non-empty entry that its confirmation repeats. - fn valid(&self, setting: bool) -> bool { - !setting || (!self.input.is_empty() && self.input == self.confirm) - } + /// The fields' verdict; `None` before the first pass, when only a dialog that asks no confirmation may be accepted. + valid: Option, } /// A question with a lock icon, the message, the masked field and the buttons. A new password adds a confirmation @@ -320,15 +408,6 @@ pub struct PasswordDialog<'a> { open: Option>, } -/// The name of the one file `files` holds; a count of several files has the plural message instead. -fn single_name(files: &PasswordFiles) -> &str { - // P3(pdf-dialogs-w2): WF-W13 — the writer words the several-files message. - match files { - PasswordFiles::One(name) => name.as_str(), - PasswordFiles::Several(_) => todo!("WF-W13"), - } -} - impl<'a> PasswordDialog<'a> { /// A dialog for `purpose`, with no error line and no tag. pub fn new(purpose: PasswordPurpose) -> Self { @@ -338,27 +417,39 @@ impl<'a> PasswordDialog<'a> { /// Shows the dialog. pub fn show(self, ui: &mut Ui) -> PasswordOutput { let PasswordDialog { purpose, tag, error, note, open } = self; - let _ = note; // P3(pdf-dialogs-w2): WF-W13 let env = Env::of(ui); let words = env.words::(); let common = env.words::(); let setting = matches!(purpose, PasswordPurpose::Set); + let counted = |count: usize| (count as u64, env.format().integer(count as u64)); let (title, message, ok) = match &purpose { PasswordPurpose::Open { files } => { - (words.open_title.clone(), Some(Label::from(words.open_message.fill(&[("name", single_name(files))]))), words.open.clone()) + let message = match files { + PasswordFiles::One(name) => words.open_message.fill(&[("name", name.as_str())]), + PasswordFiles::Several(count) => { + let (n, digits) = counted(*count); + words.open_several.text(n, &digits) + } + }; + (words.open_title.clone(), Some(Label::from(message)), words.open.clone()) + } + PasswordPurpose::Permissions { files } => { + let message = match files { + PasswordFiles::One(name) => words.permissions_message.fill(&[("name", name.as_str())]), + PasswordFiles::Several(count) => { + let (n, digits) = counted(*count); + words.permissions_several.text(n, &digits) + } + }; + (words.permissions_title.clone(), Some(Label::from(message)), words.unlock.clone()) } - PasswordPurpose::Permissions { files } => ( - words.permissions_title.clone(), - Some(Label::from(words.permissions_message.fill(&[("name", single_name(files))]))), - words.unlock.clone(), - ), PasswordPurpose::Set => (words.set_title.clone(), None, common.ok.clone()), }; let mut dialog = Dialog::new(title) .buttons([FooterButton::new(ok, DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]) - .close_guard(move |_, cx| cx.memory::().valid(setting)) + .close_guard(move |_, cx| cx.memory::().valid.unwrap_or(!setting)) .settle_buttons(move |cx, buttons| { - let valid = cx.memory::().valid(setting); + let valid = cx.memory::().valid.unwrap_or(!setting); if let Some(accept) = buttons.first_mut() { accept.set_enabled(valid); } @@ -377,65 +468,19 @@ impl<'a> PasswordDialog<'a> { Text::new(message.clone()).show(ui); }); } - let strength = (setting && !entries.input.is_empty()).then(|| PasswordStrength::of(&entries.input)); - FieldGroup::new(words.fields.clone()).show(ui, |ui, _| { - let first = if setting { words.type_password.clone() } else { words.password.clone() }; - let mut field = Field::new(first.clone()); - if let Some(strength) = strength { - let (word, tone) = match strength { - PasswordStrength::Weak => (&words.weak, Tone::Bad), - PasswordStrength::Medium => (&words.medium, Tone::Warn), - PasswordStrength::Strong => (&words.strong, Tone::Good), - }; - field = field.help(Help::Status(tone, Label::from(words.strength.fill(&[("strength", word.as_str())])))); - } else if let (false, Some(error)) = (setting, &error) { - field = field.help(Help::Status(Tone::Bad, error.clone())); - } - field.show(ui, |ui, _| { - Row::new().show(ui, |ui, _| { - let mut text = TextField::new(first.clone(), Bind::bound(&mut entries.input)); - if !entries.reveal { - text = text.masked(); - } - let text = text.show(ui); - let name = if entries.reveal { words.hide.clone() } else { words.show.clone() }; - let reveal = ToggleButton::new(name, Bind::bound(&mut entries.reveal)) - .icon(IconId::new("eye")) - .on_icon(IconId::new("eye_off")) - .icon_only() - .show(ui); - // Typing goes on in the field: the reveal button hands the focus back, as does a press that left - // nothing focused. - if clicked(reveal.response()) || focus::focused_rec(ui.ctx()).is_none() { - focus::request(ui.ctx(), FocusTarget::Id(text.response().id)); - } - }); - }); - if setting { - let mismatch = (!entries.confirm.is_empty() && entries.input != entries.confirm).then(|| words.mismatch.clone()); - let mut confirm = Field::new(words.retype_password.clone()); - if let Some(mismatch) = mismatch { - confirm = confirm.help(Help::Status(Tone::Bad, mismatch)); - } - confirm.show(ui, |ui, _| { - let mut text = TextField::new(words.retype_password.clone(), Bind::bound(&mut entries.confirm)); - if !entries.reveal { - text = text.masked(); - } - text.show(ui); - }); - } - }); - if let Some(strength) = strength { - let (filled, variant) = match strength { - PasswordStrength::Weak => (1.0 / 3.0, Variant::DANGER), - PasswordStrength::Medium => (2.0 / 3.0, Variant::look(Emphasis::Solid, Tone::Warn)), - PasswordStrength::Strong => (1.0, Variant::look(Emphasis::Solid, Tone::Good)), - }; - Progress::new(filled).variant(variant).label(words.strength_meter.clone()).show(ui); + if let Some(note) = ¬e { + Text::new(note.clone()).shade(Shade::Muted).show(ui); } + let first = if setting { words.type_password.clone() } else { words.password.clone() }; + // A new password has no wrong-password line: its first field shows the strength instead. + let mut fields = PasswordFields::new(first, Bind::bound(&mut entries.input)).error(if setting { None } else { error.clone() }); + if setting { + fields = fields.confirm(Bind::bound(&mut entries.confirm)); + } + let shown = fields.show(ui); + valid.set(shown.valid); + entries.valid = Some(shown.valid); }); - valid.set(entries.valid(setting)); *typed.borrow_mut() = entries.input.clone(); *cx.memory::() = entries; }); diff --git a/crates/ui-patterns/src/patterns/form_dialogs/password/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/password/stories.rs index 3f7c0fed2..1039a97df 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/password/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/password/stories.rs @@ -1,6 +1,6 @@ -//! Stories of `PasswordDialog`. +//! Stories of `PasswordDialog` and `PasswordFields`. -use super::{PasswordDialog, PasswordPurpose}; +use super::{PasswordDialog, PasswordFields, PasswordPurpose}; use crate::contract::Bind; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -28,3 +28,35 @@ fn password_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn password_dialog_new_password(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { PasswordDialog::new(PasswordPurpose::Set).opened(Bind::bound(data.value("open", true))).show(ui).into() } + +#[story(PasswordDialog<'static>, covers = [], drive = Drive::Never)] +fn password_dialog_several(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let asks = *data.choice("purpose", Asks::Open, &[("Open", Asks::Open), ("Permissions", Asks::Permissions)]); + let purpose = match asks { + Asks::Open => PasswordPurpose::open_several(3), + Asks::Permissions => PasswordPurpose::permissions_several(3), + }; + PasswordDialog::new(purpose) + .note("The files share one password.") + .opened(Bind::bound(data.value("open", true))) + .show(ui) + .into() +} + +#[story(PasswordFields<'static>, covers = [], drive = Drive::Never)] +fn password_fields(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let wrong = *data.value("wrong password", false); + let input = data.value("input", String::new()); + let error = wrong.then_some(crate::runtime::env::Label::Static("That password is not correct.")); + PasswordFields::new("Password", Bind::bound(input)).error(error).show(ui).into() +} + +#[story(PasswordFields<'static>, covers = [], drive = Drive::Never)] +fn password_fields_new_password(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut input = data.value("input", String::new()).clone(); + let mut confirm = data.value("confirm", String::new()).clone(); + let shown = PasswordFields::new("Type Password", Bind::bound(&mut input)).confirm(Bind::bound(&mut confirm)).show(ui); + *data.value("input", String::new()) = input; + *data.value("confirm", String::new()) = confirm; + shown.into() +} diff --git a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs index 62d48c5dd..66d887e2b 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs @@ -4,7 +4,7 @@ use crate::buttons::IconButton; use crate::contract::{ Bind, Common, Component, Cx, DisabledLook, Focus as _, Input, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, - Show as _, ShowContainer as _, + Show as _, ShowContainer as _, Styled as _, }; use crate::display::{Progress, Text}; use crate::layout_components::Row; @@ -17,8 +17,9 @@ use crate::text::NumberField; use craft_behavior::{ AccessAction, AccessData, CanvasTransform, CursorIcon, CursorPriority, IconId, Metrics, NavMove, PartKey, PointerButton, PressPhase, Sense, }; + use egui::load::SizedTexture; -use egui::{Pos2, Rect, Response, Ui, Vec2, pos2}; +use egui::{Mesh, Pos2, Rect, Response, Shape, Ui, Vec2, pos2}; use std::ops::RangeInclusive; #[cfg(feature = "testing")] @@ -287,7 +288,6 @@ pub struct PreviewPane<'a> { overlay: Option>, /// Multiplies the `Ready` picture's colours, as `ThumbPaint::tint` does. #[prop] - #[allow(dead_code)] // P3(pdf-dialogs-w2): DG-C12 tint: Option, /// Whether the picture overflows the well horizontally, and vertically. Set by `parts`, which runs before the /// root's sense is read: the wheel scrolls the pane only on an axis it pans on. @@ -583,7 +583,15 @@ impl Component for PreviewPane<'_> { pos2((visible.min.x - picture.min.x) / size.x, (visible.min.y - picture.min.y) / size.y), pos2((visible.max.x - picture.min.x) / size.x, (visible.max.y - picture.min.y) / size.y), ); - painter.picture(texture.id, visible, uv, 0.0); + match self.tint { + // The tint multiplies the mesh's vertex colours; as data, a Disabled pane still dims it. + Some(tint) => { + let mut mesh = Mesh::with_texture(texture.id); + mesh.add_rect_with_uv(visible, uv, tint.0); + painter.data_shapes([Shape::mesh(mesh)]); + } + None => painter.picture(texture.id, visible, uv, 0.0), + } } if let Some(PaneOverlay(overlay)) = self.overlay.take() { overlay(&painter, view, picture); @@ -731,13 +739,46 @@ pub struct PanePager { impl PanePager { /// The caption: "Page {p} of {n}" or "Sheet {p} of {n}", or "No pages" or "No sheets" when `count` is 0. pub fn caption(&self, env: &Env) -> Label { - let _ = env; - todo!("DG-C10") + let words = env.words::(); + if self.count == 0 { + return match self.unit { + PagerUnit::Page => words.no_pages.clone(), + PagerUnit::Sheet => words.no_sheets.clone(), + }; + } + let shown = match &self.shown_label { + Some(label) => label.as_str().to_owned(), + None => env.format().integer(self.shown as u64), + }; + let count = env.format().integer(self.count as u64); + let template = match self.unit { + PagerUnit::Page => &words.page_of, + PagerUnit::Sheet => &words.sheet_of, + }; + Label::from(template.fill(&[("p", &shown), ("n", &count)])) } - /// Shows the row; the step a press made in this pass. + /// Shows the row; the step a press made in this pass. A second pass of a frame finds no press, so a step is + /// reported once. pub fn show(self, ui: &mut Ui) -> Option { - let _ = ui; - todo!("DG-C10") + let env = Env::of(ui); + let words = env.words::(); + let caption = self.caption(&env); + let mut step = None; + Row::new().show(ui, |ui, _| { + let back = IconButton::new(IconId::new("chevron_left")).label(words.previous.clone()).enabled(self.back).show(ui); + // An empty pager has no position to report: its caption says so. + let text = Text::new(caption); + if self.count > 0 { text.numeric(self.shown as f64) } else { text }.show(ui); + let next = IconButton::new(IconId::new("chevron_right")).label(words.next.clone()).enabled(self.next).show(ui); + if crate::contract::clicked(&back) { + step = Some(PagerStep::Back); + } + if crate::contract::clicked(&next) { + step = Some(PagerStep::Next); + } + }); + step } } + diff --git a/crates/ui-patterns/src/patterns/form_dialogs/preview/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/preview/stories.rs index 68a6079b4..459f1c3f4 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/preview/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/preview/stories.rs @@ -1,8 +1,10 @@ -//! Stories of `PreviewPane` and `PreviewZoom`. +//! Stories of `PreviewPane`, `PreviewZoom` and `PanePager`. -use super::{PreviewPane, PreviewState, PreviewView, PreviewZoom, WELL}; -use crate::contract::Show as _; +use super::{PagerStep, PagerUnit, PanePager, PreviewPane, PreviewState, PreviewView, PreviewZoom, WELL}; +use crate::contract::{Show as _, ShowContainer as _}; +use crate::layout_components::Row; use crate::primitives::TextureCache; +use crate::style::DataColor; use crate::testing::{Drive, Grip, StoryData, StoryOutput, story}; use egui::load::SizedTexture; use egui::{Color32, ColorImage, Ui, Vec2}; @@ -53,6 +55,43 @@ fn preview_pane_failed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { PreviewPane::state("Preview", PreviewState::Failed("The preview could not be rendered.".into()), view).show(ui).into() } +#[story(PreviewPane<'static>, covers = [], drive = Drive::Never)] +fn preview_pane_tint(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let view = data.value("view", PreviewView::fitting()); + let tint = DataColor::new(Color32::from_rgb(0xff, 0xc0, 0x80)); + PreviewPane::state("Preview", PreviewState::Ready(picture(ui)), view).tint(tint).show(ui).into() +} + +/// A pager of `count` units that steps the shown one it keeps in `data`. +fn pager(ui: &mut Ui, data: &mut StoryData, count: usize, unit: PagerUnit) -> StoryOutput { + let shown = data.value("shown", count.min(1)); + Row::new() + .show(ui, |ui, _| { + let pager = PanePager { shown: *shown, count, back: *shown > 1, next: *shown < count, unit, ..PanePager::default() }; + match pager.show(ui) { + Some(PagerStep::Back) => *shown -= 1, + Some(PagerStep::Next) => *shown += 1, + None => {} + } + }) + .into() +} + +#[story(PanePager, covers = [], drive = Drive::Never)] +fn pane_pager(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + pager(ui, data, 12, PagerUnit::Page) +} + +#[story(PanePager, covers = [], drive = Drive::Never)] +fn pane_pager_sheets(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + pager(ui, data, 3, PagerUnit::Sheet) +} + +#[story(PanePager, covers = [], drive = Drive::Never)] +fn pane_pager_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + pager(ui, data, 0, PagerUnit::Page) +} + #[story(PreviewPane<'static>, covers = [], drive = Drive::Drag(Grip::new(WELL)))] fn preview_pane_fit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let view = data.value("view", PreviewView::fitting().zoom_range(0.01..=32.0)); diff --git a/crates/ui-patterns/tests/it/form_dialogs/password.rs b/crates/ui-patterns/tests/it/form_dialogs/password.rs index 879563c88..b7b00dd27 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/password.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/password.rs @@ -1,4 +1,4 @@ -//! The password dialog keeps the keyboard in its field. +//! The password dialog keeps the keyboard in its field and rates a new password as it is typed. use craft_ui::patterns::form_dialogs::{PasswordDialog, PasswordPurpose}; use craft_ui::testing::{Fixture, trial}; @@ -20,3 +20,32 @@ fn the_reveal_button_hands_the_focus_back_to_the_field() { assert!(fixture.by_label("Hide password").is_some(), "the press revealed the text"); assert!(focused_on(&fixture, "Password"), "the field has the focus back, so typing goes on"); } + +/// The strength meter's fill and the top of its range: the fill grows with the rating and Strong reaches the top. +fn meter(fixture: &Fixture) -> (f64, f64) { + let meter = fixture.by_label("Password strength").expect("the strength meter shows once something is typed"); + let numeric = fixture.tree().numeric_of(meter.node).expect("the meter reports how full it is"); + (numeric.value.expect("the meter reports how full it is"), *numeric.range.end()) +} + +#[trial] +fn a_password_is_rated_by_its_length_and_its_character_classes() { + let mut fixture = Fixture::new(|ui| { + let _ = PasswordDialog::new(PasswordPurpose::Set).show(ui); + }); + fixture.idle(30); + assert!(focused_on(&fixture, "Type Password"), "the dialog opens on the first field"); + assert!(fixture.by_label("Password strength").is_none(), "an empty field has no rating"); + // Each step adds characters, so the text only grows longer and gains classes. + fixture.type_text("abc").idle(2); + let (short, top) = meter(&fixture); + assert!(short < top, "three lower-case letters are not the top rating"); + fixture.type_text("DEFGH").idle(2); + let (mixed, _) = meter(&fixture); + assert!(mixed >= short, "eight characters over two classes rate no lower than three over one"); + fixture.type_text("12!x").idle(2); + let (long, _) = meter(&fixture); + assert!(long >= mixed, "more length and classes never lower the rating"); + assert!(long >= top, "twelve characters over three classes fill the meter"); + assert!(short < long, "the rating rose from weak to strong"); +} diff --git a/crates/ui-widgets/src/display/text.rs b/crates/ui-widgets/src/display/text.rs index 666161ab6..540e802db 100644 --- a/crates/ui-widgets/src/display/text.rs +++ b/crates/ui-widgets/src/display/text.rs @@ -2,6 +2,7 @@ use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Styled as _}; use crate::primitives::{DocRun, DocText, Span, TextRun, Wrap}; +use crate::runtime::access::{Access, Numeric}; use crate::runtime::env::Label; use crate::style::{ComponentStyle, StyleCx, TextLook, TypeRole}; use craft_behavior::{Metrics, Proposal, Sense}; @@ -78,12 +79,14 @@ pub struct Text { spans: Vec>, /// The label's text is set in italics. italic: bool, + /// The number the text stands for, reported to assistive technology next to the text. + numeric: Option, } impl Text { /// `text`, which is also its accessible name, in body type and the normal shade. pub fn new(text: impl Into