From 76e79d59b0fe3ba506b74d4909e14a014a4a96a2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 20 Nov 2026 10:42:24 -0500 Subject: [PATCH] Framework fwb11-c: port follow-ups (see runs/fwb11-c.md) --- crates/pages/src/ui/range.rs | 1 - crates/pages/tests/it/range.rs | 20 ++++++++ crates/ui-contract/src/contract/cx/measure.rs | 5 ++ crates/ui-contract/src/primitives/text.rs | 13 ++++- crates/ui-panels/tests/it/dialogs.rs | 28 +++++++++++ .../src/patterns/preferences/mod.rs | 2 +- .../src/patterns/preferences/window.rs | 36 ++++++++++++-- .../patterns/preferences/window/stories.rs | 25 +++++++++- .../ui-patterns/tests/it/preferences/live.rs | 48 +++++++++++++++++++ .../ui-patterns/tests/it/preferences/mod.rs | 1 + crates/ui-widgets/src/display/text.rs | 5 +- crates/ui-widgets/tests/it/table.rs | 29 +++++++++++ 12 files changed, 201 insertions(+), 12 deletions(-) create mode 100644 crates/ui-patterns/tests/it/preferences/live.rs diff --git a/crates/pages/src/ui/range.rs b/crates/pages/src/ui/range.rs index dbf9cc322..3a0d028c4 100644 --- a/crates/pages/src/ui/range.rs +++ b/crates/pages/src/ui/range.rs @@ -373,7 +373,6 @@ impl PageRangeOptions { } if let Some(value) = to { next.to = Some(value); - next.from = next.from.min(value); } if choices.subset() { let entries = [ diff --git a/crates/pages/tests/it/range.rs b/crates/pages/tests/it/range.rs index 0754cee65..6d6425f0e 100644 --- a/crates/pages/tests/it/range.rs +++ b/crates/pages/tests/it/range.rs @@ -76,3 +76,23 @@ fn a_page_range_row_keeps_its_range_as_json_and_reads_it_back() { fixture.settle(); assert_eq!(PageRangeOptions::value(&values.borrow(), "pages"), None, "a value that is not a range reads as none"); } + +/// Editing the end of a range must not silently rewrite its start, even when the range is temporarily reversed. +#[trial] +fn editing_to_preserves_from() { + let values = Rc::new(RefCell::new(DialogFields::from_pairs([( + "pages", + PageRangeOptions::field_value(&PageRange { scope: PageScope::Range, from: 8, to: Some(12), subset: Subset::All }), + )]))); + let shown = values.clone(); + let rows = page_range_row(); + let mut fixture = Fixture::new(move |ui| { + let _ = ParamRows::new("Form", &rows, Bind::bound(&mut *shown.borrow_mut())).show(ui); + }); + fixture.settle(); + let to = fixture.by_label("to").expect("the To field"); + fixture.click(&to).key(Key::A, Modifiers::COMMAND).type_text("5").key(Key::Enter, Modifiers::NONE).settle(); + let range = PageRangeOptions::value(&values.borrow(), "pages").expect("the range"); + assert_eq!(range.from, 8, "changing To must preserve From"); + assert_eq!(range.to, Some(5)); +} diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index d6ee47c52..a07d090aa 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -44,6 +44,11 @@ impl<'a, C: Component> MeasureCx<'a, C> { } impl MeasureCx<'_, C> { + /// The enclosing container's reading-width cap, if it sets one. + pub fn wrap_limit(&self) -> Option { + self.env.measure() + } + /// The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component. pub fn command(&self) -> Option<&ResolvedCommand> { self.resolved.command diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 210c94edb..d34cdc73f 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -222,7 +222,18 @@ impl TextRun<'_> { // readable characters. let galley = match self.wrap { Wrap::Elide | Wrap::ElideStart | Wrap::ElideMiddle | Wrap::ElidePath => self.layout_cut(ctx, env, &full, max_width), - _ => text_layout::layout(ctx, self.job(env, self.spans.iter().map(|s| (s, s.text.as_ref())), max_width)), + _ => { + let job = self.job(env, self.spans.iter().map(|s| (s, s.text.as_ref())), max_width); + let galley = text_layout::layout(ctx, job.clone()); + if matches!(self.wrap, Wrap::Wrap | Wrap::Clamp(_)) && galley.size().x > max_width { + // A single unbroken word can be wider than the room even after word wrapping. + let mut job = job; + job.wrap.break_anywhere = true; + text_layout::layout(ctx, job) + } else { + galley + } + } }; let elided = galley.elided || self.wrap.cuts() && galley.job.text != full; let mut layout = TextLayout::new(aligned_rows(galley, self.align, self.is_rtl(env), ctx.pixels_per_point()), elided, full); diff --git a/crates/ui-panels/tests/it/dialogs.rs b/crates/ui-panels/tests/it/dialogs.rs index 04e9adf7a..a6b7b8cb1 100644 --- a/crates/ui-panels/tests/it/dialogs.rs +++ b/crates/ui-panels/tests/it/dialogs.rs @@ -250,6 +250,19 @@ fn the_run_shows_each_dialog_once_per_pass() { assert!(over.top && !below.top, "the child over its parent is on top"); } +/// A real child dialog must be visible and accessible over its hosted parent. +#[trial] +fn a_hosted_child_dialog_is_visible() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = running(&host); + let parent = host.borrow_mut().open(SelfClosing); + fixture.idle(6); + host.borrow_mut().open_child(HostedAlert::new(Alert::new("Child notice", "Child message")), parent); + fixture.idle(6); + assert!(fixture.by_label("Child notice").is_some(), "the child is accessible"); + assert!(fixture.texts().iter().any(|text| text.text == "Child message"), "the child is painted"); +} + /// The startup queue opens its modals one at a time, in stage order, each once nothing else is open. #[trial] fn a_startup_modal_waits_for_the_open_dialogs_and_opens_in_stage_order() { @@ -315,6 +328,21 @@ fn the_platform_chords_answer_dont_save() { } } +/// A long document name must remain within the unsaved question's dialog. +#[trial] +fn unsaved_question_keeps_long_text_inside_its_dialog() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = running(&host); + fixture.room(vec2(820.0, 520.0)); + host.borrow_mut().open(UnsavedChangesDialog::new(CloseScope::Close, "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW.pdf")); + fixture.idle(6); + let dialog = fixture.by_role(Role::DIALOG).first().expect("the question").rect; + assert!(dialog.left() >= 0.0 && dialog.right() <= 820.0, "the question stays on screen: {dialog:?}"); + let runs = fixture.texts(); + let message = runs.iter().find(|run| run.text.contains("WWWWWWWW")).expect("the document name is painted"); + assert!(message.rect.left() >= dialog.left() && message.rect.right() <= dialog.right(), "message {:?} exceeds dialog {dialog:?}", message.rect); +} + /// Each open of a dialog has its own serial, kept while it stays open, though its id is the same at every open: a /// reopened dialog is told apart from the one cancelled before it. #[trial] diff --git a/crates/ui-patterns/src/patterns/preferences/mod.rs b/crates/ui-patterns/src/patterns/preferences/mod.rs index b1875f352..1aa86e7a2 100644 --- a/crates/ui-patterns/src/patterns/preferences/mod.rs +++ b/crates/ui-patterns/src/patterns/preferences/mod.rs @@ -31,4 +31,4 @@ mod window; pub use path_setting::{PathSetting, PathSettingOutput}; -pub use window::{DEFAULT_SIZE, MIN_SIZE, PreferencesState, PreferencesWindow}; +pub use window::{DEFAULT_SIZE, MIN_SIZE, PreferencesMode, PreferencesState, PreferencesWindow}; diff --git a/crates/ui-patterns/src/patterns/preferences/window.rs b/crates/ui-patterns/src/patterns/preferences/window.rs index ede32c779..09ec33c4d 100644 --- a/crates/ui-patterns/src/patterns/preferences/window.rs +++ b/crates/ui-patterns/src/patterns/preferences/window.rs @@ -27,6 +27,17 @@ pub const DEFAULT_SIZE: Vec2 = vec2(1040.0, 800.0); // design: allow[literal-siz /// The least size the window may be resized to. pub const MIN_SIZE: Vec2 = vec2(560.0, 400.0); // design: allow[literal-size/vec2](the window's own least size in points) +/// When preferences changes are applied. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum PreferencesMode { + /// Keep a draft until OK or Apply. + #[default] + Staged, + /// Apply changes as they happen; OK closes the window. + Live, +} + /// What the window keeps between passes; the host owns it and binds it with [`PreferencesWindow::new`]. #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] @@ -53,6 +64,8 @@ pub struct PreferencesState { /// - **Buttons.** OK applies and closes, Apply applies and stays (enabled while the draft differs), Cancel drops the /// draft. A failed apply keeps the window open and shows its message in the footer. Enter activates OK and Escape /// cancels, once the search text, a field's own gesture and a popup have had them. +/// - **Live mode.** [`PreferencesMode::Live`] applies changes as they occur and shows only OK, which closes without +/// applying again. Closing the window does not cancel changes. A failed apply shows its message until another edit. /// - **Nested dialogs.** While [`PreferencesModel::nested_open`] is true the window takes no input and refuses to /// close; [`PreferencesModel::nested`] draws the nested dialogs inside the window's own viewport. /// - **App-modal.** While the window is open the app's other windows take no input, show the blocked cursor and @@ -73,6 +86,7 @@ pub struct PreferencesWindow<'a> { /// Keeps the window's place and size across runs under `key`. #[prop] remember: Option, + mode: PreferencesMode, } /// What the body, the footer and the buttons' guard share during one pass: the host, the window's state as the pass @@ -130,12 +144,19 @@ impl Session<'_, '_, H> { impl<'a> PreferencesWindow<'a> { /// A window over the host's `state`. pub fn new(state: Bind<'a, PreferencesState>) -> Self { - PreferencesWindow { state, title: None, embedded: false, remember: None } + PreferencesWindow { state, title: None, embedded: false, remember: None, mode: PreferencesMode::Staged } + } + + /// Selects whether changes are staged or applied while the window is open. + #[must_use] + pub fn mode(mut self, mode: PreferencesMode) -> Self { + self.mode = mode; + self } /// Shows the window for this pass over `host`. The output's `closed` tells the host to stop showing it. pub fn show(self, ui: &mut Ui, host: &mut H) -> PreferencesOutput { - let PreferencesWindow { state, title, embedded, remember } = self; + let PreferencesWindow { state, title, embedded, remember, mode } = self; let env = Env::of(ui); let words = env.words::(); let common = env.words::(); @@ -150,7 +171,7 @@ impl<'a> PreferencesWindow<'a> { ok = ok.disabled_reason(words.cannot_ok.clone()); } let apply = FooterButton::new(words.apply.clone(), DialogRole::Other).enabled(differs).stays_open(true); - let buttons = [ok, apply, FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; + let buttons = if mode == PreferencesMode::Live { vec![ok] } else { vec![ok, apply, FooterButton::new(common.cancel.clone(), DialogRole::Cancel)] }; let mut open = true; // Filed by a swatch press in this pass. @@ -174,7 +195,7 @@ impl<'a> PreferencesWindow<'a> { session.borrow_mut().apply(cx); } }) - .close_guard(|button, cx| button.role() != DialogRole::Accept || session.borrow_mut().apply(cx)); + .close_guard(|button, cx| mode == PreferencesMode::Live || button.role() != DialogRole::Accept || session.borrow_mut().apply(cx)); if !embedded { dialog = dialog.viewport(); } @@ -215,6 +236,9 @@ impl<'a> PreferencesWindow<'a> { session.host.reset_page(&page.id); } session.host.nested(ui); + if mode == PreferencesMode::Live && session.work.error.is_none() && session.host.differs() { + session.apply(cx); + } session.page = snap.shown.map(|page| page.id); session.commit(cx); }); @@ -228,7 +252,9 @@ impl<'a> PreferencesWindow<'a> { match closed.filter(|_| !nested) { Some(CloseReason::Activated) => result.closed = Some(Closed::Ok), Some(_) => { - host.cancel(); + if mode == PreferencesMode::Staged { + host.cancel(); + } result.closed = Some(Closed::Cancel); } None => {} diff --git a/crates/ui-patterns/src/patterns/preferences/window/stories.rs b/crates/ui-patterns/src/patterns/preferences/window/stories.rs index 18d810e1c..9cc136859 100644 --- a/crates/ui-patterns/src/patterns/preferences/window/stories.rs +++ b/crates/ui-patterns/src/patterns/preferences/window/stories.rs @@ -1,7 +1,8 @@ //! Stories of `PreferencesWindow`. -use super::{PreferencesState, PreferencesWindow}; -use crate::contract::{Bind, Entry}; +use super::{PreferencesMode, PreferencesState, PreferencesWindow}; +use crate::buttons::Button; +use crate::contract::{Bind, Entry, Show as _, clicked}; use crate::patterns::preferences::{GroupSpec, PageSpec, PrefValue, PreferencesModel, RowKind, RowSpec}; use crate::runtime::env::UnitKind; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -158,3 +159,23 @@ fn preferences_window_with_error(ui: &mut Ui, data: &mut StoryData) -> StoryOutp PreferencesState { selected: "canvas".to_owned(), error: Some("The brush size can't be applied.".to_owned()), ..PreferencesState::default() }; window(ui, data, state, Demo { refuse: true, ..Demo::default() }) } + +/// Preferences that apply each edit immediately. +#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)] +fn preferences_window_live(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut open = *data.value("live_open", false); + if clicked(&Button::new("Open preferences").show(ui)) { + open = true; + } + let mut demo = data.value("live_demo", Demo::default()).clone(); + let mut result = StoryOutput::default(); + if open { + let state = data.value("live_state", PreferencesState::default()); + let shown = PreferencesWindow::new(Bind::bound(state)).mode(PreferencesMode::Live).embedded().show(ui, &mut demo); + open = shown.closed.is_none(); + result = shown.into(); + } + *data.value("live_open", false) = open; + *data.value("live_demo", Demo::default()) = demo; + result +} diff --git a/crates/ui-patterns/tests/it/preferences/live.rs b/crates/ui-patterns/tests/it/preferences/live.rs new file mode 100644 index 000000000..a26f40b9b --- /dev/null +++ b/crates/ui-patterns/tests/it/preferences/live.rs @@ -0,0 +1,48 @@ +//! Live preferences apply an edit without waiting for the window to close. + +use craft_ui::contract::Bind; +use craft_ui::patterns::preferences::{PageSpec, PrefValue, PreferencesMode, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec}; +use craft_ui::testing::{Fixture, trial}; +use egui::Ui; +use std::cell::RefCell; +use std::rc::Rc; + +#[derive(Default)] +struct Model { + draft: bool, + saved: bool, + applies: usize, +} + +impl PreferencesModel for Model { + fn pages(&self) -> Vec> { + vec![PageSpec::new("general", "General", vec![RowSpec::new("snap", "Snap", RowKind::Bool(self.draft))])] + } + fn set(&mut self, _: &str, value: PrefValue) { + if let PrefValue::Bool(value) = value { self.draft = value; } + } + fn custom_row(&mut self, _: &mut Ui, _: &str) {} + fn custom_page(&mut self, _: &mut Ui, _: &str) {} + fn differs(&self) -> bool { self.draft != self.saved } + fn apply(&mut self) -> Result<(), String> { self.saved = self.draft; self.applies += 1; Ok(()) } + fn cancel(&mut self) { self.draft = self.saved; } + fn reset_page(&mut self, _: &str) { self.draft = false; } +} + +#[trial] +fn an_edit_applies_before_ok() { + let model = Rc::new(RefCell::new(Model::default())); + let shown = model.clone(); + let mut state = PreferencesState::default(); + let mut fixture = Fixture::new(move |ui| { + let _ = PreferencesWindow::new(Bind::bound(&mut state)).mode(PreferencesMode::Live).embedded().show(ui, &mut *shown.borrow_mut()); + }); + fixture.settle(); + let snap = fixture.by_label("Snap").expect("the setting"); + fixture.click(&snap).settle(); + assert!(model.borrow().saved, "the change applies while the window remains open"); + assert_eq!(model.borrow().applies, 1); + let ok = fixture.by_label("OK").expect("the close button"); + fixture.click(&ok).settle(); + assert_eq!(model.borrow().applies, 1, "OK only closes"); +} diff --git a/crates/ui-patterns/tests/it/preferences/mod.rs b/crates/ui-patterns/tests/it/preferences/mod.rs index d2b72df8f..f973f032d 100644 --- a/crates/ui-patterns/tests/it/preferences/mod.rs +++ b/crates/ui-patterns/tests/it/preferences/mod.rs @@ -3,3 +3,4 @@ mod model; mod path_setting; +mod live; diff --git a/crates/ui-widgets/src/display/text.rs b/crates/ui-widgets/src/display/text.rs index 98c4c6bc5..ab17acfb1 100644 --- a/crates/ui-widgets/src/display/text.rs +++ b/crates/ui-widgets/src/display/text.rs @@ -174,9 +174,10 @@ impl Component for Text { }; } let role = cx.style.text.role; - // A line breaks between words, never inside one: a wrapped text is never narrower than its widest word. + // Rows reserve the widest word, up to an enclosing reading-width cap. let widest = - || cx.resolved.label.split_whitespace().map(|word| cx.layout_at(&self.run(role, word), f32::INFINITY).size().x).fold(0.0, f32::max); + || cx.resolved.label.split_whitespace().map(|word| cx.layout_at(&self.run(role, word), f32::INFINITY).size().x).fold(0.0, f32::max) + .min(cx.wrap_limit().unwrap_or(f32::INFINITY)); if cx.proposal == Proposal::Min && self.elide == Elide::Off { let widest = widest(); return Vec2::new(widest, cx.layout_at(&self.run(role, cx.resolved.label), widest).size().y); diff --git a/crates/ui-widgets/tests/it/table.rs b/crates/ui-widgets/tests/it/table.rs index ddfec096e..b4b0e61f5 100644 --- a/crates/ui-widgets/tests/it/table.rs +++ b/crates/ui-widgets/tests/it/table.rs @@ -12,6 +12,35 @@ use egui::{Key, Modifiers, Pos2, Rect}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +/// A text field in a table cell receives typing and reports its edit to the row's owner. +#[trial] +fn a_table_cell_text_field_reports_edits() { + use craft_behavior::{EditEvent, Selection}; + use craft_ui::contract::{ReorderRule, SpaceAction}; + use craft_ui::text::TextField; + let edited = Rc::new(RefCell::new(None::)); + let seen = edited.clone(); + let mut fixture = Fixture::new(move |ui| { + let columns = vec![ColumnSpec::new(NAME, "Name", ColumnWidth::fill(1.0)), ColumnSpec::new(SIZE, "Pages", ColumnWidth::fill(1.0))]; + let keys = [0_usize, 1, 2]; + let source = keyed(&keys, |key: &usize| *key); + Table::new("Files", columns).selection(Bind::given(Selection::single(0))).reorder(ReorderRule::new()).deletable(true).space(SpaceAction::Preview).show_items(ui, &source, &mut |_, icx| { + let seen = seen.clone(); + ListRow::new("File").cells(icx.cells()).cell_field(SIZE, TextField::new("Page range", Bind::given(String::new())), move |out| { + for event in out.events { + if let EditEvent::Update { value, .. } | EditEvent::Commit { after: value, .. } | EditEvent::Set { after: value, .. } = event { + *seen.borrow_mut() = Some(value); + } + } + }) + }); + }); + fixture.in_room(Room::Dialog).settle(); + let field = fixture.by_label("Page range").expect("the cell field"); + fixture.click(&field).type_text("1").settle(); + assert_eq!(edited.borrow().as_deref(), Some("1"), "typing reports an edit before Enter"); +} + const NAME: ColumnKey = ColumnKey::new("name"); const SIZE: ColumnKey = ColumnKey::new("size"); const DATE: ColumnKey = ColumnKey::new("date");