Skip to main content

nativeview_layout/taffy_store/responsive/
text.rs

1//! Responsive (`@media` + `@container`) typography: which nodes carry responsive `Typography`
2//! patches, and the exact cascade-then-inherit fold that resolves a paragraph root's effective
3//! [`ResolvedTextStyle`] under a [`ResponsiveTextEnv`].
4
5use nativeview_store::{NodeId, NodeStore, RowPatchView};
6use nativeview_tables::container::{ContainerEnv, ContainerRules};
7use nativeview_tables::media::MediaEnv;
8use nativeview_tables::tables::{Responsive, ResponsiveRules, Typography};
9
10use crate::measure::{ResolvedTextStyle, resolve_inherited_text};
11
12use super::visit_node_responsive_patches;
13
14/// Active responsive environment threaded into paragraph compilation: the `@media` environment
15/// plus the `@container` environment each node resolves against.
16#[derive(Clone, Copy)]
17pub struct ResponsiveTextEnv<'a> {
18    pub media: &'a MediaEnv,
19    pub container_env_of: &'a dyn Fn(NodeId) -> ContainerEnv,
20}
21
22/// Most `Typography`/`Responsive`-bearing ancestors folded for one paragraph root; deeper chains
23/// start the fold from the default style at the topmost recorded node.
24const MAX_STYLED_ANCESTORS: usize = 128;
25
26#[inline]
27fn patch_touches_typography(pv: RowPatchView<'_>) -> bool {
28    pv.has_table::<Typography>()
29}
30
31/// Returns `true` if `id` carries a `Responsive` rule patching any `Typography` property.
32pub(crate) fn node_has_own_responsive_typo(store: &NodeStore, id: NodeId) -> bool {
33    let Some(resp) = store.try_row::<Responsive>(id) else {
34        return false;
35    };
36    let media = !resp.rules().is_none()
37        && store
38            .resource::<ResponsiveRules>(resp.rules())
39            .is_some_and(|r| r.iter().any(|(_, pv)| patch_touches_typography(pv)));
40    media
41        || (!resp.container_rules().is_none()
42            && store
43                .resource::<ContainerRules>(resp.container_rules())
44                .is_some_and(|r| r.iter().any(|(_, pv)| patch_touches_typography(pv))))
45}
46
47/// Returns `true` if paragraph root `pid` or any inline descendant carries a responsive
48/// `Typography` patch. Zero allocations: inline subtrees deeper than the fixed stack answer
49/// `true` (conservative: it only costs a scratch compile per measure).
50pub(crate) fn paragraph_has_inline_responsive_typo(store: &NodeStore, pid: NodeId) -> bool {
51    const CAP: usize = 64;
52    if node_has_own_responsive_typo(store, pid) {
53        return true;
54    }
55    let mut stack = [NodeId::NULL; CAP];
56    let mut len = 0usize;
57    for &c in store.children(pid) {
58        if len == CAP {
59            return true;
60        }
61        stack[len] = c;
62        len += 1;
63    }
64    while len > 0 {
65        len -= 1;
66        let cur = stack[len];
67        if !store.is_live(cur) {
68            continue;
69        }
70        if node_has_own_responsive_typo(store, cur) {
71            return true;
72        }
73        for &c in store.children(cur) {
74            if len == CAP {
75                return true;
76            }
77            stack[len] = c;
78            len += 1;
79        }
80    }
81    false
82}
83
84/// Applies every `Typography` property present in `pv` onto `style` (same validation as
85/// [`resolve_inherited_text`]).
86#[inline]
87pub(crate) fn apply_patch_to_resolved_text_style(
88    pv: RowPatchView<'_>,
89    style: &mut ResolvedTextStyle,
90) {
91    if !pv.has_table::<Typography>() {
92        return;
93    }
94    if let Some(c) = pv.get_prop(Typography::COLOR) {
95        style.color = c;
96    }
97    if let Some(fs) = pv.get_prop(Typography::FONT_SIZE)
98        && fs.is_finite()
99        && fs >= 0.0
100    {
101        style.font_size = fs;
102    }
103    if let Some(lh) = pv.get_prop(Typography::LINE_HEIGHT)
104        && (lh.is_auto() || (lh.value().is_finite() && lh.value() >= 0.0))
105    {
106        style.line_height = lh;
107    }
108    if let Some(ls) = pv.get_prop(Typography::LETTER_SPACING)
109        && ls.is_finite()
110    {
111        style.letter_spacing = ls;
112    }
113    if let Some(ml) = pv.get_prop(Typography::MAX_LINES) {
114        style.max_lines = ml.map_or(0, |nz| u32::from(nz.get()));
115    }
116    if let Some(fw) = pv.get_prop(Typography::FONT_WEIGHT) {
117        style.font_weight = fw;
118    }
119    if let Some(st) = pv.get_prop(Typography::FONT_STYLE) {
120        style.font_style = st;
121    }
122    if let Some(ws) = pv.get_prop(Typography::WHITE_SPACE) {
123        style.white_space = ws;
124    }
125    if let Some(wb) = pv.get_prop(Typography::WORD_BREAK) {
126        style.word_break = wb;
127    }
128    if let Some(ow) = pv.get_prop(Typography::OVERFLOW_WRAP) {
129        style.overflow_wrap = ow;
130    }
131    if let Some(ta) = pv.get_prop(Typography::TEXT_ALIGN) {
132        style.text_align = ta;
133    }
134    if let Some(td) = pv.get_prop(Typography::TEXT_DECORATION) {
135        style.text_decoration = td;
136    }
137    if let Some(va) = pv.get_prop(Typography::VERTICAL_ALIGN) {
138        style.vertical_align = va;
139    }
140}
141
142/// Effective text style of `id` under `env`: `base -> @media -> @container` resolved on every
143/// ancestor, then inherited, exactly like CSS cascade-then-inherit. When no ancestor-or-self
144/// carries a `Responsive` row the fold is skipped and `resolve_inherited_text(parent_text)` is
145/// returned unchanged.
146pub(crate) fn responsive_inherited_text(
147    store: &NodeStore,
148    id: NodeId,
149    parent_text: ResolvedTextStyle,
150    env: ResponsiveTextEnv<'_>,
151) -> ResolvedTextStyle {
152    // Record only nodes that can change the fold (a `Typography` or `Responsive` row); all other
153    // ancestors pass their parent's style through unchanged.
154    let mut chain = [NodeId::NULL; MAX_STYLED_ANCESTORS];
155    let mut len = 0usize;
156    let mut any_responsive = false;
157    let mut cur = Some(id);
158    for _ in 0..crate::MAX_TREE_DEPTH {
159        let Some(n) = cur else { break };
160        let responsive = store.has::<Responsive>(n);
161        if (responsive || store.has::<Typography>(n)) && len < MAX_STYLED_ANCESTORS {
162            chain[len] = n;
163            len += 1;
164            any_responsive |= responsive;
165        }
166        cur = store.parent(n).filter(|&p| p != n);
167    }
168    if !any_responsive {
169        return resolve_inherited_text(store, id, parent_text);
170    }
171    let mut style = ResolvedTextStyle::default();
172    for &n in chain[..len].iter().rev() {
173        style = resolve_inherited_text(store, n, style);
174        if store.has::<Responsive>(n) {
175            visit_node_responsive_patches(store, n, env.media, (env.container_env_of)(n), |_, pv| {
176                apply_patch_to_resolved_text_style(pv, &mut style);
177            });
178        }
179    }
180    style
181}
182
183/// Recompile key of a responsive paragraph: the `MediaEnv` plus the committed `@container` env of
184/// `pid` and of every `Responsive` ancestor whose typography it may inherit.
185pub(crate) fn paragraph_env_hash(
186    store: &NodeStore,
187    pid: NodeId,
188    media_signature: u64,
189    container_env_of: &dyn Fn(NodeId) -> ContainerEnv,
190) -> u64 {
191    let mut chain = super::container_env_hash(0, container_env_of(pid));
192    let mut cur = store.parent(pid).filter(|&p| p != pid);
193    for _ in 0..crate::MAX_TREE_DEPTH {
194        let Some(n) = cur else { break };
195        if store.has::<Responsive>(n) {
196            chain = super::container_env_hash(chain, container_env_of(n));
197        }
198        cur = store.parent(n).filter(|&p| p != n);
199    }
200    super::env_hash(media_signature, chain)
201}
202
203/// Responsive paragraphs compiled under a live layout env (the committed store holds the runs
204/// of the last committed env), each compiled once per env and pass: Taffy measures a paragraph
205/// several times per pass under the same env.
206#[derive(Debug, Default)]
207pub(crate) struct MeasureParagraphs {
208    pub(crate) store: crate::ParagraphStore,
209    /// Per paragraph root: `(pass_gen, env_key)` its scratch runs were compiled under.
210    compiled: super::super::container::scope::GenSlots<(u64, u64)>,
211    pass_gen: u64,
212}
213
214impl MeasureParagraphs {
215    /// Advances the pass epoch in O(1) so base-row edits invalidate scratch compiles without
216    /// sweeping every node slot.
217    pub(crate) fn begin_pass(&mut self, cap: usize) {
218        self.compiled.ensure_len(cap);
219        self.pass_gen = self.pass_gen.wrapping_add(1);
220        if self.pass_gen == 0 {
221            self.compiled.reset_all();
222            self.pass_gen = 1;
223        }
224    }
225
226    /// Whether `pid` still needs compiling under `env_key`; records it as compiled.
227    pub(crate) fn needs_compile(&mut self, pid: NodeId, env_key: u64) -> bool {
228        let key = (self.pass_gen, env_key);
229        if self.compiled.get(pid) == Some(key) {
230            return false;
231        }
232        self.compiled.set(pid, key);
233        true
234    }
235
236    pub(crate) fn reset(&mut self) {
237        self.store.reset();
238        self.compiled.release();
239        self.pass_gen = 0;
240    }
241}