diff --git a/crates/ui-patterns/src/patterns/preferences/window.rs b/crates/ui-patterns/src/patterns/preferences/window.rs index a881cb567c..e07e5ea76a 100644 --- a/crates/ui-patterns/src/patterns/preferences/window.rs +++ b/crates/ui-patterns/src/patterns/preferences/window.rs @@ -9,10 +9,13 @@ use super::model::PreferencesModel; use super::model::{Closed, PreferencesDraft, PreferencesOutput}; use super::page::{PreferencesLayout, PreferencesPage}; use super::words::PreferencesWords; -use crate::contract::{Bind, Props as _, SaveKey, Show as _, ShowContainer as _}; +use crate::buttons::Button; +use crate::contract::{Bind, Props as _, SaveKey, Show as _, ShowContainer as _, clicked}; use crate::dialog::{ButtonPlace, Dialog, DialogOutput}; +use crate::layout_components::Row; use crate::notices::{Notice, NoticeLayout}; use crate::runtime::env::{Env, Label}; +use crate::runtime::frame::request_repaint; use crate::runtime::memory::StageAccess; use crate::runtime::overlay::CloseReason; use crate::runtime::words::CommonWords; @@ -80,14 +83,17 @@ pub struct PreferencesState { /// opens narrower, as it needs no room for a page list. /// - **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. +/// - **Page steps.** [`page_steps`](PreferencesWindow::page_steps) adds Previous and Next to the footer. They pick the +/// page before and after the shown one among the pages the search lists, and each is disabled at its end of the +/// list. A window of cards, which scrolls from page to page, does not show them. /// - **Nested dialogs.** While [`PreferencesModel::nested_open`] is true the window takes no input and refuses to /// close; [`PreferencesModel::nested`] draws the nested dialogs with the body's `Ui`, 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 /// refuse to close, and a press on one raises the window. /// - **Placement.** The window opens in its own OS window where there are any, else as a modal dialog layer -/// ([`embedded`](PreferencesWindow::embedded) forces the layer). [`remember`](PreferencesWindow::remember) keeps -/// its place and size across runs. +/// ([`embedded`](PreferencesWindow::embedded) forces the layer). [`size`](PreferencesWindow::size) sets the size it +/// opens at. [`remember`](PreferencesWindow::remember) keeps its place and size across runs. #[must_use = "show the window with `show`"] #[derive(crate::contract::Pattern, crate::contract::Props)] pub struct PreferencesWindow<'a> { @@ -107,10 +113,19 @@ pub struct PreferencesWindow<'a> { /// Lays the page out as `layout` says ([`PreferencesPage::layout`]); the default is [`PreferencesLayout::Paged`]. #[prop] layout: PreferencesLayout, + /// The size the window opens at until the user resizes it, in place of the layout's own ([`DEFAULT_SIZE`] for + /// pages, a narrower one for cards). A size under the layout's least ([`MIN_SIZE`] for pages) opens at the least; + /// a size that is not finite is ignored. + #[prop] + size: Option, /// Escape keeps the typing in the focused field ([`Dialog::escape_keeps_typing`]): in [`PreferencesMode::Live`] /// the typed value stays applied when Escape closes the window. Off by default: Escape cancels the typing. #[prop(flag)] escape_keeps_typing: bool, + /// Adds Previous and Next to the footer, which pick the listed page before and after the shown one. Only + /// [`PreferencesLayout::Paged`] shows them. + #[prop(flag)] + page_steps: bool, } /// What the body, the footer and the buttons' guard share during one pass: the host, the window's state as the pass @@ -123,6 +138,8 @@ struct Session<'h, 'b, H: ?Sized> { before: PreferencesState, work: PreferencesState, page: Option, + /// The listed pages before and after the shown one, which Previous and Next pick. + steps: (Option, Option), /// The pages the body listed this pass, in order, for Prev and Next. pages: Vec, applied: bool, @@ -181,6 +198,21 @@ impl Session<'_, '_, H> { self.commit(cx); ok } + + /// Picks the page `page` (Previous or Next) and writes the state, so the next pass shows it. + fn step(&mut self, cx: &mut impl StageAccess, page: Option) { + if let Some(page) = page { + self.work.selected = page; + self.commit(cx); + } + } +} + +/// The pages of `listed` before and after `shown`. +fn neighbors(listed: &[String], shown: Option<&str>) -> (Option, Option) { + let Some(at) = listed.iter().position(|id| Some(id.as_str()) == shown) else { return (None, None) }; + let before = at.checked_sub(1).and_then(|at| listed.get(at)); + (before.cloned(), listed.get(at + 1).cloned()) } impl<'a> PreferencesWindow<'a> { @@ -193,13 +225,16 @@ impl<'a> PreferencesWindow<'a> { remember: None, mode: PreferencesMode::Staged, layout: PreferencesLayout::Paged, + size: None, escape_keeps_typing: false, + page_steps: false, } } /// 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, mode, layout, escape_keeps_typing } = self; + let PreferencesWindow { state, title, embedded, remember, mode, layout, size: asked, escape_keeps_typing, page_steps } = self; + let page_steps = page_steps && layout == PreferencesLayout::Paged; let env = Env::of(ui); let words = env.words::(); let common = env.words::(); @@ -234,6 +269,7 @@ impl<'a> PreferencesWindow<'a> { PreferencesLayout::Cards => (CARDS_SIZE, CARDS_MIN_SIZE), PreferencesLayout::Classic => (CLASSIC_SIZE, MIN_SIZE), }; + let size = asked.filter(|asked| asked.is_finite()).unwrap_or(size); let mut open = true; // Filed by a swatch press in this pass. let mut pick_color = None; @@ -244,6 +280,7 @@ impl<'a> PreferencesWindow<'a> { before: PreferencesState::default(), work: PreferencesState::default(), page: None, + steps: (None, None), pages: Vec::new(), applied: false, }); @@ -277,7 +314,24 @@ impl<'a> PreferencesWindow<'a> { dialog = dialog.remember(key); } let shown = dialog - .footer(|ui, _| { + .footer(|ui, cx| { + if page_steps { + let (before, after) = session.borrow().steps.clone(); + let mut picked = None; + Row::new().show(ui, |ui, _| { + for (label, key, page) in [(&words.previous, "previous", &before), (&words.next, "next", &after)] { + let button = Button::new(label.clone()).enabled(page.is_some() && !nested).id_salt(key).show(ui); + if clicked(&button) { + picked.clone_from(page); + } + } + }); + // The footer is measured in a sizing pass before it is shown; only the shown pass steps. + if !ui.is_sizing_pass() && picked.is_some() { + session.borrow_mut().step(cx.dialog(), picked); + request_repaint(ui.ctx()); + } + } let message = session.borrow().work.error.clone(); if let Some(message) = message { Notice::new(Tone::Bad, Label::from(message)).layout(NoticeLayout::Inline).show(ui); @@ -298,6 +352,9 @@ impl<'a> PreferencesWindow<'a> { if mode == PreferencesMode::Live && session.work.error.is_none() && session.host.differs() { session.apply(cx); } + if page_steps { + session.steps = neighbors(&shown.pages, shown.page.as_deref()); + } session.page = shown.page; session.pages = shown.pages; session.commit(cx); diff --git a/crates/ui-patterns/src/patterns/preferences/words.rs b/crates/ui-patterns/src/patterns/preferences/words.rs index 5bc5ad95fb..780953bb57 100644 --- a/crates/ui-patterns/src/patterns/preferences/words.rs +++ b/crates/ui-patterns/src/patterns/preferences/words.rs @@ -15,6 +15,7 @@ craft_ui::words! { no_matches: "preferences.noMatches" = "No matching settings"; empty_page: "preferences.emptyPage" = "These settings aren't available yet."; apply: "preferences.apply" = "Apply"; + previous: "preferences.previous" = "Previous"; prev: "preferences.prev" = "Prev"; next: "preferences.next" = "Next"; reset_section: "preferences.resetSection" = "Reset Section"; diff --git a/crates/ui-patterns/tests/it/preferences/mod.rs b/crates/ui-patterns/tests/it/preferences/mod.rs index df4d0ca2f2..cdc7de985e 100644 --- a/crates/ui-patterns/tests/it/preferences/mod.rs +++ b/crates/ui-patterns/tests/it/preferences/mod.rs @@ -6,3 +6,5 @@ pub(crate) mod live; pub(crate) mod model; pub(crate) mod page; pub(crate) mod path_setting; +pub(crate) mod size; +pub(crate) mod steps; diff --git a/crates/ui-patterns/tests/it/preferences/size.rs b/crates/ui-patterns/tests/it/preferences/size.rs new file mode 100644 index 0000000000..17512925f4 --- /dev/null +++ b/crates/ui-patterns/tests/it/preferences/size.rs @@ -0,0 +1,64 @@ +//! The size the preferences window opens at. + +use craft_ui::contract::{Bind, Role}; +use craft_ui::patterns::preferences::{ + MIN_SIZE, PageSpec, PrefValue, PreferencesDraft, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec, +}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Rect, Ui, Vec2, vec2}; + +struct Model; + +impl PreferencesModel for Model { + fn pages(&self) -> Vec> { + ["General", "Type"].into_iter().map(|title| PageSpec::new(title, title, vec![RowSpec::new(title, title, RowKind::Bool(false))])).collect() + } + fn set(&mut self, _: &str, _: PrefValue) {} + fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool { + false + } + fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool { + false + } + fn reset_page(&mut self, _: &str) {} +} + +impl PreferencesDraft for Model { + fn differs(&self) -> bool { + false + } + fn apply(&mut self) -> Result<(), String> { + Ok(()) + } + fn cancel(&mut self) {} +} + +/// The bounds of the window opened with `size`, or at its own size without it, in a room larger than either. +fn opened(size: Option) -> Rect { + let mut state = PreferencesState::default(); + let mut fixture = Fixture::new(move |ui| { + let mut window = PreferencesWindow::new(Bind::bound(&mut state)).embedded(); + if let Some(size) = size { + window = window.size(size); + } + let _ = window.show(ui, &mut Model); + }); + fixture.room(vec2(1600.0, 1200.0)).settle(); + fixture.by_role(Role::DIALOG).first().map(|dialog| dialog.rect).unwrap_or_else(|| panic!("the preferences window")) +} + +#[trial] +fn the_window_opens_at_the_size_the_host_gives() { + let own = opened(None); + let asked = (own.size() + MIN_SIZE) / 2.0; + let smaller = opened(Some(asked)); + assert!(smaller.width() < own.width() && smaller.height() < own.height(), "{smaller:?} is not smaller than {own:?}"); + let larger = opened(Some(own.size() + vec2(100.0, 100.0))); + assert!(larger.width() > own.width() && larger.height() > own.height(), "{larger:?} is not larger than {own:?}"); +} + +#[trial] +fn a_size_that_is_not_finite_is_ignored() { + let endless = opened(Some(vec2(f32::INFINITY, f32::NAN))); + assert_eq!(endless.size(), opened(None).size(), "a size that is not finite opens the window at its own size"); +} diff --git a/crates/ui-patterns/tests/it/preferences/steps.rs b/crates/ui-patterns/tests/it/preferences/steps.rs new file mode 100644 index 0000000000..3ee161691f --- /dev/null +++ b/crates/ui-patterns/tests/it/preferences/steps.rs @@ -0,0 +1,90 @@ +//! Previous and Next in the preferences window's footer. + +use craft_ui::contract::Bind; +use craft_ui::patterns::preferences::{ + PageSpec, PrefValue, PreferencesDraft, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec, +}; +use craft_ui::testing::{Fixture, trial}; +use egui::Ui; +use std::cell::RefCell; +use std::rc::Rc; + +struct Model; + +impl PreferencesModel for Model { + fn pages(&self) -> Vec> { + ["General", "Type", "Units"] + .into_iter() + .map(|title| PageSpec::new(title, title, vec![RowSpec::new(title, title, RowKind::Bool(false))])) + .collect() + } + fn set(&mut self, _: &str, _: PrefValue) {} + fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool { + false + } + fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool { + false + } + fn reset_page(&mut self, _: &str) {} +} + +impl PreferencesDraft for Model { + fn differs(&self) -> bool { + false + } + fn apply(&mut self) -> Result<(), String> { + Ok(()) + } + fn cancel(&mut self) {} +} + +/// A window with Previous and Next, and the page it shows after each pass. +fn window() -> (Fixture, Rc>>) { + let page = Rc::new(RefCell::new(None)); + let seen = page.clone(); + let mut state = PreferencesState::default(); + let fixture = Fixture::new(move |ui| { + let shown = PreferencesWindow::new(Bind::bound(&mut state)).page_steps().embedded().show(ui, &mut Model); + *seen.borrow_mut() = shown.page; + }); + (fixture, page) +} + +/// Whether the footer button `label` is disabled. +fn disabled(fixture: &Fixture, label: &str) -> bool { + let button = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} button")); + fixture.tree().is_disabled_key(button.node) +} + +#[trial] +fn next_and_previous_step_through_the_pages() { + let (mut fixture, page) = window(); + fixture.settle(); + assert_eq!(page.borrow().as_deref(), Some("General")); + assert!(disabled(&fixture, "Previous"), "the first page has no page before it"); + let next = fixture.by_label("Next").expect("the Next button"); + fixture.click(&next).settle(); + assert_eq!(page.borrow().as_deref(), Some("Type"), "Next shows the next page"); + let next = fixture.by_label("Next").expect("the Next button"); + fixture.click(&next).settle(); + assert_eq!(page.borrow().as_deref(), Some("Units")); + assert!(disabled(&fixture, "Next"), "the last page has no page after it"); + let previous = fixture.by_label("Previous").expect("the Previous button"); + fixture.click(&previous).settle(); + assert_eq!(page.borrow().as_deref(), Some("Type"), "Previous shows the page before"); +} + +#[trial] +fn the_steps_follow_the_pages_the_search_lists() { + let (mut fixture, page) = window(); + fixture.settle(); + let search = fixture.by_label("Search settings").expect("the search field"); + fixture.click(&search).settle(); + // Lists General and Units, not Type. + fixture.type_text("n").settle(); + assert_eq!(page.borrow().as_deref(), Some("General")); + let next = fixture.by_label("Next").expect("the Next button"); + fixture.click(&next).settle(); + assert_eq!(page.borrow().as_deref(), Some("Units"), "Next passes over the page the search hides"); + assert!(disabled(&fixture, "Next"), "Units is the last listed page"); +}