Skip to main content

pax_std/core/
scroller.rs

1use crate::common::{native_surface_opacity, patch_if_needed};
2use kurbo::{Affine, BezPath, RoundedRect, Shape};
3use pax_engine::api::{LocalProperty, PropertyBinding};
4use pax_engine::api::{Property, Size};
5use pax_engine::*;
6use pax_message::{AnyCreatePatch, NativeInterrupt, ScrollerPatch};
7use pax_runtime::api::{borrow, borrow_mut, use_RefCell, Layer, NodeContext};
8use pax_runtime::{
9    bind_content_measurement_effect, measure_content_children_forward_extents, BaseInstance,
10    ContentMeasurementGeometry, ExpandedNode, ExpandedNodeIdentifier, InstanceFlags, InstanceNode,
11    InstantiationArgs, RuntimeContext, ScrollerSurfaceState, ScrollerSurfaceStateChange,
12};
13use std::iter;
14use std::rc::Rc;
15
16use_RefCell!();
17
18/// A scrolling container, which clips its bounds and offers platform-native scrolling
19/// on either or both of the horizontal and vertical axes.
20#[pax]
21#[engine_import_path("pax_engine")]
22#[inlined(
23    <ScrollerHost
24        scroll_pos_x=bind:scroll_pos_x
25        scroll_pos_y=bind:scroll_pos_y
26        scroll_width={self._resolved_scroll_width}
27        scroll_height={self._resolved_scroll_height}
28        corner_radius={self.corner_radius}
29        snap_positions_x={self.snap_positions_x}
30        snap_positions_y={self.snap_positions_y}
31        _clip_content={!$suspended}
32    >
33        for i in 0..self._projected_children_count {
34            slot(i)
35        }
36    </ScrollerHost>
37
38    @settings {
39        @mount: on_mount
40    }
41
42)]
43#[custom(Default)]
44pub struct Scroller {
45    /// Horizontal scroll offset, in pixels.
46    pub scroll_pos_x: Property<f64>,
47    /// Vertical scroll offset, in pixels.
48    pub scroll_pos_y: Property<f64>,
49    /// Width of the scrollable content pane.
50    pub scroll_width: Property<Size>,
51    /// Height of the scrollable content pane.
52    pub scroll_height: Property<Size>,
53    /// Automatically sizes the scroll pane on its default axes when possible.
54    ///
55    /// For `Scroller`, the default autosized axis is `y`; `x` remains bound to
56    /// `scroll_width` unless `autosize_x` explicitly opts in.
57    pub autosize: Property<bool>,
58    /// Optional override for whether autosize manages the `x` axis.
59    pub autosize_x: Property<Option<bool>>,
60    /// Optional override for whether autosize manages the `y` axis.
61    pub autosize_y: Property<Option<bool>>,
62    /// Corner radius for the scroller clipping region, in pixels.
63    pub corner_radius: Property<f64>,
64    /// Scroll snap anchors expressed in px/% along each axis.
65    /// Web maps to CSS scroll-snap-type + scroll-snap-align; Apple chassis map these
66    /// offsets to native scroll end-points while keeping engine scroll state authoritative.
67    pub snap_positions_x: Property<Vec<Size>>,
68    /// Vertical scroll snap anchors expressed in px/%.
69    pub snap_positions_y: Property<Vec<Size>>,
70
71    // Controls whether the scroller clips content to its own bounds.
72    // Used by pax create; might become public once the API is settled.
73    pub _clip_content: Property<bool>,
74
75    // Private template bookkeeping.
76    pub _projected_children_count: Property<usize>,
77    // Host-facing resolved content width after applying autosize semantics.
78    pub _resolved_scroll_width: Property<Size>,
79    // Host-facing resolved content height after applying autosize semantics.
80    pub _resolved_scroll_height: Property<Size>,
81}
82
83impl Default for Scroller {
84    fn default() -> Self {
85        Self {
86            scroll_pos_x: Default::default(),
87            scroll_pos_y: Default::default(),
88            scroll_width: Default::default(),
89            scroll_height: Default::default(),
90            autosize: Property::new(false),
91            autosize_x: Property::new(None),
92            autosize_y: Property::new(None),
93            corner_radius: Property::new(0.0),
94            snap_positions_x: Default::default(),
95            snap_positions_y: Default::default(),
96            _clip_content: Property::new(true),
97            _projected_children_count: Default::default(),
98            _resolved_scroll_width: Default::default(),
99            _resolved_scroll_height: Default::default(),
100        }
101    }
102}
103
104#[pax]
105#[engine_import_path("pax_engine")]
106#[primitive("pax_std::core::scroller::ScrollerHostInstance")]
107#[custom(Default)]
108// Internal native-host component used by `Scroller`.
109pub struct ScrollerHost {
110    // Bound horizontal scroll offset mirrored to/from the platform-native host.
111    pub scroll_pos_x: Property<f64>,
112    // Bound vertical scroll offset mirrored to/from the platform-native host.
113    pub scroll_pos_y: Property<f64>,
114    // Native inner pane width.
115    pub scroll_width: Property<Size>,
116    // Native inner pane height.
117    pub scroll_height: Property<Size>,
118    // Native clipping corner radius.
119    pub corner_radius: Property<f64>,
120    // Horizontal native snap anchors.
121    pub snap_positions_x: Property<Vec<Size>>,
122    // Vertical native snap anchors.
123    pub snap_positions_y: Property<Vec<Size>>,
124    // Scroll offset actually presented by the native host, including tile-window offsets.
125    pub _presentation_scroll_x: Property<f64>,
126    // Scroll offset actually presented by the native host, including tile-window offsets.
127    pub _presentation_scroll_y: Property<f64>,
128    // Controls native host clipping.
129    pub _clip_content: Property<bool>,
130}
131
132impl Default for ScrollerHost {
133    fn default() -> Self {
134        Self {
135            scroll_pos_x: Default::default(),
136            scroll_pos_y: Default::default(),
137            scroll_width: Default::default(),
138            scroll_height: Default::default(),
139            corner_radius: Property::new(0.0),
140            snap_positions_x: Default::default(),
141            snap_positions_y: Default::default(),
142            _presentation_scroll_x: Default::default(),
143            _presentation_scroll_y: Default::default(),
144            _clip_content: Property::new(true),
145        }
146    }
147}
148
149// Runtime instance backing `<ScrollerHost>`.
150pub struct ScrollerHostInstance {
151    base: BaseInstance,
152}
153
154fn mark_canvas_descendants_dirty(expanded_node: &ExpandedNode, context: &Rc<RuntimeContext>) {
155    for child in expanded_node.children.get().iter() {
156        if borrow!(child.instance_node).base().flags().layer == Layer::Canvas {
157            context.mark_canvas_node_dirty(child.id);
158            context.set_canvas_dirty(child.occlusion.get().render_layer_id);
159        }
160        mark_canvas_descendants_dirty(child, context);
161    }
162}
163
164fn resolve_scroller_island_layer(expanded_node: &ExpandedNode) -> Option<usize> {
165    if let Some(layer_id) = expanded_node.browser_content_layer_id.get() {
166        return Some(layer_id as usize);
167    }
168
169    let own_layer = expanded_node.occlusion.get().render_layer_id;
170    fn find_descendant_layer(node: &ExpandedNode, own_layer: usize) -> Option<usize> {
171        let mut resolved: Option<usize> = None;
172        for child in node.children.get().iter() {
173            let child_layer = child.occlusion.get().render_layer_id;
174            if child_layer != own_layer {
175                resolved = Some(match resolved {
176                    Some(current) => current.min(child_layer),
177                    None => child_layer,
178                });
179            }
180            if let Some(descendant_layer) = find_descendant_layer(child, own_layer) {
181                resolved = Some(match resolved {
182                    Some(current) => current.min(descendant_layer),
183                    None => descendant_layer,
184                });
185            }
186        }
187        resolved
188    }
189
190    find_descendant_layer(expanded_node, own_layer)
191}
192
193fn scroller_clip_path(
194    expanded_node: &ExpandedNode,
195    clip_content: bool,
196    corner_radius: f64,
197) -> Option<BezPath> {
198    if !clip_content {
199        return None;
200    }
201
202    let t_and_b = expanded_node.transform_and_bounds.get();
203    let transform = t_and_b.transform;
204    let (width, height) = t_and_b.bounds;
205    let max_radius = 0.5 * width.max(0.0).min(height.max(0.0));
206    let radius = corner_radius.clamp(0.0, max_radius);
207
208    let bez_path = if radius > f64::EPSILON {
209        RoundedRect::new(0.0, 0.0, width, height, radius).to_path(0.1)
210    } else {
211        let mut bez_path = BezPath::new();
212        bez_path.move_to((0.0, 0.0));
213        bez_path.line_to((width, 0.0));
214        bez_path.line_to((width, height));
215        bez_path.line_to((0.0, height));
216        bez_path.line_to((0.0, 0.0));
217        bez_path.close_path();
218        bez_path
219    };
220
221    Some(<Affine>::from(transform) * bez_path)
222}
223
224fn clamp_offset(value: f64, content: f64, viewport: f64) -> f64 {
225    if content <= viewport {
226        return 0.0;
227    }
228    if !value.is_finite() {
229        return 0.0;
230    }
231    value.max(0.0).min((content - viewport).max(0.0))
232}
233
234fn root_scroller_delegates_to_page_scroll(
235    expanded_node: &ExpandedNode,
236    context: &RuntimeContext,
237) -> bool {
238    context.get_root_scroller_id() == Some(expanded_node.id.to_u32())
239        && context.get_visual_viewport_state().is_some()
240}
241
242fn effective_presentation_scroll(
243    expanded_node: &ExpandedNode,
244    context: &RuntimeContext,
245) -> (f64, f64) {
246    let (scroll_x, scroll_y) = context
247        .get_scroller_surface_scroll(expanded_node.id.to_u32())
248        .unwrap_or_else(|| {
249            expanded_node.with_properties_unwrapped(|scroller: &mut ScrollerHost| {
250                (
251                    scroller._presentation_scroll_x.local().get(),
252                    scroller._presentation_scroll_y.local().get(),
253                )
254            })
255        });
256    if context.get_root_scroller_id() == Some(expanded_node.id.to_u32()) {
257        if let Some(visual) = context.get_visual_viewport_state() {
258            let visual_x = visual.page_scroll_x + visual.offset_x;
259            let visual_y = visual.page_scroll_y + visual.offset_y;
260            if visual_x.is_finite() && visual_y.is_finite() {
261                let computed_tab = expanded_node.transform_and_bounds.get();
262                let (fallback_viewport_width, fallback_viewport_height) = computed_tab.bounds;
263                let viewport_width = if visual.width.is_finite() {
264                    visual.width
265                } else {
266                    fallback_viewport_width
267                };
268                let viewport_height = if visual.height.is_finite() {
269                    visual.height
270                } else {
271                    fallback_viewport_height
272                };
273                let (content_width, content_height) =
274                    expanded_node.with_properties_unwrapped(|scroller: &mut ScrollerHost| {
275                        (
276                            scroller
277                                .scroll_width
278                                .local()
279                                .get()
280                                .get_pixels(fallback_viewport_width),
281                            scroller
282                                .scroll_height
283                                .local()
284                                .get()
285                                .get_pixels(fallback_viewport_height),
286                        )
287                    });
288                return (
289                    clamp_offset(visual_x, content_width, viewport_width),
290                    clamp_offset(visual_y, content_height, viewport_height),
291                );
292            }
293        }
294    }
295    (scroll_x, scroll_y)
296}
297
298impl InstanceNode for ScrollerHostInstance {
299    fn instantiate(args: InstantiationArgs) -> Rc<Self>
300    where
301        Self: Sized,
302    {
303        Rc::new(Self {
304            base: BaseInstance::new(
305                args,
306                InstanceFlags {
307                    invisible_to_slot: false,
308                    invisible_to_raycasting: true,
309                    layer: Layer::Native,
310                    is_component: false,
311                    is_slot: false,
312                },
313            ),
314        })
315    }
316
317    fn handle_mount(
318        self: Rc<Self>,
319        expanded_node: &Rc<ExpandedNode>,
320        context: &Rc<RuntimeContext>,
321    ) {
322        let id = expanded_node.id.to_u32();
323        if expanded_node.parent_frame.get().is_none() {
324            context.set_root_scroller_id(Some(id));
325        }
326        context.enqueue_native_message(pax_message::NativeMessage::ScrollerCreate(
327            AnyCreatePatch {
328                id,
329                parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
330                render_layer_id: 0,
331            },
332        ));
333
334        let env = Rc::clone(&expanded_node.stack);
335        let children = borrow!(self.base().get_instance_children());
336        let children_with_envs = children.iter().cloned().zip(iter::repeat(env));
337        let child_parent_frame: LocalProperty<Option<ExpandedNodeIdentifier>> =
338            LocalProperty::new(Some(expanded_node.id));
339        let new_children =
340            expanded_node.generate_children(children_with_envs, context, &child_parent_frame, true);
341        expanded_node.children.set(new_children);
342
343        let weak_self_ref = Rc::downgrade(&expanded_node);
344        let context = Rc::clone(context);
345        let last_patch = Rc::new(RefCell::new(ScrollerPatch {
346            id,
347            ..Default::default()
348        }));
349        let last_presentation_scroll = Rc::new(RefCell::new((0.0, 0.0)));
350
351        let deps: Vec<_> = borrow!(expanded_node.properties_scope)
352            .values()
353            .cloned()
354            .map(|v| v.get_untyped_property().clone())
355            .chain([
356                expanded_node.transform_and_bounds.untyped(),
357                expanded_node.computed_opacity.untyped(),
358                expanded_node.occlusion.untyped(),
359            ])
360            .collect();
361        expanded_node
362            .changed_listener
363            .replace_with(LocalProperty::computed(
364                move || {
365                    let Some(expanded_node) = weak_self_ref.upgrade() else {
366                        return;
367                    };
368                    let mut old_state = borrow_mut!(last_patch);
369                    let mut previous_presentation_scroll = borrow_mut!(last_presentation_scroll);
370                    let mut patch = ScrollerPatch {
371                        id,
372                        ..Default::default()
373                    };
374
375                    expanded_node.with_properties_unwrapped(|properties: &mut ScrollerHost| {
376                        let computed_tab = expanded_node.transform_and_bounds.get();
377                        let (width, height) = computed_tab.bounds;
378                        let corner_radius = properties.corner_radius.local().get();
379                        let max_radius = 0.5 * width.max(0.0).min(height.max(0.0));
380                        let clamped_radius = corner_radius.clamp(0.0, max_radius);
381                        let scroll_width = properties.scroll_width.local().get().get_pixels(width);
382                        let scroll_height =
383                            properties.scroll_height.local().get().get_pixels(height);
384                        let snap_points_x: Vec<f64> = properties
385                            .snap_positions_x
386                            .local()
387                            .get()
388                            .iter()
389                            .map(|pos| pos.get_pixels(width))
390                            .collect();
391                        let snap_points_y: Vec<f64> = properties
392                            .snap_positions_y
393                            .local()
394                            .get()
395                            .iter()
396                            .map(|pos| pos.get_pixels(height))
397                            .collect();
398                        let scroll_enabled_x = scroll_width > width + 0.5;
399                        let scroll_enabled_y = scroll_height > height + 0.5;
400                        let logical_scroll = (
401                            properties.scroll_pos_x.local().get(),
402                            properties.scroll_pos_y.local().get(),
403                        );
404                        // A property write is a new scroll request, not a replay of the last
405                        // native observation. Move presentation by the same delta, preserving
406                        // any host-relative offset. Before the first observation, start at the
407                        // authored position so native hosts and tile plans agree on the viewport.
408                        let presentation_scroll = context
409                            .get_scroller_surface_state(id)
410                            .map(|previous| {
411                                let advance = |requested: f64, logical: f64, presented: f64| {
412                                    if presented.is_finite() {
413                                        presented + (requested - logical)
414                                    } else {
415                                        requested
416                                    }
417                                };
418                                (
419                                    advance(
420                                        logical_scroll.0,
421                                        previous.scroll_x,
422                                        previous.presentation_scroll_x,
423                                    ),
424                                    advance(
425                                        logical_scroll.1,
426                                        previous.scroll_y,
427                                        previous.presentation_scroll_y,
428                                    ),
429                                )
430                            })
431                            .unwrap_or(logical_scroll);
432                        properties
433                            ._presentation_scroll_x
434                            .local()
435                            .set_if_neq(presentation_scroll.0);
436                        properties
437                            ._presentation_scroll_y
438                            .local()
439                            .set_if_neq(presentation_scroll.1);
440                        let presentation_changed =
441                            (presentation_scroll.0 - previous_presentation_scroll.0).abs() > 1e-4
442                                || (presentation_scroll.1 - previous_presentation_scroll.1).abs()
443                                    > 1e-4;
444                        *previous_presentation_scroll = presentation_scroll;
445                        let scroller_island_layer = resolve_scroller_island_layer(&expanded_node);
446                        let has_scroller_island = scroller_island_layer.is_some();
447                        let surface_change = context.set_scroller_surface_state(
448                            id,
449                            ScrollerSurfaceState {
450                                viewport_width: width,
451                                viewport_height: height,
452                                content_width: scroll_width,
453                                content_height: scroll_height,
454                                scroll_x: properties.scroll_pos_x.local().get(),
455                                scroll_y: properties.scroll_pos_y.local().get(),
456                                presentation_scroll_x: presentation_scroll.0,
457                                presentation_scroll_y: presentation_scroll.1,
458                                clip_content: properties._clip_content.local().get(),
459                            },
460                        );
461                        if surface_change == ScrollerSurfaceStateChange::ScrollOnly
462                            && !has_scroller_island
463                        {
464                            context.mark_occlusion_dirty();
465                        }
466                        let updates = [
467                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
468                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
469                            patch_if_needed(
470                                &mut old_state.corner_radius,
471                                &mut patch.corner_radius,
472                                clamped_radius,
473                            ),
474                            patch_if_needed(
475                                &mut old_state.parent_frame,
476                                &mut patch.parent_frame,
477                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
478                            ),
479                            patch_if_needed(
480                                &mut old_state.z_index,
481                                &mut patch.z_index,
482                                expanded_node.occlusion.get().z_index,
483                            ),
484                            patch_if_needed(
485                                &mut old_state.size_inner_pane_x,
486                                &mut patch.size_inner_pane_x,
487                                scroll_width,
488                            ),
489                            patch_if_needed(
490                                &mut old_state.size_inner_pane_y,
491                                &mut patch.size_inner_pane_y,
492                                scroll_height,
493                            ),
494                            patch_if_needed(
495                                &mut old_state.snap_points_x,
496                                &mut patch.snap_points_x,
497                                snap_points_x,
498                            ),
499                            patch_if_needed(
500                                &mut old_state.snap_points_y,
501                                &mut patch.snap_points_y,
502                                snap_points_y,
503                            ),
504                            patch_if_needed(
505                                &mut old_state.scroll_x,
506                                &mut patch.scroll_x,
507                                properties.scroll_pos_x.local().get(),
508                            ),
509                            patch_if_needed(
510                                &mut old_state.scroll_y,
511                                &mut patch.scroll_y,
512                                properties.scroll_pos_y.local().get(),
513                            ),
514                            patch_if_needed(
515                                &mut old_state.presentation_scroll_x,
516                                &mut patch.presentation_scroll_x,
517                                presentation_scroll.0,
518                            ),
519                            patch_if_needed(
520                                &mut old_state.presentation_scroll_y,
521                                &mut patch.presentation_scroll_y,
522                                presentation_scroll.1,
523                            ),
524                            patch_if_needed(
525                                &mut old_state.scroll_enabled_x,
526                                &mut patch.scroll_enabled_x,
527                                scroll_enabled_x,
528                            ),
529                            patch_if_needed(
530                                &mut old_state.scroll_enabled_y,
531                                &mut patch.scroll_enabled_y,
532                                scroll_enabled_y,
533                            ),
534                            patch_if_needed(
535                                &mut old_state.transform,
536                                &mut patch.transform,
537                                computed_tab.transform.coeffs().to_vec(),
538                            ),
539                            patch_if_needed(
540                                &mut old_state.opacity,
541                                &mut patch.opacity,
542                                native_surface_opacity(&expanded_node, &context),
543                            ),
544                            patch_if_needed(
545                                &mut old_state.clip_content,
546                                &mut patch.clip_content,
547                                properties._clip_content.local().get(),
548                            ),
549                        ];
550                        let scroll_updated = patch.scroll_x.is_some()
551                            || patch.scroll_y.is_some()
552                            || patch.presentation_scroll_x.is_some()
553                            || patch.presentation_scroll_y.is_some();
554                        let visual_update = patch.size_x.is_some()
555                            || patch.size_y.is_some()
556                            || patch.size_inner_pane_x.is_some()
557                            || patch.size_inner_pane_y.is_some()
558                            || patch.scroll_enabled_x.is_some()
559                            || patch.scroll_enabled_y.is_some()
560                            || patch.transform.is_some()
561                            || patch.opacity.is_some()
562                            || patch.clip_content.is_some();
563                        if updates.into_iter().any(|updated| updated) {
564                            context.enqueue_native_message(
565                                pax_message::NativeMessage::ScrollerUpdate(patch),
566                            );
567                            if visual_update {
568                                // Browser-owned scroller islands now keep tiled canvases mounted in
569                                // content coordinates, so ordinary scroll motion is handled by the
570                                // browser moving the host. Reserve descendant canvas invalidation
571                                // for real visual/layout changes; tile-window shifts are handled by
572                                // the chassis surface-refresh path instead of rerendering every
573                                // canvas node on each scroll tick.
574                                mark_canvas_descendants_dirty(&expanded_node, &context);
575                            } else if scroll_updated && !has_scroller_island {
576                                // Root/non-island scrollers still render into a fixed surface; when
577                                // scroll changes, their vector content needs a redraw to stay aligned.
578                                mark_canvas_descendants_dirty(&expanded_node, &context);
579                            } else if scroll_updated {
580                                // Scroller islands keep geometry in content coordinates, but
581                                // inherited lights must be re-expressed through the current scroll
582                                // transform and uploaded to the retained surface.
583                                if let Some(layer) = scroller_island_layer {
584                                    context.set_canvas_dirty(layer);
585                                }
586                            }
587                        } else if presentation_changed && !scroll_updated {
588                            mark_canvas_descendants_dirty(&expanded_node, &context);
589                        }
590                    });
591                },
592                &deps,
593            ));
594    }
595
596    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
597        expanded_node
598            .changed_listener
599            .replace_with(LocalProperty::default());
600        if context.get_root_scroller_id() == Some(expanded_node.id.to_u32()) {
601            context.set_root_scroller_id(None);
602        }
603        context.remove_scroller_surface_state(expanded_node.id.to_u32());
604        context.enqueue_native_message(pax_message::NativeMessage::ScrollerDelete(
605            expanded_node.id.to_u32(),
606        ));
607    }
608
609    fn handle_native_interrupt(
610        &self,
611        expanded_node: &Rc<ExpandedNode>,
612        interrupt: &NativeInterrupt,
613    ) {
614        if let NativeInterrupt::ScrollerPosition(args) = interrupt {
615            expanded_node.with_properties_unwrapped(|props: &mut ScrollerHost| {
616                if (props.scroll_pos_x.local().get() - args.scroll_x).abs() > 1e-4 {
617                    props.scroll_pos_x.set(args.scroll_x);
618                }
619                if (props.scroll_pos_y.local().get() - args.scroll_y).abs() > 1e-4 {
620                    props.scroll_pos_y.set(args.scroll_y);
621                }
622            });
623        }
624    }
625
626    fn resolve_effect_clip_path(&self, expanded_node: &ExpandedNode) -> Option<BezPath> {
627        let (clip_content, corner_radius) =
628            expanded_node.with_properties_unwrapped(|scroller: &mut ScrollerHost| {
629                (
630                    scroller._clip_content.local().get(),
631                    scroller.corner_radius.local().get(),
632                )
633            });
634        scroller_clip_path(expanded_node, clip_content, corner_radius)
635    }
636
637    fn handle_pre_render(
638        &self,
639        expanded_node: &ExpandedNode,
640        rtc: &Rc<RuntimeContext>,
641        rcs: &mut dyn pax_runtime::api::RenderContext,
642    ) {
643        let layers = rcs.layers();
644        let has_dirty_layer = (0..layers).any(|layer| rtc.is_canvas_dirty(&layer));
645        if !has_dirty_layer {
646            return;
647        }
648
649        if resolve_scroller_island_layer(expanded_node).is_some()
650            || root_scroller_delegates_to_page_scroll(expanded_node, rtc)
651        {
652            return;
653        }
654
655        let clip_content =
656            expanded_node.with_properties_unwrapped(|scroller: &mut ScrollerHost| {
657                scroller._clip_content.local().get()
658            });
659        let (scroll_x, scroll_y) = effective_presentation_scroll(expanded_node, rtc);
660        let should_translate = scroll_x.abs() > f64::EPSILON || scroll_y.abs() > f64::EPSILON;
661        if !clip_content && !should_translate {
662            return;
663        }
664        let transformed_bez_path = clip_content
665            .then(|| self.resolve_effect_clip_path(expanded_node))
666            .flatten();
667
668        #[cfg(debug_assertions)]
669        let mut applied_layers = 0;
670
671        for layer in 0..layers {
672            if !rtc.is_canvas_dirty(&layer) {
673                continue;
674            }
675            // Scroller clip/translation is inherited by descendants. Bounds-aware culling belongs
676            // to leaf draw nodes so the transform stack remains balanced on every active renderer.
677            if !rcs.begin_node(
678                layer,
679                expanded_node.id.to_u32(),
680                expanded_node.occlusion.get().z_index,
681                0,
682            ) {
683                continue;
684            }
685            rcs.save(layer);
686            if let Some(transformed_bez_path) = transformed_bez_path.clone() {
687                rcs.clip(layer, transformed_bez_path);
688            }
689            if should_translate {
690                rcs.transform(layer, Affine::translate((-scroll_x, -scroll_y)));
691            }
692            let _ = rcs.end_node(layer, expanded_node.id.to_u32());
693            #[cfg(debug_assertions)]
694            {
695                applied_layers += 1;
696            }
697        }
698
699        #[cfg(debug_assertions)]
700        log::trace!(
701            "scroller layer pre_render: node={}, total_layers={}, applied_layers={}, clip={}, translate={}",
702            expanded_node.id.to_u32(),
703            layers,
704            applied_layers,
705            clip_content,
706            should_translate,
707        );
708    }
709
710    fn handle_post_render(
711        &self,
712        expanded_node: &ExpandedNode,
713        rtc: &Rc<RuntimeContext>,
714        rcs: &mut dyn pax_runtime::api::RenderContext,
715    ) {
716        if resolve_scroller_island_layer(expanded_node).is_some()
717            || root_scroller_delegates_to_page_scroll(expanded_node, rtc)
718        {
719            return;
720        }
721
722        let clip_content =
723            expanded_node.with_properties_unwrapped(|scroller: &mut ScrollerHost| {
724                scroller._clip_content.local().get()
725            });
726        let (scroll_x, scroll_y) = effective_presentation_scroll(expanded_node, rtc);
727        if !clip_content && scroll_x.abs() <= f64::EPSILON && scroll_y.abs() <= f64::EPSILON {
728            return;
729        }
730
731        let layers = rcs.layers();
732        let has_dirty_layer = (0..layers).any(|layer| rtc.is_canvas_dirty(&layer));
733        if !has_dirty_layer {
734            return;
735        }
736
737        #[cfg(debug_assertions)]
738        let mut restored_layers = 0;
739
740        for layer in 0..layers {
741            if !rtc.is_canvas_dirty(&layer) {
742                continue;
743            }
744            rcs.restore(layer);
745            #[cfg(debug_assertions)]
746            {
747                restored_layers += 1;
748            }
749        }
750
751        #[cfg(debug_assertions)]
752        log::trace!(
753            "scroller layer post_render: node={}, total_layers={}, restored_layers={}",
754            expanded_node.id.to_u32(),
755            layers,
756            restored_layers,
757        );
758    }
759
760    fn clips_content(&self, expanded_node: &ExpandedNode) -> bool {
761        expanded_node.with_properties_unwrapped(|scroller: &mut ScrollerHost| {
762            scroller._clip_content.local().get()
763        })
764    }
765
766    fn scrolls_content(&self, _expanded_node: &ExpandedNode) -> bool {
767        true
768    }
769
770    fn property_requires_occlusion_recompute(&self, property_name: &str) -> bool {
771        // Scroll deltas update presentation state without changing scroller ownership, clipping,
772        // or native mask structure; structural scroller properties still recompute occlusion.
773        !matches!(
774            property_name,
775            "scroll_pos_x" | "scroll_pos_y" | "_presentation_scroll_x" | "_presentation_scroll_y"
776        )
777    }
778
779    fn resolve_scroll_offset(&self, expanded_node: &ExpandedNode) -> Option<(f64, f64)> {
780        Some(
781            expanded_node.with_properties_unwrapped(|scroller: &mut ScrollerHost| {
782                (
783                    scroller._presentation_scroll_x.local().get(),
784                    scroller._presentation_scroll_y.local().get(),
785                )
786            }),
787        )
788    }
789
790    fn resolve_debug(
791        &self,
792        f: &mut std::fmt::Formatter,
793        expanded_node: Option<&ExpandedNode>,
794    ) -> std::fmt::Result {
795        match expanded_node {
796            Some(expanded_node) => {
797                expanded_node.with_properties_unwrapped(|_scroller: &mut ScrollerHost| {
798                    f.debug_struct("ScrollerHost").finish()
799                })
800            }
801            None => f.debug_struct("ScrollerHost").finish_non_exhaustive(),
802        }
803    }
804
805    fn base(&self) -> &BaseInstance {
806        &self.base
807    }
808}
809
810impl Scroller {
811    // Binds slot count and the reactive autosize measurement for the inline template.
812    pub fn on_mount(&mut self, ctx: &NodeContext) {
813        let projected_children_count = ctx.projected_children_count.clone();
814        let deps = [projected_children_count.untyped()];
815        self._projected_children_count
816            .replace_with(LocalProperty::computed(
817                move || projected_children_count.get(),
818                &deps,
819            ));
820
821        let Some(expanded_node) = ctx.expanded_node.upgrade() else {
822            return;
823        };
824
825        self._resolved_scroll_width.set(self.scroll_width.get());
826        self._resolved_scroll_height.set(self.scroll_height.get());
827
828        let autosize = self.autosize.local();
829        let autosize_x = self.autosize_x.local();
830        let autosize_y = self.autosize_y.local();
831        let scroll_width = self.scroll_width.local();
832        let scroll_height = self.scroll_height.local();
833        let resolved_scroll_width = self._resolved_scroll_width.local();
834        let resolved_scroll_height = self._resolved_scroll_height.local();
835        let deps = [
836            autosize.untyped(),
837            autosize_x.untyped(),
838            autosize_y.untyped(),
839            scroll_width.untyped(),
840            scroll_height.untyped(),
841        ];
842        bind_content_measurement_effect(
843            &expanded_node,
844            ctx,
845            "scroller autosize",
846            ContentMeasurementGeometry::Placed,
847            &deps,
848            move |_node, node_ctx| {
849                sync_scroller_autosize(
850                    node_ctx,
851                    &autosize,
852                    &autosize_x,
853                    &autosize_y,
854                    &scroll_width,
855                    &scroll_height,
856                    &resolved_scroll_width,
857                    &resolved_scroll_height,
858                );
859            },
860        );
861    }
862}
863
864fn resolve_axis_autosize(
865    autosize: bool,
866    axis_override: Option<bool>,
867    default_when_enabled: bool,
868) -> bool {
869    axis_override.unwrap_or(autosize && default_when_enabled)
870}
871
872fn sync_scroller_autosize(
873    ctx: &NodeContext,
874    autosize: &impl PropertyBinding<bool>,
875    autosize_x: &impl PropertyBinding<Option<bool>>,
876    autosize_y: &impl PropertyBinding<Option<bool>>,
877    scroll_width: &impl PropertyBinding<Size>,
878    scroll_height: &impl PropertyBinding<Size>,
879    resolved_scroll_width: &impl PropertyBinding<Size>,
880    resolved_scroll_height: &impl PropertyBinding<Size>,
881) {
882    let (content_width, content_height) = measure_content_children_forward_extents(ctx);
883    let manage_width =
884        resolve_axis_autosize(autosize.local().get(), autosize_x.local().get(), false);
885    let manage_height =
886        resolve_axis_autosize(autosize.local().get(), autosize_y.local().get(), true);
887
888    let resolved_width = if manage_width {
889        content_width
890            .map(|width| Size::Pixels(width.into()))
891            .unwrap_or_else(|| scroll_width.local().get())
892    } else {
893        scroll_width.local().get()
894    };
895    if resolved_scroll_width.local().get() != resolved_width {
896        resolved_scroll_width.local().set(resolved_width);
897    }
898
899    let resolved_height = if manage_height {
900        content_height
901            .map(|height| Size::Pixels(height.into()))
902            .unwrap_or_else(|| scroll_height.local().get())
903    } else {
904        scroll_height.local().get()
905    };
906    if resolved_scroll_height.local().get() != resolved_height {
907        resolved_scroll_height.local().set(resolved_height);
908    }
909}
910
911#[cfg(test)]
912mod scroll_position_tests;
913
914#[cfg(test)]
915mod tests {
916    use super::resolve_axis_autosize;
917
918    #[test]
919    fn autosize_defaults_only_manage_y_for_scroller() {
920        assert!(!resolve_axis_autosize(true, None, false));
921        assert!(resolve_axis_autosize(true, None, true));
922    }
923
924    #[test]
925    fn axis_override_precedence_beats_default_autosize_semantics() {
926        assert!(resolve_axis_autosize(false, Some(true), false));
927        assert!(!resolve_axis_autosize(true, Some(false), true));
928    }
929}