nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! Self-gated clean-frame skip parity: `compute_layout` returns `false` (no pass) only when
//! nothing layout-relevant changed, and every layout input reopens the pass with results equal to
//! a from-scratch layout.

use std::sync::Arc;

use super::hoisted_tests::{VP, assert_matches_layout_of};
use crate::TaffyStoreLayout;
use crate::{TextMeasurer, TextStyle};
use nativeview_tables::tables::{
    AlignSelf, Display, FlexDirection, FontStyle, Layout, Overflow, OverflowWrap, Position,
    TextContent, Typography, Visual, WhiteSpace, WordBreak,
};
use nativeview_engine::Viewport;
use nativeview_store::{ChangeSet, Length, NodeId, NodeStore, Transaction};

/// Deterministic measurer whose box depends on every measure-affecting typography field (and
/// never on paint-only `color`), so every text input changes the measured box.
struct WeightedMeasurer {
    scale: f32,
}

impl TextMeasurer for WeightedMeasurer {
    fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
        let chars = text.chars().count() as f32;
        let glyph = style.font_size * 0.5 * self.scale * f32::from(style.font_weight) / 400.0
            + style.letter_spacing;
        let family: f32 = style.font_family.bytes().map(f32::from).sum::<f32>() * 0.1;
        let modes = f32::from(style.white_space as u8)
            + f32::from(style.word_break as u8) * 2.0
            + f32::from(style.overflow_wrap as u8) * 4.0
            + f32::from(style.font_style as u8) * 8.0;
        let natural = chars * glyph + family + modes;
        let line = style.line_height_points().unwrap_or(style.font_size * 1.25);
        (
            max_width.map_or(natural, |w| natural.min(w)),
            line + style.max_lines as f32,
        )
    }
}

struct Fixture {
    store: NodeStore,
    changes: ChangeSet,
    layout: TaffyStoreLayout,
    measurer: Arc<dyn TextMeasurer>,
    parent: NodeId,
    label: NodeId,
    boxed: NodeId,
}

impl Fixture {
    fn new() -> Self {
        let mut store = NodeStore::new();
        let mut changes = ChangeSet::default();
        let (parent, label, boxed) = {
            let mut tx = store.tx();
            let [parent, label, row, boxed, inner] = [(); 5].map(|_| tx.create());
            tx.set_children(NodeId::ROOT, &[parent]);
            tx.set_children(parent, &[label, row]);
            tx.set_children(row, &[boxed]);
            tx.set_children(boxed, &[inner]);
            tx.edit::<Layout>(parent)
                .flex_direction(FlexDirection::Column);
            // `label` inherits its typography from `parent` and sizes to its text.
            tx.edit::<Typography>(parent)
                .font_size(16.0)
                .font_weight(400);
            tx.edit::<TextContent>(label).text("Hello");
            tx.edit::<Layout>(label).align_self(AlignSelf::FlexStart);
            // Attaching a row is itself layout-relevant; paint-only frames edit existing rows.
            tx.edit::<Typography>(label).color(nativeview_store::Rgba::BLACK);
            tx.edit::<Visual>(boxed).opacity(1.0);
            // `boxed` holds content wider than the 400pt row: its automatic minimum size keeps
            // it at content width until it becomes a scroll container.
            tx.edit::<Layout>(row).flex_direction(FlexDirection::Row);
            tx.edit::<Layout>(inner)
                .width(Length::points(600.0))
                .height(Length::points(30.0));
            tx.commit_into(&mut changes);
            (parent, label, boxed)
        };
        let measurer: Arc<dyn TextMeasurer> = Arc::new(WeightedMeasurer { scale: 1.0 });
        let mut layout = TaffyStoreLayout::new();
        layout.set_text_measurer(Arc::clone(&measurer));
        layout.sync_changes(&store, &changes);
        assert!(
            layout.compute_layout(&store, NodeId::ROOT, VP),
            "first frame lays out"
        );
        Self {
            store,
            changes,
            layout,
            measurer,
            parent,
            label,
            boxed,
        }
    }

