diff --git a/crates/color/src/ui/paint_chip.rs b/crates/color/src/ui/paint_chip.rs index a9e159230..54d9e01b1 100644 --- a/crates/color/src/ui/paint_chip.rs +++ b/crates/color/src/ui/paint_chip.rs @@ -16,7 +16,7 @@ use craft_theme::Srgba; use craft_ui::buttons::Button; use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchFace}; use craft_ui::contract::{ - Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, + Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, }; use craft_ui::display::{Shade, Text}; @@ -480,62 +480,73 @@ impl Component for PaintChip<'_> { let full_picker = self.full_picker; let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated()); let solid_now = if let Paint::Solid(color) = &paint { Some(*color) } else { None }; - let entries: Vec> = self.kinds().into_iter().map(|kind| Entry::new(kind, kind_label(&words, kind))).collect(); + let kinds = self.kinds(); + let entries: Vec> = kinds.iter().map(|kind| Entry::new(*kind, kind_label(&words, *kind))).collect(); + // Each tab's page shows the paint a switch to it would set, so a hidden page measures as it will show. + let page_paints: Vec<(FillKind, Paint)> = + kinds.iter().map(|kind| (*kind, if *kind == current { paint.clone() } else { self.switched(*kind, solid) })).collect(); let (gradient, pattern, picture, swatches) = (&mut self.gradient, &mut self.pattern, &mut self.picture, &mut self.swatches); let shown = ui.show(popup, Overlay::popover(), |ui, _| { - let mut shown = Shown::default(); let mut kind = current; + let mut full_picker_pressed = false; Row::new().show(ui, |ui, _| { Segmented::new(name.clone(), Bind::bound(&mut kind), &entries).show(ui); if full_picker { let button = Button::new(words.color_picker.clone()).show(ui); - shown.full_picker = craft_ui::contract::clicked(&button); + full_picker_pressed = craft_ui::contract::clicked(&button); } }); - shown.kind = (kind != current).then_some(kind); - match &paint { - Paint::None => {} - Paint::Solid(color) => { - let picked = compact_picker(name.clone(), Bind::given(PickedColor::rgb(*color)), sampled).alpha(true).eyedropper(true).show(ui); - shown.edit = picked.events; - shown.screen_pick = picked.screen_pick; - if !recent_cells.is_empty() { - Text::new(words.recent.clone()).shade(Shade::Faint).show(ui); - let mut chosen = *color; - let recent = SwatchPalette::new(words.recent.clone(), Bind::bound(&mut chosen), &recent_cells).show(ui); - shown.picked = recent.edit.as_ref().and_then(|edit| edit.value()).copied(); - } - if let Some((groups, state)) = swatches.as_mut() { - let groups: &[SwatchGroup] = groups; - let rows = swatch_rows(groups, &swatch_words); - let colors: HashMap<&str, &SwatchColor> = - groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect(); - let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &rows) - .toolbar(false) - .row_menu(false) - .default_open(DefaultOpen::None) - .room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS) - .thumb(|painter: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| { - if let SwatchKey::Swatch(name) = info.key + let mut shown = Pages::new("paint", &kinds, ¤t).show(ui, |ui, page| { + let mut shown = Shown::default(); + let Some((_, paint)) = page_paints.iter().find(|(kind, _)| kind == page) else { return shown }; + match paint { + Paint::None => {} + Paint::Solid(color) => { + let picked = + compact_picker(name.clone(), Bind::given(PickedColor::rgb(*color)), sampled).alpha(true).eyedropper(true).show(ui); + shown.edit = picked.events; + shown.screen_pick = picked.screen_pick; + if !recent_cells.is_empty() { + Text::new(words.recent.clone()).shade(Shade::Faint).show(ui); + let mut chosen = *color; + let recent = SwatchPalette::new(words.recent.clone(), Bind::bound(&mut chosen), &recent_cells).show(ui); + shown.picked = recent.edit.as_ref().and_then(|edit| edit.value()).copied(); + } + if let Some((groups, state)) = swatches.as_mut() { + let groups: &[SwatchGroup] = groups; + let rows = swatch_rows(groups, &swatch_words); + let colors: HashMap<&str, &SwatchColor> = + groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect(); + let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &rows) + .toolbar(false) + .row_menu(false) + .default_open(DefaultOpen::None) + .room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS) + .thumb(|painter: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| { + if let SwatchKey::Swatch(name) = info.key + && let Some(color) = colors.get(name.as_str()) + { + SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(painter, rect); + } + }) + .show(ui); + for event in out.events { + if let PresetEvent::Select { key: SwatchKey::Swatch(name), .. } = event && let Some(color) = colors.get(name.as_str()) { - SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(painter, rect); + shown.picked = Some(color.to_srgb(cmyk)); } - }) - .show(ui); - for event in out.events { - if let PresetEvent::Select { key: SwatchKey::Swatch(name), .. } = event - && let Some(color) = colors.get(name.as_str()) - { - shown.picked = Some(color.to_srgb(cmyk)); } } } + Paint::Gradient(_) => shown.gradient = gradient.as_mut().and_then(|(_, editor)| editor.show(ui)), + Paint::Pattern(_) => shown.pattern = pattern.as_mut().and_then(|(_, editor)| editor.show(ui)), + Paint::Picture(_) => shown.picture = picture.as_mut().and_then(|(_, editor)| editor.show(ui)), } - Paint::Gradient(_) => shown.gradient = gradient.as_mut().and_then(|(_, editor)| editor.show(ui)), - Paint::Pattern(_) => shown.pattern = pattern.as_mut().and_then(|(_, editor)| editor.show(ui)), - Paint::Picture(_) => shown.picture = picture.as_mut().and_then(|(_, editor)| editor.show(ui)), - } + shown + }); + shown.kind = (kind != current).then_some(kind); + shown.full_picker = full_picker_pressed; shown }); let Some(shown) = shown else { return }; diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index e46b1b273..c756b6d3d 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -21,6 +21,7 @@ mod level_table; mod looks; mod mount; pub mod overlay; +mod pages; mod paint_ui; mod props; mod registry; @@ -88,6 +89,7 @@ pub use lazy::Lazy; pub use level::{Catalog, CatalogEntry, Level, StoryLayout, Surface, catalog, stale_table_rows, story_title}; pub use looks::Looks; pub use overlay::{Overlay, OverlayUi, Overlays, Popup, PopupHandle, SizeLimits, Trigger}; +pub use pages::Pages; pub use paint_ui::PaintUi; pub use props::{Common, Props, Resolved, Tooltip, TooltipAt, TooltipSpec, TooltipWhen}; #[doc(hidden)] diff --git a/crates/ui-contract/src/contract/pages.rs b/crates/ui-contract/src/contract/pages.rs new file mode 100644 index 000000000..6ca6fee43 --- /dev/null +++ b/crates/ui-contract/src/contract/pages.rs @@ -0,0 +1,98 @@ +//! `Pages`: pages that take turns in one place, which keeps the size of the largest so a switch neither moves nor +//! resizes what is around them. + +use crate::layout::flow_region; +use crate::runtime::egui::alloc; +use crate::runtime::layout_memory; +use crate::runtime::lazy::{self, Place}; +use crate::runtime::memory::sub; +use crate::runtime::{measure, reads, replay}; +use egui::{Pos2, Rect, Ui, UiBuilder, Vec2}; +use std::hash::Hash; + +/// Pages that take turns in one place, such as the paint kinds of a paint chip's popover: one shows, and the place +/// is as wide and as tall as the largest of them, so switching the page moves and resizes nothing around it. A child +/// of the shown page that fills its width takes the width of the largest page. +/// +/// The pages it does not show are measured only. Each runs in a measuring run (`measure::run`) inside an invisible egui +/// sizing child, where every component stops after its measure (steps 1 to 6): it senses nothing and adds no hit +/// shape, focus stop, access node, paint or memory write. A hidden page reuses the size its last measuring run found +/// while nothing it read has changed, under the settled rules of `Lazy::settles` for content without a content +/// version: it is measured again in a frame where a value it read was written, something in it still moves, the app +/// asked for a repaint, or the frame or the one before had input other than pointer motion. +/// +/// The page closure runs for the shown page and for every hidden page it measures, so it builds what it shows from its +/// page argument alone and changes nothing outside a component's value (a measuring run applies no edit). +#[must_use] +pub struct Pages<'a, K> { + salt: u64, + pages: &'a [K], + current: &'a K, +} + +impl<'a, K: Hash + PartialEq> Pages<'a, K> { + /// The pages `pages`, with `current` shown. `salt` names this set among the others in the same `Ui`. + pub fn new(salt: impl Hash, pages: &'a [K], current: &'a K) -> Self { + Pages { salt: hash(&salt), pages, current } + } + + /// Shows the current page through `page` in a child `Ui` placed in flow in `ui`, at the size of the largest page, + /// and returns what `page` returned for it. + pub fn show(self, ui: &mut Ui, mut page: impl FnMut(&mut Ui, &K) -> R) -> R { + let ctx = ui.ctx().clone(); + let base = sub(ui.scope_id(), ("pages", self.salt)); + let region = flow_region(ui); + let layout = *ui.layout(); + let hidden = self.pages.iter().filter(|key| *key != self.current).fold(Vec2::ZERO, |largest, key| { + let id = sub(base, hash(key)); + let place = Place { + room: Rect::from_min_size(Pos2::ZERO, Vec2::new(region.width(), f32::INFINITY)), + clip: Rect::EVERYTHING, + layer: ui.layer_id(), + layout, + pixels_per_point: ctx.pixels_per_point(), + }; + let kept = lazy::measured(&ctx, id, place).map(|(size, reads)| { + // The page reads them again, as far as an edit later in the pass sees it. + for key in reads { + reads::note(&ctx, key, id, true, &[]); + } + size + }); + let size = kept.unwrap_or_else(|| { + replay::open(&ctx); + let size = measure::run(&ctx, || { + // What the hidden page measures joins no transcript around it: the run that shows the pages does + // not show it, so nothing there checks it. + layout_memory::boundary(&ctx, true, || { + let room = Rect::from_min_size(region.min, Vec2::new(region.width(), f32::INFINITY)); + let mut child = alloc::child(ui, UiBuilder::new().max_rect(room).layout(layout).id_salt(id).sizing_pass().invisible()); + page(&mut child, key); + child.min_rect().size() + }) + }); + let record = replay::close(&ctx, ui.layer_id()); + lazy::measured_run(&ctx, id, record.facts, place, size); + size + }); + largest.max(size) + }); + let id = sub(base, hash(self.current)); + let mut child = alloc::child(ui, UiBuilder::new().max_rect(region).layout(layout).id_salt(id)); + child.set_min_size(hidden.min(region.size())); + let out = page(&mut child, self.current); + let rect = child.min_rect(); + drop(child); + // What the place took comes from the hidden pages' measures as well as from the shown page's components. + layout_memory::backstop(&ctx, base, rect.size()); + alloc::advance_past(ui, rect); + out + } +} + +fn hash(value: &impl Hash) -> u64 { + use std::hash::Hasher as _; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + value.hash(&mut hasher); + hasher.finish() +} diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 4f897ea44..6e56309a9 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -113,6 +113,8 @@ struct Entry { decided: Option<(u64, bool)>, /// The last real run of a settling child. settled: Option>, + /// The last measuring run of a measure-only child (`measured`). + measured: Option, /// Whether this pass replays the settling child's last run, under the pass number that decided it. replays: Option<(u64, bool)>, /// The last frame that read or wrote the entry. @@ -130,6 +132,18 @@ pub(crate) struct Place { pub(crate) pixels_per_point: f32, } +/// The last measuring run of a measure-only child: content a pass measures and never shows, as a page `Pages` holds +/// out of view. +#[derive(Clone)] +struct MeasuredRun { + facts: replay::Facts, + /// The pass and the frame it ran in. + pass: u64, + frame: u64, + place: Place, + size: Vec2, +} + /// The last real run of a settling child. struct Settled { record: Record, @@ -159,6 +173,19 @@ struct Changes { edited: (u64, HashSet), } +impl Changes { + /// Looks at the input of the pass `pass_nr` of `frame` once: input other than pointer motion unsettles the children + /// with no content version for this frame and the next. + fn scan(&mut self, pass_nr: u64, frame: u64, input: bool) { + if self.scanned != pass_nr { + self.scanned = pass_nr; + if input { + self.input_through = self.input_through.max(frame + 1); + } + } + } +} + #[derive(Default)] pub(crate) struct Store { entries: IdMap, @@ -272,12 +299,7 @@ pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, pl let now = frame::clock(ctx); let held = (input_state::dragged(ctx), focus_state::focused(ctx)); let settled = with(ctx, |store, pass_nr, frame| { - if store.changes.scanned != pass_nr { - store.changes.scanned = pass_nr; - if input { - store.changes.input_through = store.changes.input_through.max(frame + 1); - } - } + store.changes.scan(pass_nr, frame, input); let changes = &store.changes; // Usually empty: only the values written this frame. let edited = (changes.edited.0 == frame).then(|| changes.edited.1.clone()); @@ -292,10 +314,8 @@ pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, pl settled.frame < frame && settled.content == content && !settled.engaged - && !facts.unsettled && !facts.blocked - && facts.wake.is_none_or(|at| at > now) - && edited.as_ref().is_none_or(|edited| facts.reads.is_disjoint(edited)) + && facts.quiet(now, edited.as_ref()) && !settled.record.focus.stop_ids().any(|stop| targets.contains(&Some(stop))) && ![held.0, held.1].iter().flatten().any(|widget| settled.record.widgets.contains(widget)) }); @@ -361,6 +381,40 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec }); } +/// Whether the measure-only child `id` takes the size its last measuring run at `place` found, in place of measuring +/// again, and that size. It does when that run was in this pass, or in an earlier frame and since then none of the +/// settled rules a measure reads has broken (`settled`): nothing in it moves or asked to be shown again, no value it +/// read changed, no frame unsettled every child, and the frame and the one before had no input other than pointer +/// motion. A measure-only child has no place on screen, no stops and no widgets, so the pointer, the focus and what a +/// replay repeats do not count. Returns the values that run read with the size: the caller notes them as read again, +/// so an edit of one later in the pass reruns it. +pub(crate) fn measured(ctx: &Context, id: Id, place: Place) -> Option<(Vec2, Vec)> { + let input = ctx.input(|input| { + input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) + }); + let now = frame::clock(ctx); + with(ctx, |store, pass_nr, frame| { + store.changes.scan(pass_nr, frame, input); + let changes = &store.changes; + let edited = (changes.edited.0 == frame).then(|| changes.edited.1.clone()); + let unsettled = changes.unsettled_through >= frame || changes.input_through >= frame; + let run = store.touch(None, id, frame).measured.as_ref()?; + let same_pass = run.pass == pass_nr; + let quiet = !unsettled && run.frame < frame && run.facts.quiet(now, edited.as_ref()); + // This pass's measuring run found the size the pass places by: a later run in the pass takes it, whatever room it + // has. + (same_pass || (run.place == place && quiet)).then(|| (run.size, run.facts.reads.iter().copied().collect())) + }) +} + +/// Keeps the measuring run of the measure-only child `id` at `place`: what its record found (`replay::close`) and the +/// size it took. +pub(crate) fn measured_run(ctx: &Context, id: Id, facts: replay::Facts, place: Place, size: Vec2) { + with(ctx, |store, pass_nr, frame| { + store.touch(None, id, frame).measured = Some(MeasuredRun { facts, pass: pass_nr, frame, place, size }); + }); +} + /// Notes that the value `key` changed in this frame: a settling child that read it runs. pub(crate) fn note_edit(ctx: &Context, key: BindKey) { with(ctx, |store, _, frame| { diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index 41ab0882b..ce184f479 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -88,6 +88,8 @@ pub(crate) fn note(ctx: &Context, key: BindKey, reader: Id, measuring: bool, sam let runs = if measuring { with_runs(ctx, |runs| runs.clone()) } else { Vec::new() }; let samples = Samples::from_slice(samples); if measuring && crate::runtime::measure::active(ctx) { + // The records open around a measuring run (a measure-only child's) hold the read too. + crate::runtime::replay::note_read(ctx, key); layout_memory::contribute(ctx, Arc::new(MeasuredRead { key, reader, runs, samples })); } else { let read = Read { key, reader, measuring, runs, samples }; diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 6ae7d5d91..d9b7d67ca 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -1,5 +1,6 @@ //! Run records: what a real run of a settling region (`Lazy::settles`) added to its pass, so a later pass adds it again -//! in place of running the region. A record holds the region's paint, egui widget rects and AccessKit nodes (egui's +//! in place of running the region. A measuring run of a measure-only child (a page `Pages` holds out of view) opens a +//! record too; only its facts are kept, so a later pass takes its size in place of measuring it again. A record holds the region's paint, egui widget rects and AccessKit nodes (egui's //! pass records), what it registered with the focus service (`focus::Transcript`), and a journal of every other //! registration the services below take per pass: each service that keeps one notes it here while a record is open, //! as the call that makes it again. Records nest: a region's record holds the records its settled regions replayed. @@ -115,6 +116,14 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { Record { focus: focus::transcript(ctx, open.focus), journal, widgets: egui.widgets().iter().map(|widget| widget.id).collect(), egui, facts } } +impl Facts { + /// Whether the run these facts are of still holds at `now`, after the values `edited` changed in the frame: nothing + /// in it moves, the time it asked to be shown again has not come, and it read none of them. + pub(crate) fn quiet(&self, now: f64, edited: Option<&HashSet>) -> bool { + !self.unsettled && self.wake.is_none_or(|at| at > now) && edited.is_none_or(|edited| self.reads.is_disjoint(edited)) + } +} + fn min_wake(a: Option, b: Option) -> Option { match (a, b) { (Some(a), Some(b)) => Some(a.min(b)), diff --git a/crates/ui-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index c75a53dd4..b37aa95dc 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -3,6 +3,7 @@ mod fixes; mod gesture; mod hit_order; +mod pages; mod pointer; mod style; mod visited_type; diff --git a/crates/ui-contract/tests/it/contract/pages.rs b/crates/ui-contract/tests/it/contract/pages.rs new file mode 100644 index 000000000..acf6b4394 --- /dev/null +++ b/crates/ui-contract/tests/it/contract/pages.rs @@ -0,0 +1,117 @@ +//! `Pages`: a hidden page is measured only, and its measure is reused while nothing it read changed. + +use craft_ui::contract::{Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Pages, Props as _, Role, Show as _}; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Frames, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Ui, Vec2}; +use std::cell::{Cell, RefCell}; + +/// A leaf as wide as its bound value, or as `fixed` when given; it sets its value to `set_to` when given. +#[derive(Component)] +struct Width<'a> { + #[common] + common: Common, + value: Bind<'a, f32>, + fixed: Option, + set_to: Option, +} + +impl Component for Width<'_> { + const ROLE: Role = Role::None; + type Style = PlainStyle; + type Output = EditResponse; + + fn style(_: &StyleCx<'_>, _: WidthStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(self.fixed.unwrap_or_else(|| cx.value().copied().unwrap_or(0.0)), 10.0) + } + + fn bind(&mut self) -> Option> { + Some(self.value.reborrow()) + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + if let Some(to) = self.set_to.take() { + cx.set(to); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> EditResponse { + cx.edit_response() + } +} + +/// Two pages: page 0 shows a fixed-width leaf that can edit `value`; page 1, hidden, is as wide as `value`. +struct Scene { + /// The value, kept in place across frames: a settled reader knows a bound value by where it lives. + value: RefCell, + /// What page 0's leaf sets the value to in the next pass that shows it. + set_to: Cell>, + /// The runs of the hidden page's closure. + hidden_runs: Cell, + /// The width the pages took in the last pass. + width: Cell, +} + +impl Scene { + fn new() -> Scene { + Scene { value: RefCell::new(60.0), set_to: Cell::new(None), hidden_runs: Cell::new(0), width: Cell::new(0.0) } + } + + fn show(&self, ui: &mut Ui) { + let pages = [0_u8, 1]; + let shown = ui.scope(|ui| { + Pages::new("trial", &pages, &0).show(ui, |ui, page| { + if *page == 1 { + self.hidden_runs.set(self.hidden_runs.get() + 1); + let mut value = self.value.borrow_mut(); + Width { common: Common::new(), value: Bind::bound(&mut *value), fixed: None, set_to: None }.id_salt("reader").show(ui); + } else { + let set_to = self.set_to.take(); + let mut value = self.value.borrow_mut(); + Width { common: Common::new(), value: Bind::bound(&mut *value), fixed: Some(20.0), set_to }.id_salt("editor").show(ui); + } + }); + }); + self.width.set(shown.response.rect.width()); + } + + /// The hidden page's runs in one frame with no input. + fn frame(&self, frames: &mut Frames) -> usize { + self.hidden_runs.set(0); + frames.frame(vec![], |ui| self.show(ui)); + self.hidden_runs.get() + } +} + +/// The pages take the size of the largest, a hidden one included; in a settled frame the hidden page's measure is +/// reused and its closure runs in no pass. +#[trial] +fn a_settled_hidden_page_runs_no_body() { + let scene = Scene::new(); + let mut frames = Frames::new(); + frames.idle(30, |ui| scene.show(ui)); + assert!(scene.width.get() > 20.0, "the pages are as wide as the hidden page, wider than the shown one"); + for frame in 0..4 { + assert_eq!(scene.frame(&mut frames), 0, "settled frame {frame} ran the hidden page"); + } +} + +/// An edit of a value the hidden page read measures that page again in the frame of the edit, and the pages take its +/// new size there. +#[trial] +fn an_edit_of_a_value_a_hidden_page_read_measures_it_again() { + let scene = Scene::new(); + let mut frames = Frames::new(); + frames.idle(30, |ui| scene.show(ui)); + let before = scene.width.get(); + scene.set_to.set(Some(before * 3.0)); + assert!(scene.frame(&mut frames) > 0, "the edit ran the hidden page"); + assert!(scene.width.get() > before, "the pages took the hidden page's new width in the frame of the edit"); + frames.idle(30, |ui| scene.show(ui)); + assert_eq!(scene.frame(&mut frames), 0, "the hidden page settles again"); +} diff --git a/crates/ui-widgets/tests/it/overlay/mod.rs b/crates/ui-widgets/tests/it/overlay/mod.rs index c65c75ebb..f2ad8e89c 100644 --- a/crates/ui-widgets/tests/it/overlay/mod.rs +++ b/crates/ui-widgets/tests/it/overlay/mod.rs @@ -3,4 +3,5 @@ mod hosting; pub(crate) mod kit; mod modal; +mod pages; mod sampler; diff --git a/crates/ui-widgets/tests/it/overlay/pages.rs b/crates/ui-widgets/tests/it/overlay/pages.rs new file mode 100644 index 000000000..72aedf23f --- /dev/null +++ b/crates/ui-widgets/tests/it/overlay/pages.rs @@ -0,0 +1,124 @@ +//! A component popover sized from its content, whose pages switch in place. + +use super::kit::{Leaf, PlainStyle, Seen}; +use craft_behavior::Sense; +use craft_ui::contract::{Common, Component, Cx, MeasureCx, Overlay, OverlayUi, Overlays as _, Pages, Props as _, Role, Show as _, Sizing}; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, Room, trial}; +use egui::{Response, Vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +/// What the trials read from the popover. +#[derive(Default)] +struct Paged { + /// The page shown. + page: Cell, + /// Presses on the rows of page 0 and page 1. + row_a: RefCell, + row_b: RefCell, + tab_a: RefCell, + tab_b: RefCell, + fill: RefCell, +} + +/// An opener whose popover shows two tabs and, under them, the page of the tab picked: page 0 a narrow row, page 1 a +/// wide row and a leaf that fills the width. +#[derive(Component)] +struct PagedOpener<'a> { + #[common] + common: Common, + paged: &'a Paged, +} + +impl Component for PagedOpener<'_> { + const ROLE: Role = Role::BUTTON; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: PagedOpenerStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(60.0, 20.0) + } + + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + cx.popup("pages").open(cx); + } + + fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { + let popup = cx.popup("pages"); + let paged = self.paged; + ui.show(popup, Overlay::popover(), |ui, _| { + ui.horizontal(|ui| { + if craft_ui::contract::clicked(&Leaf::new(&paged.tab_a, Vec2::new(40.0, 20.0)).label("Tab A").show(ui)) { + paged.page.set(0); + } + if craft_ui::contract::clicked(&Leaf::new(&paged.tab_b, Vec2::new(40.0, 20.0)).label("Tab B").show(ui)) { + paged.page.set(1); + } + }); + let pages = [0_u8, 1]; + Pages::new("pages", &pages, &paged.page.get()).show(ui, |ui, page| { + if *page == 0 { + Leaf::new(&paged.row_a, Vec2::new(40.0, 20.0)).label("A row").show(ui); + } else { + Leaf::new(&paged.row_b, Vec2::new(160.0, 20.0)).label("B row").show(ui); + Leaf::new(&paged.fill, Vec2::new(40.0, 20.0)).label("Fill").sizing(Sizing::Fill).show(ui); + } + }); + }); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +fn fixture(paged: &Rc) -> Fixture { + let shown = paged.clone(); + let mut fixture = Fixture::new(move |ui| { + PagedOpener { common: Common::new(), paged: &shown }.label("Paint").show(ui); + }); + fixture.in_room(Room::Window); + fixture.settle(); + fixture +} + +/// The popover takes its content's size: a leaf that fills the width fills the popover, which is narrower than the +/// window, not the window. +#[trial] +fn a_content_sized_popover_is_narrower_than_the_room() { + let paged = Rc::new(Paged::default()); + paged.page.set(1); + let fixture = fixture(&paged); + let fill = fixture.by_label("Fill").expect("the filling leaf shows"); + let row = fixture.by_label("B row").expect("the wide row shows"); + assert!(fill.rect.width() < Room::Window.size().x / 2.0, "the filling leaf takes the popover's width, not the window's"); + assert!(fill.rect.width() + 0.5 >= row.rect.width(), "the filling leaf fills the width the popover settled on"); +} + +/// A page switch moves and resizes nothing: the tabs stay where they were, and a click on the new page's row in the +/// frame after the switch lands on it. +#[trial] +fn a_page_switch_keeps_the_popover_and_the_next_click_lands_on_the_new_page() { + let paged = Rc::new(Paged::default()); + let mut fixture = fixture(&paged); + let tab_b = fixture.by_label("Tab B").expect("the tabs show"); + let row_a = fixture.by_label("A row").expect("page 0 shows"); + fixture.click(&tab_b); + fixture.frame(Vec::new()); + assert_eq!(paged.page.get(), 1, "the tab switched the page"); + let tab_after = fixture.by_label("Tab B").expect("the tabs still show"); + assert!((tab_after.rect.min - tab_b.rect.min).length() < 0.5, "the switch did not move the tabs"); + let row_b = fixture.by_label("B row").expect("page 1 shows"); + assert!((row_b.rect.min - row_a.rect.min).length() < 0.5, "the new page starts where the old one did"); + fixture.click(&row_b); + assert_eq!(paged.row_b.borrow().presses, 1, "the click right after the switch landed on the new page's row"); +}