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
//! Native responsive (`@media` + `@container`) box-style resolution for
//! [`super::TaffyStoreLayout`]: the tiered patch visitor, O(1) environment hashing, and the
//! stack-resident 5-table responsive style overlay.

pub(crate) mod sync;
pub(crate) mod text;

use nativeview_store::{NodeId, NodeStore, NvTable, ResourceId, RowPatchView, Word};
use nativeview_tables::container::{ContainerEnv, ContainerRules};
use nativeview_tables::media::{ConditionalTier, MediaEnv, MediaQuery, cascade_display};
use nativeview_tables::tables::{
    ContainerType, GridItem, GridLayout, Layout as NvLayout, Position as NvPosition,
    Overflow as NvOverflow, Responsive, ResponsiveRules, Transform as TransformTable, Visual,
};
use nativeview_tables::transform::Transform2D;

#[inline(always)]
fn canon_f32_bits(v: f32) -> u32 {
    if v == 0.0 {
        0.0f32.to_bits()
    } else {
        v.to_bits()
    }
}

/// Strong 64-bit mix of `seed` and `v` (splitmix64 finalizer): the per-call key mixer of the
/// layout hot path, where a streaming hasher costs more than the lookup it guards.
#[inline(always)]
fn mix64(seed: u64, v: u64) -> u64 {
    let mut z = seed ^ v.wrapping_add(0x9E37_79B9_7F4A_7C15).rotate_left(29);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// Folds `cenv` into `seed` (container chain hashes and committed paragraph env hashes).
#[inline]
pub(crate) fn container_env_hash(seed: u64, cenv: ContainerEnv) -> u64 {
    let bits = |v: Option<f32>| u64::from(canon_f32_bits(v.unwrap_or(0.0)));
    let (sw, sh) = cenv.size_pt.unzip();
    let axes = u64::from(cenv.inline_pt.is_some()) | (u64::from(cenv.size_pt.is_some()) << 1);
    let seed = mix64(mix64(seed, axes), bits(cenv.inline_pt));
    mix64(seed, bits(sw) | (bits(sh) << 32))
}

/// Deterministic non-zero mix of a [`MediaBreakpoints::signature`] and a container chain hash: the O(1)
/// Taffy cache key of responsive subtrees and the recompile key of responsive paragraphs.
#[inline]
pub(crate) fn env_hash(media_signature: u64, container_chain: u64) -> u64 {
    mix64(mix64(0x4E56_4543_5145_4E56, media_signature), container_chain).max(1)
}

/// Every width edge (`min`, `max + 1`) of the store's `@media` rules and `show_on` gates, sorted
/// and unique. Within one interval between edges every width query matches identically, so the
/// interval index (plus the non-width media features) is the media part of every responsive
/// cache key: a resize that crosses no breakpoint keeps Taffy's caches warm, in O(log edges).
#[derive(Debug, Default)]
pub(crate) struct MediaBreakpoints {
    edges: Vec<f32>,
}

impl MediaBreakpoints {
    /// Recollects the edges (only when the responsive rule set changed).
    pub(crate) fn rebuild(&mut self, store: &NodeStore) {
        self.edges.clear();
        let mut push = |q: MediaQuery| {
            if let Some(min) = q.min_width_opt() {
                self.edges.push(f32::from(min));
            }
            if let Some(max) = q.max_width_opt() {
                self.edges.push(f32::from(max) + 1.0);
            }
        };
        for i in 0..store.capacity() {
            let Some(id) = store.id_at(i) else { continue };
            let Some(resp) = store.try_row::<Responsive>(id) else {
                continue;
            };
            if let Some(q) = resp.show_on() {
                push(q);
            }
            if let Some(rules) = store.resource::<ResponsiveRules>(resp.rules()) {
                for (q, _) in rules.iter() {
                    push(q);
                }
            }
        }
        self.edges.sort_unstable_by(f32::total_cmp);
        self.edges.dedup();
    }

    /// The media signature of `media`: width interval index + color scheme, reduced motion,
    /// and pointer bits.
    #[inline]
    pub(crate) fn signature(&self, media: &MediaEnv) -> u64 {
        let interval = self.edges.partition_point(|&e| e <= media.width_pt) as u64;
        interval
            | (u64::from(media.dark_mode) << 32)
            | (u64::from(media.reduced_motion) << 33)
            | (u64::from(media.coarse_pointer) << 34)
    }
}

const _: () = {
    assert!(NvLayout::DESC.defaults.len() == 26);
    assert!(GridItem::DESC.defaults.len() == 2);
    assert!(TransformTable::DESC.defaults.len() == 7);
};

/// Stack-resident 5-table responsive style overlay (`Layout`, `Visual` layout fields,
/// `GridLayout`, `GridItem`, `Transform`) resolved zero-alloc for nodes with active `Responsive`
/// rules (Patch #5).
#[derive(Clone, Copy)]
pub(crate) struct ResolvedResponsiveStyle {
    pub(crate) show_on_hidden: bool,
    pub(crate) layout_words: [Word; 26],
    pub(crate) border_width: f32,
    pub(crate) overflow_x: NvOverflow,
    pub(crate) overflow_y: NvOverflow,
    pub(crate) grid_template_columns: ResourceId,
    pub(crate) grid_template_rows: ResourceId,
    pub(crate) grid_item_words: [Word; 2],
    pub(crate) has_transform: bool,
}

impl ResolvedResponsiveStyle {
    #[inline]
    fn from_store_base(store: &NodeStore, id: NodeId) -> (Self, [Word; 7]) {
        let mut layout_words = [0u32; 26];
        store.copy_row_words::<NvLayout>(id, &mut layout_words);
        let vis = store.row::<Visual>(id);
        let (grid_template_columns, grid_template_rows) = store
            .try_row::<GridLayout>(id)
            .map_or((ResourceId::NONE, ResourceId::NONE), |g| {
                (g.template_columns(), g.template_rows())
            });
        let mut grid_item_words = [0u32; 2];
        store.copy_row_words::<GridItem>(id, &mut grid_item_words);
        let mut tf_words = [0u32; 7];
        store.copy_row_words::<TransformTable>(id, &mut tf_words);
        let has_transform = transform_words_non_identity(store, &tf_words);
        (
            Self {
                show_on_hidden: false,
                layout_words,
                border_width: vis.border_width(),
                overflow_x: vis.overflow_x(),
                overflow_y: vis.overflow_y(),
                grid_template_columns,
                grid_template_rows,
                grid_item_words,
                has_transform,
            },
            tf_words,
        )
    }

    #[inline]
    fn hidden_only() -> Self {
        let mut layout_words = [0u32; 26];
        layout_words.copy_from_slice(NvLayout::DESC.defaults);
        let mut grid_item_words = [0u32; 2];
        grid_item_words.copy_from_slice(GridItem::DESC.defaults);
        Self {
            show_on_hidden: true,
            layout_words,
            border_width: 0.0,
            overflow_x: NvOverflow::Visible,
            overflow_y: NvOverflow::Visible,
            grid_template_columns: ResourceId::NONE,
            grid_template_rows: ResourceId::NONE,
            grid_item_words,
            has_transform: false,
        }
    }

    #[inline]
    fn apply_patch(&mut self, store: &NodeStore, pv: RowPatchView<'_>, tf_words: &mut [Word; 7]) {
        pv.apply_table::<NvLayout>(&mut self.layout_words);
        if pv.has_table::<Visual>() {
            if let Some(bw) = pv.get_prop(Visual::BORDER_WIDTH) {
                self.border_width = bw;
            }
            if let Some(ox) = pv.get_prop(Visual::OVERFLOW_X) {
                self.overflow_x = ox;
            }
            if let Some(oy) = pv.get_prop(Visual::OVERFLOW_Y) {
                self.overflow_y = oy;
            }
        }
        if pv.has_table::<GridLayout>() {
            if let Some(cols) = pv.get_res_id(GridLayout::TEMPLATE_COLUMNS) {
                self.grid_template_columns = cols;
            }
            if let Some(rows) = pv.get_res_id(GridLayout::TEMPLATE_ROWS) {
                self.grid_template_rows = rows;
            }
        }
        pv.apply_table::<GridItem>(&mut self.grid_item_words);
        if pv.apply_table::<TransformTable>(tf_words) {
            self.has_transform = transform_words_non_identity(store, tf_words);
        }
    }
}

#[inline]
fn transform_words_non_identity(store: &NodeStore, tf_words: &[Word; 7]) -> bool {
    let t = store.row_from_words::<TransformTable>(tf_words);
    !Transform2D {
        translate_x: t.translate_x(),
        translate_y: t.translate_y(),
        scale_x: t.scale_x(),
        scale_y: t.scale_y(),
        rotate_deg: t.rotate_deg(),
        origin_x: t.origin_x(),
        origin_y: t.origin_y(),
    }
    .is_identity()
}

/// Visits every matching `@media` rule followed by every matching `@container` rule on `id`
/// in deterministic cascade order (`@layer nv-m` then `@layer nv-cq`), zero allocations.
#[inline]
pub(crate) fn visit_node_responsive_patches<'a>(
    store: &'a NodeStore,
    id: NodeId,
    media_env: &MediaEnv,
    container_env: ContainerEnv,
    mut f: impl FnMut(ConditionalTier, RowPatchView<'a>),
) {
    let Some(resp) = store.try_row::<Responsive>(id) else {
        return;
    };
    if let Some(mrules) = store.resource::<ResponsiveRules>(resp.rules()) {
        for (q, pv) in mrules.iter() {
            if q.matches(media_env) {
                f(ConditionalTier::Media, pv);
            }
        }
    }
    if container_env.is_none() {
        return;
    }
    if let Some(crules) = store.resource::<ContainerRules>(resp.container_rules()) {
        for (q, pv) in crules.iter() {
            if q.matches(&container_env) {
                f(ConditionalTier::Container, pv);
            }
        }
    }
}

/// Returns `true` when `id` has a `Responsive::show_on` media gate that fails under `media_env`
/// (Patch #17: matches Web's `display:none!important;`, beating `@media`, `@container`, and
/// `StateRules`).
#[inline]
pub(crate) fn is_node_show_on_hidden(store: &NodeStore, id: NodeId, media_env: &MediaEnv) -> bool {
    store
        .try_row::<Responsive>(id)
        .and_then(|r| r.show_on())
        .is_some_and(|q| !q.matches(media_env))
}

/// Resolves the 5-table responsive overlay for `id`, returning `None` (zero 104-byte copy) when
/// `id` has no `Responsive` row or no rule matches and `show_on` passes.
#[inline]
pub(crate) fn resolve_responsive_style(
    store: &NodeStore,
    id: NodeId,
    media_env: &MediaEnv,
    container_env: ContainerEnv,
) -> Option<ResolvedResponsiveStyle> {
    let resp = store.try_row::<Responsive>(id)?;
    if resp.show_on().is_some_and(|q| !q.matches(media_env)) {
        return Some(ResolvedResponsiveStyle::hidden_only());
    }
    let mut state: Option<(ResolvedResponsiveStyle, [Word; 7])> = None;
    visit_node_responsive_patches(store, id, media_env, container_env, |tier, pv| {
        let (r, tf) =
            state.get_or_insert_with(|| ResolvedResponsiveStyle::from_store_base(store, id));
        let word = NvLayout::DISPLAY.word() as usize;
        let saved = r.layout_words[word];
        let before = NvLayout::DISPLAY.get(&r.layout_words);
        r.apply_patch(store, pv, tf);
        let after = NvLayout::DISPLAY.get(&r.layout_words);
        if cascade_display(store, id, before, Some(tier), after) != after {
            let bits = NvLayout::DISPLAY.mask();
            r.layout_words[word] = (r.layout_words[word] & !bits) | (saved & bits);
        }
    });
    state.map(|(r, _)| r)
}

/// One node's in-pass responsive input of the shared [`crate::StyleCascade`]: the `@media`
/// env plus the `@container` env that node queries in this layout pass.
pub(crate) struct PassPatches<'a> {
    pub(crate) media: &'a MediaEnv,
    pub(crate) container_env: ContainerEnv,
}