    /// Commits `edit` and runs one frame; returns whether a layout pass ran.
    fn commit(&mut self, edit: impl FnOnce(&mut Transaction<'_>)) -> bool {
        let mut tx = self.store.tx();
        edit(&mut tx);
        tx.commit_into(&mut self.changes);
        self.layout.sync_changes(&self.store, &self.changes);
        self.layout.compute_layout(&self.store, NodeId::ROOT, VP)
    }

    /// A frame with an empty transaction.
    fn frame(&mut self) -> bool {
        self.commit(|_| {})
    }

    fn assert_matches_fresh(&self) {
        let mut fresh = TaffyStoreLayout::new();
        fresh.set_text_measurer(Arc::clone(&self.measurer));
        assert_matches_layout_of(&self.store, &self.layout, fresh);
    }

    fn rect(&self, id: NodeId) -> (f32, f32, f32, f32) {
        let r = self.layout.layout_of(id).expect("laid out");
        (r.x, r.y, r.width, r.height)
    }

    /// The reopened pass ran, matches a fresh layout, moved `watched`, and the next empty
    /// frame skips again.
    fn assert_reopened(
        &mut self,
        ran: bool,
        watched: NodeId,
        before: (f32, f32, f32, f32),
        what: &str,
    ) {
        assert!(ran, "{what} must reopen the layout pass");
        self.assert_matches_fresh();
        assert_ne!(
            self.rect(watched),
            before,
            "{what} must change the layout of {watched:?}"
        );
        let pass = self.layout.layout_gen;
        assert!(!self.frame(), "a clean frame after {what} must skip");
        assert_eq!(self.layout.layout_gen, pass);
        self.assert_matches_fresh();
    }
}

#[test]
fn clean_frames_skip_and_paint_only_edits_stay_skipped() {
    let mut f = Fixture::new();
    let pass = f.layout.layout_gen;
    assert!(!f.frame(), "an empty frame skips");
    let (boxed, label) = (f.boxed, f.label);
    assert!(!f.commit(|tx| {
        tx.edit::<Visual>(boxed).opacity(0.5);
        tx.edit::<Typography>(label).color(nativeview_store::Rgba::WHITE);
    }));
    assert_eq!(
        f.layout.layout_gen, pass,
        "paint-only edits never run a pass"
    );
    f.assert_matches_fresh();
    // A viewport change reopens with no store change.
    assert!(
        f.layout
            .compute_layout(&f.store, NodeId::ROOT, Viewport { width: 320.0, ..VP })
    );
    assert!(
        !f.layout
            .compute_layout(&f.store, NodeId::ROOT, Viewport { width: 320.0, ..VP })
    );
}

#[test]
fn text_content_and_inherited_typography_reopen_the_pass() {
    let mut f = Fixture::new();
    let (parent, label) = (f.parent, f.label);

    let before = f.rect(label);
    let ran = f.commit(|tx| {
        tx.edit::<TextContent>(label).text("Hello, wider world");
    });
    f.assert_reopened(ran, label, before, "TextContent::text");

    // Edited on the parent only: reaches the label through inheritance.
    let before = f.rect(label);
    let ran = f.commit(|tx| {
        tx.edit::<Typography>(parent).font_size(24.0);
    });
    f.assert_reopened(ran, label, before, "inherited Typography::font_size");

    let before = f.rect(label);
    let ran = f.commit(|tx| {
        tx.edit::<Typography>(parent).font_weight(700);
    });
    f.assert_reopened(ran, label, before, "inherited Typography::font_weight");
}

/// Every measure-affecting typography field edited on an ancestor re-measures the inheriting
/// descendant; a paint-only `color` edit on the ancestor never runs a pass.
#[test]
fn every_inherited_measure_field_reopens_and_color_stays_skipped() {
    let mut f = Fixture::new();
    let (parent, label) = (f.parent, f.label);
    type Edit = fn(&mut Transaction<'_>, NodeId);
    let edits: [(&str, Edit); 8] = [
        ("line_height", |tx, p| {
            tx.edit::<Typography>(p).line_height(Length::points(40.0));
        }),
        ("letter_spacing", |tx, p| {
            tx.edit::<Typography>(p).letter_spacing(3.0);
        }),
        ("white_space", |tx, p| {
            tx.edit::<Typography>(p).white_space(WhiteSpace::NoWrap);
        }),
        ("max_lines", |tx, p| {
            tx.edit::<Typography>(p).max_lines(core::num::NonZeroU16::new(3));
        }),
        ("font_style", |tx, p| {
            tx.edit::<Typography>(p).font_style(FontStyle::Italic);
        }),
        ("word_break", |tx, p| {
            tx.edit::<Typography>(p).word_break(WordBreak::BreakAll);
        }),
        ("overflow_wrap", |tx, p| {
            tx.edit::<Typography>(p)
                .overflow_wrap(OverflowWrap::Anywhere);
        }),
        ("font_family", |tx, p| {
            tx.edit::<Typography>(p).font_family("Arial");
        }),
    ];
    for (what, edit) in edits {
        let before = f.rect(label);
        let ran = f.commit(|tx| edit(tx, parent));
        f.assert_reopened(ran, label, before, what);
    }

    // Same-length family replaced in place (the arena reuses the span): still re-measured.
    let span = f.layout.resolved_text(label).font_family.span;
    let before = f.rect(label);
    let ran = f.commit(|tx| {
        tx.edit::<Typography>(parent).font_family("Inter");
    });
    assert_eq!(
        f.layout.resolved_text(label).font_family.span,
        span,
        "same-size family edits reuse the span"
    );
    f.assert_reopened(ran, label, before, "same-length font_family");

    let pass = f.layout.layout_gen;
    assert!(!f.commit(|tx| {
        tx.edit::<Typography>(parent).color(nativeview_store::Rgba::WHITE);
    }));
    assert_eq!(f.layout.layout_gen, pass, "inherited color never relayouts");
    f.assert_matches_fresh();
}

#[test]
fn layout_affecting_visual_fields_reopen_the_pass() {
    let mut f = Fixture::new();
    let boxed = f.boxed;
    assert_eq!(
        f.rect(boxed).2,
        600.0,
        "automatic minimum size holds content width"
    );

    let before = f.rect(boxed);
    let ran = f.commit(|tx| {
        tx.edit::<Visual>(boxed).border_width(7.0);
    });
    f.assert_reopened(ran, boxed, before, "Visual::border_width");
    assert_eq!(f.rect(boxed).2, 614.0);

    // Scroll containers have a zero automatic minimum size: `boxed` shrinks into the row.
    let before = f.rect(boxed);
    let ran = f.commit(|tx| {
        tx.edit::<Visual>(boxed).overflow_x(Overflow::Scroll);
    });
    f.assert_reopened(ran, boxed, before, "Visual::overflow_x");
    assert_eq!(f.rect(boxed).2, 400.0);
}

#[test]
fn measurer_swap_and_invalidate_all_reopen_the_pass() {
    let mut f = Fixture::new();
    let label = f.label;

    let before = f.rect(label);
    f.measurer = Arc::new(WeightedMeasurer { scale: 2.0 });
    f.layout.set_text_measurer(Arc::clone(&f.measurer));
    let ran = f.layout.compute_layout(&f.store, NodeId::ROOT, VP);
    f.assert_reopened(ran, label, before, "set_text_measurer");

    let pass = f.layout.layout_gen;
    f.layout.invalidate_all(&f.store);
    assert!(
        f.layout.compute_layout(&f.store, NodeId::ROOT, VP),
        "invalidate_all must reopen"
    );
    assert_ne!(f.layout.layout_gen, pass);
    f.assert_matches_fresh();
    assert!(!f.frame(), "a clean frame after invalidate_all must skip");
}

/// Panics while `armed`, like a faulting host measurer behind `ffi_catch_unwind`.
struct FaultingMeasurer {
    armed: std::sync::atomic::AtomicBool,
    /// Faults only on text containing this (`""`: every text).
    fault_on: &'static str,
}

impl TextMeasurer for FaultingMeasurer {
    fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
        assert!(
            !(self.armed.load(std::sync::atomic::Ordering::Relaxed)
                && text.contains(self.fault_on)),
            "host measurer fault"
        );
        WeightedMeasurer { scale: 1.0 }.measure(text, style, max_width)
    }
}

#[test]
fn a_pass_unwinding_out_of_the_measurer_stays_dirty_and_retries() {
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::sync::atomic::{AtomicBool, Ordering};

    let mut f = Fixture::new();
    let faulting = Arc::new(FaultingMeasurer {
        armed: AtomicBool::new(true),
        fault_on: "",
    });
    f.layout.set_text_measurer(faulting.clone());
    let unwound = catch_unwind(AssertUnwindSafe(|| {
        f.layout.compute_layout(&f.store, NodeId::ROOT, VP)
    }));
    assert!(unwound.is_err(), "the armed measurer must fault mid-pass");

    faulting.armed.store(false, Ordering::Relaxed);
    assert!(
        f.layout.compute_layout(&f.store, NodeId::ROOT, VP),
        "the frame after an unwound pass must retry, not skip"
    );
    f.measurer = Arc::new(WeightedMeasurer { scale: 1.0 });
    f.assert_matches_fresh();
    assert!(!f.frame());
}

#[test]
fn a_fault_while_measuring_a_fixed_box_never_drops_fixed_subtrees() {
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::sync::atomic::{AtomicBool, Ordering};

    let mut f = Fixture::new();
    let boxed = f.boxed;
    let existing = f.store.children(boxed).to_vec();
    let (fixed, fixed_text) = {
        let mut tx = f.store.tx();
        let [fixed, fixed_text] = [(); 2].map(|_| tx.create());
        tx.edit::<Layout>(fixed)
            .position(nativeview_tables::tables::Position::Fixed)
            .inset_right(Length::points(8.0))
            .inset_bottom(Length::points(6.0));
        tx.edit::<TextContent>(fixed_text).text("FIXED toast");
        tx.set_children(fixed, &[fixed_text]);
        let mut kids = existing;
        kids.push(fixed);
        tx.set_children(boxed, &kids);
        tx.commit_into(&mut f.changes);
        (fixed, fixed_text)
    };
    f.layout.sync_changes(&f.store, &f.changes);
    assert!(f.layout.compute_layout(&f.store, NodeId::ROOT, VP));
    assert_eq!(f.layout.hoisted.get(NodeId::ROOT.index()), &[fixed]);
    f.assert_matches_fresh();

    // Every in-flow box measures (and the root's in-flow layout is cached) before the root
    // positioning pass measures the fixed toast's text and faults.
    let faulting = Arc::new(FaultingMeasurer {
        armed: AtomicBool::new(true),
        fault_on: "FIXED",
    });
    f.layout.set_text_measurer(faulting.clone());
    let unwound = catch_unwind(AssertUnwindSafe(|| {
        f.layout.compute_layout(&f.store, NodeId::ROOT, VP)
    }));
    assert!(
        unwound.is_err(),
        "the fixed toast's text must fault mid-pass"
    );

    faulting.armed.store(false, Ordering::Relaxed);
    assert!(f.layout.compute_layout(&f.store, NodeId::ROOT, VP));
    assert_eq!(
        f.layout.hoisted.get(NodeId::ROOT.index()),
        &[fixed],
        "the retry must re-record the root's fixed boxes"
    );
    assert!(
        f.layout.layout_of(fixed_text).is_some(),
        "fixed subtree laid out"
    );
    f.measurer = Arc::new(WeightedMeasurer { scale: 1.0 });
    f.assert_matches_fresh();
}

#[test]
fn switching_the_layout_root_round_trips_to_fresh_layouts() {
    let mut f = Fixture::new();
    let (parent, label, boxed) = (f.parent, f.label, f.boxed);
    // A `position: fixed` toast below an intermediate container (`row`): hoisted to whichever
    // node is the layout root.
    let row = f.store.parent(boxed).expect("row");
    let mut toast = NodeId::ROOT;
    assert!(f.commit(|tx| {
        // An absolute, viewport-sized `parent` is laid out under `ROOT` with exactly the inputs
        // of a root pass (known size = available space = parent size = viewport), so both share
        // its cache key: a cache entry left from the nested pass would be hit on the way back.
        tx.edit::<Layout>(parent)
            .position(Position::Absolute)
            .inset_left(Length::points(0.0))
            .inset_top(Length::points(0.0))
            .width(Length::points(VP.width))
            .height(Length::points(VP.height));
        toast = tx.create();
        tx.edit::<Layout>(toast)
            .position(Position::Fixed)
            .inset_top(Length::points(7.0))
            .width(Length::points(40.0))
            .height(Length::points(10.0));
        tx.set_children(row, &[boxed, toast]);
        // Non-default state on slots outside the nested root: `ROOT`'s own typography and a
        // `display: contents` sibling of `parent`, which a fresh engine laid out from
        // `parent` never resolves.
        tx.edit::<Typography>(NodeId::ROOT).font_size(24.0);
        let aside = tx.create();
        tx.edit::<Layout>(aside).display(Display::Contents);
        tx.set_children(NodeId::ROOT, &[parent, aside]);
    }));
    let subtree = [parent, label, row, boxed, toast];

    // Round 1 keeps every inherited value, so only the root switch itself can invalidate;
    // round 2 flips the root's `direction`, which nothing below `parent` inherits when nested.
    for round in 0..2 {
        if round == 1 {
            assert!(f.commit(|tx| {
                tx.edit::<Layout>(NodeId::ROOT)
                    .direction(nativeview_tables::tables::Direction::Rtl);
            }));
            assert!(f.layout.resolved_rtl(label), "inherits the root's rtl");
        }
        assert_eq!(f.layout.hoisted.get(NodeId::ROOT.index()), &[parent, toast]);
        f.assert_matches_fresh();

        // Laid out from `parent`: the toast hoists to `parent` and nothing above `parent` is
        // inherited, exactly as in a fresh engine.
        assert!(f.layout.compute_layout(&f.store, parent, VP));
        let mut fresh = TaffyStoreLayout::new();
        fresh.set_text_measurer(Arc::clone(&f.measurer));
        assert!(fresh.compute_layout(&f.store, parent, VP));
        // Inherited state matches a fresh engine on every slot, including `ROOT` and the
        // slots outside the nested root.
        for idx in 0..f.store.capacity() {
            assert_eq!(
                (
                    f.layout.resolved_rtl[idx],
                    f.layout.resolved_text[idx],
                    f.layout.was_contents[idx],
                ),
                (
                    fresh.resolved_rtl[idx],
                    fresh.resolved_text[idx],
                    fresh.was_contents[idx],
                ),
                "inherited state of slot {idx}"
            );
        }
        for id in subtree {
            assert_eq!(f.layout.layout_of(id), fresh.layout_of(id), "{id:?}");
            assert_eq!(
                f.layout.hoisted.get(id.index()),
                fresh.hoisted.get(id.index()),
                "hoisted list of {id:?}"
            );
        }
        assert_eq!(f.layout.hoisted.get(parent.index()), &[toast]);

        // Back to the root: no cache, rect, hoisted, or box-children list of the nested pass
        // survives.
        assert!(f.layout.compute_layout(&f.store, NodeId::ROOT, VP));
        assert!(
            f.layout.hoisted.get(parent.index()).is_empty(),
            "round {round}"
        );
        f.assert_matches_fresh();
        assert!(!f.frame(), "settled again");
    }
}

#[test]
fn invalidating_everything_disarms_an_unwound_pass() {
    let mut f = Fixture::new();
    f.layout.pass_root = Some(f.parent);
    f.layout.invalidate_all(&f.store);
    assert_eq!(f.layout.pass_root, None);
    assert!(f.frame(), "invalidation reopens the pass");
    f.assert_matches_fresh();
}

#[test]
fn style_view_fits_in_64_bytes_and_state_box_patch_flag_is_exact() {
    use nativeview_store::RowPatch;
    use nativeview_tables::interaction::{InteractionState, StateStyleRule};
    use nativeview_tables::tables::{ContainerType, Display, Interaction, Position, StateRules, Visual};

    use super::responsive::sync::NodeStyleFlags;
    use super::style::StyleView;

    assert!(
        core::mem::size_of::<StyleView<'_>>() <= 64,
        "StyleView grew to {} bytes (> 64)",
        core::mem::size_of::<StyleView<'_>>()
    );

    let mut store = NodeStore::new();
    store.set_realization_order(nativeview_tables::tables::core_realization_order());
    let mut changes = ChangeSet::default();
    let (plain, paint_only, hover_disp, active_pos, focus_ct) = {
        let mut tx = store.tx();
        let plain = tx.create();
        let paint_only = tx.create();
        let mut p = RowPatch::new();
        p.set(Visual::OPACITY, 0.5);
        tx.set_resource(
            paint_only,
            Interaction::STATE_RULES,
            Some(&StateRules::new(vec![StateStyleRule::new(
                InteractionState::HOVER,
                p,
            )])),
        );
        let hover_disp = tx.create();
        let mut p = RowPatch::new();
        p.set(Layout::DISPLAY, Display::None);
        tx.set_resource(
            hover_disp,
            Interaction::STATE_RULES,
            Some(&StateRules::new(vec![StateStyleRule::new(
                InteractionState::HOVER,
                p,
            )])),
        );
        let active_pos = tx.create();
        let mut p = RowPatch::new();
        p.set(Layout::POSITION, Position::Absolute);
        tx.set_resource(
            active_pos,
            Interaction::STATE_RULES,
            Some(&StateRules::new(vec![StateStyleRule::new(
                InteractionState::ACTIVE,
                p,
            )])),
        );
        let focus_ct = tx.create();
        let mut p = RowPatch::new();
        p.set(Layout::CONTAINER_TYPE, ContainerType::Size);
        tx.set_resource(
            focus_ct,
            Interaction::STATE_RULES,
            Some(&StateRules::new(vec![StateStyleRule::new(
                InteractionState::FOCUS,
                p,
            )])),
        );
        tx.set_children(
            NodeId::ROOT,
            &[plain, paint_only, hover_disp, active_pos, focus_ct],
        );
        tx.commit_into(&mut changes);
        (plain, paint_only, hover_disp, active_pos, focus_ct)
    };
    let mut layout = TaffyStoreLayout::new();
    layout.sync_changes(&store, &changes);
    layout.compute_layout(&store, NodeId::ROOT, VP);
    let has = |l: &TaffyStoreLayout, id: NodeId| {
        l.style_flags[id.index()].contains(NodeStyleFlags::HAS_STATE_BOX_PATCH)
    };
    assert!(!has(&layout, plain));
    assert!(!has(&layout, paint_only));
    assert!(has(&layout, hover_disp));
    assert!(has(&layout, active_pos));
    assert!(has(&layout, focus_ct));

    // Detaching `Interaction` clears the flag incrementally without a full recount.
    {
        let mut tx = store.tx();
        tx.detach::<Interaction>(hover_disp);
        tx.commit_into(&mut changes);
    }
    layout.sync_changes(&store, &changes);
    assert!(!has(&layout, hover_disp));
}