From 765c2ca9f7f1ffdc4fbda1e33b221aa2975073ae Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 15:20:13 +0000 Subject: [PATCH] craft-ui-gallery: story cards and their stories as memoized views Each card is a memoized view over its spec and the states of its stories; each story's surface is a memoized view keyed by its data's revision, which the end of its run, the Properties editors and the dialog opener move through StoryData::settle. The story's surface is inside its view, so a story that fills takes its content's height there. The card Lazy no longer settles; inspection records and value texts are journaled, so a replay keeps them. The browse places and relink stories ask for their next run with the framework's repaint, which reruns the view. Trials: an idle Overview runs no card or story, a story data edit runs one card, a scroll runs only cards in view, a story with its dialog open runs every frame, and the inspected card replays with its run's record. --- crates/browse/src/ui/places/stories.rs | 3 +- crates/browse/src/ui/relink/stories.rs | 5 +- crates/ui-contract/src/contract/level.rs | 4 +- crates/ui-contract/src/runtime/inspect.rs | 15 +- .../ui-contract/src/runtime/layout_memory.rs | 3 + crates/ui-gallery/src/chrome/card.rs | 227 +++++++++++++----- crates/ui-gallery/src/chrome/inspect.rs | 2 +- crates/ui-gallery/src/chrome/overview.rs | 11 +- crates/ui-gallery/src/chrome/panels.rs | 2 + crates/ui-gallery/src/viewer/layout.rs | 2 +- crates/ui-gallery/src/viewer/picks.rs | 11 + crates/ui-gallery/tests/it/overview.rs | 151 +++++++++++- .../ui-widgets/src/display/inspect_overlay.rs | 2 +- 13 files changed, 352 insertions(+), 86 deletions(-) diff --git a/crates/browse/src/ui/places/stories.rs b/crates/browse/src/ui/places/stories.rs index afaadc74c..b43bfd15f 100644 --- a/crates/browse/src/ui/places/stories.rs +++ b/crates/browse/src/ui/places/stories.rs @@ -162,8 +162,9 @@ fn show_places(ui: &mut Ui, data: &mut StoryData, setup: Setup) -> StoryOutput { }) .clone(); let mut demo = demo.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // The framework's repaint runs the story's view again, where the next jobs run. if !setup.slow && demo.jobs.run_all() > 0 { - ctx.request_repaint(); + craft_ui::runtime::frame::request_repaint(&ctx); } let current = demo.current.clone(); let places = { diff --git a/crates/browse/src/ui/relink/stories.rs b/crates/browse/src/ui/relink/stories.rs index 690c2260c..2783995b4 100644 --- a/crates/browse/src/ui/relink/stories.rs +++ b/crates/browse/src/ui/relink/stories.rs @@ -156,10 +156,11 @@ fn dialog_story(ui: &mut Ui, data: &mut StoryData, search: bool, finish: bool) - if search && !*started { *started = true; dialog.begin_search(); - ui.ctx().request_repaint(); + craft_ui::runtime::frame::request_repaint(ui.ctx()); } + // The framework's repaint runs the story's view again, where the next jobs run. if finish && demo.jobs.run_all() > 0 { - ui.ctx().request_repaint(); + craft_ui::runtime::frame::request_repaint(ui.ctx()); } StoryOutput::default() } diff --git a/crates/ui-contract/src/contract/level.rs b/crates/ui-contract/src/contract/level.rs index a16df9f30..a92d43e8f 100644 --- a/crates/ui-contract/src/contract/level.rs +++ b/crates/ui-contract/src/contract/level.rs @@ -56,7 +56,7 @@ impl Level { } /// The surface a type's stories sit on in an app; a viewer draws a story on it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)] #[non_exhaustive] pub enum Surface { /// A dock panel (`surface.panel`): most types. @@ -71,7 +71,7 @@ pub enum Surface { } /// How a viewer lays out the stories of one type together, as the old gallery's story of the type laid out its cases. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)] #[non_exhaustive] pub enum StoryLayout { /// One under the other, each under its caption. diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index 18e4138cf..8b6bf54bf 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -215,12 +215,19 @@ pub fn record(ui: &mut Ui, key: Id, body: impl FnOnce(&mut Ui) -> R) -> (R, O let out = body(ui); let Some(open) = pass_state::with::(&ctx, |log| log.open.pop()) else { return (out, None) }; let recorded = Arc::new(finish(&ctx, open)); - write(&ctx, key, |kept| { - let changed = kept.recorded.as_deref() != Some(&*recorded); - kept.recorded = Some(Arc::clone(&recorded)); + keep(&ctx, key, &recorded); + // A memoized view that replays this region keeps its record as the run left it. + crate::runtime::replay::journal(&ctx, || (key, Arc::clone(&recorded)), |ctx, (key, recorded)| keep(ctx, *key, recorded)); + (out, Some(recorded)) +} + +/// Keeps `recorded` as the record of the region `key`. +fn keep(ctx: &Context, key: Id, recorded: &Arc) { + write(ctx, key, |kept| { + let changed = kept.recorded.as_deref() != Some(&**recorded); + kept.recorded = Some(Arc::clone(recorded)); changed }); - (out, Some(recorded)) } /// The latest record of the region `key`, read as a value: when the region shows later in the pass with a different diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 7dd9c6e6d..a54c1c05a 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -505,8 +505,11 @@ pub(crate) fn emit_shrink(ctx: &Context, id: Id, measured: Measured, dropped: bo /// hands forward a measure: it serves the rest of this pass, and a later pass that takes the kept measurement of a body /// it ran in gets it with that measurement, where the content that found it does not run. A real run emits it too: a /// text other than the one a kept transcript gave the pass shows that transcript changed. +/// +/// A memoized view that replays emits it again. pub fn emit_text(ctx: &Context, id: Id, text: Option<&str>) { emit(ctx, id, Recorded::Text(text.map(Arc::from))); + super::replay::journal(ctx, || (id, text.map(Arc::::from)), |ctx, (id, text)| emit(ctx, *id, Recorded::Text(text.clone()))); } /// The text a run of this pass handed forward under `id` ([`emit_text`]), or a kept transcript gave this pass. diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index 9f5d56520..853baadce 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -11,12 +11,14 @@ use craft_i18n::Direction; use craft_theme::{ControlSize, Mode}; use craft_ui::buttons::Button; use craft_ui::contract::Show as _; -use craft_ui::contract::{CommandSet, Commands as _, Gap, Pad, Props as _, ShowContainer as _, Sizing, StoryLayout, Surface, ThemeScope}; +use craft_ui::contract::{ + CommandSet, Commands as _, Gap, MemoProps, MemoView, Outbox, Pad, Props as _, ShowContainer as _, Sizing, StoryLayout, Surface, ThemeScope, +}; use craft_ui::display::{InspectLayers, InspectOverlay, Shade, Text}; use craft_ui::layout_components::{Grid, Stack}; use craft_ui::runtime::env::Env; use craft_ui::runtime::env::with_env; -use craft_ui::runtime::inspect::{self, Recorded}; +use craft_ui::runtime::inspect; use craft_ui::runtime::layout_memory; use craft_ui::sections::{HeaderCommand, HeaderStrength, Panel}; use craft_ui::style::SurfaceKind; @@ -25,7 +27,6 @@ use craft_ui::testing::{StoryData, StoryOutput, StoryRegistration}; /// A story's show function. type StoryFn = fn(&mut Ui, &mut StoryData) -> StoryOutput; use egui::{Id, Rect, Ui}; -use std::sync::Arc; /// The header commands of a card. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] @@ -55,6 +56,14 @@ pub struct Look { pub size: Option, } +/// The theme's own enums, by their derived `Hash`. +impl MemoProps for Look { + fn key(&self, key: &mut craft_ui::contract::MemoKey) { + let Look { mode, direction, size } = *self; + key.feed_hash(&(mode, direction, size)); + } +} + /// One story a card shows. #[non_exhaustive] pub struct CardStory<'a> { @@ -66,6 +75,15 @@ pub struct CardStory<'a> { pub caption: &'a str, } +/// The story's index, its caption and which registration it is (an address: registrations are static items). +impl MemoProps for CardStory<'_> { + fn key(&self, key: &mut craft_ui::contract::MemoKey) { + self.index.key(key); + self.caption.key(key); + (std::ptr::from_ref(self.story) as usize).key(key); + } +} + impl<'a> CardStory<'a> { /// The story at catalog index `index`, under `caption`. pub fn new(index: usize, story: &'static StoryRegistration, caption: &'a str) -> Self { @@ -74,6 +92,7 @@ impl<'a> CardStory<'a> { } /// What one card shows. +#[derive(MemoProps)] #[non_exhaustive] pub struct Card<'a> { /// The id scope of the card: unique among the cards of a pass. @@ -129,9 +148,55 @@ static COLUMNS: [ColumnWidth; 4] = [ColumnWidth::fill(1.0); 4]; /// wide as its widest story, so each value sits a gap past its control, as the old gallery showed it. const FORM_ROWS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::fill(1.0)]; +/// The states of the stories a card shows, by catalog index. +type States<'a, 's> = &'s mut [(usize, &'a mut CardState)]; + +/// The state of the story at catalog index `index`. +fn state_of<'s>(states: &'s mut [(usize, &mut CardState)], index: usize) -> &'s mut CardState { + match states.iter_mut().find(|(at, _)| *at == index) { + Some((_, state)) => state, + None => unreachable!("the card holds the state of each of its stories"), + } +} + +/// What a card's view reads: the card and the states of its stories. The card's own run reports through `events`. +#[derive(MemoProps)] +struct CardProps<'a> { + card: &'a Card<'a>, + states: Vec<(usize, &'a mut CardState)>, + events: Outbox<'a, CardEvents>, +} + +fn card_view(props: &mut CardProps<'_>, ui: &mut Ui) -> Option { + let CardProps { card, states, events } = props; + let shown = card.run(ui, states); + let rect = shown.rect; + events.send(shown); + rect +} + impl Card<'_> { - /// Shows the card in the room `ui` offers, with the states of its stories. + /// Shows the card in the room `ui` offers, with the states of its stories: a memoized view, which replays its last + /// run until the card, a state of its stories or what it shows around it changes. A replay reports no events. pub fn show(&self, ui: &mut Ui, cells: &mut Cells) -> CardEvents { + for story in self.stories { + cells.entry(story.index).or_default(); + } + let mut states: Vec<(usize, &mut CardState)> = cells + .iter_mut() + .filter(|(index, _)| self.stories.iter().any(|story| story.index == **index)) + .map(|(index, state)| (*index, state)) + .collect(); + states.sort_unstable_by_key(|(index, _)| *index); + let mut sent = Vec::new(); + let props = CardProps { card: self, states, events: Outbox::new(&mut sent) }; + let rect = MemoView::new(("gallery.card", &self.key), props, card_view).show(ui).flatten(); + let mut events = sent.pop().unwrap_or_default(); + events.rect = rect; + events + } + + fn run(&self, ui: &mut Ui, states: States<'_, '_>) -> CardEvents { let mut events = CardEvents::default(); // A story on the card's own surface sits inside the card's padding; any other surface runs edge to edge under the // header band. @@ -158,7 +223,7 @@ impl Card<'_> { if self.usable { commands.push(HeaderCommand::new(IconId::new("check"), CardCommands::Use).size(ControlSize::Sm)); } - let away = self.stories.iter().any(|story| cells.get(&story.index).is_some_and(|state| state.changed() || state.dialog.shown)); + let away = states.iter().any(|(_, state)| state.changed() || state.dialog.shown); if away { commands.push(HeaderCommand::new(IconId::new("undo"), CardCommands::Reset).size(ControlSize::Sm)); } @@ -171,16 +236,16 @@ impl Card<'_> { } } events.pressed |= cx.surface_pressed(); - self.stories_in(ui, cells); + self.stories_in(ui, &mut *states); }); events.rect = Some(shown.response.rect); events } /// The card's stories in its layout; a lone story outside form rows without its caption. - fn stories_in(&self, ui: &mut Ui, cells: &mut Cells) { + fn stories_in(&self, ui: &mut Ui, states: States<'_, '_>) { if let ([story], false) = (self.stories, self.layout == StoryLayout::FormRows) { - self.body(ui, story, None, cells); + self.body(ui, story, None, states); return; } match self.layout { @@ -189,7 +254,7 @@ impl Card<'_> { for story in self.stories { Text::new(story.caption.to_owned()).show(ui); let body = self.story_body(story, None); - body.show(ui, cells.entry(story.index).or_default()); + body.show(ui, state_of(states, story.index)); Text::new(body.value_text(ui).unwrap_or_default()).shade(Shade::Muted).show(ui); } }); @@ -203,14 +268,14 @@ impl Card<'_> { let columns = fit.clamp(1, usize::from(most).clamp(1, COLUMNS.len())); Grid::new(&COLUMNS[..columns]).gap(Gap::Item).fill_width().show(ui, |ui, _| { for story in self.stories { - self.body(ui, story, Some(story.caption), cells); + self.body(ui, story, Some(story.caption), states); } }); } _ => { Stack::new().fill_width().show(ui, |ui, _| { for story in self.stories { - self.body(ui, story, Some(story.caption), cells); + self.body(ui, story, Some(story.caption), states); } }); } @@ -218,8 +283,8 @@ impl Card<'_> { } /// The body of `story`, with its state, under `caption` when given. - fn body(&self, ui: &mut Ui, story: &CardStory<'_>, caption: Option<&str>, cells: &mut Cells) -> BodyShown { - self.story_body(story, caption).show(ui, cells.entry(story.index).or_default()) + fn body(&self, ui: &mut Ui, story: &CardStory<'_>, caption: Option<&str>, states: States<'_, '_>) -> BodyShown { + self.story_body(story, caption).show(ui, state_of(states, story.index)) } /// The body of `story` under `caption` when given. @@ -303,42 +368,36 @@ impl StoryBody { // A story that has not painted yet runs only in a pass that can still be discarded: what the shell's count finds // open would paint otherwise. The next frame's first pass runs it. let runs = state.dialog.painted || craft_ui::runtime::frame::discardable(ui.ctx()); - // Whether the story ran for real in this pass (not in a measuring run, nor in place of a kept measurement), and - // whether a dialog of it showed then. - let ran = std::cell::Cell::new(None); - let value_key = self.value_key(); - let data = &mut state.data; - // The record of the story's real run, when it is inspected. - let mut recorded = None; - let surface = host.stack().show(ui, |ui, cx| { - if !runs { - return; - } - let shell = cx.shell(); - let before = shell.as_ref().map_or(0, |shell| shell.dialogs_shown()); - let (output, record) = host.content(ui, show, data, self.inspect.map(|(key, _)| key)); - recorded = record.or(recorded.take()); - if let Some(readout) = &output.readout { - Text::new(readout.clone()).shade(Shade::Muted).show(ui); - } - if !ui.is_sizing_pass() { - ran.set(Some(shell.is_some_and(|shell| shell.dialogs_shown() > before))); - } - layout_memory::emit_text(ui.ctx(), value_key, output.value_text.as_deref()); - }); + let mut reported = Vec::new(); + let props = StoryProps { + show, + data: &mut state.data, + host, + runs, + region: self.inspect.map(|(key, _)| key), + value_key: self.value_key(), + reported: Outbox::new(&mut reported), + }; + let surface = MemoView::new((host.id, "story"), props, story_view).show(ui); + // Whether a dialog of the story showed in a real run of it in this pass; `None` when it did not run for real. + let ran = reported.pop().and_then(|run| run.dialog); if !runs { ui.ctx().request_repaint(); } - if let (Some((key, layers)), Some(recorded)) = (self.inspect, recorded) { + if let Some((key, layers)) = self.inspect + && let Some(recorded) = inspect::recorded(ui.ctx(), key) + { let pointed = inspect::pointed(ui.ctx(), key); let overlay = InspectOverlay::new(recorded).layers(layers); let overlay = match pointed { Some(index) => overlay.pointed(index), None => overlay, }; - overlay.show_at(ui, surface.output.rect); + if let Some(rect) = surface { + overlay.show_at(ui, rect); + } } - if let Some(shown) = ran.get() { + if let Some(shown) = ran { let dialog = &mut state.dialog; if shown && !dialog.painted { close_at_start(state); @@ -354,7 +413,7 @@ impl StoryBody { // only the measuring run or held the story back has not made them yet. state.note_start(); } - BodyShown { flow: Some(surface.output.rect) } + BodyShown { flow: surface } } /// The shown value as the story's component words it ([`StoryOutput::value_text`]), as this pass's run of the @@ -375,11 +434,12 @@ fn close_at_start(state: &mut CardState) { if let Some(open) = state.data.present::("open") { *open = false; } + state.data.settle(); state.start = None; } /// What a story runs in inside its card. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, MemoProps)] struct Host<'a> { caption: Option<&'a str>, id: Id, @@ -410,30 +470,67 @@ impl Host<'_> { } stack } +} - /// The caption, when the story has one. - fn caption_in(&self, ui: &mut Ui) { - if let Some(caption) = self.caption { - Text::new(caption.to_owned()).shade(Shade::Muted).show(ui); - } - } +/// What a story's run reported: whether a dialog of it showed, `None` in a sizing run. +struct StoryRun { + dialog: Option, +} - /// The story under its caption, in the card's direction and control size; shown as the inspected region `region` - /// when given, with the region's record of a real run. - fn content(&self, ui: &mut Ui, show: StoryFn, data: &mut StoryData, region: Option) -> (StoryOutput, Option>) { - self.caption_in(ui); - let (look, gated) = (self.look, self.gated); - with_env( - ui, - |env| { - env.direction = look.direction; - env.size = look.size; - env.wheel = gated.then_some(craft_ui::runtime::env::WheelScope::Gated); - }, - |ui| match region { - Some(key) => inspect::record(ui, key, |ui| show(ui, data)), - None => (show(ui, data), None), - }, - ) - } +/// What a story's view shows: the story's surface with the story under its caption, in the card's direction and control +/// size, as the inspected region `region` when given, and its readout under it. The surface is in the view, so a story +/// that fills takes its content's height there, as the surface sizes from its content. +#[derive(MemoProps)] +struct StoryProps<'a> { + #[memo_props(hash = "a fn pointer names the story's code")] + show: StoryFn, + data: &'a mut StoryData, + host: Host<'a>, + /// Whether the story runs in this pass: the surface shows empty otherwise. + runs: bool, + region: Option, + /// Where the story's value text is handed forward (`layout_memory::emit_text`). + value_key: Id, + /// What the run reported: a replay sends nothing. + reported: Outbox<'a, StoryRun>, +} + +fn story_view(props: &mut StoryProps<'_>, ui: &mut Ui) -> Rect { + let StoryProps { show, data, host, runs, region, value_key, reported } = props; + let (host, show, region, value_key) = (*host, *show, *region, *value_key); + host.stack() + .show(ui, |ui, cx| { + if !*runs { + return; + } + let shell = cx.shell(); + let before = shell.as_ref().map_or(0, |shell| shell.dialogs_shown()); + if let Some(caption) = host.caption { + Text::new(caption.to_owned()).shade(Shade::Muted).show(ui); + } + let look = host.look; + let output = with_env( + ui, + |env| { + env.direction = look.direction; + env.size = look.size; + env.wheel = host.gated.then_some(craft_ui::runtime::env::WheelScope::Gated); + }, + |ui| match region { + Some(key) => inspect::record(ui, key, |ui| show(ui, data)).0, + None => show(ui, data), + }, + ); + // The run may have changed a value: settling moves the revision the view keys on, so it runs once more and + // replays. + data.settle(); + if let Some(readout) = &output.readout { + Text::new(readout.clone()).shade(Shade::Muted).show(ui); + } + layout_memory::emit_text(ui.ctx(), value_key, output.value_text.as_deref()); + let dialog = (!ui.is_sizing_pass()).then(|| shell.is_some_and(|shell| shell.dialogs_shown() > before)); + reported.send(StoryRun { dialog }); + }) + .output + .rect } diff --git a/crates/ui-gallery/src/chrome/inspect.rs b/crates/ui-gallery/src/chrome/inspect.rs index 4db7b920c..5935c4626 100644 --- a/crates/ui-gallery/src/chrome/inspect.rs +++ b/crates/ui-gallery/src/chrome/inspect.rs @@ -36,7 +36,7 @@ impl Inspect<'_> { } /// How a card's stories are inspected: the tab the card is in, which keys their regions, and the drawings shown. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct Inspected { /// The centre tab the card is in. diff --git a/crates/ui-gallery/src/chrome/overview.rs b/crates/ui-gallery/src/chrome/overview.rs index f9892f4bd..1a093ad3b 100644 --- a/crates/ui-gallery/src/chrome/overview.rs +++ b/crates/ui-gallery/src/chrome/overview.rs @@ -150,9 +150,9 @@ pub(super) fn on_background(ui: &mut Ui, key: &str, mut add: impl FnMut(&mut Ui, } /// The cards in one or two columns, scrolling vertically; each row is as tall as its tallest card. A row out of view -/// does not run (`Lazy`), and a settled card in view repaints its last run (`Lazy::settles`); the card of the component -/// `reveal` names glides to the top of the view. The selected card of -/// `tab` is inspected while the inspector is on. The cards report into `reported`. +/// does not run (`Lazy`). Each card and each story in it is a memoized view that replays its last run until its inputs +/// change (the story's data by its revision, the card's look and state, the room and place). The card of the component `reveal` names glides to the top of the view. The selected card of `tab` is +/// inspected while the inspector is on. The cards report into `reported`. pub(super) fn grid( ui: &mut Ui, scroll_id: impl std::hash::Hash + std::fmt::Debug, @@ -179,9 +179,8 @@ pub(super) fn grid( Lazy::new((generation, columns, keys), estimate).reveal(revealed).show(ui, |ui| { Grid::new(if columns == 1 { ONE } else { TWO }).gap(Gap::CardColumn).fill_width().show(ui, |ui, _| { for (at, spec) in chunk.iter().enumerate() { - // A settled card repaints its last run; a card that does not run reports nothing, as it took - // no press and ran no command. - Lazy::new((generation, spec.key.as_str()), spec.estimate(&tokens)).settles(true).show(ui, |ui| { + // A card out of view does not run and reports nothing, as it took no press and ran no command. + Lazy::new((generation, spec.key.as_str()), spec.estimate(&tokens)).show(ui, |ui| { let stories = spec.card_stories(); let mut card = spec.card(&stories, format!("{}-{generation}", spec.key), room); card.inspect = p.inspect.of(tab, spec.selected); diff --git a/crates/ui-gallery/src/chrome/panels.rs b/crates/ui-gallery/src/chrome/panels.rs index b31ba7167..744ddd924 100644 --- a/crates/ui-gallery/src/chrome/panels.rs +++ b/crates/ui-gallery/src/chrome/panels.rs @@ -267,6 +267,8 @@ impl Panels<'_> { }); story_props(ui, &mut state.data); }); + // An edit in the editors moves the revision the story's view keys on. + state.data.settle(); if reset { state.reset(); } diff --git a/crates/ui-gallery/src/viewer/layout.rs b/crates/ui-gallery/src/viewer/layout.rs index 01c993a00..85e44ce8a 100644 --- a/crates/ui-gallery/src/viewer/layout.rs +++ b/crates/ui-gallery/src/viewer/layout.rs @@ -13,7 +13,7 @@ use std::collections::BTreeSet; use std::sync::{Mutex, PoisonError}; /// A panel of the viewer's dock layouts. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum PanelId { /// The component tree. diff --git a/crates/ui-gallery/src/viewer/picks.rs b/crates/ui-gallery/src/viewer/picks.rs index 702603565..f5b54cbea 100644 --- a/crates/ui-gallery/src/viewer/picks.rs +++ b/crates/ui-gallery/src/viewer/picks.rs @@ -33,6 +33,16 @@ pub struct CardState { pub resets: u32, } +/// A card's view of a story's state, by what the card shows from it: the values by their revision (whether they differ +/// from the start follows from it and the start), whether the start is taken, the dialog's flags and the reset count. A +/// write the card's own run makes moves the key, so the card runs once more and then replays. +impl craft_ui::contract::MemoProps for &mut CardState { + fn key(&self, key: &mut craft_ui::contract::MemoKey) { + let DialogState { known, hidden, shown, painted } = self.dialog; + (self.data.revision(), self.start.is_some(), (known, hidden, shown, painted), self.resets).key(key); + } +} + impl CardState { /// Whether the story's values differ from the ones it started with. pub fn changed(&self) -> bool { @@ -53,6 +63,7 @@ impl CardState { if let Some(open) = self.data.present::("open") { *open = true; } + self.data.settle(); } /// Gives the story its start values again, on a fresh id scope. diff --git a/crates/ui-gallery/tests/it/overview.rs b/crates/ui-gallery/tests/it/overview.rs index a7a3e70f9..869e8c3ac 100644 --- a/crates/ui-gallery/tests/it/overview.rs +++ b/crates/ui-gallery/tests/it/overview.rs @@ -3,9 +3,9 @@ use craft_settings::{Location, OpenOptions, SettingsStore}; use craft_ui::runtime::access::Role; use craft_ui::shell::app::ShellApp; -use craft_ui::testing::{Fixture, last_pass_measuring_runs, last_pass_runs, pointer, trial}; -use craft_ui_gallery::chrome::{Gallery, Persisted}; -use craft_ui_gallery::viewer::{Catalog, GallerySettings, by_level}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_measuring_runs, last_pass_runs, pointer, trial}; +use craft_ui_gallery::chrome::{Gallery, Persisted, region_key}; +use craft_ui_gallery::viewer::{Catalog, GallerySettings, PanelId, by_level}; use egui::Vec2; fn gallery_at(level: &str) -> Gallery { @@ -202,6 +202,32 @@ fn a_storys_dialog_starts_closed_opens_over_the_view_and_closes_back_to_the_open assert_eq!(openers(&fixture), closed, "closing the story's dialog brings the opener back"); } +/// A story whose dialog is open runs in every frame: the dialog paints on a layer of its own, which a replay can't add, +/// so the shell counts the dialog in every pass and the card keeps the story in place of its opener. +#[trial] +fn a_story_with_its_dialog_open_runs_every_frame_and_keeps_the_dialog_counted() { + let mut gallery = gallery_filtered(level_of("FindReplaceDialog"), "FindReplaceDialog"); + let mut fixture = Fixture::new(move |ui| gallery.ui(ui)); + fixture.room(Vec2::new(1400.0, 900.0)).settle(); + let closed = openers(&fixture); + let opener = fixture + .by_role(Role::BUTTON) + .into_iter() + .filter(|button| fixture.tree().name_of(button.node) == Some("Show dialog")) + .min_by(|a, b| a.rect.top().total_cmp(&b.rect.top())) + .expect("an opener"); + fixture.click(&opener).settle(); + let open = painted_times(&fixture, "Find what:"); + for frame in 0..3 { + fixture.idle(1); + let stories = + last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(ty, _, run)| ty.contains("::StoryProps") && *run == MemoRun::Ran).count(); + assert!(stories >= 1, "idle frame {frame}: the story with its dialog open ran"); + assert_eq!(openers(&fixture), closed - 1, "idle frame {frame}: the card keeps the story, its dialog counted"); + assert_eq!(painted_times(&fixture, "Find what:"), open, "idle frame {frame}: the dialog stays open"); + } +} + /// Regression: the wheel over a canvas card went to its story and the Overview stopped scrolling; inside a /// card the wheel takers take the wheel only while focused or armed, so it scrolls the Overview. #[trial] @@ -328,3 +354,122 @@ fn a_card_of_a_filling_story_is_as_tall_as_its_content() { assert!(short < 900.0, "the card fits the window: {short}"); assert!((tall - short).abs() < 1.0, "the card keeps its content's height in a taller window: {short} -> {tall}"); } + +/// The card and story views of the last frame by id, with how each took part: ran, replayed or out of view. Sizing and +/// measuring calls count. +fn view_runs(fixture: &Fixture) -> Vec<(egui::Id, MemoRun)> { + let views = |ty: &str| ty.contains("::CardProps") || ty.contains("::StoryProps"); + last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(ty, _, _)| views(ty)).map(|(_, id, run)| (id, run)).collect() +} + +/// The card views of the last frame that ran, by id, once each. +fn cards_ran(fixture: &Fixture) -> Vec { + let mut ids: Vec<_> = last_frame_memo_runs(fixture.ctx()) + .into_iter() + .filter(|(ty, _, run)| ty.contains("::CardProps") && *run == MemoRun::Ran) + .map(|(_, id, _)| id) + .collect(); + ids.sort_unstable_by_key(|id| id.value()); + ids.dedup(); + ids +} + +fn ran(runs: &[(egui::Id, MemoRun)]) -> Vec { + runs.iter().filter(|(_, run)| *run == MemoRun::Ran).map(|(id, _)| *id).collect() +} + +/// An idle Overview runs no card and no story: every card in view replays its last run, the stories in it included. +/// The Button card's Variants story animates a loading button, which runs every frame by itself, so the Controls level +/// shows its Slider cards only. +#[trial] +fn an_idle_overview_runs_no_card_or_story() { + for (level, filter) in [("Primitives", ""), ("Composites", ""), ("Patterns", ""), ("Shells", ""), ("Controls", "Slider")] { + let mut gallery = gallery_filtered(level, filter); + let mut fixture = Fixture::new(move |ui| gallery.ui(ui)); + fixture.room(Vec2::new(1400.0, 900.0)).settle().idle(3); + let runs = view_runs(&fixture); + assert!(runs.iter().any(|(_, run)| *run == MemoRun::Replayed), "{level}: the cards in view replay"); + assert!(ran(&runs).is_empty(), "{level}: an idle frame ran {} of {} card and story views: {:?}", ran(&runs).len(), runs.len(), ran(&runs)); + } +} + +/// An edit of one story's data runs that card alone: the click that flips a checkbox of one card, and the confirming run +/// of the changed values after it, run no other card. +#[trial] +fn a_story_data_edit_runs_one_card() { + let mut gallery = gallery_filtered("Controls", "Checkbox"); + let mut fixture = Fixture::new(move |ui| gallery.ui(ui)); + fixture.room(Vec2::new(1400.0, 900.0)).settle().idle(2); + let target = *fixture.by_role(Role::CHECK_BOX).first().expect("a checkbox"); + let checked = |fixture: &Fixture| fixture.tree().toggled_of(target.node); + let before = checked(&fixture); + let mut cards = Vec::new(); + for events in [vec![pointer::moved(target.center())], vec![pointer::press(target.center())], vec![pointer::release(target.center())]] { + fixture.frame(events); + cards.extend(cards_ran(&fixture)); + } + fixture.frame(vec![pointer::moved(egui::pos2(1.0, 1.0))]); + cards.extend(cards_ran(&fixture)); + // The card settles within a frame after `settle`. + fixture.settle(); + cards.extend(cards_ran(&fixture)); + fixture.idle(1); + cards.extend(cards_ran(&fixture)); + assert_ne!(checked(&fixture), before, "the click flipped the checkbox"); + cards.sort_unstable_by_key(|id| id.value()); + cards.dedup(); + assert_eq!(cards.len(), 1, "an edit of one story ran these cards: {cards:?}"); + fixture.idle(1); + assert!(ran(&view_runs(&fixture)).is_empty(), "then every card replays: {:?}", ran(&view_runs(&fixture))); +} + +/// While the Overview scrolls, every card in view runs in each scrolled frame, since its place moved and a replay adds +/// its record at the place it ran. No card out of view runs, and the frame after the scroll ends replays every card. +/// A replay that moves its record with the scroll would run only the cards a scroll newly shows: a separate task +/// (egui `replay_pass_records` with an offset). +#[trial] +fn scrolling_runs_the_cards_in_view_and_none_out_of_view() { + let mut gallery = gallery_at("Composites"); + let mut fixture = Fixture::new(move |ui| gallery.ui(ui)); + fixture.room(Vec2::new(1400.0, 900.0)).settle().idle(2); + let header = fixture.by_label("Open").expect("a card header").center(); + fixture.frame(vec![pointer::moved(header)]).settle(); + let listed = listed("Composites", "").len(); + for _ in 0..4 { + fixture.frame(vec![pointer::wheel(-120.0)]); + let cards = cards_ran(&fixture); + assert!(!cards.is_empty(), "the cards in view run at their new place (until replays move with the scroll)"); + assert!(cards.len() < listed / 2, "only the cards in view run while the Overview scrolls: {} of {listed}", cards.len()); + } + fixture.settle().idle(1); + assert!(ran(&view_runs(&fixture)).is_empty(), "the frame after the scroll ends replays every card: {:?}", ran(&view_runs(&fixture))); +} + +/// The inspected card replays as every card does, and keeps the inspector's record of its run: the record a replay +/// leaves is the one the real run made. +#[trial] +fn the_inspected_card_replays_with_the_record_of_its_run() { + const CHECKBOX: &str = "craft_ui_widgets::choice::check::Checkbox<'_>"; + let mut gallery = gallery_filtered("Controls", "Checkbox"); + let mut fixture = Fixture::new(move |ui| gallery.ui(ui)); + fixture.room(Vec2::new(1400.0, 900.0)).settle(); + let title = fixture.texts().iter().find(|run| run.text == "Checkbox").expect("the card's title").rect; + fixture.click_at(title.center()).settle(); + let tab = fixture.by_label("Inspect").expect("the Inspect tab"); + fixture.click(&tab).settle(); + let catalog = Catalog::linked(); + let records = |fixture: &Fixture| -> Vec<_> { + catalog + .stories_of(CHECKBOX) + .iter() + .filter_map(|story| craft_ui::runtime::inspect::recorded(fixture.ctx(), region_key(PanelId::Overview, *story))) + .collect() + }; + let ran = records(&fixture); + assert!(!ran.is_empty(), "the selected card's stories are inspected"); + fixture.idle(3); + assert!(view_runs(&fixture).iter().all(|(_, run)| *run != MemoRun::Ran), "the inspected card replays"); + let replayed = records(&fixture); + assert_eq!(replayed.len(), ran.len(), "every inspected story keeps its record"); + assert!(replayed.iter().zip(&ran).all(|(now, then)| **now == **then), "a replay keeps the record the real run made"); +} diff --git a/crates/ui-widgets/src/display/inspect_overlay.rs b/crates/ui-widgets/src/display/inspect_overlay.rs index baacd2f6f..55457a030 100644 --- a/crates/ui-widgets/src/display/inspect_overlay.rs +++ b/crates/ui-widgets/src/display/inspect_overlay.rs @@ -14,7 +14,7 @@ use std::sync::Arc; mod stories; /// Which drawings an [`InspectOverlay`] shows. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)] #[non_exhaustive] pub struct InspectLayers { /// Each element's box, its padding filled.