Skip to main content

nsh_core/core/
cull.rs

1//! Scroll views make the native views of their content near their
2//! viewport only (`EngineConfig::content_culling`). The rows of an
3//! `<Each>` far from it wait as placeholders sized like the rows rendered
4//! (`Op::Placeholder`): JS renders a row once its placeholder would be
5//! made (`JsEvent::Rows`).
6//!
7//! While the user scrolls, the window reaches further ahead the way the
8//! scroll moves, by its last steps (within a bound): the platform moves the
9//! content in the frames before what a step makes arrives, so a fast scroll
10//! finds its content made rather than empty.
11//!
12//! A view whose transform moves it culls with its rectangle widened by how
13//! far the transform may take it ([`Core::reach_of`]): a static translation
14//! or one animated by values the core can bound (`animation/reach.rs`), as
15//! a section's entrance slides it a few points. A transform it cannot bound
16//! (a scale, a rotation, a gesture's or a scroll view's value) keeps the
17//! view and what it holds made with their parent, as does `position:
18//! sticky`: its scroll view moves it to its viewport's edge however far its
19//! frame is.
20
21use taffy::Position;
22
23use super::{Core, Key, Kind, NO_KEY, Origin, rounded, scroll_extent};
24use crate::{geometry::Bounds, mount::MountItem, ops::EventKind, text::TextEngine};
25
26/// How far around its viewport a scroll view mounts its content, in
27/// viewports on each side (as lists' overscan).
28const OVERSCAN: f32 = 1.0;
29
30/// How far from its viewport a scroll view lets made views go again, in
31/// viewports on each side: further than [`OVERSCAN`], so a view scrolled
32/// a little out and back stays.
33const RECLAIM: f32 = 3.0;
34
35/// How many of its last steps a scrolling view's culling window reaches
36/// ahead, the way it moves: what a step makes shows a frame or two later
37/// (the engine's commit, the platform's next frame), when the platform
38/// has moved on as far again.
39pub(super) const LEAD_STEPS: f32 = 3.0;
40
41/// How many steps ahead what is made counts as in sight, made at once
42/// rather than within the turn's budget (`pace.rs`): where the next frame
43/// shows. What lies further comes nearest first, as the budget allows.
44pub(super) const SIGHT_STEPS: f32 = 1.0;
45
46/// The furthest a scrolling view reaches ahead, in viewports; a longer
47/// step is a jump (a scroll bar dragged across), which reaches no further.
48const LEAD_MAX: f32 = 8.0;
49
50/// The most views a subtree given up may have: a larger one is kept, so
51/// the check stays cheap on every scroll.
52const RECLAIM_MAX_NODES: usize = 200;
53
54/// How high a placeholder is until rows rendered beside it give its size.
55const PLACEHOLDER_HEIGHT: f32 = 44.0;
56
57impl<M: TextEngine> Core<M> {
58    /// The scroll view that culls the children of `parent` (`parent`
59    /// itself, or the nearest scroll view around it), when there is one.
60    pub(super) fn cull_scope(&self, parent: Key) -> Option<Key> {
61        // A terminal's views are its Cells, as cheap as the core's nodes,
62        // and its search and focus keys read all of them.
63        if self.layout.grid().is_some() || !self.culls_content {
64            return None;
65        }
66        let mut key = parent;
67        while key != NO_KEY {
68            let node = &self.nodes[key as usize];
69            if node.list.is_some() || node.kind == Kind::Cell || node.is_layout_root() {
70                return None;
71            }
72            // A view inside a text (an attachment) is laid out on its own
73            // and placed by its text, which makes it with its view:
74            // culling's walk never reaches into it, so what it holds
75            // would wait for good.
76            if node.inline && node.kind != Kind::Text && node.layout.is_some() {
77                return None;
78            }
79            if node.kind == Kind::Scroll {
80                return node
81                    .scroll
82                    .as_ref()
83                    .is_some_and(|s| !s.behavior.zooms())
84                    .then_some(key);
85            }
86            // Content that moves as a whole by more than can be told: where
87            // its children show is not near their frames. A translation of
88            // known reach widens their rectangles instead (`sync_culled_in`).
89            self.reach_of(key)?;
90            key = node.parent;
91        }
92        None
93    }
94
95    /// Whether `key` is made with its parent wherever it is: it may show
96    /// away from its frame, or lays out on its own (a dialog's modal, which
97    /// [`Core::sync_culled`] never comes back to).
98    pub(super) fn never_culled(&self, key: Key) -> bool {
99        let node = &self.nodes[key as usize];
100        node.follow.is_some()
101            || node.decoration
102            || node.is_overlay()
103            || node.is_layout_root()
104            || self.reach_of(key).is_none()
105    }
106
107    /// How far `key`'s transform may move it from its frame, in points
108    /// along x and along y (either way): `(0, 0)` without one; `None` when
109    /// that cannot be told, for a scale, a rotation, a skew or a
110    /// perspective, or a translation by a value without a bound (a
111    /// gesture's, a scroll view's: `animation/reach.rs`), and for a sticky
112    /// view, which its scroll view pins. Animated opacity and colors move
113    /// nothing.
114    pub(super) fn reach_of(&self, key: Key) -> Option<(f32, f32)> {
115        use crate::{animation::AnimationProp, transform::TransformKind};
116        let node = &self.nodes[key as usize];
117        if node.sticky.is_some() {
118            return None;
119        }
120        let ops = node.view_style.transform.ops();
121        if ops.is_empty() {
122            return Some((0.0, 0.0));
123        }
124        let (mut x, mut y) = (0.0f32, 0.0f32);
125        for (i, op) in ops.iter().enumerate() {
126            let animated = node
127                .animated
128                .iter()
129                .find(|(prop, _)| *prop == AnimationProp::Transform(i as u8))
130                .map(|&(_, value)| value);
131            let (lo, hi) = match animated {
132                Some(value) => self.reach.range(value)?,
133                None => (op.value, op.value),
134            };
135            let far = lo.abs().max(hi.abs());
136            let size = node.frame.size;
137            match op.kind {
138                TransformKind::TranslateX => x += far,
139                TransformKind::TranslateY => y += far,
140                TransformKind::TranslateXFraction if size.width.0.is_finite() => {
141                    x += far * size.width.0
142                }
143                TransformKind::TranslateYFraction if size.height.0.is_finite() => {
144                    y += far * size.height.0
145                }
146                // An entry that changes nothing (a scale of 1).
147                kind if animated.is_none() && op.value == kind.identity() => {}
148                _ => return None,
149            }
150        }
151        (x.is_finite() && y.is_finite()).then_some((x, y))
152    }
153
154    /// Holds back `child`, about to be made in `scope`'s content, when it
155    /// may be culled; whether it was.
156    pub(super) fn hold_back(&mut self, scope: Option<Key>, child: Key) -> bool {
157        if self.nodes[child as usize].placeholder && (scope.is_none() || self.never_culled(child)) {
158            // Nothing culls it: its row is rendered in its place now.
159            self.ask_row(child);
160            return true;
161        }
162        let Some(scope) = scope else {
163            return self.pace_hold(child);
164        };
165        if self.nodes[child as usize].created || self.never_culled(child) {
166            return false;
167        }
168        self.nodes[child as usize].culled = true;
169        if let Some(scroll) = self.nodes[scope as usize].scroll.as_mut()
170            && !scroll.culls
171        {
172            scroll.culls = true;
173            self.culling.push(scope);
174        }
175        self.cull_dirty = true;
176        true
177    }
178
179    /// The frame of culled `key` and its subtree's, as
180    /// [`Core::emit_frames_in`] gives made views theirs, with no mount
181    /// items: what `onLayout`, `measure()` and [`Core::sync_culled`] read.
182    pub(super) fn cull_frames_in(&mut self, key: Key, hidden: bool, origin: Origin) {
183        let node = &mut self.nodes[key as usize];
184        node.culled = true;
185        let Some(layout) = node.layout else { return };
186        let hidden = hidden || self.layout.displays_none(layout);
187        let unrounded = *self.layout.unrounded_layout(layout);
188        // Placed in a containing block further up, as `emit_frames_in`
189        // places it.
190        let position = self.layout.style(layout).position;
191        let escaping = position == Position::Fixed
192            || (position == Position::Absolute
193                && !self
194                    .layout
195                    .parent(layout)
196                    .is_some_and(|p| self.layout.style(p).position.is_positioned()));
197        let containing = if escaping {
198            self.containing_origin(layout)
199        } else {
200            origin
201        };
202        let ratio = self.frame_ratio();
203        let frame = if hidden {
204            Bounds::default()
205        } else {
206            let l = rounded(&unrounded, containing, ratio);
207            let offset = origin.to(containing, ratio);
208            let mut frame = crate::geometry::rect(
209                l.location.x + offset.x,
210                l.location.y + offset.y,
211                l.size.width,
212                l.size.height,
213            );
214            // A scroll view's content size, sent with the frame when it is
215            // made (a list's view in its parent's viewport has none).
216            let node = &mut self.nodes[key as usize];
217            if node.kind == Kind::Scroll
218                && let Some(scroll) = node.scroll.as_mut()
219            {
220                scroll.culled_content = Some(scroll_extent(&l, scroll.horizontal));
221            }
222            if let Some(parent) = self.nodes.get(self.nodes[key as usize].parent as usize)
223                && parent.rtl
224                && parent.kind == Kind::Scroll
225                && let Some(scroll) = parent.scroll.as_deref()
226                && scroll.horizontal
227                && let Some(content) = scroll.content
228            {
229                frame.origin.x = content.width - frame.origin.x - frame.size.width;
230            }
231            frame
232        };
233        let node = &mut self.nodes[key as usize];
234        // Laid out again whenever it is made.
235        node.emitted = None;
236        if node.frame != frame {
237            node.frame = frame;
238            if node.events.contains(EventKind::Layout) {
239                self.events.push(crate::element::JsEvent::Event(
240                    node.id,
241                    EventKind::Layout,
242                    crate::ops::EventPayload::Layout(frame),
243                ));
244            }
245        }
246        self.layout.emitted(layout);
247        let node = &self.nodes[key as usize];
248        if !node.kind.is_container() || node.kind == Kind::List {
249            return;
250        }
251        let inner = Origin::of(
252            taffy::Point {
253                x: containing.at.x + unrounded.location.x,
254                y: containing.at.y + unrounded.location.y,
255            },
256            unrounded.size,
257            ratio,
258        );
259        let children = std::mem::take(&mut self.nodes[key as usize].children);
260        for &child in &children {
261            let c = &self.nodes[child as usize];
262            if !c.is_layout_root() && !c.created {
263                self.cull_frames_in(child, hidden, inner);
264            }
265        }
266        self.nodes[key as usize].children = children;
267    }
268
269    /// Scroll view `key` scrolled or was laid out again: what it culls is
270    /// looked at again in this commit.
271    pub(super) fn cull_moved(&mut self, key: Key) {
272        if self.nodes[key as usize]
273            .scroll
274            .as_ref()
275            .is_some_and(|s| s.culls)
276        {
277            self.cull_dirty = true;
278        }
279    }
280
281    /// Whether scroll views mount their content as it comes near
282    /// (`cull.rs`, the default), or all of it as it is made: what a test
283    /// driver reads (`nsh test`'s steps reach every view of a page, as
284    /// they always did). Turned off, what is culled is made in the next
285    /// commit.
286    pub fn set_content_culling(&mut self, enabled: bool) {
287        if self.culls_content == enabled {
288            return;
289        }
290        self.culls_content = enabled;
291        // Off: what is culled is made. On again: what went far away while
292        // it was off is given up (the scroll views stay in `culling`).
293        if !self.culling.is_empty() {
294            self.cull_dirty = true;
295        }
296    }
297
298    /// Makes the culled views that came within the window of the scroll
299    /// views around them; whether it made any (their styles, texts and
300    /// images then go out in another round of the commit).
301    pub(super) fn sync_culled(&mut self) -> bool {
302        self.cull_dirty = false;
303        let mut made = false;
304        let mut i = 0;
305        while i < self.culling.len() {
306            let scope = self.culling[i];
307            let (made_here, left) = self.sync_culled_in(scope);
308            made |= made_here;
309            if left {
310                i += 1;
311            } else {
312                // Gone, or everything in it made with culling off.
313                if let Some(scroll) = self
314                    .nodes
315                    .get_mut(scope as usize)
316                    .and_then(|n| n.scroll.as_mut())
317                {
318                    scroll.culls = false;
319                }
320                self.culling.swap_remove(i);
321            }
322        }
323        made
324    }
325
326    /// [`Core::sync_culled`] in scroll view `scope`: whether it made views,
327    /// and whether it is still to be looked at (some of its content is
328    /// culled, or may be given up as it scrolls).
329    fn sync_culled_in(&mut self, scope: Key) -> (bool, bool) {
330        let Some(node) = self.nodes.get(scope as usize) else {
331            return (false, false);
332        };
333        let Some(scroll) = node.scroll.as_deref() else {
334            return (false, false);
335        };
336        // Gone (its slot may hold another node now).
337        if node.kind != Kind::Scroll || !scroll.culls {
338            return (false, false);
339        }
340        // Not made or not placed yet: looked at once it is.
341        if !node.created || node.frame.origin.x.0.is_nan() || !self.in_tree(scope) {
342            return (false, true);
343        }
344        let (w, h) = (node.frame.size.width.0, node.frame.size.height.0);
345        let (x, y) = scroll.offset;
346        // Each reaches ahead of a scroll as far as its next frames take it.
347        let ahead = scroll.lead(w, h, LEAD_STEPS);
348        let window = ahead.widen((
349            x - w * OVERSCAN,
350            y - h * OVERSCAN,
351            x + w * (1.0 + OVERSCAN),
352            y + h * (1.0 + OVERSCAN),
353        ));
354        let far = ahead.widen((
355            x - w * RECLAIM,
356            y - h * RECLAIM,
357            x + w * (1.0 + RECLAIM),
358            y + h * (1.0 + RECLAIM),
359        ));
360        let sight = scroll.lead(w, h, SIGHT_STEPS).widen((x, y, x + w, y + h));
361        let holders = self.view_holders();
362        let mut made = false;
363        let mut stack = std::mem::take(&mut self.cull_scratch);
364        stack.clear();
365        stack.push((scope, 0.0f32, 0.0f32, 0.0f32, 0.0f32));
366        // `ex`, `ey`: how far the transforms between the scroll view and
367        // `parent` may move what it holds; each child's rectangle is
368        // widened by them and its own (`Core::reach_of`).
369        while let Some((parent, px, py, ex, ey)) = stack.pop() {
370            let mut i = 0;
371            while let Some(&child) = self.nodes[parent as usize].children.get(i) {
372                i += 1;
373                let c = &self.nodes[child as usize];
374                if c.layout.is_none() || c.is_layout_root() {
375                    continue;
376                }
377                let f = c.frame;
378                let (cx, cy) = (px + f.origin.x.0, py + f.origin.y.0);
379                let (cw, ch) = (f.size.width.0, f.size.height.0);
380                // Where its transforms may take it: without a bound, it
381                // shows wherever it is.
382                let (ox, oy) = self
383                    .reach_of(child)
384                    .unwrap_or((f32::INFINITY, f32::INFINITY));
385                let (rx, ry) = (ex + ox, ey + oy);
386                // Its rectangle widened by them (left, top, right, bottom).
387                let r = (cx - rx, cy - ry, cx + cw + rx, cy + ch + ry);
388                let meets =
389                    |w: (f32, f32, f32, f32)| r.0 < w.2 && r.1 < w.3 && r.2 > w.0 && r.3 > w.1;
390                let c = &self.nodes[child as usize];
391                if c.created {
392                    // Far away, holding nothing a view keeps: given up.
393                    let away = cw > 0.0 && ch > 0.0 && !meets(far);
394                    if away && self.culls_content && self.reclaimable(child, &holders) {
395                        self.reclaim(child);
396                        continue;
397                    }
398                    let c = &self.nodes[child as usize];
399                    if c.kind.is_container() && c.kind != Kind::Scroll && c.list.is_none() {
400                        stack.push((child, cx, cy, rx, ry));
401                    }
402                    continue;
403                }
404                if !c.culled {
405                    continue;
406                }
407                // Not placed yet (NaN), empty (what it holds may overflow
408                // it), or within the window.
409                let near = meets(window);
410                let shows = !self.culls_content
411                    || f.origin.x.0.is_nan()
412                    || cw <= 0.0
413                    || ch <= 0.0
414                    || near
415                    || self.never_culled(child);
416                if !shows {
417                    continue;
418                }
419                if self.nodes[child as usize].placeholder {
420                    self.ask_row(child);
421                    continue;
422                }
423                // In the overscan, not in sight (nor where the scroll goes
424                // next): within the turn's budget (`pace.rs`).
425                let seen = meets(sight);
426                if self.culls_content
427                    && !seen
428                    && !f.origin.x.0.is_nan()
429                    && cw > 0.0
430                    && ch > 0.0
431                    && !self.never_culled(child)
432                    && !self.pace_overscan()
433                {
434                    continue;
435                }
436                self.make_culled(parent, child);
437                made = true;
438                if self.nodes[child as usize].kind.is_container() {
439                    stack.push((child, cx, cy, rx, ry));
440                }
441            }
442        }
443        self.cull_scratch = stack;
444        // Still to be looked at as it scrolls, though all its content is
445        // made: what is far away is given up (with culling off too, so that
446        // turned on again it gives up what went far away meanwhile).
447        (made, true)
448    }
449
450    /// Makes culled `child`'s native view in made `parent`'s, at its place
451    /// among its siblings, with the frame the core has for it.
452    pub(super) fn make_culled(&mut self, parent: Key, child: Key) {
453        self.ensure_created(child);
454        let before = self.native_before(parent, child);
455        self.mount.push(MountItem::Insert {
456            parent: self.nodes[parent as usize].id,
457            child: self.nodes[child as usize].id,
458            before,
459        });
460        self.cull_made = true;
461    }
462
463    /// Makes culled `key` and the culled views around it (a command for it
464    /// needs its native view); whether it is made now.
465    pub(super) fn uncull(&mut self, key: Key) -> bool {
466        let mut chain = Vec::new();
467        let mut k = key;
468        while k != NO_KEY && !self.nodes[k as usize].created {
469            if !self.nodes[k as usize].culled {
470                return false;
471            }
472            chain.push(k);
473            k = self.nodes[k as usize].parent;
474        }
475        if k == NO_KEY {
476            return false;
477        }
478        for &node in chain.iter().rev() {
479            let parent = self.nodes[node as usize].parent;
480            self.make_culled(parent, node);
481        }
482        self.nodes[key as usize].created
483    }
484
485    /// Makes any culled descendants of made `root` that no longer sit under
486    /// an outer scroll view's culling scope (for example, a view promoted to
487    /// `position: fixed`, which becomes a layout root that the outer scroll
488    /// view's `sync_culled_in` skips). Stops at nested scroll views, lists,
489    /// overlays, and layout roots, which manage their own subtrees.
490    pub(super) fn uncull_subtree(&mut self, root: Key) {
491        let node = &self.nodes[root as usize];
492        if !node.created
493            || !node.kind.is_container()
494            || node.kind == Kind::Scroll
495            || node.list.is_some()
496        {
497            return;
498        }
499        let mut stack = vec![root];
500        while let Some(parent) = stack.pop() {
501            let mut i = 0;
502            while let Some(&child) = self.nodes[parent as usize].children.get(i) {
503                i += 1;
504                let c = &self.nodes[child as usize];
505                if c.layout.is_none() || c.is_layout_root() || c.is_overlay() {
506                    continue;
507                }
508                if c.created {
509                    if c.kind.is_container() && c.kind != Kind::Scroll && c.list.is_none() {
510                        stack.push(child);
511                    }
512                    continue;
513                }
514                if c.culled {
515                    if c.placeholder {
516                        self.ask_row(child);
517                    } else {
518                        self.make_culled(parent, child);
519                    }
520                }
521            }
522        }
523    }
524
525    /// Text block `key` gets its view: what it was laid out with while
526    /// culled, an estimate, gives way to its measured size in the next
527    /// layout, which keeps what the scroll views show where it is
528    /// (`resize_anchor.rs`), as text that waited through a resize does.
529    pub(super) fn measure_for_real(&mut self, key: Key) {
530        let Some(layout) = self.nodes[key as usize].layout else {
531            return;
532        };
533        let Some(super::LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
534            return;
535        };
536        cx.deferred = false;
537        if std::mem::take(&mut cx.estimated) {
538            cx.cache = None;
539            cx.baseline = None;
540            cx.min_content = None;
541            self.layout.mark_dirty(layout);
542            self.needs_layout = true;
543            self.resize_settling = true;
544        }
545    }
546
547    /// The nodes whose views must outlive scrolling away: the focus, the
548    /// hosts of open overlays and the ends of a text selection.
549    fn view_holders(&self) -> Vec<Key> {
550        let mut holders: Vec<Key> = self
551            .selection_kept
552            .iter()
553            .filter_map(|&id| self.key(id).ok())
554            .collect();
555        if let Some((key, _)) = self.focus {
556            holders.push(key);
557        }
558        // A reveal is resolved after layout; its target must survive the
559        // culling pass until that command has its text attachment's position.
560        holders.extend(self.commands.iter().filter_map(|(id, command)| {
561            matches!(command, crate::Command::Reveal(_))
562                .then(|| self.key(*id).ok())
563                .flatten()
564        }));
565        holders.extend(
566            self.overlays
567                .iter()
568                .filter_map(|&o| self.overlay(o).and_then(|o| o.host))
569                .filter_map(|id| self.key(id).ok()),
570        );
571        holders
572    }
573
574    /// Whether made `key`'s views may go, to be made again as it comes
575    /// back: nothing in it keeps state in its native view (a field, a
576    /// player, a page, a scroll position, a component), holds the focus,
577    /// an overlay or a selection, is pressed or hovered, or may show
578    /// away from its frame; and it is small enough to tell.
579    fn reclaimable(&self, key: Key, holders: &[Key]) -> bool {
580        use crate::tailwind::state;
581        let live = state::PRESSED | state::HOVERED | state::FOCUSED | state::FOCUS_WITHIN;
582        let mut stack = vec![key];
583        let mut seen = 0;
584        while let Some(k) = stack.pop() {
585            seen += 1;
586            if seen > RECLAIM_MAX_NODES {
587                return false;
588            }
589            let node = &self.nodes[k as usize];
590            let keeps = matches!(
591                node.kind,
592                Kind::Input
593                    | Kind::WebView
594                    | Kind::Video
595                    | Kind::Native
596                    | Kind::Canvas
597                    | Kind::Shader
598                    | Kind::GpuView
599                    | Kind::Scroll
600                    | Kind::List
601                    | Kind::Stack
602            ) || node.kind.is_root()
603                || node.component.is_some()
604                // Its animation bindings go with its view.
605                || !node.animated.is_empty()
606                || node.states & live != 0
607                || node.layout.is_some() && self.never_culled(k)
608                || holders.contains(&k);
609            if keeps {
610                return false;
611            }
612            stack.extend(node.children.iter().copied());
613        }
614        true
615    }
616
617    /// Gives up the views of made `key`'s subtree: it is culled again, its
618    /// layout and measurements kept, and made again as it comes near.
619    fn reclaim(&mut self, key: Key) {
620        let id = self.nodes[key as usize].id;
621        self.mount.push(MountItem::Remove { id });
622        // Children first, each from the view it is in.
623        let mut order = Vec::new();
624        let mut stack = vec![key];
625        while let Some(k) = stack.pop() {
626            let node = &self.nodes[k as usize];
627            if !node.created {
628                continue;
629            }
630            order.push(k);
631            stack.extend(node.children.iter().copied());
632        }
633        for &k in order.iter().rev() {
634            let node = &mut self.nodes[k as usize];
635            node.created = false;
636            node.culled = true;
637            node.emitted = None;
638            node.overflow = None;
639            let (id, layout, text) = (node.id, node.layout, node.kind == Kind::Text);
640            self.mount.push(MountItem::Delete { id });
641            if text
642                && let Some(layout) = layout
643                && let Some(super::LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
644            {
645                // Its next view gets its text again.
646                cx.laid_out = None;
647            }
648        }
649        self.tree_order_changed |= self.track_tree_order;
650        self.tab_places_stale = true;
651    }
652
653    /// View `key` is the placeholder of an `<Each>` row
654    /// ([`crate::Op::Placeholder`]).
655    pub(super) fn placeholder(&mut self, key: Key) {
656        let node = &mut self.nodes[key as usize];
657        if node.placeholder || node.kind != Kind::View {
658            return;
659        }
660        node.placeholder = true;
661        self.placeholders.push((key, node.id));
662        if let Some(layout) = node.layout {
663            let mut style = self.layout.style(layout).clone();
664            style.size.height = taffy::Dimension::length(PLACEHOLDER_HEIGHT);
665            self.layout.set_style(layout, style);
666        }
667    }
668
669    /// Asks JS to render the row of placeholder `key` (once).
670    pub(super) fn ask_row(&mut self, key: Key) {
671        let node = &mut self.nodes[key as usize];
672        if !node.row_asked {
673            node.row_asked = true;
674            self.asked_rows.push(node.id);
675        }
676    }
677
678    /// Sizes each placeholder as the rows rendered beside it are on
679    /// average (as lists estimate rows not measured); whether any changed
680    /// (then laid out again).
681    pub(super) fn size_placeholders(&mut self) -> bool {
682        let mut sizes: Vec<(Key, Option<(f32, f32)>)> = Vec::new();
683        let mut changed = false;
684        let mut i = 0;
685        while i < self.placeholders.len() {
686            let (key, id) = self.placeholders[i];
687            // Released (its key may be another node's now).
688            if !self
689                .nodes
690                .get(key as usize)
691                .is_some_and(|n| n.id == id && n.placeholder)
692            {
693                self.placeholders.swap_remove(i);
694                continue;
695            }
696            i += 1;
697            let node = &self.nodes[key as usize];
698            let (parent, layout) = (node.parent, node.layout);
699            // Its row replaces it soon.
700            let Some(layout) = layout.filter(|_| parent != NO_KEY && !node.row_asked) else {
701                continue;
702            };
703            let size = match sizes.iter().find(|(p, _)| *p == parent) {
704                Some(&(_, size)) => size,
705                None => {
706                    let size = self.rendered_size(parent);
707                    sizes.push((parent, size));
708                    size
709                }
710            };
711            let Some((width, height)) = size else {
712                continue;
713            };
714            let style = self.layout.style(layout);
715            if near(style.size.width, width) && near(style.size.height, height) {
716                continue;
717            }
718            let mut style = style.clone();
719            style.size = taffy::Size {
720                width: taffy::Dimension::length(width),
721                height: taffy::Dimension::length(height),
722            };
723            self.layout.set_style(layout, style);
724            changed = true;
725        }
726        if changed {
727            self.needs_layout = true;
728            self.placeholders_resized = true;
729            // What the scroll views show stays where it is.
730            self.resize_settling = true;
731        }
732        changed
733    }
734
735    /// The average size of the children of `parent` in its flow that are
736    /// not placeholders, when it has any.
737    fn rendered_size(&self, parent: Key) -> Option<(f32, f32)> {
738        let (mut width, mut height, mut count) = (0.0f32, 0.0f32, 0u32);
739        for &child in &self.nodes[parent as usize].children {
740            let node = &self.nodes[child as usize];
741            let Some(layout) = node.layout else { continue };
742            if node.placeholder
743                || node.is_layout_root()
744                || node.is_overlay()
745                || self.layout.displays_none(layout)
746                || self.layout.style(layout).position == Position::Absolute
747            {
748                continue;
749            }
750            let size = self.layout.unrounded_layout(layout).size;
751            width += size.width;
752            height += size.height;
753            count += 1;
754        }
755        (count > 0).then(|| {
756            (
757                (width / count as f32).round(),
758                (height / count as f32).round(),
759            )
760        })
761    }
762}
763
764/// Whether `dimension` is a length within 5% (and a point) of `value`: a
765/// placeholder close to its estimate keeps its size.
766fn near(dimension: taffy::Dimension, value: f32) -> bool {
767    let raw = dimension.into_raw();
768    raw.tag() == taffy::CompactLength::LENGTH_TAG
769        && (raw.value() - value).abs() < (value * 0.05).max(1.0)
770}
771
772/// How far a scrolling view reaches ahead the way it moves, in points
773/// along x and y (`ScrollState::lead`).
774#[derive(Debug, Clone, Copy, Default)]
775pub(super) struct Lead(f32, f32);
776
777impl Lead {
778    /// Rectangle `r` (left, top, right, bottom) reaching as far ahead.
779    pub(super) fn widen(self, r: (f32, f32, f32, f32)) -> (f32, f32, f32, f32) {
780        (
781            r.0 + self.0.min(0.0),
782            r.1 + self.1.min(0.0),
783            r.2 + self.0.max(0.0),
784            r.3 + self.1.max(0.0),
785        )
786    }
787}
788
789impl super::ScrollState {
790    /// How far ahead of its viewport (`w` by `h`) `steps` of the user's
791    /// last step reach, at most [`LEAD_MAX`] viewports; none after a
792    /// longer step (a jump).
793    pub(super) fn lead(&self, w: f32, h: f32, steps: f32) -> Lead {
794        let along = |step: f32, size: f32| match step.abs() <= size * LEAD_MAX {
795            true => (step * steps).clamp(-size * LEAD_MAX, size * LEAD_MAX),
796            false => 0.0,
797        };
798        Lead(along(self.step.0, w), along(self.step.1, h))
799    }
800}