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