Preferences: an opt-in classic layout with a framed page list, group boxes and Prev/Next

PreferencesLayout::Classic draws the paged body as a desktop preferences dialog does:
the page list in a frame as tall as the page (SectionList::framed) with room before the
page, no heading over the page, and each titled group a GroupBox. The window puts OK,
Cancel, Prev and Next in a column at the end edge (ButtonPlace::Side) and opens at
1030 x 660; Prev and Next step through the listed pages and wrap. Paged and Cards are
unchanged. PreferencesPageOutput::pages lists the page ids the search keeps.

For storytold/photocraft#17014.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
David Mann
2026-11-25 23:46:32 +01:00
co-authored by Claude Opus 5.5
parent 4269318aa5
commit f74fe090fc
6 changed files with 247 additions and 37 deletions
@@ -2,12 +2,13 @@
//! body and the properties dialog's list of tabs.
use crate::contract::{
ActivateOn, Bind, CollectionEvent, Props as _, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
ActivateOn, Bind, CollectionEvent, Gap, Pad, Props as _, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
};
use crate::display::Divider;
use crate::layout_components::{Row, Stack};
use crate::list::{List, ListRow};
use crate::runtime::env::Label;
use crate::style::SurfaceKind;
use craft_behavior::{ItemSource, Selection, SelectionChange};
use egui::Ui;
use std::hash::Hash;
@@ -34,12 +35,13 @@ pub struct SectionList<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
id: Option<egui::Id>,
body_label: Option<Label>,
foot: Option<Foot<'a>>,
framed: bool,
}
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> SectionList<'a, K> {
/// The list labelled `label` over the sections of `source`, with `shown` picked.
pub fn new(label: impl Into<Label>, source: &'a dyn ItemSource<K>, shown: K) -> Self {
SectionList { label: label.into(), source, shown, id: None, body_label: None, foot: None }
SectionList { label: label.into(), source, shown, id: None, body_label: None, foot: None, framed: false }
}
/// The list's id, for a search field that drives it (`TextField::drives`).
@@ -60,13 +62,22 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> SectionList<'a, K> {
self
}
/// Draws the list's column in a frame as tall as the body, with no divider beside it: a desktop preferences
/// window's page list.
pub fn framed(mut self) -> Self {
self.framed = true;
self
}
/// Shows the list with a row per section from `row` and `body` beside it; the section picked this pass.
// PLAN: ty.X70 gives `body: impl FnOnce`; a container runs its body again for a measuring pass, so `body` and
// `foot` are `FnMut`.
pub fn show(self, ui: &mut Ui, mut row: impl FnMut(&K) -> ListRow<'static>, mut body: impl FnMut(&mut Ui)) -> Option<K> {
let SectionList { label, source, shown, id, body_label, mut foot } = self;
let SectionList { label, source, shown, id, body_label, mut foot, framed } = self;
let mut picked = None;
Row::new().fill().show(ui, |ui, _| {
// A framed list stands apart from the body; an unframed one has the divider between them.
let gap = if framed { Gap::Section } else { Gap::default() };
Row::new().fill().gap(gap).show(ui, |ui, _| {
let mut list = |ui: &mut Ui| {
let mut sections = List::<K>::new(label.clone())
.select(SelectMode::Single)
@@ -88,16 +99,25 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> SectionList<'a, K> {
}
}
};
match foot.as_mut() {
Some(foot) => {
Stack::new().show(ui, |ui, _| {
list(ui);
if framed {
Stack::new().surface(SurfaceKind::Frame).pad(Pad::Tight).sizing(Sizing::FillHeight).show(ui, |ui, _| {
list(ui);
if let Some(foot) = foot.as_mut() {
foot(ui);
});
}
});
} else {
match foot.as_mut() {
Some(foot) => {
Stack::new().show(ui, |ui, _| {
list(ui);
foot(ui);
});
}
None => list(ui),
}
None => list(ui),
Divider::vertical().show(ui);
}
Divider::vertical().show(ui);
let mut shown_body = Stack::new().fill().scroll(Scroll::vertical());
if let Some(label) = &body_label {
shown_body = shown_body.label(label.clone());
@@ -18,7 +18,7 @@ use crate::patterns::form_dialogs::SectionList;
use crate::runtime::env::{Env, Label, Units};
use crate::runtime::memory::Remember as _;
use crate::runtime::requests::ColorRequest;
use crate::sections::Section;
use crate::sections::{GroupBox, Section};
use crate::style::{SurfaceKind, TypeRole};
use crate::text::TextField;
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed};
@@ -38,6 +38,10 @@ pub enum PreferencesLayout {
/// line and a short choice as a segmented control ([`RowSpec::pills`](super::RowSpec::pills)); the search field
/// shows its match count beside it, and the column brings the picked page into view once: PdfCraft's preferences.
Cards,
/// [`Paged`](Self::Paged) as a desktop preferences dialog draws it: the page list in a frame as tall as the page,
/// no heading over the page, and each titled group a framed group box with its title on the frame; the window puts
/// OK, Cancel, Prev and Next in a column at the end edge: PhotoCraft's preferences.
Classic,
}
/// A preferences page that applies each value at once, with search and Reset Section. [`PreferencesWindow`] shows its
@@ -74,6 +78,8 @@ pub struct PreferencesPageOutput {
/// The id of the page shown, `None` when the search lists no page. With [`PreferencesLayout::Cards`], the picked
/// page while the search lists it, else the first card.
pub page: Option<String>,
/// The ids of the pages the search lists, in order: the pages Prev and Next step through.
pub pages: Vec<String>,
}
impl Outcome for PreferencesPageOutput {
@@ -99,6 +105,7 @@ struct PageRun {
work: PreferencesState,
out: BodyOut,
page: Option<String>,
listed: Vec<String>,
}
impl<'a> PreferencesPage<'a> {
@@ -127,20 +134,23 @@ impl<'a> PreferencesPage<'a> {
}
let matcher = Matcher::new(&env.folder(), work.search.trim());
let mut out = BodyOut::default();
let listed: Vec<String>;
let page = match layout {
PreferencesLayout::Paged => {
PreferencesLayout::Paged | PreferencesLayout::Classic => {
let snap = snapshot(&*host, &matcher, &work.selected);
show_body(ui, &mut *host, &snap, &mut work, &words, &units, &mut out);
show_body(ui, &mut *host, &snap, &mut work, &Look { words: &words, units: &units, layout }, &mut out);
listed = snap.list.iter().map(|entry| entry.id.clone()).collect();
snap.shown.map(|page| page.id)
}
PreferencesLayout::Cards => {
let snap = cards_snapshot(&*host, &matcher);
show_cards(ui, &mut *host, &snap, &mut work, &words, &units, &mut out);
listed = snap.shown.iter().map(|page| page.id.clone()).collect();
let shown = snap.shown.iter().find(|page| page.id == work.selected).or(snap.shown.first());
shown.map(|page| page.id.clone())
}
};
PageRun { before, work, out, page }
PageRun { before, work, out, page, listed }
});
let pick_color = shown
.settle(|cx, run| {
@@ -161,8 +171,8 @@ impl<'a> PreferencesPage<'a> {
run.out.rows.pick_color.take()
})
.flatten();
let page = shown.inner.and_then(|run| run.page);
PreferencesPageOutput { response: shown.output, pick_color, page }
let (page, pages) = shown.inner.map_or((None, Vec::new()), |run| (run.page, run.listed));
PreferencesPageOutput { response: shown.output, pick_color, page, pages }
}
}
@@ -255,6 +265,14 @@ fn shown_page(matcher: &Matcher, listed: &Listed, page: &PageSpec<'_>) -> ShownP
}
}
/// What a paged body draws with: the words, the units and the layout.
#[derive(Clone, Copy)]
struct Look<'a> {
words: &'a PreferencesWords,
units: &'a Units,
layout: PreferencesLayout,
}
/// The page list's rows: one per listed page, keyed by the page id.
struct Pages<'a>(&'a [PageEntry]);
@@ -281,10 +299,10 @@ fn show_body<H: PreferencesModel + ?Sized>(
host: &mut H,
snap: &Snapshot,
state: &mut PreferencesState,
words: &PreferencesWords,
units: &Units,
look: &Look<'_>,
out: &mut BodyOut,
) {
let words = look.words;
let list_id = ui.scope_id().with("pages");
TextField::search(words.search_label.clone(), Bind::bound(&mut state.search))
.placeholder(words.search_placeholder.clone())
@@ -295,14 +313,18 @@ fn show_body<H: PreferencesModel + ?Sized>(
return;
};
let source = Pages(&snap.list);
let picked = SectionList::new(words.pages_label.clone(), &source, page.id.clone()).id(list_id).body_label(page.title.clone()).show(
let mut sections = SectionList::new(words.pages_label.clone(), &source, page.id.clone()).id(list_id).body_label(page.title.clone());
if look.layout == PreferencesLayout::Classic {
sections = sections.framed();
}
let picked = sections.show(
ui,
|key| {
let entry = snap.list.iter().find(|entry| entry.id == *key);
let row = ListRow::new(entry.map_or_else(Label::default, |entry| entry.title.clone()));
if entry.is_some_and(|entry| entry.dimmed) { row.ink(RowInk::Dimmed) } else { row }
},
|ui| show_page(ui, host, page, snap.searching, words, units, out),
|ui| show_page(ui, host, page, snap.searching, look, out),
);
if let Some(key) = picked {
state.selected = key;
@@ -310,16 +332,12 @@ fn show_body<H: PreferencesModel + ?Sized>(
}
/// The page's title, groups, footnote and Reset Section.
fn show_page<H: PreferencesModel + ?Sized>(
ui: &mut Ui,
host: &mut H,
page: &ShownPage,
searching: bool,
words: &PreferencesWords,
units: &Units,
out: &mut BodyOut,
) {
Text::new(page.title.clone()).role(TypeRole::Title).show(ui);
fn show_page<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H, page: &ShownPage, searching: bool, look: &Look<'_>, out: &mut BodyOut) {
let Look { words, units, layout } = *look;
let classic = layout == PreferencesLayout::Classic;
if !classic {
Text::new(page.title.clone()).role(TypeRole::Title).show(ui);
}
if page.custom {
Stack::new().show(ui, |ui, _| out.custom_changed |= host.custom_page(ui, &page.id));
} else if page.groups.is_empty() && !searching {
@@ -336,6 +354,9 @@ fn show_page<H: PreferencesModel + ?Sized>(
});
};
match &group.title {
Some(title) if classic => {
GroupBox::new(title.clone(), None).id_salt(at).show(ui, |ui, _| rows(ui));
}
Some(title) => {
Section::fixed(title.clone()).id_salt(at).show(ui, |ui, _| rows(ui));
}
@@ -10,7 +10,7 @@ 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::dialog::{Dialog, DialogOutput};
use crate::dialog::{ButtonPlace, Dialog, DialogOutput};
use crate::notices::{Notice, NoticeLayout};
use crate::runtime::env::{Env, Label};
use crate::runtime::memory::StageAccess;
@@ -32,6 +32,8 @@ pub const MIN_SIZE: Vec2 = vec2(560.0, 400.0);
const CARDS_SIZE: Vec2 = vec2(640.0, 720.0);
/// The least size a window of cards may be resized to.
const CARDS_MIN_SIZE: Vec2 = vec2(420.0, 320.0);
/// The size a [`PreferencesLayout::Classic`] window opens at: a desktop preferences dialog's.
const CLASSIC_SIZE: Vec2 = vec2(1030.0, 660.0);
/// When preferences changes are applied.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -121,10 +123,31 @@ struct Session<'h, 'b, H: ?Sized> {
before: PreferencesState,
work: PreferencesState,
page: Option<String>,
/// The pages the body listed this pass, in order, for Prev and Next.
pages: Vec<String>,
applied: bool,
}
impl<H: PreferencesDraft + ?Sized> Session<'_, '_, H> {
/// Shows the page `step` places from the shown one among the listed pages, wrapping at either end; the first
/// listed page when none is shown.
fn step_page(&mut self, cx: &mut impl StageAccess, step: isize) {
let count = self.pages.len();
if count == 0 {
return;
}
let at = self.page.as_ref().and_then(|page| self.pages.iter().position(|id| id == page));
let to = match at {
Some(at) => (at as isize + step).rem_euclid(count as isize) as usize,
None => 0,
};
if let Some(id) = self.pages.get(to) {
self.work.selected = id.clone();
self.page = Some(id.clone());
}
self.commit(cx);
}
/// Reads the state at the start of the body. The page clears the search and the error of a window that has just
/// opened.
fn begin(&mut self, cx: &mut impl StageAccess) {
@@ -189,13 +212,27 @@ impl<'a> PreferencesWindow<'a> {
if !can_ok {
ok = ok.disabled_reason(words.cannot_ok.clone());
}
let apply = FooterButton::new(words.apply.clone(), DialogRole::Other).enabled(differs).stays_open(true);
let buttons =
if mode == PreferencesMode::Live { vec![ok] } else { vec![ok, apply, FooterButton::new(common.cancel.clone(), DialogRole::Cancel)] };
let classic = layout == PreferencesLayout::Classic;
let cancel = FooterButton::new(common.cancel.clone(), DialogRole::Cancel);
let buttons = if classic {
// A desktop preferences dialog steps through its pages instead of applying in place.
let step = |label: &Label| FooterButton::new(label.clone(), DialogRole::Other).enabled(!nested).stays_open(true);
let mut buttons = vec![ok];
if mode == PreferencesMode::Staged {
buttons.push(cancel);
}
buttons.extend([step(&words.prev), step(&words.next)]);
buttons
} else if mode == PreferencesMode::Live {
vec![ok]
} else {
vec![ok, FooterButton::new(words.apply.clone(), DialogRole::Other).enabled(differs).stays_open(true), cancel]
};
let (size, least) = match layout {
PreferencesLayout::Paged => (DEFAULT_SIZE, MIN_SIZE),
PreferencesLayout::Cards => (CARDS_SIZE, CARDS_MIN_SIZE),
PreferencesLayout::Classic => (CLASSIC_SIZE, MIN_SIZE),
};
let mut open = true;
// Filed by a swatch press in this pass.
@@ -207,6 +244,7 @@ impl<'a> PreferencesWindow<'a> {
before: PreferencesState::default(),
work: PreferencesState::default(),
page: None,
pages: Vec::new(),
applied: false,
});
let mut dialog = Dialog::new(title.clone())
@@ -216,11 +254,22 @@ impl<'a> PreferencesWindow<'a> {
.close_on_enter(can_ok)
.escape_keeps_typing(escape_keeps_typing)
.on_pick(|button, cx| {
if button.role() == DialogRole::Other && !nested {
session.borrow_mut().apply(cx);
if button.role() != DialogRole::Other || nested {
return;
}
let mut session = session.borrow_mut();
if !classic {
session.apply(cx);
} else if button.label() == &words.prev {
session.step_page(cx, -1);
} else if button.label() == &words.next {
session.step_page(cx, 1);
}
})
.close_guard(|button, cx| mode == PreferencesMode::Live || button.role() != DialogRole::Accept || session.borrow_mut().apply(cx));
if classic {
dialog = dialog.button_place(ButtonPlace::Side);
}
if !embedded {
dialog = dialog.viewport();
}
@@ -250,6 +299,7 @@ impl<'a> PreferencesWindow<'a> {
session.apply(cx);
}
session.page = shown.page;
session.pages = shown.pages;
session.commit(cx);
});
@@ -15,6 +15,8 @@ craft_ui::words! {
no_matches: "preferences.noMatches" = "No matching settings";
empty_page: "preferences.emptyPage" = "These settings aren't available yet.";
apply: "preferences.apply" = "Apply";
prev: "preferences.prev" = "Prev";
next: "preferences.next" = "Next";
reset_section: "preferences.resetSection" = "Reset Section";
hex_label: "preferences.hexLabel" = "Hex color";
default_hint: "preferences.defaultHint" = "Default";
@@ -0,0 +1,116 @@
//! The classic preferences window: OK, Cancel, Prev and Next in a column beside the page, Prev and Next stepping
//! through the listed pages, OK and Cancel as before.
use craft_ui::contract::Bind;
use craft_ui::patterns::preferences::{
GroupSpec, PageSpec, PrefValue, PreferencesDraft, PreferencesLayout, 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,
}
impl PreferencesModel for Model {
fn pages(&self) -> Vec<PageSpec<'_>> {
vec![
PageSpec::new("general", "General", vec![RowSpec::new("snap", "Snap", RowKind::Bool(self.draft))]),
PageSpec::new("tools", "Tools", Vec::new())
.group(GroupSpec::new(Some("Options"), vec![RowSpec::new("tips", "Show Tips", RowKind::Bool(true))])),
PageSpec::new("type", "Type", vec![RowSpec::new("fonts", "Font Previews", RowKind::Bool(true))]),
]
}
fn set(&mut self, _: &str, value: PrefValue) {
if let PrefValue::Bool(value) = value {
self.draft = value;
}
}
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) {
self.draft = false;
}
}
impl PreferencesDraft for Model {
fn differs(&self) -> bool {
self.draft != self.saved
}
fn apply(&mut self) -> Result<(), String> {
self.saved = self.draft;
Ok(())
}
fn cancel(&mut self) {
self.draft = self.saved;
}
}
/// A classic window over a fresh model, opened on `page`, with the state it binds.
fn classic(page: &str) -> (Fixture, Rc<RefCell<Model>>, Rc<RefCell<PreferencesState>>) {
let model = Rc::new(RefCell::new(Model::default()));
let state = Rc::new(RefCell::new(PreferencesState::default()));
state.borrow_mut().selected = page.to_string();
let (shown, bound) = (model.clone(), state.clone());
let mut fixture = Fixture::new(move |ui| {
let mut state = bound.borrow_mut();
let _ = PreferencesWindow::new(Bind::bound(&mut *state)).layout(PreferencesLayout::Classic).embedded().show(ui, &mut *shown.borrow_mut());
});
fixture.settle();
(fixture, model, state)
}
fn press(fixture: &mut Fixture, label: &str) {
let button = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} button"));
fixture.click(&button).settle();
}
#[trial]
fn next_and_prev_step_through_the_pages_and_wrap() {
let (mut fixture, _, state) = classic("general");
press(&mut fixture, "Next");
assert_eq!(state.borrow().selected, "tools");
press(&mut fixture, "Next");
press(&mut fixture, "Next");
assert_eq!(state.borrow().selected, "general", "Next on the last page shows the first");
press(&mut fixture, "Prev");
assert_eq!(state.borrow().selected, "type", "Prev on the first page shows the last");
assert!(fixture.by_label("Font Previews").is_some(), "the page Prev picked is shown");
}
#[trial]
fn the_buttons_stand_in_a_column_beside_the_page_with_no_apply() {
let (fixture, _, _) = classic("tools");
assert!(fixture.by_label("Apply").is_none(), "the classic window steps through pages instead of applying in place");
let ok = fixture.by_label("OK").expect("OK").rect;
let cancel = fixture.by_label("Cancel").expect("Cancel").rect;
let prev = fixture.by_label("Prev").expect("Prev").rect;
let next = fixture.by_label("Next").expect("Next").rect;
let row = fixture.by_label("Show Tips").expect("the row").rect;
for (name, button) in [("Cancel", cancel), ("Prev", prev), ("Next", next)] {
assert!((button.left() - ok.left()).abs() < 1.0, "{name} stands under OK: {button:?} vs {ok:?}");
}
assert!(ok.top() < cancel.top() && cancel.top() < prev.top() && prev.top() < next.top(), "OK, Cancel, Prev, Next top to bottom");
assert!(ok.left() > row.right(), "the buttons stand beside the page, not under it");
}
#[trial]
fn ok_applies_and_cancel_drops_the_draft() {
let (mut fixture, model, _) = classic("general");
press(&mut fixture, "Snap");
press(&mut fixture, "Cancel");
assert!(!model.borrow().saved && !model.borrow().draft, "Cancel drops the edit");
let (mut fixture, model, _) = classic("general");
press(&mut fixture, "Snap");
press(&mut fixture, "OK");
assert!(model.borrow().saved, "OK applies the edit");
}
@@ -1,6 +1,7 @@
//! The data and rules of the preferences family: the search over the row model and the settings document, the
//! window's answers and the hex codec.
pub(crate) mod classic;
pub(crate) mod live;
pub(crate) mod model;
pub(crate) mod page;