From 906be95f25d4ed39181dd170fc4724494d3beb23 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 07:42:50 +0000 Subject: [PATCH] craft-ui: kept records hold no read of a place by address; Tracked bindings key by source A place's address names it in its pass only: a record kept for a later pass (a memoized view's) keeps no BindKey::Place read and its replay notes none, while a measure-only record used within its pass keeps them. State more than one part shows or edits is Tracked: a bind_tracked! binding keys by the value's source and the field's offset (BindKey::Tracked), in its read, its edit and its memo key, so a replay in a later pass re-notes the read and an edit later in the pass reruns it. StoryData::bind binds a story value the same way, and the Properties editor binds and notes its edits through it. The memo_settled reader and editor share a Tracked value. --- crates/tracked/src/lib.rs | 10 +-- crates/ui-contract/src/contract/pages.rs | 2 +- crates/ui-contract/src/contract/values.rs | 56 +++++++++----- crates/ui-contract/src/runtime/inspect.rs | 2 +- crates/ui-contract/src/runtime/reads.rs | 11 ++- crates/ui-contract/src/runtime/replay.rs | 25 +++++- crates/ui-contract/src/testing/story.rs | 76 ++++++++++++++++++- crates/ui-widgets/src/story_kit/props.rs | 44 +++++++---- .../ui-widgets/tests/it/body/memo_settled.rs | 18 +++-- 9 files changed, 187 insertions(+), 57 deletions(-) diff --git a/crates/tracked/src/lib.rs b/crates/tracked/src/lib.rs index 17f12e09a..9fdd5c3a1 100644 --- a/crates/tracked/src/lib.rs +++ b/crates/tracked/src/lib.rs @@ -305,13 +305,13 @@ impl Tracked { f(&mut **self) } - /// Called by craft-ui's `bind_tracked!` only: the value without moving the revision, and the write count. The - /// macro borrows each bound field from the value through a field path and gives the binding the count, which it - /// moves on every write that changes the field. A direct call can write any part of the value without moving the + /// Called by craft-ui's `bind_tracked!` only: the value without moving the revision, the write count and the + /// source id. The macro borrows each bound field from the value through a field path and gives the binding the + /// count, which it moves on every write that changes the field, and the source, which names the field's reads. A direct call can write any part of the value without moving the /// revision, so readers keyed by it would miss the write; design-lint rejects direct calls in UI crates. #[doc(hidden)] - pub fn __split_for_bind(&mut self) -> (&mut T, &Cell) { - (&mut self.value, Cell::from_mut(&mut self.revision.count)) + pub fn __split_for_bind(&mut self) -> (&mut T, &Cell, u64) { + (&mut self.value, Cell::from_mut(&mut self.revision.count), self.revision.source) } /// The value, leaving the tracking. diff --git a/crates/ui-contract/src/contract/pages.rs b/crates/ui-contract/src/contract/pages.rs index d1cea7bf4..28c7b0916 100644 --- a/crates/ui-contract/src/contract/pages.rs +++ b/crates/ui-contract/src/contract/pages.rs @@ -52,7 +52,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { size }); let size = kept.unwrap_or_else(|| { - replay::open(&ctx); + replay::open_in_pass(&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. diff --git a/crates/ui-contract/src/contract/values.rs b/crates/ui-contract/src/contract/values.rs index ec48191d3..cf6592046 100644 --- a/crates/ui-contract/src/contract/values.rs +++ b/crates/ui-contract/src/contract/values.rs @@ -145,11 +145,19 @@ enum Source<'a, T> { MutMixed(&'a mut Mixed), /// Write-through to a field of a `Tracked` (`bind_tracked!`), whose write count moves only when an edit changes /// the field. - Tracked { value: &'a mut T, count: &'a Cell }, + Tracked { value: &'a mut T, count: &'a Cell, at: TrackedAt }, /// No caller value: session memory under the component id, or the saved tier. Kept, } +/// Where a `bind_tracked!` binding's field is: the source id of the `Tracked` that holds it and the field's offset in +/// bytes from the start of that value. It names the field in every pass, wherever the value lives. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct TrackedAt { + source: u64, + offset: usize, +} + /// The binding of a value component: a value the app owns, the check on it and the value a reset restores. The same /// binding produces the same events whichever source it has. pub struct Bind<'a, T> { @@ -177,11 +185,12 @@ impl<'a, T: Value> Bind<'a, T> { Self::from_source(Source::MutMixed(v)) } - /// Called by [`bind_tracked!`](crate::bind_tracked) only: edits write through to `value`, and an edit that - /// changes it moves `count`, the write count of the `Tracked` that holds it. + /// Called by [`bind_tracked!`](crate::bind_tracked) only: edits write through to `value`, a field `offset` bytes + /// into the value of the `Tracked` with source id `source`, and an edit that changes it moves `count`, that + /// `Tracked`'s write count. #[doc(hidden)] - pub fn __tracked(value: &'a mut T, count: &'a Cell) -> Self { - Self::from_source(Source::Tracked { value, count }) + pub fn __tracked(value: &'a mut T, count: &'a Cell, source: u64, offset: usize) -> Self { + Self::from_source(Source::Tracked { value, count, at: TrackedAt { source, offset } }) } /// No caller value: the component keeps it in session memory under its id. Until something is stored, it reads @@ -250,7 +259,7 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(value) => Source::Given(value.clone()), Source::Mut(value) => Source::Mut(&mut **value), Source::MutMixed(value) => Source::MutMixed(&mut **value), - Source::Tracked { value, count } => Source::Tracked { value: &mut **value, count }, + Source::Tracked { value, count, at } => Source::Tracked { value: &mut **value, count, at: *at }, Source::Kept => Source::Kept, }; let check = self.check.as_deref().map(|check| Box::new(check) as Box>); @@ -285,7 +294,7 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(value) => SourceMut::Given(value), Source::Mut(value) => SourceMut::Mut(&mut **value), Source::MutMixed(value) => SourceMut::MutMixed(&mut **value), - Source::Tracked { value, count } => SourceMut::Tracked { value: &mut **value, count }, + Source::Tracked { value, count, at } => SourceMut::Tracked { value: &mut **value, count, at: *at }, Source::Kept => SourceMut::Kept, }; BindMut { source, policy: self.policy, check: self.check.as_deref(), save: self.save.as_ref(), reset: self.reset.as_ref() } @@ -333,7 +342,7 @@ impl MemoProps for CheckFn { /// A binding in a memoized view's props: by what the view reads through it. A given value keys by value; a /// write-through source by its value and its address, the place the framework knows its reads by (a large value is /// bound through `bind_tracked!` or held as `&Tracked` instead: its value is hashed for each key); a `Tracked` field -/// (`bind_tracked!`) by its address and the write count of its `Tracked`; a kept value by the writes the context counts +/// (`bind_tracked!`) by its `Tracked`'s source, the field's place in the value and the write count; a kept value by the writes the context counts /// outside a component's edit: of its saved value (`set_saved_value`, `forget_saved`), or of session memory /// (`forget`). The framework tracks the component's own reads and edits. The policy, the reset value, the save key and /// the check's inputs and `fn` (`check_with`) feed too. @@ -356,9 +365,10 @@ impl MemoProps for Bind<'_, T> { Mixed::::key(value, key); std::ptr::from_ref::>(value).addr().key(key); } - Source::Tracked { value, count } => { + Source::Tracked { count, at, .. } => { key.write_u32(3); - address(value).key(key); + at.source.key(key); + at.offset.key(key); count.get().key(key); } Source::Kept => { @@ -388,7 +398,7 @@ enum SourceMut<'a, T> { Given(&'a Mixed), Mut(&'a mut T), MutMixed(&'a mut Mixed), - Tracked { value: &'a mut T, count: &'a Cell }, + Tracked { value: &'a mut T, count: &'a Cell, at: TrackedAt }, Kept, } @@ -422,7 +432,7 @@ impl BindMut<'_, T> { SourceMut::Given(_) => None, SourceMut::Mut(value) => Some(BindKey::Place(std::ptr::from_ref::(value) as usize, TypeId::of::())), SourceMut::MutMixed(value) => Some(BindKey::Place(std::ptr::from_ref::>(value) as usize, TypeId::of::>())), - SourceMut::Tracked { value, .. } => Some(BindKey::Place(std::ptr::from_ref::(value) as usize, TypeId::of::())), + SourceMut::Tracked { at, .. } => Some(BindKey::Tracked(at.source, at.offset, TypeId::of::())), SourceMut::Kept => Some(match self.save { Some(save) => BindKey::Saved(Id::NULL.with(&save.key)), None => BindKey::Kept(id), @@ -564,7 +574,7 @@ impl BindMut<'_, T> { match &mut self.source { SourceMut::Mut(value) => event.apply(&mut **value), SourceMut::MutMixed(value) => event.apply_mixed(&mut **value), - SourceMut::Tracked { value, count } => { + SourceMut::Tracked { value, count, .. } => { // A gesture's start and a cancel with nothing to restore never write. if matches!(event, EditEvent::Begin { .. } | EditEvent::Cancel { before: None, .. }) { return Applied::Unchanged; @@ -790,15 +800,23 @@ pub(crate) enum Checked { #[macro_export] macro_rules! bind_tracked { ($tracked:expr => $first:tt $(. $rest:tt)*) => {{ - let (model, count) = $tracked.__split_for_bind(); - $crate::contract::Bind::__tracked(&mut model.$first $(.$rest)*, count) + let (model, count, source) = $tracked.__split_for_bind(); + let base = ::std::ptr::from_ref(&*model).addr(); + let field = &mut model.$first $(.$rest)*; + let offset = ::std::ptr::from_ref(&*field).addr() - base; + $crate::contract::Bind::__tracked(field, count, source, offset) }}; ($tracked:expr => $($first:tt $(. $rest:tt)*),+ $(,)?) => {{ - let (model, count) = $tracked.__split_for_bind(); - ($($crate::contract::Bind::__tracked(&mut model.$first $(.$rest)*, count),)+) + let (model, count, source) = $tracked.__split_for_bind(); + let base = ::std::ptr::from_ref(&*model).addr(); + ($({ + let field = &mut model.$first $(.$rest)*; + let offset = ::std::ptr::from_ref(&*field).addr() - base; + $crate::contract::Bind::__tracked(field, count, source, offset) + },)+) }}; ($tracked:expr) => {{ - let (model, count) = $tracked.__split_for_bind(); - $crate::contract::Bind::__tracked(model, count) + let (model, count, source) = $tracked.__split_for_bind(); + $crate::contract::Bind::__tracked(model, count, source, 0) }}; } diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index e26e54174..8d4f45586 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -292,7 +292,7 @@ fn write(ctx: &Context, key: Id, edit: impl FnOnce(&mut Kept) -> bool) { /// Notes an edit of the record `read` that `editor` made: a settled memoized view that read it runs, and so does the /// pass when something read it earlier in the pass. -fn edited(ctx: &Context, read: BindKey, editor: Id) { +pub(crate) fn edited(ctx: &Context, read: BindKey, editor: Id) { crate::runtime::lazy::note_edit(ctx, read); if reads::earlier(ctx, read, editor).other { log::debug!(target: crate::runtime::egui::sizing::RERUN_LOG, "{editor:?} edited {read:?}, read earlier in the pass"); diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index 78c71cced..22b3185d2 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -15,8 +15,11 @@ use std::sync::Arc; /// lives. A given value has none. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) enum BindKey { - /// A write-through place: its address and the type stored there. + /// A write-through place: its address and the type stored there. An address names the place in its pass only: + /// a record kept for a later pass keeps no such read. Place(usize, TypeId), + /// A field of a `Tracked` value (`bind_tracked!`): the value's source id, the field's offset in it and its type. + Tracked(u64, usize, TypeId), /// Session memory under this component id. Kept(Id), /// The saved tier under the key with this hash. @@ -97,8 +100,10 @@ pub(crate) fn note(ctx: &Context, key: BindKey, reader: Id, measuring: bool, sam let read = Read { key, reader, measuring, runs, samples }; crate::runtime::replay::note_read(ctx, key); // The reads are a set to what reads them: a run that measures a component again (a kept transcript's check) - // reads nothing new. - crate::runtime::replay::journal_distinct(ctx, || read.clone(), |ctx, read| with(ctx, |reads| reads.reads.push(read.clone()))); + // reads nothing new. A place's address names it in this pass only: a replay in a later pass notes no such read. + if !matches!(key, BindKey::Place(..)) { + crate::runtime::replay::journal_distinct(ctx, || read.clone(), |ctx, read| with(ctx, |reads| reads.reads.push(read.clone()))); + } with(ctx, |reads| reads.reads.push(read)); } } diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 7ca5e501e..33a4e931f 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -109,6 +109,9 @@ struct Open { focus: focus::Mark, egui: egui::PassMark, facts: Facts, + /// The record is kept for a later pass (a memoized view's), not used only within its pass (a measure-only child's): + /// it keeps no read of a place by address, which names the place in this pass only. + kept: bool, /// The record is around a run of the replay audit (`runtime::audit`). #[cfg(feature = "testing")] audit: bool, @@ -123,6 +126,7 @@ impl Open { focus: focus::mark(ctx), egui: ctx.pass_mark(), facts: Facts { blocked: crate::runtime::access::scope::depth(ctx) > 0, ..Facts::default() }, + kept: true, #[cfg(feature = "testing")] audit: false, } @@ -183,6 +187,12 @@ pub(crate) fn open(ctx: &Context) { push(ctx, Open::empty(ctx)); } +/// Opens a record used only within its pass, around a measuring run of a measure-only child, which `close` ends: it +/// keeps the places the run read by address too. +pub(crate) fn open_in_pass(ctx: &Context) { + push(ctx, Open { kept: false, ..Open::empty(ctx) }); +} + fn push(ctx: &Context, open: Open) { pass_state::with::(ctx, |recorder| recorder.open.push(Open { from: recorder.journal.len(), ..open })); OPEN.fetch_add(1, Ordering::AcqRel); @@ -219,7 +229,8 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { outer.facts.owners.extend(open.facts.owners.iter().copied()); outer.facts.layout_keeps.extend(open.facts.layout_keeps.iter().copied()); outer.facts.wake = min_wake(outer.facts.wake, open.facts.wake); - outer.facts.reads.extend(open.facts.reads.iter().copied()); + let kept = outer.kept; + outer.facts.reads.extend(open.facts.reads.iter().copied().filter(|key| !kept || !matches!(key, BindKey::Place(..)))); outer.facts.inputs.extend(open.facts.inputs); outer.facts.instances.extend(open.facts.instances.iter().copied()); } else { @@ -386,9 +397,15 @@ where /// Notes that the running code read the value `key`. pub(crate) fn note_read(ctx: &Context, key: BindKey) { - with_open(ctx, |facts| { - facts.reads.insert(key); - }); + if OPEN.load(Ordering::Acquire) > 0 && frame::running(ctx).is_some() { + pass_state::with::(ctx, |recorder| { + if let Some(open) = recorder.open.last_mut() + && (!open.kept || !matches!(key, BindKey::Place(..))) + { + open.facts.reads.insert(key); + } + }); + } } /// Notes that the running code read the framework input `input`. diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index 02a055e58..bd7b10533 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -244,6 +244,27 @@ pub struct StoryData { written: Tracked<()>, /// The values as the last [`StoryData::settle`] found them. settled: Option, + /// The revision after the last [`StoryData::settle`]: a write through a binding ([`StoryData::bind`]) moved it + /// since, and settle moves it no further for that write. + settled_at: Option, +} + +/// A story value as the Properties editor binds it ([`StoryData::__slot`]). +#[doc(hidden)] +pub struct Slot<'a> { + pub value: &'a mut dyn Shown, + pub how: Option<&'a Edit>, + pub count: &'a std::cell::Cell, + pub source: u64, + pub offset: usize, +} + +impl Slot<'_> { + /// A binding of the value as `T`, as [`StoryData::bind`] makes it; `None` when the value is not a `T`. + pub fn bind(&mut self) -> Option> { + let value = self.value.any_mut().downcast_mut::()?; + Some(crate::contract::Bind::__tracked(value, self.count, self.source, self.offset)) + } } /// How the Properties editor edits a value, beyond what its type says. @@ -339,6 +360,47 @@ impl StoryData { } } + /// A binding of the value named `name` of type `T`, created from `init` on first use. Every view that binds a value + /// shows and edits one value: the story's view, and the Properties editor in the same pass. The binding names + /// the value by this data's source, so a reader that replays sees an edit made later in its pass, and an edit + /// moves the [`revision`](Self::revision) at the write. + #[allow(clippy::unreachable, reason = "the slot key holds the type, so the downcast cannot fail")] + pub fn bind(&mut self, name: &'static str, init: T) -> crate::contract::Bind<'_, T> { + let StoryData { values, written, .. } = self; + let slot = values.entry((name, TypeId::of::())).or_insert_with(|| Box::new(init)); + let (_, count, source) = written.__split_for_bind(); + match slot.any_mut().downcast_mut::() { + Some(value) => crate::contract::Bind::__tracked(value, count, source, slot_offset(name)), + None => unreachable!("a slot's value has the type its key names"), + } + } + + /// Like [`StoryData::bind`] for a number the Properties editor keeps inside `range`. + pub fn bind_ranged(&mut self, name: &'static str, init: T, range: RangeInclusive) -> crate::contract::Bind<'_, T> { + self.how.entry((name, TypeId::of::())).or_insert(Edit::Range(range)); + self.bind(name, init) + } + + /// Called by the Properties editor only: the value under `key` with what binds it as [`StoryData::bind`] does (the + /// write count, the source and the value's place in the data). + #[doc(hidden)] + pub fn __slot(&mut self, key: (&'static str, TypeId)) -> Option> { + let StoryData { values, how, written, .. } = self; + let value = values.get_mut(&key)?.as_mut(); + let (_, count, source) = written.__split_for_bind(); + Some(Slot { value, how: how.get(&key), count, source, offset: slot_offset(key.0) }) + } + + /// Called by the Properties editor only: it wrote the value under `key` outside a binding (an assignment after a + /// picked choice or an edited number). The revision moves, and a view that read the value earlier in the pass + /// runs again. + #[doc(hidden)] + pub fn __wrote(&mut self, ctx: &egui::Context, key: (&'static str, TypeId)) { + *self.written = (); + let read = crate::runtime::reads::BindKey::Tracked(self.written.source(), slot_offset(key.0), key.1); + crate::runtime::inspect::edited(ctx, read, Id::NULL); + } + /// Like [`StoryData::value`] for a number the Properties editor keeps inside `range`. pub fn ranged(&mut self, name: &'static str, init: T, range: RangeInclusive) -> &mut T { self.how.entry((name, TypeId::of::())).or_insert(Edit::Range(range)); @@ -371,9 +433,12 @@ impl StoryData { last.values.len() == self.values.len() && last.values.iter().all(|(key, was)| self.values.get(key).is_some_and(|now| now.same(&**was))) }); if !same { - *self.written = (); + if self.settled_at.is_none_or(|at| at == self.written.revision()) { + *self.written = (); + } self.settled = Some(self.snapshot()); } + self.settled_at = Some(self.written.revision()); } /// The revision of the values: unique to this data, and moved by every [`settle`](Self::settle) that finds a @@ -616,3 +681,12 @@ where crate::runtime::env::Env::restore(ui.ctx(), installed); shown } + +/// A story value's place in its data, by its name: with the data's source and the value's type it names the value in +/// every pass (`BindKey::Tracked`). +fn slot_offset(name: &str) -> usize { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + name.hash(&mut hasher); + hasher.finish() as usize +} diff --git a/crates/ui-widgets/src/story_kit/props.rs b/crates/ui-widgets/src/story_kit/props.rs index e4415f775..42618446f 100644 --- a/crates/ui-widgets/src/story_kit/props.rs +++ b/crates/ui-widgets/src/story_kit/props.rs @@ -11,7 +11,7 @@ use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use crate::display::{Shade, Text}; use crate::form::{Field, FieldGroup}; use crate::pickers::Select; -use crate::testing::story::{Edit, Shown, StoryData}; +use crate::testing::story::{Edit, Slot, StoryData}; use crate::text::{NumberField, TextField}; use egui::{Response, Ui}; use std::any::Any; @@ -58,46 +58,57 @@ fn label_of(name: &str) -> String { chars.next().map(|first| first.to_uppercase().chain(chars).collect()).unwrap_or_default() } -/// The editable form of `data`'s values, one row each, sorted by name; returns the form's response. +/// The editable form of `data`'s values, one row each, sorted by name; returns the form's response. A value an editor +/// changes is one the story's view binds too (`StoryData::bind`): a story view that read it earlier in the pass runs +/// again. pub fn story_props(ui: &mut Ui, data: &mut StoryData) -> Response { let mut keys: Vec<_> = data.values.keys().copied().collect(); keys.sort_by_key(|(name, _)| *name); + let ctx = ui.ctx().clone(); FieldGroup::new("Properties") .show(ui, |ui, _| { for key in keys.iter().copied() { let label = label_of(key.0); - let how = data.how.get(&key); - let Some(value) = data.values.get_mut(&key) else { continue }; - Field::new(label.clone()).show(ui, |ui, _| row(ui, &label, value.as_mut(), how)); + let Some(mut slot) = data.__slot(key) else { continue }; + let mut wrote = false; + Field::new(label.clone()).show(ui, |ui, _| row(ui, &label, &mut slot, &mut wrote)); + if wrote { + data.__wrote(&ctx, key); + } } }) .output } -fn row(ui: &mut Ui, label: &str, value: &mut dyn Shown, how: Option<&Edit>) -> Response { +/// The editor of one value; `wrote` is set when it assigned the value outside its binding. +fn row(ui: &mut Ui, label: &str, slot: &mut Slot<'_>, wrote: &mut bool) -> Response { + let how = slot.how; if let Some(Edit::Choice(options)) = how { let entries: Vec<_> = options.iter().enumerate().map(|(at, (name, _))| Entry::new(at, *name)).collect(); - let mut at = options.iter().position(|(_, option)| option.same(&*value)).unwrap_or(usize::MAX); + let mut at = options.iter().position(|(_, option)| option.same(&*slot.value)).unwrap_or(usize::MAX); let shown = Select::new(label.to_owned(), Bind::bound(&mut at), &entries).show(ui); - if let Some((_, picked)) = options.get(at) { - value.assign(&**picked); + if let Some((_, picked)) = options.get(at) + && !picked.same(&*slot.value) + { + slot.value.assign(&**picked); + *wrote = true; } return shown.response; } - let any = value.any_mut(); - if let Some(on) = any.downcast_mut::() { - return Checkbox::new(Bind::bound(on)).label(label.to_owned()).show(ui).response; + if let Some(on) = slot.bind::() { + return Checkbox::new(on).label(label.to_owned()).show(ui).response; } - if let Some(text) = any.downcast_mut::() { - return TextField::new(label.to_owned(), Bind::bound(text)).show(ui).response; + if let Some(text) = slot.bind::() { + return TextField::new(label.to_owned(), text).show(ui).response; } - if let Some(number) = any.downcast_mut::>() { - let mut field = NumberField::new(label.to_owned(), Bind::bound(number)); + if let Some(number) = slot.bind::>() { + let mut field = NumberField::new(label.to_owned(), number); if let Some(Edit::Range(range)) = how { field = field.range(range.clone()); } return field.show(ui).response.clone(); } + let any = slot.value.any_mut(); if let Some(current) = number_of(&*any) { let mut number = Some(current); let mut field = NumberField::new(label.to_owned(), Bind::bound(&mut number)); @@ -110,6 +121,7 @@ fn row(ui: &mut Ui, label: &str, value: &mut dyn Shown, how: Option<&Edit>) -> R let shown = field.show(ui).response.clone(); if let Some(edited) = number.filter(|edited| *edited != current) { set_number(any, edited); + *wrote = true; } return shown; } diff --git a/crates/ui-widgets/tests/it/body/memo_settled.rs b/crates/ui-widgets/tests/it/body/memo_settled.rs index c39e9c4e8..f7e542724 100644 --- a/crates/ui-widgets/tests/it/body/memo_settled.rs +++ b/crates/ui-widgets/tests/it/body/memo_settled.rs @@ -7,7 +7,7 @@ use crate::values::kit::{AT, INITIAL, Scrub, Seen}; use craft_theme::{Contrast, Mode, Size}; use craft_ui::buttons::Button; use craft_ui::choice::{Radio, RadioGroup}; -use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Sizing, Tracked, bind_tracked}; use craft_ui::display::Spinner; use craft_ui::layout_components::Stack; use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Commands as _}; @@ -80,10 +80,11 @@ fn other(props: &mut Other, ui: &mut Ui) { } } -/// Two memoized views, `reader` and `other`, and a scrub outside them bound to the value the reader's own scrub shows. +/// Two memoized views, `reader` and `other`, and a scrub outside them bound to the value the reader's own scrub shows: +/// state two parts show and edit, so it is `Tracked` and both bind it by its source. /// The scrub that edits comes before the views in the pass when `editor_first`, else after them. struct Scene { - value: RefCell, + value: RefCell>, room: Cell, editor_first: bool, spinner: bool, @@ -92,7 +93,7 @@ struct Scene { impl Scene { fn new(editor_first: bool, spinner: bool) -> Scene { - Scene { value: RefCell::new(INITIAL), room: Cell::new(ROOM), editor_first, spinner, repaints: Cell::new(false) } + Scene { value: RefCell::new(Tracked::new(INITIAL)), room: Cell::new(ROOM), editor_first, spinner, repaints: Cell::new(false) } } fn show(&self, ui: &mut Ui) { @@ -100,7 +101,9 @@ impl Scene { self.editor(ui); } in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { - MemoView::new("reader", Reader { value: Bind::bound(&mut *self.value.borrow_mut()) }, reader).show(ui); + let mut value = self.value.borrow_mut(); + MemoView::new("reader", Reader { value: bind_tracked!(value) }, reader).show(ui); + drop(value); MemoView::new("other", Other { repaints: self.repaints.get(), spinner: self.spinner }, other).show(ui); }); if !self.editor_first { @@ -109,7 +112,8 @@ impl Scene { } fn editor(&self, ui: &mut Ui) { - Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("editor").show_at(ui, AT); + let mut value = self.value.borrow_mut(); + Scrub::new(bind_tracked!(value)).id_salt("editor").show_at(ui, AT); } /// The runs of each view in one frame with `events`. @@ -189,7 +193,7 @@ fn drag(scene: &Scene) -> Vec<(usize, [usize; 2], bool)> { for step in 0..=4 { let event = if step == 0 { press(from) } else { moved(from + Vec2::new(10.0 * step as f32 + 10.0, 0.0)) }; let passes = frames.frame(vec![event], |ui| scene.show(ui)); - let shows = SEEN.with(|seen| seen.shown.get()) == Some(*scene.value.borrow()); + let shows = SEEN.with(|seen| seen.shown.get()) == Some(**scene.value.borrow()); seen.push((passes, [runs_of(&frames.ctx, "Reader"), runs_of(&frames.ctx, "Other")], shows)); } scene.frame(&mut frames, vec![release(from + Vec2::new(50.0, 0.0))]);