craft-ui: bind_tracked! binds several fields of one Tracked at once

bind_tracked!(doc => title, style.size) splits the Tracked into its value and
its write count (a Cell over the count) and gives each field path its own
write-through binding, so the borrow checker rejects overlapping paths. A
binding moves the count at each write that changes its field; making and
reading bindings every pass leaves the revision. Bind::tracked, Field, Place,
Projection and field! are gone: this is the one way to bind a tracked field.
This commit is contained in:
aiongg
2026-11-19 07:00:52 +00:00
parent c0df034524
commit 02b3ea4a34
4 changed files with 116 additions and 157 deletions
+13 -122
View File
@@ -5,8 +5,8 @@
//! A reader that only needs to know whether the data changed compares the [`Revision`] (two integers) instead of the
//! data. The revision is complete because the compiler sees every write:
//!
//! - Every way to change the data goes through `&mut Tracked<T>`: [`DerefMut`], [`Tracked::edit`] and a
//! [`Field`]'s writes, and each moves the revision.
//! - Every way to change the data goes through `&mut Tracked<T>`: [`DerefMut`] and [`Tracked::edit`] move the
//! revision, and craft-ui's `bind_tracked!` binds fields that move it when an edit changes them.
//! - `T` is [`PlainData`], so a shared reference can't change it: interior mutability, raw pointers, `dyn` objects
//! and closures have no implementation, and a `Tracked` holding one does not compile.
//!
@@ -182,6 +182,7 @@
// The derive reaches this crate as `::craft_tracked`, here too.
extern crate self as craft_tracked;
use std::cell::Cell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicU64, Ordering};
@@ -268,7 +269,7 @@ pub struct Revision {
/// `T` with a revision that every write moves.
///
/// `Deref` reads; `DerefMut`, [`edit`](Self::edit) and a [`Field`]'s writes move the revision whether or not the
/// `Deref` reads; `DerefMut` and [`edit`](Self::edit) move the revision whether or not the
/// write changes the data (a write with no change costs a reader one needless run, never a stale one). A clone is a
/// new source: two clones written apart never share a revision.
#[derive(Debug)]
@@ -304,9 +305,13 @@ impl<T: PlainData> Tracked<T> {
f(&mut **self)
}
/// One place inside the value, chosen with [`field!`]: reading it leaves the revision, writing it moves it.
pub fn field<U>(&mut self, projection: Projection<T, U>) -> Field<'_, T, U> {
Field { tracked: self, projection }
/// 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
/// 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<u64>) {
(&mut self.value, Cell::from_mut(&mut self.revision.count))
}
/// The value, leaving the tracking.
@@ -336,116 +341,6 @@ impl<T: PlainData> DerefMut for Tracked<T> {
}
}
/// The way to one field of an `M`, as a read and a write projection. Only [`field!`] builds one, from a field path,
/// so neither projection can do anything but select the field: the read projection leaves the revision, and only a
/// write runs the write projection.
pub struct Projection<M, U> {
read: fn(&M) -> &U,
write: fn(&mut M) -> &mut U,
}
impl<M, U> Clone for Projection<M, U> {
fn clone(&self) -> Self {
*self
}
}
impl<M, U> Copy for Projection<M, U> {}
impl<M, U> Projection<M, U> {
/// Called by [`field!`] only: a hand-written projection could write the value while selecting a field, and that
/// write would not move the revision.
#[doc(hidden)]
pub const fn __from_field_path(read: fn(&M) -> &U, write: fn(&mut M) -> &mut U) -> Self {
Projection { read, write }
}
}
/// A [`Projection`] to the field at `path` (`field!(name)`, `field!(style.size)`, `field!(0.title)`): field names
/// and tuple indices only.
///
/// ```
/// use craft_tracked::{Tracked, field};
/// # #[derive(craft_ui_macros::PlainData)] struct Style { size: f32 }
/// # #[derive(craft_ui_macros::PlainData)] struct Doc { style: Style }
/// let mut doc = Tracked::new(Doc { style: Style { size: 12.0 } });
/// let before = doc.revision();
/// let mut size = doc.field(field!(style.size));
/// assert_eq!(*size.get(), 12.0);
/// size.set(14.0);
/// assert_ne!(doc.revision(), before);
/// ```
///
/// A method call or an index is not a field path:
///
/// ```compile_fail
/// use craft_tracked::{Tracked, field};
/// let mut names = Tracked::new(vec![String::new()]);
/// let _ = names.field(field!(first()));
/// ```
#[macro_export]
macro_rules! field {
($first:tt $(. $rest:tt)*) => {
$crate::Projection::__from_field_path(|m| &m.$first $(.$rest)*, |m| &mut m.$first $(.$rest)*)
};
}
/// One field inside a [`Tracked`]: reading it leaves the revision, writing it moves it.
pub struct Field<'a, M: PlainData, U> {
tracked: &'a mut Tracked<M>,
projection: Projection<M, U>,
}
impl<M: PlainData, U> Field<'_, M, U> {
/// The field's value.
pub fn get(&self) -> &U {
(self.projection.read)(&self.tracked.value)
}
/// Replaces the field's value and moves the revision.
pub fn set(&mut self, value: U) {
self.edit(|field| *field = value);
}
/// Changes the field through `f` and moves the revision.
pub fn edit<R>(&mut self, f: impl FnOnce(&mut U) -> R) -> R {
f((self.projection.write)(&mut **self.tracked))
}
/// The same field, borrowed for a shorter time.
pub fn reborrow(&mut self) -> Field<'_, M, U> {
Field { tracked: &mut *self.tracked, projection: self.projection }
}
}
/// A field of some tracked value, for code that knows only the field's type (a value binding).
pub trait Place<U> {
/// The field's value.
fn get(&self) -> &U;
/// Replaces the field's value and moves the revision.
fn set(&mut self, value: U);
}
impl<M: PlainData, U> Place<U> for Field<'_, M, U> {
fn get(&self) -> &U {
Field::get(self)
}
fn set(&mut self, value: U) {
Field::set(self, value);
}
}
impl<U, P: Place<U> + ?Sized> Place<U> for &mut P {
fn get(&self) -> &U {
(**self).get()
}
fn set(&mut self, value: U) {
(**self).set(value);
}
}
#[cfg(test)]
mod tests {
use super::Tracked;
@@ -462,8 +357,7 @@ mod tests {
let mut doc = Tracked::new(Doc { name: "a".into(), size: (1, 2) });
let start = doc.revision();
assert_eq!(doc.name, "a");
let size = doc.field(field!(size.1));
assert_eq!(*size.get(), 2);
assert_eq!(doc.size.1, 2);
assert_eq!(doc.revision(), start, "reads leave the revision");
doc.name.push('b');
@@ -471,10 +365,7 @@ mod tests {
assert_eq!(after_deref.count, start.count + 1, "a `&mut` access moves it");
doc.edit(|doc| doc.size.0 = 3);
assert_eq!(doc.revision().count, start.count + 2, "an edit moves it");
doc.field(field!(size.1)).set(4);
doc.field(field!(name)).edit(|name| name.clear());
assert_eq!(doc.revision().count, start.count + 4, "a field's set and edit move it");
assert_eq!((doc.size, doc.name.as_str()), ((3, 4), ""));
assert_eq!((doc.size, doc.name.as_str()), ((3, 2), "ab"));
assert_eq!(doc.source(), start.source);
let mut a = Tracked::new(1_u32);
+2 -1
View File
@@ -38,6 +38,7 @@ pub mod toast;
pub mod tooltip;
mod values;
pub use crate::bind_tracked;
pub use crate::layout::{BodyLayout, RowAlign};
pub use crate::primitives::FacesCx;
pub use crate::runtime::access::{Access, FieldLabel, GridPlace, Name, Numeric, Politeness, PopupKind, Role, SetPosition, SubNode, announce};
@@ -66,7 +67,7 @@ pub use container::{
BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth,
Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth,
};
pub use craft_tracked::{Field, Place, PlainData, Projection, Revision, Tracked, field};
pub use craft_tracked::{PlainData, Revision, Tracked};
pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract};
#[doc(hidden)]
pub use cx::THUMB;
+76 -21
View File
@@ -5,10 +5,10 @@ use crate::runtime::env::Message;
use crate::runtime::memory::{MemoryStage, Savable, SaveKey, StageAccess};
use crate::runtime::reads::{self, BindKey};
use craft_behavior::{Applied, CanvasView, EditEvent, EditEvents, EditPolicy, Mixed, Value};
use craft_tracked::{Place, PlainData, Projection, Tracked};
use egui::Id;
use egui::Response;
use std::any::TypeId;
use std::cell::Cell;
use std::sync::Arc;
/// What a check says about a value, with the message type of craft-ui.
@@ -107,8 +107,9 @@ enum Source<'a, T> {
Mut(&'a mut T),
/// Write-through for a multi-selection field.
MutMixed(&'a mut Mixed<T>),
/// Write-through to a field of a `Tracked`, whose revision moves only when an edit changes the field.
Tracked(Box<dyn Place<T> + 'a>),
/// 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<u64> },
/// No caller value: session memory under the component id, or the saved tier.
Kept,
}
@@ -139,11 +140,11 @@ impl<'a, T: Value> Bind<'a, T> {
Self::from_source(Source::MutMixed(v))
}
/// Edits write through to one field of `tracked`, chosen with `craft_tracked::field!`
/// (`Bind::tracked(&mut doc, field!(style.size))`). Making and reading the binding leaves the revision; only an
/// edit that changes the field moves it, so a binding made every pass does not invalidate the value's readers.
pub fn tracked<M: PlainData>(tracked: &'a mut Tracked<M>, field: Projection<M, T>) -> Self {
Self::from_source(Source::Tracked(Box::new(tracked.field(field))))
/// 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.
#[doc(hidden)]
pub fn __tracked(value: &'a mut T, count: &'a Cell<u64>) -> Self {
Self::from_source(Source::Tracked { value, count })
}
/// No caller value: the component keeps it in session memory under its id. Until something is stored, it reads
@@ -198,7 +199,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(place) => Source::Tracked(Box::new(&mut **place)),
Source::Tracked { value, count } => Source::Tracked { value: &mut **value, count },
Source::Kept => Source::Kept,
};
let check = self.check.as_deref().map(|check| Box::new(move |value: &T| check(value)) as Box<Check<'_, T>>);
@@ -222,7 +223,7 @@ impl<'a, T: Value> Bind<'a, T> {
Source::Given(Mixed::Same(value)) => value == shown,
Source::Mut(value) => **value == *shown,
Source::MutMixed(Mixed::Same(value)) => value == shown,
Source::Tracked(place) => place.get() == shown,
Source::Tracked { value, .. } => **value == *shown,
_ => false,
}
}
@@ -233,7 +234,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(place) => SourceMut::Tracked(&mut **place),
Source::Tracked { value, count } => SourceMut::Tracked { value: &mut **value, count },
Source::Kept => SourceMut::Kept,
};
BindMut { source, policy: self.policy, check: self.check.as_deref(), save: self.save.as_ref(), reset: self.reset.as_ref() }
@@ -250,7 +251,7 @@ enum SourceMut<'a, T> {
Given(&'a Mixed<T>),
Mut(&'a mut T),
MutMixed(&'a mut Mixed<T>),
Tracked(&'a mut dyn Place<T>),
Tracked { value: &'a mut T, count: &'a Cell<u64> },
Kept,
}
@@ -272,7 +273,7 @@ impl<T: Value> BindMut<'_, T> {
SourceMut::Given(value) => Some((*value).clone()),
SourceMut::Mut(value) => Some(Mixed::Same((**value).clone())),
SourceMut::MutMixed(value) => Some((**value).clone()),
SourceMut::Tracked(place) => Some(Mixed::Same(place.get().clone())),
SourceMut::Tracked { value, .. } => Some(Mixed::Same((**value).clone())),
SourceMut::Kept => None,
}
}
@@ -284,7 +285,7 @@ impl<T: Value> BindMut<'_, T> {
SourceMut::Given(_) => None,
SourceMut::Mut(value) => Some(BindKey::Place(std::ptr::from_ref::<T>(value) as usize, TypeId::of::<T>())),
SourceMut::MutMixed(value) => Some(BindKey::Place(std::ptr::from_ref::<Mixed<T>>(value) as usize, TypeId::of::<Mixed<T>>())),
SourceMut::Tracked(place) => Some(BindKey::Place(std::ptr::from_ref::<T>(place.get()) as usize, TypeId::of::<T>())),
SourceMut::Tracked { value, .. } => Some(BindKey::Place(std::ptr::from_ref::<T>(value) as usize, TypeId::of::<T>())),
SourceMut::Kept => Some(match self.save {
Some(save) => BindKey::Saved(Id::NULL.with(&save.key)),
None => BindKey::Kept(id),
@@ -306,7 +307,7 @@ impl<T: Value> BindMut<'_, T> {
match &self.source {
SourceMut::Given(Mixed::Same(value)) | SourceMut::MutMixed(Mixed::Same(value)) => value == shown,
SourceMut::Mut(value) => **value == *shown,
SourceMut::Tracked(place) => place.get() == shown,
SourceMut::Tracked { value, .. } => **value == *shown,
_ => false,
}
}
@@ -405,7 +406,7 @@ impl<T: Value> BindMut<'_, T> {
pub(crate) fn writes(&self, event: &EditEvent<T>) -> bool {
match self.source {
SourceMut::Given(_) | SourceMut::Kept => false,
SourceMut::Mut(_) | SourceMut::MutMixed(_) | SourceMut::Tracked(_) => {
SourceMut::Mut(_) | SourceMut::MutMixed(_) | SourceMut::Tracked { .. } => {
self.policy == EditPolicy::WriteThrough || !matches!(event, EditEvent::Update { .. })
}
}
@@ -420,12 +421,14 @@ impl<T: Value> BindMut<'_, T> {
match &mut self.source {
SourceMut::Mut(value) => event.apply(&mut **value),
SourceMut::MutMixed(value) => event.apply_mixed(&mut **value),
// Applied to a copy, so an event that leaves the field as it was does not move the revision.
SourceMut::Tracked(place) => {
let mut value = place.get().clone();
let applied = event.apply(&mut value);
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;
}
let applied = event.apply(&mut **value);
if applied != Applied::Unchanged {
place.set(value);
count.set(count.get().wrapping_add(1));
}
applied
}
@@ -594,3 +597,55 @@ pub(crate) enum Checked {
/// A refused one-shot change reaches nothing.
Drop,
}
/// Write-through bindings to fields of a [`Tracked`](crate::contract::Tracked) value: `bind_tracked!(doc => size)`
/// gives one [`Bind`], `bind_tracked!(doc => title, style.size)` a tuple with one per field path (field names and
/// tuple indices only). Making and reading the bindings leaves the revision; an edit that changes a field moves it at
/// the write, so bindings made every pass don't invalidate the value's readers. Each binding borrows its own field,
/// so the paths must not overlap.
///
/// ```
/// # extern crate craft_ui_contract as craft_ui;
/// use craft_ui::contract::{PlainData, Tracked, bind_tracked};
///
/// #[derive(PlainData)]
/// struct Doc {
/// title: String,
/// style: (f32, bool),
/// }
///
/// let mut doc = Tracked::new(Doc { title: "a".into(), style: (12.0, false) });
/// let (title, size) = bind_tracked!(doc => title, style.0);
/// # let _ = (title, size);
/// ```
///
/// Overlapping paths don't compile:
///
/// ```compile_fail,E0499
/// # extern crate craft_ui_contract as craft_ui;
/// use craft_ui::contract::{Tracked, bind_tracked};
/// let mut doc = Tracked::new((1_u32, 2_u32));
/// let (a, b) = bind_tracked!(doc => 0, 0);
/// # let _ = (a, b);
/// ```
///
/// A method call is not a field path (a macro with no matching rule reports no error code):
///
/// ```compile_fail
/// # extern crate craft_ui_contract as craft_ui;
/// use craft_ui::contract::{Tracked, bind_tracked};
/// let mut names = Tracked::new(vec![String::new()]);
/// let first = bind_tracked!(names => first());
/// # let _ = first;
/// ```
#[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)
}};
($tracked:expr => $($first:tt $(. $rest:tt)*),+ $(,)?) => {{
let (model, count) = $tracked.__split_for_bind();
($($crate::contract::Bind::__tracked(&mut model.$first $(.$rest)*, count),)+)
}};
}
@@ -1,32 +1,44 @@
//! A write-through binding to a field of a `Tracked` value.
//! Write-through bindings to fields of a `Tracked` value.
use craft_behavior::{EditEvent, Mixed};
use craft_ui::contract::{Bind, PlainData, Tracked, field};
use craft_ui::contract::{PlainData, Tracked, bind_tracked};
use craft_ui::testing::trial;
#[derive(PlainData)]
struct Doc {
title: String,
style: Style,
}
#[derive(PlainData)]
struct Style {
size: f32,
}
/// Making and reading the binding every pass leaves the revision, and so does an edit to the value the field already
/// holds; an edit that changes the field moves it once and lands in the field.
/// Passes that bind two fields of one model and read them leave the revision, and so does an edit to the value a
/// field already holds; an edit that changes one field moves the revision once, at the write.
#[trial]
fn a_tracked_binding_moves_the_revision_only_when_it_writes() {
let mut doc = Tracked::new(Doc { title: "a".into(), size: 12.0 });
fn tracked_bindings_move_the_revision_only_when_an_edit_changes_a_field() {
let mut doc = Tracked::new(Doc { title: "a".into(), style: Style { size: 12.0 } });
let start = doc.revision();
for _ in 0..3 {
let mut bind = Bind::tracked(&mut doc, field!(size));
assert_eq!(bind.reborrow().get(), Some(Mixed::Same(12.0)));
let (mut title, mut size) = bind_tracked!(doc => title, style.size);
assert_eq!(title.reborrow().get(), Some(Mixed::Same("a".to_owned())));
assert_eq!(size.reborrow().get(), Some(Mixed::Same(12.0)));
}
assert_eq!(doc.revision(), start, "bindings made and read every pass leave the revision");
assert_eq!(doc.revision(), start, "two bindings made and read every pass, and written by neither, leave the revision");
let set = |after: f32| EditEvent::set(Mixed::Same(12.0), after, "Size".into(), None);
Bind::tracked(&mut doc, field!(size)).reborrow().apply(&set(12.0));
{
let (_title, mut size) = bind_tracked!(doc => title, style.size);
size.reborrow().apply(&set(12.0));
}
assert_eq!(doc.revision(), start, "an edit to the value the field holds leaves the revision");
Bind::tracked(&mut doc, field!(size)).reborrow().apply(&set(14.0));
assert_eq!(doc.revision().count, start.count + 1, "a changing edit moves it once");
assert_eq!((doc.size, doc.title.as_str()), (14.0, "a"));
{
let (_title, mut size) = bind_tracked!(doc => title, style.size);
size.reborrow().apply(&set(14.0));
}
assert_eq!(doc.revision().count, start.count + 1, "a changing edit to one field moves it once");
assert_eq!((doc.style.size, doc.title.as_str()), (14.0, "a"));
}