impl crate::scene::ResponsivePatches for PassPatches<'_> {
    #[inline]
    fn visit_responsive_patches<'a>(
        &self,
        store: &'a NodeStore,
        id: NodeId,
        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
    ) {
        visit_node_responsive_patches(store, id, self.media, self.container_env, f);
    }

    #[inline]
    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool {
        is_node_show_on_hidden(store, id, self.media)
    }
}

/// One memoized responsive overlay: `(env key, resolved style)`; key `0` = empty.
pub(crate) type RespMemo = (u64, Option<ResolvedResponsiveStyle>);

/// Zero-`unsafe` `Sync` wrapper for `Send`-only scratch accessed exclusively via `&mut self`
/// (e.g. `Vec<RefCell<RespMemo>>`). `Mutex::get_mut` compiles to a direct pointer dereference
/// with zero locking or atomic instructions.
#[derive(Debug, Default)]
pub(crate) struct SyncOnlyMut<T>(std::sync::Mutex<T>);

impl<T> SyncOnlyMut<T> {
    #[inline]
    pub(crate) fn new(value: T) -> Self {
        Self(std::sync::Mutex::new(value))
    }

    #[inline(always)]
    pub(crate) fn get_mut(&mut self) -> &mut T {
        self.0
            .get_mut()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

/// Dense index of a responsive node's [`RespMemo`] entry (`NONE` = no `Responsive` row).
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RespMemoSlot(u32);

impl RespMemoSlot {
    pub(crate) const NONE: Self = Self(u32::MAX);

    #[inline]
    pub(crate) fn new(index: usize) -> Self {
        Self(u32::try_from(index).unwrap_or(u32::MAX))
    }

    #[inline]
    pub(crate) fn index(self) -> Option<usize> {
        (self != Self::NONE).then_some(self.0 as usize)
    }
}

/// Which conditional rule lists [`responsive_rules_any`] scans.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RuleLists {
    Media,
    MediaAndContainer,
}

/// Whether any of `id`'s `@media` (and, with [`RuleLists::MediaAndContainer`], `@container`)
/// rules matches `pred`, regardless of whether the rule currently applies: the one scan behind
/// every "may a rule change this?" question (position, display, container type).
pub(crate) fn responsive_rules_any(
    store: &NodeStore,
    id: NodeId,
    lists: RuleLists,
    pred: impl Fn(RowPatchView<'_>) -> bool,
) -> bool {
    let Some(resp) = store.try_row::<Responsive>(id) else {
        return false;
    };
    let media = !resp.rules().is_none()
        && store
            .resource::<ResponsiveRules>(resp.rules())
            .is_some_and(|r| r.iter().any(|(_, pv)| pred(pv)));
    media
        || (lists == RuleLists::MediaAndContainer
            && !resp.container_rules().is_none()
            && store
                .resource::<ContainerRules>(resp.container_rules())
                .is_some_and(|r| r.iter().any(|(_, pv)| pred(pv))))
}

/// Whether `id` is, or through a conditional/state rule may become, a query container.
pub(crate) fn node_may_be_container(store: &NodeStore, id: NodeId) -> bool {
    let is_container = |pv: RowPatchView<'_>| {
        pv.get_prop(NvLayout::CONTAINER_TYPE)
            .is_some_and(|c| c != ContainerType::Normal)
    };
    store.is_live(id)
        && !store.is_inline(id)
        && (store
            .try_row::<NvLayout>(id)
            .is_some_and(|l| l.container_type() != ContainerType::Normal)
            || responsive_rules_any(store, id, RuleLists::MediaAndContainer, is_container)
            || crate::scene::state_rules_of(store, id)
                .is_some_and(|r| r.iter().any(|(_, pv)| is_container(pv))))
}

/// Whether `id` is, or through a conditional/state rule may become, a `ContainerType::Size`
/// container (the only kind that can act as a relayout containment boundary).
pub(crate) fn node_may_be_size_container(store: &NodeStore, id: NodeId) -> bool {
    let is_size = |pv: RowPatchView<'_>| {
        pv.get_prop(NvLayout::CONTAINER_TYPE) == Some(ContainerType::Size)
    };
    store.is_live(id)
        && !store.is_inline(id)
        && (store
            .try_row::<NvLayout>(id)
            .is_some_and(|l| l.container_type() == ContainerType::Size)
            || responsive_rules_any(store, id, RuleLists::MediaAndContainer, is_size)
            || crate::scene::state_rules_of(store, id)
                .is_some_and(|r| r.iter().any(|(_, pv)| is_size(pv))))
}

/// Whether Taffy may lay `id` out under a containing block instead of its flat-tree parent
/// (`position: absolute | fixed` from its base row, an `@media` / `@container` rule, or a state
/// rule), so its `@container` scope must be looked up from its flat-tree ancestors. Hoisting is
/// checked live (`TopLayerIndex`); this static part is precomputed per node.
pub(crate) fn node_may_be_out_of_flow(store: &NodeStore, id: NodeId) -> bool {
    let out_of_flow = |p: NvPosition| matches!(p, NvPosition::Absolute | NvPosition::Fixed);
    let patches_position = |pv: RowPatchView<'_>| pv.get_prop(NvLayout::POSITION).is_some();
    store.is_live(id)
        && !store.is_inline(id)
        && (store.try_row::<NvLayout>(id).is_some_and(|l| out_of_flow(l.position()))
            || responsive_rules_any(store, id, RuleLists::MediaAndContainer, patches_position)
            || crate::scene::state_rules_of(store, id)
                .is_some_and(|r| r.iter().any(|(_, pv)| patches_position(pv))))
}