diff --git a/crates/platform/src/autosave/recovery.rs b/crates/platform/src/autosave/recovery.rs index 2d72999a7..440e24475 100644 --- a/crates/platform/src/autosave/recovery.rs +++ b/crates/platform/src/autosave/recovery.rs @@ -168,8 +168,11 @@ impl RecoveryStore { adopted.get(&id).cloned().unwrap_or_else(|| format!("doc-{}-{id}", self.session)) } - /// Writes a copy of document `id`; call from a job. + /// Writes a copy of document `id`; call from a job. Makes the folder again if it was removed + /// since the store opened. + // pdfcraft: crates/ui-egui/src/persist/recovery.rs:215 (create_dir before the write) pub fn write(&self, id: u64, meta: &RecoveryMeta, bytes: &[u8]) -> std::io::Result<()> { + create_private_dir(&self.dir)?; let key = self.key(id); let mut meta = meta.clone(); meta.extension = sanitize_extension(&meta.extension); diff --git a/crates/platform/src/autosave/timer.rs b/crates/platform/src/autosave/timer.rs index 0f08170b3..55b11fb28 100644 --- a/crates/platform/src/autosave/timer.rs +++ b/crates/platform/src/autosave/timer.rs @@ -82,12 +82,15 @@ pub struct Autosave { saved: HashMap, in_flight: HashMap, due_now: bool, + /// A document has changes no autosave holds or is writing: a dirty revision neither autosaved + /// nor in flight, or one whose autosave failed. + pending: bool, } impl Autosave { /// `None` turns autosave off (PhotoCraft's `fileHandling.autosave = false`). pub fn new(interval: Option) -> Self { - Self { interval, next: None, saved: HashMap::new(), in_flight: HashMap::new(), due_now: false } + Self { interval, next: None, saved: HashMap::new(), in_flight: HashMap::new(), due_now: false, pending: false } } /// A changed preference; the next deadline moves to now plus the new interval. @@ -131,6 +134,7 @@ impl Autosave { self.in_flight.remove(id); } let mut due = AutosaveDue { save: Vec::new(), discard }; + self.pending = docs.iter().any(|d| self.needs_save(d)); let Some(interval) = self.interval else { self.next = None; return due; @@ -146,14 +150,20 @@ impl Autosave { } self.next = Some(now + interval); for d in docs { - if d.dirty && self.saved.get(&d.id) != Some(&d.revision) && !self.in_flight.contains_key(&d.id) { + if self.needs_save(&d) { self.in_flight.insert(d.id, d.revision); due.save.push(d.id); } } + self.pending = false; due } + /// Whether `doc` has a revision to autosave that no autosave holds or is writing. + fn needs_save(&self, doc: &AutosaveDoc) -> bool { + doc.dirty && self.saved.get(&doc.id) != Some(&doc.revision) && !self.in_flight.contains_key(&doc.id) + } + /// An autosave ended. On success `revision` is remembered; on failure the status text /// ([`AUTOSAVE_FAILED`] filled in) comes back for the status bar. pub fn finished(&mut self, id: u64, revision: u64, result: Result<(), String>) -> Option { @@ -168,7 +178,10 @@ impl Autosave { self.saved.insert(id, revision); None } - Err(error) => Some(AUTOSAVE_FAILED.replace("{error}", &error)), + Err(error) => { + self.pending = true; + Some(AUTOSAVE_FAILED.replace("{error}", &error)) + } } } @@ -179,8 +192,11 @@ impl Autosave { self.in_flight.remove(&id); } - /// When the next interval ends, for `request_repaint_after`. + /// When the next interval ends, for `request_repaint_after`; `None` while nothing is left to + /// autosave (as of the last [`due`](Self::due), or a failed [`finished`](Self::finished)), so + /// an idle window can sleep. The clock keeps running: an edit wakes the window, and its `due` + /// call brings the deadline back. pub fn deadline(&self) -> Option { - self.next + self.next.filter(|_| self.pending) } } diff --git a/crates/platform/src/autosave_tests.rs b/crates/platform/src/autosave_tests.rs index 1b8450802..34170c1e6 100644 --- a/crates/platform/src/autosave_tests.rs +++ b/crates/platform/src/autosave_tests.rs @@ -78,6 +78,40 @@ fn due_picks_dirty_changed_documents_each_interval() { assert_eq!(timer.deadline(), None); } +// The deadline wakes the window only while something waits to be autosaved: none when every +// document is clean, autosaved or being written; back on an edit or a failed write. +#[test] +fn the_deadline_is_none_while_nothing_waits_to_be_autosaved() { + let minute = Duration::from_secs(60); + let t0 = Instant::now(); + let mut timer = Autosave::new(Some(minute)); + timer.due(t0, [doc(1, 1, false)]); + assert_eq!(timer.deadline(), None, "a clean document has nothing to save"); + timer.due(t0 + minute / 2, [doc(1, 2, true)]); + assert!(timer.deadline().is_some(), "an edit brings the deadline back"); + assert_eq!(timer.due(t0 + minute, [doc(1, 2, true)]).save, vec![1]); + assert_eq!(timer.deadline(), None, "the revision is being written"); + assert_eq!(timer.finished(1, 2, Ok(())), None); + timer.due(t0 + minute * 2, [doc(1, 2, true)]); + assert_eq!(timer.deadline(), None, "the revision is autosaved"); + timer.due(t0 + minute * 5 / 2, [doc(1, 3, true)]); + assert!(timer.deadline().is_some()); + assert_eq!(timer.due(t0 + minute * 3, [doc(1, 3, true)]).save, vec![1]); + assert!(timer.finished(1, 3, Err("disk full".into())).is_some()); + assert!(timer.deadline().is_some(), "a failed revision is tried again"); +} + +// An autosave after the recovery folder was removed (a cleaner, the user) makes it again. +#[test] +fn a_write_after_the_folder_was_removed_makes_it_again() { + let scratch = Scratch::new(); + let dir = scratch.0.join("Recovery"); + let store = RecoveryStore::open(&dir).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + store.write(1, &meta("a.psd", 1), b"work").unwrap(); + assert_eq!(std::fs::read(dir.join(format!("{}.pcraft", store.key(1)))).unwrap(), b"work"); +} + // A copy written by a run that is gone is a leftover; one of a live instance (its lock held) is // not; discard removes copy and sidecar. #[test] diff --git a/crates/print/src/ui/dialog.rs b/crates/print/src/ui/dialog.rs index d4055c857..bc738c314 100644 --- a/crates/print/src/ui/dialog.rs +++ b/crates/print/src/ui/dialog.rs @@ -16,7 +16,7 @@ use craft_ui::layout::RowAlign; use craft_ui::layout_components::{Row, Stack}; use craft_ui::notices::{Notice, NoticeLayout}; use craft_ui::patterns::form_dialogs::{ - DialogFields, FieldValue, FormDialog, HostRequests, PagerStep, PanePager, Param, ParamRows, set_color_field, set_param_field, + DialogFields, FieldValue, FormDialog, HostRequests, PagerStep, PanePager, Param, ParamKind, ParamRows, set_color_field, }; use craft_ui::primitives::{ContentPainterCx, TextRun, Wrap, fill_polygon}; use craft_ui::runtime::env::{Env, Label}; @@ -1231,7 +1231,9 @@ impl StackDialog for HostedPrint { } /// The `Settings` keys (`printer`, `copies`, `duplex`, `grayscale`, `collate`) and each section parameter's value as - /// [`DialogFields`] serializes it. `printer` is the printer's name, or `null` for Save as PDF. + /// [`DialogFields`] serializes it. `printer` is the printer's name, or `null` for Save as PDF. With a preview pager, + /// `sheet` is the sheet it shows (from 1) and `sheets` how many there are. `notes` lists the keys of the sections' + /// read-only text rows ([`Param::read_only_text`]) the values show, in order: what the dialog tells the user. fn json_fields(&self) -> Option { let mut map = match serde_json::to_value(&self.fields).ok()? { serde_json::Value::Object(map) => map, @@ -1247,6 +1249,13 @@ impl StackDialog for HostedPrint { map.insert("duplex".to_owned(), duplex_json(settings.duplex)); map.insert("grayscale".to_owned(), settings.grayscale.into()); map.insert("collate".to_owned(), settings.collate.into()); + if let Some(pager) = &self.preview_pager { + map.insert("sheet".to_owned(), pager.shown.into()); + map.insert("sheets".to_owned(), pager.count.into()); + } + let notes = self.sections.iter().flat_map(|section| §ion.params); + let notes = notes.filter(|param| matches!(param.kind, ParamKind::ReadOnlyText { .. }) && param.visible(&self.fields)); + map.insert("notes".to_owned(), notes.map(|param| serde_json::Value::from(param.key.clone())).collect()); if let Some(form) = &self.json_form { form(&self.fields, &mut map); } @@ -1255,7 +1264,9 @@ impl StackDialog for HostedPrint { /// Sets a `Settings` key, or a section parameter through the shared parameter-field rule. `printer` takes a listed /// printer's name, or `null` for Save as PDF where the layout offers it; the write is a choice the app takes with - /// [`take_printer_chosen`](HostedPrint::take_printer_chosen). + /// [`take_printer_chosen`](HostedPrint::take_printer_chosen). A section parameter's set is recorded as an edit of its + /// row, as the user's is ([`HostRequests::set_field`]): the app reads it with `take_edited` in its next pass, so + /// the app's own value does not overwrite it. fn set_json_field(&mut self, _: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> { match field { "printer" => { @@ -1281,7 +1292,7 @@ impl StackDialog for HostedPrint { let section = self.sections.iter().find(|section| section.params.iter().any(|param| param.key == field || param.unit_key() == Some(field))); let section = section.ok_or_else(|| FieldRefusal::Unknown.message(field))?; - return set_param_field(§ion.params, &mut self.fields, field, value); + return self.requests.set_field(§ion.params, &mut self.fields, field, value); } } Ok(()) diff --git a/crates/print/tests/it/dialog.rs b/crates/print/tests/it/dialog.rs index 745c91fcf..19982d873 100644 --- a/crates/print/tests/it/dialog.rs +++ b/crates/print/tests/it/dialog.rs @@ -6,11 +6,12 @@ use std::sync::mpsc::channel; use craft_behavior::EditEvent; use craft_print::ui::{ - Destination, DriverControls, HostedPrint, PrintDialog, PrintFinish, PrintLayout, PrintSheet, Printer, Settings, SheetPage, State, + Destination, DriverControls, HostedPrint, PrintDialog, PrintFinish, PrintLayout, PrintSection, PrintSheet, Printer, Settings, SheetPage, + State, }; use craft_ui::contract::Bind; use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, StackDialog as _, dialog_id}; -use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue}; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, PanePager, Param}; use craft_ui::primitives::TextureCache; use craft_ui::runtime::env::{Label, Scale}; use craft_ui::testing::{Fixture, trial}; @@ -129,6 +130,38 @@ fn the_json_form_adds_to_the_listing() { assert!(listed.get("copies").is_some(), "the settings keys stay"); } +/// The listing carries the preview pager's sheet and count, and the keys of the note rows the values show: a note +/// whose row is hidden is not listed. +#[trial] +fn the_listing_carries_the_pager_and_the_shown_notes() { + let notes = vec![ + Param::read_only_text("note.shown", Label::default(), "Printed as asked."), + Param::read_only_text("note.hidden", Label::default(), "Two-sided is off.").visible_when("two_sided", FieldValue::Bool(true)), + Param::parse_list(r#"{"range":1..9=1}"#).remove(0), + ]; + let mut dialog = HostedPrint::new(State::default(), DialogFields::default(), vec![PrintSection::new("Paper", notes)]); + dialog.set_preview_pager(Some(PanePager { shown: 2, count: 3, ..PanePager::default() })); + let listed = dialog.json_fields().expect("a listing"); + assert_eq!((listed["sheet"].as_u64(), listed["sheets"].as_u64()), (Some(2), Some(3))); + assert_eq!(listed["notes"], serde_json::json!(["note.shown"]), "only the shown note rows, and no other row"); + + dialog.fields_mut().set("two_sided", FieldValue::Bool(true)); + assert_eq!(dialog.json_fields().expect("a listing")["notes"], serde_json::json!(["note.shown", "note.hidden"])); +} + +/// A section value set through automation is recorded as an edit of its row, as the user's edit is, so the app's pass +/// that writes its own values back leaves it; a settings key is no row. +#[trial] +fn a_section_value_set_through_automation_is_an_edit() { + let rows = PrintSection::new("Pages", Param::parse_list(r#"{"range":1..9=1}"#)); + let mut dialog = HostedPrint::new(State::default(), DialogFields::default(), vec![rows]); + let ctx = egui::Context::default(); + dialog.set_json_field(&ctx, "range", serde_json::json!(4)).expect("the range row takes a number"); + dialog.set_json_field(&ctx, "copies", serde_json::json!(2)).expect("copies takes a count"); + assert_eq!(dialog.requests_mut().take_edited(), ["range"]); + assert_eq!(dialog.fields_mut().number("range"), Some(4.0)); +} + /// A held print dialog over the printer "Office", in a `DialogHost` run every pass. While `twice` is on, egui runs each /// frame twice and gives the frame's input to its first pass only. fn held_print(twice: &Rc>) -> (Fixture, Rc>) { diff --git a/crates/theme-store/README.md b/crates/theme-store/README.md index c941aa4b3..2dc3e23c5 100644 --- a/crates/theme-store/README.md +++ b/crates/theme-store/README.md @@ -38,7 +38,7 @@ match store.update(&base, SelectionChange::pick_theme(&picked)) { | `ThemeRecord`, `ThemeEntry`, `format` | a parsed user theme file (`craft-design-theme` v1, craft-theme's `format`) with its stored bytes, unknown keys included; the library skips files in another format, such as the pilot's `craft-theme` | | `SuiteClient` | what an app calls: per-frame `sync`, the optimistic `shown` choice, `change`, conflict and failure notices with `apply_mine` and `retry`, the `theme` lookup, `preview` for any theme's picker card | | `SuiteWatch`, `Snapshot`, `Op`, `OpOutput` | the store on a worker thread: snapshots by generation, queued operations with results | -| `ui` (feature `ui`) | the Preferences appearance page `AppearancePage` (modes, light and dark theme rows of `ThemeChip`s with favorites, Size and UI Font Size; tokens `theme_chip.*`); feature `screen-testing` adds egui_kittest input tests of the page | +| `ui` (feature `ui`) | the Preferences appearance page `AppearancePage` (modes, light and dark theme rows of `ThemeChip`s with favorites, Size, UI Font Size, Contrast and Motion, where an app leaves out favorites and the rows it does not keep; tokens `theme_chip.*`); feature `screen-testing` adds egui_kittest input tests of the page | | `FileStamp`, `library_files`, `selection_stamp`, `theme_stamp`, `parse_counts` | cheap change checks for a watcher | `Store` methods block on file I/O and on the lock (up to 2 s). Apps use `SuiteClient` over a diff --git a/crates/theme-store/src/ui/chip.rs b/crates/theme-store/src/ui/chip.rs index c08356b26..40e4ec3af 100644 --- a/crates/theme-store/src/ui/chip.rs +++ b/crates/theme-store/src/ui/chip.rs @@ -115,6 +115,10 @@ pub struct ThemeChip<'a> { /// Whether the chip shows the favourite star. #[prop] favorite: bool, + /// Whether the chip offers the favourite star (default on). Off, for an app that keeps no favourites, the chip has + /// no badge and says nothing of favourites. + #[prop] + can_favorite: bool, checked: bool, sampled: [Color32; 3], star: Option, @@ -129,6 +133,7 @@ impl<'a> ThemeChip<'a> { theme, dark, favorite: false, + can_favorite: true, checked: false, sampled: [Color32::TRANSPARENT; 3], star: None, @@ -178,7 +183,7 @@ impl Component for ThemeChip<'_> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { self.star = None; - if !(self.favorite || cx.hovered()) { + if !self.can_favorite || !(self.favorite || cx.hovered()) { return; } // The badge sits in the chip's top end corner, inside its rect: overhanging it would reach into the next chip. @@ -213,7 +218,7 @@ impl Component for ThemeChip<'_> { fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { let words = cx.words::(); - if self.favorite { + if self.favorite && self.can_favorite { access.value(words.favorite.as_str()); } if self.star.is_some() { diff --git a/crates/theme-store/src/ui/page.rs b/crates/theme-store/src/ui/page.rs index 268b09c14..c2f338073 100644 --- a/crates/theme-store/src/ui/page.rs +++ b/crates/theme-store/src/ui/page.rs @@ -73,7 +73,9 @@ impl Outcome for AppearancePageOutput { /// Rows, top to bottom, with the labels at the start: Appearance Mode (Sync with system, Dark, Light), Light Theme and /// Dark Theme (a row of [`ThemeChip`]s each: the built-in themes, then the library's, each in the rows for the modes it /// has; "Active" after the chips of the row for the mode the app shows now), Size (Compact, Comfortable), UI Font Size -/// (the [`TextSize`] steps), Contrast and Motion (Sync with system, Standard or Full, High or Reduced). +/// (the [`TextSize`] steps), Contrast and Motion (Sync with system, Standard or Full, High or Reduced). An app that keeps +/// its own appearance shows only what it keeps: the `size`, `text_size` and `contrast` props leave those rows out, and +/// `can_favorite` the favourite stars and their menu. /// /// The page edits the bound draft, a [`SelectionChange`] the Preferences model keeps; the chips and lists show /// [`SuiteClient::shown`] (through the [`SuiteView`]) with the draft applied. Nothing reaches the suite until the window applies: the model's @@ -88,9 +90,19 @@ pub struct AppearancePage<'a> { /// The themes marked with a filled star. #[prop] favorites: &'a [ThemeId], + /// Offers favourites (default on): the chips' stars and their Add to Favorites / Remove from Favorites menu. An app + /// that keeps no favourites turns it off; the page then reports no `favorite_toggled`. + #[prop] + can_favorite: bool, + /// Shows the Size row (default on); an app that keeps no size of its own turns it off. + #[prop] + size: bool, /// Shows the UI Font Size row (default on); an app with its own text-size control turns it off. #[prop] text_size: bool, + /// Shows the Contrast row (default on); an app that keeps no contrast choice turns it off. + #[prop] + contrast: bool, /// The system shows its dark mode: which row is active when the mode follows the system. #[prop] system_dark: bool, @@ -99,12 +111,12 @@ pub struct AppearancePage<'a> { impl<'a> AppearancePage<'a> { /// The page over the suite `suite` (from [`SuiteClient::view`]), editing `draft`. pub fn new(suite: &'a SuiteView, draft: Bind<'a, SelectionChange>) -> Self { - AppearancePage { suite, draft, favorites: &[], text_size: true, system_dark: false } + AppearancePage { suite, draft, favorites: &[], can_favorite: true, size: true, text_size: true, contrast: true, system_dark: false } } /// Shows the page. pub fn show(self, ui: &mut Ui) -> AppearancePageOutput { - let AppearancePage { suite, draft, favorites, text_size, system_dark } = self; + let AppearancePage { suite, draft, favorites, can_favorite, size, text_size, contrast, system_dark } = self; let words = Env::of(ui).words::(); let themes = themes(suite); let mut held = Held::new(draft); @@ -130,6 +142,7 @@ impl<'a> AppearancePage<'a> { } for dark in [false, true] { let (title, chosen) = if dark { (&words.dark_theme, &shown.theme_dark) } else { (&words.light_theme, &shown.theme_light) }; + let favorites = can_favorite.then_some(favorites); let row = ChipRow { title, dark, active: dark == dark_active, chosen: chosen.as_ref(), themes: &themes, favorites, words: &words }; let (picked, flipped) = row.show(ui); if let Some(id) = picked { @@ -137,9 +150,11 @@ impl<'a> AppearancePage<'a> { } toggled = toggled.take().or(flipped); } - let sizes = [Entry::new(Size::Compact, words.compact.clone()), Entry::new(Size::Comfortable, words.comfortable.clone())]; - if let Some(size) = pick(ui, &words.size, "size", shown.size.unwrap_or_default(), &sizes) { - now.size = Some(size); + if size { + let sizes = [Entry::new(Size::Compact, words.compact.clone()), Entry::new(Size::Comfortable, words.comfortable.clone())]; + if let Some(size) = pick(ui, &words.size, "size", shown.size.unwrap_or_default(), &sizes) { + now.size = Some(size); + } } if text_size { let steps = [ @@ -152,13 +167,15 @@ impl<'a> AppearancePage<'a> { now.text_size = Some(step); } } - let contrasts = [ - Entry::new(ContrastChoice::System, words.contrast_system.clone()), - Entry::new(ContrastChoice::Standard, words.contrast_standard.clone()), - Entry::new(ContrastChoice::High, words.contrast_high.clone()), - ]; - if let Some(contrast) = pick(ui, &words.contrast, "contrast", shown.contrast.unwrap_or_default(), &contrasts) { - now.contrast = Some(contrast); + if contrast { + let contrasts = [ + Entry::new(ContrastChoice::System, words.contrast_system.clone()), + Entry::new(ContrastChoice::Standard, words.contrast_standard.clone()), + Entry::new(ContrastChoice::High, words.contrast_high.clone()), + ]; + if let Some(contrast) = pick(ui, &words.contrast, "contrast", shown.contrast.unwrap_or_default(), &contrasts) { + now.contrast = Some(contrast); + } } let motions = [ Entry::new(MotionChoice::System, words.motion_system.clone()), @@ -204,7 +221,8 @@ struct ChipRow<'a> { active: bool, chosen: Option<&'a ThemeId>, themes: &'a [ThemeDef], - favorites: &'a [ThemeId], + /// The favourite themes; `None` offers no favourites. + favorites: Option<&'a [ThemeId]>, words: &'a AppearanceWords, } @@ -220,7 +238,11 @@ impl ChipRow<'_> { let group = RadioGroup::new(self.title.clone(), Bind::given(self.chosen.cloned())).id_salt("group").show(ui, |ui, _| { Row::new().wrap(true).show(ui, |ui, _| { for theme in self.themes.iter().filter(|theme| fits(theme)) { - let favorite = self.favorites.contains(&theme.id); + let Some(favorites) = self.favorites else { + ThemeChip::new(theme, self.dark).can_favorite(false).id_salt(theme.id.as_str()).show(ui); + continue; + }; + let favorite = favorites.contains(&theme.id); let chip = ThemeChip::new(theme, self.dark).favorite(favorite).id_salt(theme.id.as_str()).show(ui); if chip.favorite_clicked { flipped = Some(theme.id.clone()); diff --git a/crates/theme-store/src/ui/stories.rs b/crates/theme-store/src/ui/stories.rs index 3350b963a..e93e069eb 100644 --- a/crates/theme-store/src/ui/stories.rs +++ b/crates/theme-store/src/ui/stories.rs @@ -27,6 +27,30 @@ fn appearance_page_without_text_size(ui: &mut Ui, data: &mut StoryData) -> Story AppearancePage::new(&client, Bind::bound(data.value("plain", SelectionChange::default()))).text_size(false).system_dark(true).show(ui).into() } +/// The page of an app that keeps its own appearance: the mode, the two theme rows without favourite stars, and Motion. +#[story(AppearancePage<'static>, covers = [], drive = Drive::Never)] +fn appearance_page_with_kept_rows_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let client = SuiteClient::memory().view(); + let draft = Bind::bound(data.value("kept", SelectionChange::default())); + AppearancePage::new(&client, draft).can_favorite(false).size(false).text_size(false).contrast(false).show(ui).into() +} + +/// Chips that offer no favourite star, for an app that keeps no favourites. +#[story(ThemeChip<'static>, covers = [], drive = Drive::Never)] +fn theme_chips_without_favorites(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let themes = builtins(); + let chosen = data.value("chosen", Some(themes[1].id.clone())); + RadioGroup::new("Light Theme", Bind::bound(chosen)) + .show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + for theme in themes.iter().take(4) { + ThemeChip::new(theme, false).can_favorite(false).id_salt(theme.id.as_str()).show(ui); + } + }); + }) + .into() +} + /// One theme's chips in a group: plain, chosen, favourite, and both. A click on a star toggles the chip's favourite. #[story(ThemeChip<'static>, covers = [Default], drive = Drive::Never)] fn theme_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { diff --git a/crates/theme-store/tests/it/main.rs b/crates/theme-store/tests/it/main.rs index c99ae0479..049d58a39 100644 --- a/crates/theme-store/tests/it/main.rs +++ b/crates/theme-store/tests/it/main.rs @@ -1 +1,40 @@ //! The screen tests of craft-theme-store, folded into the lib's test target. + +use craft_theme::builtins; +use craft_theme_store::ui::AppearancePage; +use craft_theme_store::{SelectionChange, SuiteClient}; +use craft_ui::contract::Bind; +use craft_ui::testing::{Fixture, trial}; + +/// The page over a memory suite with the first built-in theme a favourite; `keep_only` leaves out favourites, Size and +/// Contrast, as an app with its own appearance setting does. +fn page(keep_only: bool) -> Fixture { + let favorites = vec![builtins()[0].id.clone()]; + let mut draft = SelectionChange::default(); + let mut fixture = Fixture::new(move |ui| { + let client = SuiteClient::memory().view(); + let page = AppearancePage::new(&client, Bind::bound(&mut draft)).favorites(&favorites); + let page = if keep_only { page.can_favorite(false).size(false).contrast(false) } else { page }; + page.show(ui); + }); + fixture.settle(); + fixture +} + +// An app that keeps its own appearance shows only what it keeps: no Size or Contrast row and no favourite star, while +// the mode, theme and Motion rows stay; the full page has them all. +#[trial] +fn an_app_with_its_own_appearance_shows_only_the_rows_it_keeps() { + let star = format!("Remove from Favorites: {}", builtins()[0].name); + let full = page(false); + for label in ["Size", "Contrast", star.as_str()] { + assert!(full.by_label(label).is_some(), "the full page has {label}"); + } + let kept = page(true); + for label in ["Size", "Contrast", star.as_str()] { + assert!(kept.by_label(label).is_none(), "the kept page leaves out {label}"); + } + for label in ["Appearance Mode", "Light Theme", "Dark Theme", "Motion"] { + assert!(kept.by_label(label).is_some(), "the kept page keeps {label}"); + } +} diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs index c7069e7fe..e97a7625a 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs @@ -7,7 +7,7 @@ use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, List use super::form::{FormDialog, FormDialogWords}; use super::host_requests::HostRequests; -use super::param::{Param, ParamKind, edited_rows, open_fields, set_color_field}; +use super::param::{Param, ParamKind, open_fields, set_color_field}; use super::preview::{PagerStep, PaneOverlay, PanePager, PreviewPane, PreviewState, PreviewView, PreviewZoom}; use super::rows::{ParamRows, ParamRowsOutput}; @@ -1082,7 +1082,9 @@ type Build = dyn for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send; /// capture a picture that changes; [`is_previewing`](HostedParamDialog::is_previewing) and /// [`is_comparing`](HostedParamDialog::is_comparing) say what to render. /// - What the host's jobs find about the values comes the same way: the lines under the rows from -/// [`set_notes`](HostedParamDialog::set_notes), and whether OK can be pressed from +/// [`set_notes`](HostedParamDialog::set_notes), a row's label and whether it shows from +/// [`set_param_label`](HostedParamDialog::set_param_label) and [`set_param_shown`](HostedParamDialog::set_param_shown), +/// and whether OK can be pressed from /// [`set_ready`](HostedParamDialog::set_ready). What the values alone decide stays in `build`. /// - With [`held_ok`](HostedParamDialog::held_ok), OK files its answer for the host to check /// ([`take_ok`](HostedParamDialog::take_ok)) and the dialog waits, OK disabled, for @@ -1120,6 +1122,8 @@ pub struct HostedParamDialog { tint: Option, /// The lines under the rows the host last gave (`set_notes`). notes: Vec