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};
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);
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);
tx.edit::<Typography>(label).color(nativeview_store::Rgba::BLACK);
tx.edit::<Visual>(boxed).opacity(1.0);
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,
}
}
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)
}
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)
}
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();
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");
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");
}
#[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);
}
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);
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");
}
struct FaultingMeasurer {
armed: std::sync::atomic::AtomicBool,
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();
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);
let row = f.store.parent(boxed).expect("row");
let mut toast = NodeId::ROOT;
assert!(f.commit(|tx| {
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]);
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];
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();
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));
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]);
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));
{
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));
}