craft-ui: a scrolling body's measuring run lays its content out beside the bars, and again at full view when it fits

The first sweep takes the view an overflowing body shows; content that fits leaves another view, so the sweep is
taken back through the draft journal (lazy-store writes included) and runs once more there. The body's measure no
longer keys on the last pass's extent. Trials: the first frame lays content out at the settled width, and an
overflowing body's settled memoized children run no measuring run when the body measures again.
This commit is contained in:
aiongg
2026-11-20 07:13:24 +00:00
parent d368d684c9
commit c3c1ef70ad
6 changed files with 198 additions and 25 deletions
+7 -2
View File
@@ -103,8 +103,9 @@ pub(super) struct BodyHooks<'b> {
scroll_bound: bool,
moved: bool,
last: BodyView,
/// The content's extent. Step 4 and the measuring run read the last pass's, kept with the offset it bounds
/// (`ScrollState`); from step 5 the real run takes what this pass's measuring run found.
/// The content's extent. Step 4 reads the last pass's, kept with the offset it bounds (`ScrollState`): the moves
/// it applies act on the content that pass showed. A measuring run lays the content out for the extent it sets
/// (`measure_run`); from step 5 the real run takes what this pass's measuring run found.
last_extent: (f32, f32),
/// The height of a scroll strip (`ScrollIndicator::Strips`).
strip: f32,
@@ -127,6 +128,9 @@ pub(super) struct BodyHooks<'b> {
settle: Option<crate::layout::Columns>,
unsettled: Option<crate::layout::Columns>,
extent: Option<Vec2>,
/// The content extent a measuring run found that leaves another view than the one the run laid the content out
/// for: the run lays it out again at that view.
view_moves: Option<(f32, f32)>,
view: Option<Rect>,
save: Option<SaveKey>,
layer: bool,
@@ -221,6 +225,7 @@ impl<'b> BodyHooks<'b> {
settle: None,
unsettled: None,
extent: None,
view_moves: None,
view: None,
save: None,
layer: false,
+48 -6
View File
@@ -735,6 +735,42 @@ impl BodyHooks<'_> {
let (layer, rect) = self.begin_measure_run(at, cx);
let mut values = AppValues::default();
comp.content_env(cx, &mut values);
// A scrolling body's view (a bar that takes room, the strips) follows from its content's overflow. The content is
// laid out as overflowing along every axis it scrolls, beside the bars; when its overflow leaves another view
// (content that fits), the sweep is taken back and the content runs once more at that view. Content that
// overflows, whose children are the costly ones to run twice, runs once.
let overflows = crate::contract::MAX_EXTENT;
(self.last_extent, self.view_moves) = ((overflows, overflows), None);
if scroll_of(&self.props).is_some() {
let ctx = at.ui.ctx().clone();
let (overflow, _) = crate::contract::draft(
&ctx,
|| {
self.sweeps(comp, at, cx, (layer, rect), &values);
self.view_moves.take()
},
Option::is_none,
);
if let Some(extent) = overflow {
self.last_extent = extent;
self.sweeps(comp, at, cx, (layer, rect), &values);
self.view_moves = None;
}
} else {
self.sweeps(comp, at, cx, (layer, rect), &values);
}
self.end_measure_run(at, cx.core.id, key, content)
}
/// The measuring run's sweeps of the regions at the view it lays the content out for.
fn sweeps<C: Container>(
&mut self,
comp: &mut C,
at: &Measuring<'_, '_>,
cx: &mut Cx<'_, C>,
(layer, rect): (areas::LayerKey, Rect),
values: &AppValues,
) {
// A label group settles its columns before a measure inside stands: when a row of a body that shows at its
// measured width read a column narrower than the group's widest, the sweep is taken back and the content runs
// once more with the group opened at the widths the first sweep found.
@@ -743,20 +779,19 @@ impl BodyHooks<'_> {
let (unsettled, _) = crate::contract::draft(
&ctx,
|| {
self.sweep(comp, at, cx, (layer, rect), &values);
self.sweep(comp, at, cx, (layer, rect), values);
self.unsettled.take()
},
Option::is_none,
);
if let Some(widths) = unsettled {
(self.settle, self.reached) = (Some(widths), None);
self.sweep(comp, at, cx, (layer, rect), &values);
self.sweep(comp, at, cx, (layer, rect), values);
(self.settle, self.unsettled) = (None, None);
}
} else {
self.sweep(comp, at, cx, (layer, rect), &values);
self.sweep(comp, at, cx, (layer, rect), values);
}
self.end_measure_run(at, cx.core.id, key, content)
}
/// Opens the measuring run of `cx`'s container: its rect at the room's start edge, which `cx` takes, and the layer
@@ -944,6 +979,8 @@ struct ScrollRegion {
bar: f32,
/// The run lays the content out for the view.
lays_out: bool,
/// The bars' inset and the part of the body the content shows in, as the extent the run starts from gives them.
laid_for: (Vec2, Rect),
}
/// The `Ui` a measuring run lays a transformed body out in: on the body layer the real run shows it on.
@@ -1414,14 +1451,14 @@ impl BodyHooks<'_> {
}
let env = run.env.derive_local(|scoped| scoped.lazy = Some(view));
let installed = Env::install_for(&region_ui, env.clone());
ScrollRegion { ui: region_ui, env, installed, seen, max, shown, bar, lays_out }
ScrollRegion { ui: region_ui, env, installed, seen, max, shown, bar, lays_out, laid_for: (inset, shows) }
}
/// After a scrolling body's content ran: the anchor and glide follow what it placed, and the body takes what the
/// view shows of it.
fn scrolled(&mut self, run: &BodyRun<'_>, scroll: Scroll, at: Rect, region: ScrollRegion, bars: &mut Vec2) -> Option<Vec2> {
let (ctx, id) = (run.ctx, run.id);
let ScrollRegion { ui: region_ui, installed, seen, max, shown, bar, lays_out, .. } = region;
let ScrollRegion { ui: region_ui, installed, seen, max, shown, bar, lays_out, laid_for, .. } = region;
Env::restore(ctx, installed);
if lays_out {
crate::contract::run::close_bar_line(ctx, id);
@@ -1440,6 +1477,11 @@ impl BodyHooks<'_> {
crate::runtime::egui::widgets::note_scroll_region(ctx, region_ui.clip_rect(), region_ui.min_rect().intersect(max));
}
self.extent = Some(extent);
// A measuring run whose content leaves another view than the one it laid the content out for runs again there.
let leaves = (overflow_inset(scroll, extent, at.size(), bar), view_within(scroll, extent, at, self.strip));
if !run.real && leaves != laid_for {
self.view_moves = Some((extent.x, extent.y));
}
// Along an axis it scrolls the body took what the view shows; along the other it took its content.
*bars = overflow_inset(scroll, extent, at.size(), bar);
// Strips take their height from the view: a body that overflows takes all of its room.
@@ -28,8 +28,6 @@ pub(super) struct MeasureKey {
width: Option<f32>,
/// Whether the body shows, and how much of it an animated collapse shows.
shows: (bool, f32),
/// The content extent the view keeps, which decides the scroll bars' inset.
extent: (f32, f32),
env: EnvFacts,
}
@@ -93,7 +91,6 @@ impl<'b> BodyHooks<'b> {
wide: self.wide(),
width,
shows: (self.open, self.presence.t),
extent: self.last_extent,
env: EnvFacts::of(env),
}
}
@@ -186,6 +186,8 @@ enum Undo {
/// An input the entry open at the place read, before the draft read it.
Input(usize, Id, Option<f32>),
Contribution(TakeBack),
/// What restores a write the draft made to a store outside layout memory (`note_undo`).
Store(TakeBack),
}
impl Scope {
@@ -333,8 +335,9 @@ impl Entries {
}
/// Takes a draft that ended back: the records, kept transcripts and transcript entries are as before it. Returns
/// what takes its contributions back, in reverse order, to run outside the memory's lock.
fn take_back(&mut self, draft: Draft) -> Vec<TakeBack> {
/// what takes its contributions and its writes to other stores back, in reverse order, to run outside the memory's
/// lock, each with whether it takes a contribution back.
fn take_back(&mut self, draft: Draft) -> Vec<(TakeBack, bool)> {
let mut later = Vec::new();
for undo in draft.undo.into_iter().rev() {
match undo {
@@ -373,7 +376,8 @@ impl Entries {
}
}
}
Undo::Contribution(undo) => later.push(undo),
Undo::Contribution(undo) => later.push((undo, true)),
Undo::Store(undo) => later.push((undo, false)),
}
}
if let Some((at, len)) = draft.items
@@ -696,14 +700,34 @@ pub(crate) fn draft<R>(ctx: &Context, run: impl FnOnce() -> R, keep: impl FnOnce
}
Some(memory.take_back(draft))
});
for undo in undo.into_iter().flatten() {
for (undo, contribution) in undo.into_iter().flatten() {
guard::emitting(|| undo(ctx));
#[cfg(feature = "testing")]
crate::runtime::measure::count_contribution(ctx, -1);
if contribution {
crate::runtime::measure::count_contribution(ctx, -1);
}
let _ = contribution;
}
(out, kept)
}
/// Whether a draft is open (`draft`): a store outside layout memory that a measuring run writes hands what restores
/// the write to `note_undo`.
pub(crate) fn drafting(ctx: &Context) -> bool {
with(ctx, &Moment::of(ctx), |memory| !memory.drafts.is_empty())
}
/// Adds `undo`, which restores a write to a store outside layout memory (the lazy children's entries), to the innermost
/// open draft: a draft taken back runs it, so the draft leaves nothing behind; one kept hands it to the draft around it.
/// Nothing outside a draft.
pub(crate) fn note_undo(ctx: &Context, undo: TakeBack) {
with(ctx, &Moment::of(ctx), |memory| {
if let Some(draft) = memory.drafts.last_mut() {
draft.undo.push(Undo::Store(undo));
}
});
}
/// Runs `f` as content whose emits no enclosing transcript takes, and whose real run no enclosing body checks: a
/// collection's rows and its largest-row probe (kept by its own transcript), a layer's content, a lazy
/// child. `stops_changes`: a change the real run finds inside drops no kept transcript outside. Content whose extent
+31 -6
View File
@@ -19,6 +19,7 @@ use crate::runtime::egui::{focus as focus_state, input as input_state, pass};
use crate::runtime::focus::{self, Transcript};
use crate::runtime::frame::{self, PerViewport};
use crate::runtime::inputs::{self, Input};
use crate::runtime::layout_memory;
use crate::runtime::reads::BindKey;
use crate::runtime::replay::{self, Record};
use crate::style::EnvKey;
@@ -342,13 +343,37 @@ fn with<R>(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R {
})
}
/// Runs `f` on the store as `with` does, for a write to the entry of the child `id`: inside a draft
/// (`layout_memory::draft`) the entry as it was goes to the draft, so a measuring run taken back leaves the entry, its
/// extents and this pass's decisions included, as it found it.
fn write<R>(ctx: &Context, id: Id, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R {
let drafting = layout_memory::drafting(ctx);
let (out, before) = with(ctx, |store, pass_nr, frame| {
let before = drafting.then(|| store.entries.get(&id).cloned());
(f(store, pass_nr, frame), before)
});
if let Some(before) = before {
let viewport = pass::current_viewport(ctx);
layout_memory::note_undo(
ctx,
Box::new(move |ctx: &Context| {
PerViewport::<Store>::with(ctx, viewport, |store| match before {
Some(entry) => drop(store.entries.insert(id, entry)),
None => drop(store.entries.remove(&id)),
});
}),
);
}
out
}
/// Decides whether the child `id`, whose content starts at `at` in this run, runs this pass. It runs when its extent
/// placed at `at` meets the view, or when one of its stops holds focus or is the target of a focus request. Its
/// extent is the one a run showed it at, else `estimate`. The first run of a pass decides; every later run of the
/// pass gets the same answer, so a measuring run and the real run lay out the same children.
pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) -> Rect, sizing: bool, estimate: Vec2) -> Decision {
let targets = crate::runtime::focus::targets(ctx);
with(ctx, |store, pass_nr, frame| {
write(ctx, id, |store, pass_nr, frame| {
let entry = store.touch(Some(view.owner), id, frame);
let kind = usize::from(!sizing);
// A child the other kind of run showed last takes that run's extent.
@@ -369,7 +394,7 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) -
/// Records what a run that showed the child `id` found: what it measured in a run of this kind and, from a real run,
/// what it registered with the focus service.
pub(crate) fn shown(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, measured: Measured, registered: Option<Transcript>) {
with(ctx, |store, _, frame| {
write(ctx, id, |store, _, frame| {
let entry = store.touch(owner, id, frame);
entry.sizes[usize::from(!sizing)] = Some(measured);
if let Some(registered) = registered {
@@ -428,7 +453,7 @@ pub(crate) fn settled(
let now = frame::clock(ctx);
let held = (input_state::dragged(ctx), focus_state::focused(ctx));
let transformed = place.is_some_and(|place| ctx.layer_transform_to_global(place.layer).is_some());
let settled = with(ctx, |store, pass_nr, frame| {
let settled = write(ctx, id, |store, pass_nr, frame| {
let changes = &store.changes;
// Usually `None`: only the values written this frame.
let edited = changes.edited_in(frame);
@@ -483,7 +508,7 @@ pub(crate) fn settled(
|| crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives)
|| moved(ctx, &settled, view)
{
with(ctx, |store, pass_nr, _| {
write(ctx, id, |store, pass_nr, _| {
if let Some(entry) = store.entries.get_mut(&id) {
entry.replays = Some((pass_nr, false));
}
@@ -591,7 +616,7 @@ pub(crate) fn measured(ctx: &Context, id: Id) -> Option<(Vec2, Vec<BindKey>)> {
/// Keeps the measuring run of the measure-only child `id` in this pass: the values it read and the size it took.
pub(crate) fn measured_run(ctx: &Context, id: Id, reads: Vec<BindKey>, size: Vec2) {
with(ctx, |store, pass_nr, frame| {
write(ctx, id, |store, pass_nr, frame| {
store.touch(None, id, frame).measured = Some(MeasuredRun { reads, pass: pass_nr, size });
});
}
@@ -612,7 +637,7 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) {
/// it does not build by it (its item layout answers for rows it never built), and every run of the pass that reaches
/// the row takes it without measuring the row again.
pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) {
with(ctx, |store, pass_nr, frame| {
write(ctx, id, |store, pass_nr, frame| {
let entry = store.touch(Some(owner), id, frame);
entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING });
entry.measured_in = Some(pass_nr);
+83 -3
View File
@@ -3,12 +3,12 @@
use craft_behavior::{ColumnWidth, PartKey};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, ContainerProps, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
use craft_ui::contract::{Bind, ContainerProps, MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
use craft_ui::layout_components::Grid;
use craft_ui::runtime::focus::{FocusTarget, request};
use craft_ui::testing::layout::{Block, in_region};
use craft_ui::testing::layout::{Block, in_region, measured_block};
use craft_ui::testing::text::widget_id;
use craft_ui::testing::{Frames, pointer, trial};
use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, pointer, trial};
use craft_ui::text::TextField;
use craft_ui_test_kit::body::Slab;
use egui::{Id, Pos2, Rect, Ui, Vec2};
@@ -339,6 +339,86 @@ fn content_that_grows_inside_a_lazy_cell_that_fills_it_grows_its_row() {
assert!(card.get().expand(SAME).contains_rect(content.get()), "the card grew to its content: {:?} in {:?}", content.get(), card.get());
}
/// A scrolling body whose content overflows lays the content out at the view its overflow leaves (beside the scroll
/// bar) in its first frame: content that takes the view's width has the width it has once the body settles.
#[trial]
fn overflowing_content_takes_the_view_beside_the_bar_in_its_first_frame() {
// The widths of the last real run that ran the content.
let widths = RefCell::new(Vec::new());
let mut show = |ui: &mut Ui| {
let ran = RefCell::new(Vec::new());
in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| {
Slab::new(ContainerProps::new().scroll(Scroll::vertical())).id_salt("overflowing").show(ui, |ui, _| {
for _ in 0..30 {
let rect = Block::new(Vec2::new(ui.available_width(), LINE.y)).show(ui).rect;
if !ui.is_sizing_pass() && !craft_ui::testing::is_measuring(ui.ctx()) {
ran.borrow_mut().push(rect.width());
}
}
});
});
if !ran.borrow().is_empty() {
*widths.borrow_mut() = ran.into_inner();
}
};
let mut frames = Frames::new();
frames.idle(1, &mut show);
let first = widths.borrow().clone();
frames.idle(3, &mut show);
assert!(!first.is_empty(), "the content ran in the first frame");
assert_eq!(first, *widths.borrow(), "the first frame lays the content out at the settled view's width");
}
/// A memoized line as wide as its view.
#[derive(MemoProps)]
struct Line {
at: usize,
}
fn line(props: &mut Line, ui: &mut Ui) -> usize {
Block::new(Vec2::new(ui.available_width(), LINE.y)).show(ui);
props.at
}
/// A memoized block whose measured width is `width`: a new width asks the body around it to measure again.
#[derive(MemoProps)]
struct Grown {
width: f32,
}
fn grown(props: &mut Grown, ui: &mut Ui) -> f32 {
measured_block(ui, "grown", Vec2::new(props.width, LINE.y));
Block::new(Vec2::new(props.width, LINE.y)).show(ui);
props.width
}
/// Count trial: an overflowing scrolling body's measuring run lays its content out once, at the view beside the bar.
/// In a pass that measures the body again, its settled memoized children in view replay in the measuring run as in
/// the real run: none runs a measuring run at another width.
#[trial]
fn an_overflowing_bodys_settled_memo_children_run_no_measuring_run_when_it_measures_again() {
let width = Cell::new(40.0);
let mut show = |ui: &mut Ui| {
in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| {
Slab::new(ContainerProps::new().scroll(Scroll::vertical())).id_salt("memo_lines").show(ui, |ui, _| {
MemoView::new("grown", Grown { width: width.get() }, grown).show(ui);
for at in 0..30 {
MemoView::new(("line", at), Line { at }, line).show(ui);
}
});
});
};
let mut frames = Frames::new();
frames.idle(5, &mut show);
width.set(60.0);
frames.idle(1, &mut show);
let runs = last_frame_memo_runs(&frames.ctx);
let ran = |name: &str| runs.iter().filter(|(of, _, run)| of.contains(name) && *run == MemoRun::Ran).count();
assert!(ran("::Grown") >= 2, "the changed view ran in the body's measuring run and its real run: {runs:?}");
assert!(runs.iter().any(|(of, _, run)| of.contains("::Line") && *run == MemoRun::Replayed), "the lines in view took part: {runs:?}");
assert_eq!(ran("::Line"), 0, "no settled line ran, in a measuring run or the real run: {runs:?}");
}
/// A vertical scroll body of `Lazy` children, child `at` as tall as `height(at)` and estimated at `estimate(at)`
/// before it ran. It counts each child's runs and keeps the rects of the children the last real pass ran.
struct LazyColumn {