Skip to main content

pax_std/core/
mask.rs

1use std::iter;
2use std::rc::Rc;
3
4use crate::common::{native_surface_opacity, patch_if_needed};
5use kurbo::Affine;
6use pax_engine::*;
7use pax_message::{AnyCreatePatch, FramePatch};
8use pax_runtime::api as pax_runtime_api;
9use pax_runtime::api::{
10    bez_path_to_svg_path_data, borrow, borrow_mut, use_RefCell, Layer, Property, RenderContext,
11};
12use pax_runtime::{
13    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
14};
15use_RefCell!();
16
17/// Clips its first child using its second child subtree, which is not rendered as
18/// visible content. By default, this is a geometric coverage mask. Set `alpha=true`
19/// to use painted alpha instead, and `feather` to soften its edge:
20///
21/// ```pax
22/// <Mask width=100% height=100% alpha=true feather=12.0>
23///     <Rectangle width=100% height=100% fill=#FF0088/>
24///     <Ellipse x=50% y=50% anchor=50% width=240px height=240px
25///         fill=TRANSPARENT stroke={color: WHITE, width: 40px}/>
26/// </Mask>
27/// ```
28///
29/// The example reveals pink only underneath the soft ring. `feather` is Gaussian
30/// standard deviation in logical pixels, independent of display pixel density;
31/// zero disables feathering. Both properties default to zero/false, preserving
32/// existing coverage-mask behavior.
33///
34/// Alpha sources support `Rectangle`, `Ellipse`, and `Path` fills and strokes,
35/// including source-relative opacity, transforms, and linear/radial gradient alpha
36/// (up to eight ordered stops). Source RGB does not matter. Grouping and keyed
37/// `for` loops combine paints using source-over alpha: overlapping half-opacity
38/// sources yield 75% coverage, not XOR. Nested alpha masks on content multiply;
39/// ordinary geometric clips continue to intersect them. An empty alpha source
40/// hides all content. Cached surface-sized GPU textures are reused until paint,
41/// feather, enclosing alpha, or surface dimensions change.
42///
43/// Current boundary: WGPU canvas rendering, verified on web. Native controls and
44/// the legacy Piet renderer do not support alpha masks. Source-side `Frame`/`Mask`
45/// clipping, images, text, and native elements are not alpha sources; use vector
46/// leaves inside `Group`/repeat containers. Alpha masks modulate canvas draw alpha,
47/// not an isolated offscreen group, and do not change hit testing. Keep interactive
48/// hit targets separate from purely visual alpha reveals.
49#[pax]
50#[engine_import_path("pax_engine")]
51#[primitive("pax_std::core::mask::MaskInstance")]
52pub struct Mask {
53    /// Use painted alpha instead of geometric coverage.
54    pub alpha: Property<bool>,
55    /// Gaussian feather standard deviation, in logical pixels, for alpha masks.
56    pub feather: Property<f64>,
57}
58
59// Runtime instance backing `<Mask>`.
60pub struct MaskInstance {
61    base: BaseInstance,
62}
63
64#[cfg(test)]
65mod tests;
66
67impl MaskInstance {
68    fn alpha_settings(node: &ExpandedNode) -> (bool, f64) {
69        node.with_properties_unwrapped(|p: &mut Mask| (p.alpha.get(), p.feather.get().max(0.0)))
70    }
71
72    fn collect_alpha_paints(
73        node: &ExpandedNode,
74        paints: &mut Vec<pax_runtime_api::AlphaMaskPaint>,
75    ) {
76        paints.extend(borrow!(node.instance_node).resolve_alpha_mask_paints(node));
77        for child in node.children.get().iter().rev() {
78            Self::collect_alpha_paints(child, paints);
79        }
80    }
81    fn sync_mask_source_layout(expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
82        let children = expanded_node.children.get();
83        let mounted_children = borrow!(expanded_node.mounted_children);
84        let children_changed = children.len() != mounted_children.len()
85            || children
86                .iter()
87                .zip(mounted_children.iter())
88                .any(|(child, mounted)| !Rc::ptr_eq(child, mounted));
89        drop(mounted_children);
90
91        let needs_parent_binding = children.iter().any(|child| {
92            borrow!(child.render_parent)
93                .upgrade()
94                .is_none_or(|parent| !Rc::ptr_eq(&parent, expanded_node))
95        });
96
97        if children_changed || needs_parent_binding {
98            expanded_node.attach_children(children.clone(), context, &expanded_node.parent_frame);
99        }
100
101        for child in children {
102            Self::sync_mask_source_layout(&child, context);
103        }
104    }
105
106    fn refresh_mask_source_layout(expanded_node: &ExpandedNode, context: &Rc<RuntimeContext>) {
107        let mask_source = {
108            let sidecar_children = borrow!(expanded_node.sidecar_children);
109            sidecar_children.first().cloned()
110        };
111        if let Some(mask_source) = mask_source {
112            Self::sync_mask_source_layout(&mask_source, context);
113        }
114    }
115
116    fn mark_canvas_descendants_dirty(expanded_node: &ExpandedNode, context: &Rc<RuntimeContext>) {
117        for child in expanded_node.children.get().iter() {
118            if borrow!(child.instance_node).base().flags().layer == Layer::Canvas {
119                context.mark_canvas_node_dirty(child.id);
120                context.set_canvas_dirty(child.occlusion.get().render_layer_id);
121            }
122            Self::mark_canvas_descendants_dirty(child, context);
123        }
124    }
125
126    fn resolve_mask_path(expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
127        let mask_source = {
128            let sidecar_children = borrow!(expanded_node.sidecar_children);
129            sidecar_children.first().cloned()
130        };
131        let Some(mask_source) = mask_source else {
132            return None;
133        };
134        Self::resolve_subtree_coverage_path(&mask_source)
135    }
136
137    fn resolve_subtree_coverage_path(expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
138        let mut coverage = kurbo::BezPath::new();
139        if let Some(path) =
140            borrow!(expanded_node.instance_node).resolve_coverage_path(expanded_node)
141        {
142            coverage.extend(path.elements().iter().copied());
143        }
144        for child in expanded_node.children.get().iter() {
145            if let Some(path) = Self::resolve_subtree_coverage_path(child) {
146                coverage.extend(path.elements().iter().copied());
147            }
148        }
149
150        if coverage.elements().is_empty() {
151            None
152        } else {
153            Some(coverage)
154        }
155    }
156
157    fn watch_mask_source(
158        owner: &Rc<ExpandedNode>,
159        source: &Rc<ExpandedNode>,
160        context: &Rc<RuntimeContext>,
161    ) -> Property<()> {
162        let mut deps = vec![
163            source.children.untyped(),
164            source.transform_and_bounds.untyped(),
165            source.computed_opacity.untyped(),
166        ];
167        deps.extend(
168            borrow!(source.properties_scope)
169                .values()
170                .cloned()
171                .map(|v| v.get_untyped_property().clone()),
172        );
173        let weak_owner = Rc::downgrade(owner);
174        let weak_source = Rc::downgrade(source);
175        let weak_context = Rc::downgrade(context);
176        let child_watches: RefCell<Vec<(pax_runtime::ExpandedNodeIdentifier, Property<()>)>> =
177            RefCell::new(Vec::new());
178        let watcher = Property::computed_with_name(
179            move || {
180                let (Some(owner), Some(source), Some(context)) = (
181                    weak_owner.upgrade(),
182                    weak_source.upgrade(),
183                    weak_context.upgrade(),
184                ) else {
185                    return;
186                };
187                let children = source.children.get();
188                let mut watches = borrow_mut!(child_watches);
189                let unchanged = children.len() == watches.len()
190                    && children
191                        .iter()
192                        .zip(watches.iter())
193                        .all(|(child, (id, _))| child.id == *id);
194                if !unchanged {
195                    // Keep subscriptions for retained children, bind new leaves,
196                    // and release retired ones. Mask sources are off-tree, so
197                    // their paint changes must invalidate the visible content.
198                    let mut previous = std::mem::take(&mut *watches);
199                    *watches = children
200                        .iter()
201                        .map(|child| {
202                            let watch = previous
203                                .iter()
204                                .position(|(id, _)| *id == child.id)
205                                .map(|i| previous.swap_remove(i).1)
206                                .unwrap_or_else(|| {
207                                    Self::watch_mask_source(&owner, child, &context)
208                                });
209                            (child.id, watch)
210                        })
211                        .collect();
212                }
213                owner.changed_listener.invalidate();
214            },
215            &deps,
216            "mask source invalidation",
217        );
218        context.register_expanded_node_effect_property_named(owner, &watcher, "mask source");
219        watcher
220    }
221
222    fn mask_path_for_layer(
223        mask_path: &kurbo::BezPath,
224        expanded_node: &ExpandedNode,
225        layer: usize,
226        context: &RuntimeContext,
227    ) -> kurbo::BezPath {
228        Self::mask_transform_for_layer(expanded_node, layer, context) * mask_path.clone()
229    }
230
231    fn mask_transform_for_layer(
232        expanded_node: &ExpandedNode,
233        layer: usize,
234        context: &RuntimeContext,
235    ) -> Affine {
236        let Some(owner_id) = context.get_layer_scroller_owner(layer) else {
237            return Affine::IDENTITY;
238        };
239        let Some(owner) = context.get_expanded_node_by_eid(owner_id) else {
240            return Affine::IDENTITY;
241        };
242        let owner_inverse = Affine::from(owner.transform_and_bounds.get().transform.inverse());
243        let mut layer_transform = owner_inverse;
244
245        // If this mask contains the scroller that owns the target canvas layer, the mask is fixed
246        // in the scroller viewport while the OS/browser moves the canvas host in content
247        // coordinates. Convert the viewport-local mask into content coordinates so the retained
248        // canvas clip stays aligned with the native view mask during scroll.
249        if owner.is_descendant_of(&expanded_node.id) {
250            if let Some(state) = context.get_scroller_surface_state(owner_id.to_u32()) {
251                let scroll_x = if state.presentation_scroll_x.is_finite() {
252                    state.presentation_scroll_x
253                } else {
254                    state.scroll_x
255                };
256                let scroll_y = if state.presentation_scroll_y.is_finite() {
257                    state.presentation_scroll_y
258                } else {
259                    state.scroll_y
260                };
261                layer_transform = Affine::translate((scroll_x, scroll_y)) * layer_transform;
262            }
263        }
264
265        layer_transform
266    }
267
268    fn layer_clip_is_handled_by_scroller_dom(
269        expanded_node: &ExpandedNode,
270        layer: usize,
271        context: &RuntimeContext,
272    ) -> bool {
273        if Self::alpha_settings(expanded_node).0 {
274            // CSS coverage clips cannot represent feathered alpha.
275            return false;
276        }
277        let Some(owner_id) = context.get_layer_scroller_owner(layer) else {
278            return false;
279        };
280        let Some(owner) = context.get_expanded_node_by_eid(owner_id) else {
281            return false;
282        };
283
284        // Browser-owned scroller islands mount their canvas host inside the native scroller DOM
285        // subtree. When that subtree is already inside this Mask's CSS clip container, applying a
286        // second vector stencil clip in content coordinates double-clips and drifts during native
287        // scroll. The DOM ancestor clip is the authoritative clip for that island.
288        owner.is_descendant_of(&expanded_node.id)
289    }
290}
291
292impl InstanceNode for MaskInstance {
293    fn instantiate(args: InstantiationArgs) -> Rc<Self>
294    where
295        Self: Sized,
296    {
297        Rc::new(Self {
298            base: BaseInstance::new(
299                args,
300                InstanceFlags {
301                    invisible_to_slot: false,
302                    invisible_to_raycasting: true,
303                    layer: Layer::DontCare,
304                    is_component: false,
305                    is_slot: false,
306                },
307            ),
308        })
309    }
310
311    fn handle_mount(
312        self: Rc<Self>,
313        expanded_node: &Rc<ExpandedNode>,
314        context: &Rc<RuntimeContext>,
315    ) {
316        let id = expanded_node.id.to_u32();
317        context.enqueue_native_message(pax_message::NativeMessage::FrameCreate(AnyCreatePatch {
318            id,
319            parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
320            render_layer_id: 0,
321        }));
322
323        let env = Rc::clone(&expanded_node.stack);
324        let children = borrow!(self.base().get_instance_children());
325        if children.len() != 2 {
326            log::warn!(
327                "Mask expects exactly 2 direct children, got {}",
328                children.len()
329            );
330        }
331        let this_mask_prop = Property::new(Some(expanded_node.id));
332
333        let mut itr = children.iter().cloned();
334        if let Some(content_child) = itr.next() {
335            let content = expanded_node.generate_children(
336                iter::once((content_child, Rc::clone(&env))),
337                context,
338                &this_mask_prop,
339                true,
340            );
341            expanded_node.children.set(content);
342        } else {
343            expanded_node.children.set(Vec::new());
344        }
345
346        if let Some(mask_child) = itr.next() {
347            let sidecar = expanded_node.create_children_detached(
348                iter::once((mask_child, Rc::clone(&env))),
349                context,
350                &Rc::downgrade(expanded_node),
351            );
352            let sidecar = expanded_node.attach_sidecar_children(
353                sidecar,
354                context,
355                &expanded_node.parent_frame,
356            );
357            for child in sidecar.iter() {
358                child.recurse_control_flow_expansion(context);
359            }
360        }
361
362        let weak_self_ref = Rc::downgrade(expanded_node);
363        let context = Rc::clone(context);
364        let last_patch = Rc::new(RefCell::new(FramePatch {
365            id,
366            ..Default::default()
367        }));
368
369        let mut deps = vec![
370            expanded_node.transform_and_bounds.untyped(),
371            expanded_node.computed_opacity.untyped(),
372            expanded_node.occlusion.untyped(),
373        ];
374        expanded_node.with_properties_unwrapped(|p: &mut Mask| {
375            deps.extend([p.alpha.untyped(), p.feather.untyped()]);
376        });
377        if let Some(mask_child) = borrow!(expanded_node.sidecar_children).first() {
378            Self::sync_mask_source_layout(mask_child, &context);
379            // Observe structure as well as paint: repeats/conditionals may be
380            // empty at mount, and their last removal still needs a redraw.
381            let watcher = Self::watch_mask_source(expanded_node, mask_child, &context);
382            borrow_mut!(expanded_node.subscriptions).push(watcher);
383        }
384
385        expanded_node
386            .changed_listener
387            .replace_with(Property::computed(
388                move || {
389                    let Some(expanded_node) = weak_self_ref.upgrade() else {
390                        return;
391                    };
392
393                    Self::refresh_mask_source_layout(&expanded_node, &context);
394                    if Self::alpha_settings(&expanded_node).0 {
395                        Self::mark_canvas_descendants_dirty(&expanded_node, &context);
396                    }
397                    let clip_path = if Self::alpha_settings(&expanded_node).0 {
398                        String::new()
399                    } else {
400                        Self::resolve_mask_path(&expanded_node)
401                            .map(|path| bez_path_to_svg_path_data(&path))
402                            .unwrap_or_default()
403                    };
404
405                    let mut old_state = borrow_mut!(last_patch);
406                    let mut patch = FramePatch {
407                        id,
408                        ..Default::default()
409                    };
410                    let computed_tab = expanded_node.transform_and_bounds.get();
411                    let (width, height) = computed_tab.bounds;
412
413                    let updates = [
414                        patch_if_needed(
415                            &mut old_state.clip_content,
416                            &mut patch.clip_content,
417                            !clip_path.is_empty(),
418                        ),
419                        patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
420                        patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
421                        patch_if_needed(
422                            &mut old_state.transform,
423                            &mut patch.transform,
424                            computed_tab.transform.coeffs().to_vec(),
425                        ),
426                        patch_if_needed(&mut old_state.clip_path, &mut patch.clip_path, clip_path),
427                        patch_if_needed(
428                            &mut old_state.opacity,
429                            &mut patch.opacity,
430                            native_surface_opacity(&expanded_node, &context),
431                        ),
432                        patch_if_needed(
433                            &mut old_state.parent_frame,
434                            &mut patch.parent_frame,
435                            expanded_node.parent_frame.get().map(|v| v.to_u32()),
436                        ),
437                        patch_if_needed(
438                            &mut old_state.z_index,
439                            &mut patch.z_index,
440                            expanded_node.occlusion.get().z_index,
441                        ),
442                    ];
443
444                    if updates.into_iter().any(|updated| updated) {
445                        context
446                            .enqueue_native_message(pax_message::NativeMessage::FrameUpdate(patch));
447                        Self::mark_canvas_descendants_dirty(&expanded_node, &context);
448                    }
449                },
450                &deps,
451            ));
452    }
453
454    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
455        expanded_node
456            .changed_listener
457            .replace_with(Property::default());
458        context.enqueue_native_message(pax_message::NativeMessage::FrameDelete(
459            expanded_node.id.to_u32(),
460        ));
461    }
462
463    fn handle_pre_render(
464        &self,
465        expanded_node: &ExpandedNode,
466        rtc: &Rc<RuntimeContext>,
467        rcs: &mut dyn RenderContext,
468    ) {
469        let layers = rcs.layers();
470        let has_dirty_layer = (0..layers).any(|layer| rtc.is_canvas_dirty(&layer));
471        if !has_dirty_layer {
472            return;
473        }
474
475        Self::refresh_mask_source_layout(expanded_node, rtc);
476        let (alpha, feather) = Self::alpha_settings(expanded_node);
477        // Painted alpha consumes the source paints directly. Building a hard
478        // coverage outline here is unused work (especially for curved strokes).
479        let mask_path = (!alpha)
480            .then(|| Self::resolve_mask_path(expanded_node))
481            .flatten();
482        if mask_path.is_none() && !alpha {
483            return;
484        }
485        let mut paints = Vec::new();
486        if alpha {
487            if let Some(source) = borrow!(expanded_node.sidecar_children).first() {
488                Self::collect_alpha_paints(source, &mut paints);
489            }
490            // The mask's own ancestor opacity already applies to its content.
491            // Only source-relative opacity should modulate that content again.
492            let inherited_opacity = expanded_node.computed_opacity.get();
493            if inherited_opacity > f64::EPSILON {
494                for paint in &mut paints {
495                    paint.opacity = (paint.opacity / inherited_opacity).clamp(0.0, 1.0);
496                }
497            }
498        }
499
500        #[cfg(debug_assertions)]
501        let mut applied_layers = 0;
502        #[cfg(debug_assertions)]
503        let mut scroller_dom_layers = 0;
504
505        for layer in 0..layers {
506            if !rtc.is_canvas_dirty(&layer) {
507                continue;
508            }
509            if Self::layer_clip_is_handled_by_scroller_dom(expanded_node, layer, rtc) {
510                #[cfg(debug_assertions)]
511                {
512                    scroller_dom_layers += 1;
513                }
514                continue;
515            }
516            // Mask clips are stack effects for descendants, not leaf draw nodes. Keep them
517            // unbounded so every active layer renderer receives the matching save/clip state.
518            if !rcs.begin_node(
519                layer,
520                expanded_node.id.to_u32(),
521                expanded_node.occlusion.get().z_index,
522                0,
523            ) {
524                continue;
525            }
526            rcs.save(layer);
527            if alpha {
528                let mapping = Self::mask_transform_for_layer(expanded_node, layer, rtc);
529                let mut layer_paints = paints.clone();
530                for paint in &mut layer_paints {
531                    paint.transform = mapping * paint.transform;
532                }
533                rcs.clip_alpha(layer, &layer_paints, feather);
534            } else if let Some(path) = &mask_path {
535                rcs.clip(
536                    layer,
537                    Self::mask_path_for_layer(path, expanded_node, layer, rtc),
538                );
539            }
540            let _ = rcs.end_node(layer, expanded_node.id.to_u32());
541            #[cfg(debug_assertions)]
542            {
543                applied_layers += 1;
544            }
545        }
546
547        #[cfg(debug_assertions)]
548        log::trace!(
549            "mask clip pre_render: node={}, total_layers={}, applied_layers={}, scroller_dom_layers={}",
550            expanded_node.id.to_u32(),
551            layers,
552            applied_layers,
553            scroller_dom_layers,
554        );
555    }
556
557    fn handle_post_render(
558        &self,
559        expanded_node: &ExpandedNode,
560        rtc: &Rc<RuntimeContext>,
561        rcs: &mut dyn RenderContext,
562    ) {
563        let layers = rcs.layers();
564        let has_dirty_layer = (0..layers).any(|layer| rtc.is_canvas_dirty(&layer));
565        if !has_dirty_layer {
566            return;
567        }
568        if !Self::alpha_settings(expanded_node).0
569            && Self::resolve_mask_path(expanded_node).is_none()
570        {
571            return;
572        }
573
574        #[cfg(debug_assertions)]
575        let mut restored_layers = 0;
576        #[cfg(debug_assertions)]
577        let mut scroller_dom_layers = 0;
578
579        for layer in 0..layers {
580            if !rtc.is_canvas_dirty(&layer) {
581                continue;
582            }
583            if Self::layer_clip_is_handled_by_scroller_dom(expanded_node, layer, rtc) {
584                #[cfg(debug_assertions)]
585                {
586                    scroller_dom_layers += 1;
587                }
588                continue;
589            }
590            rcs.restore(layer);
591            #[cfg(debug_assertions)]
592            {
593                restored_layers += 1;
594            }
595        }
596
597        #[cfg(debug_assertions)]
598        log::trace!(
599            "mask clip post_render: node={}, total_layers={}, restored_layers={}, scroller_dom_layers={}",
600            expanded_node.id.to_u32(),
601            layers,
602            restored_layers,
603            scroller_dom_layers,
604        );
605    }
606
607    fn resolve_effect_clip_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
608        // A hard coverage projection would truncate the feather and incorrectly
609        // occlude content through partially transparent regions.
610        if Self::alpha_settings(expanded_node).0 {
611            None
612        } else {
613            Self::resolve_mask_path(expanded_node)
614        }
615    }
616
617    fn clips_content(&self, expanded_node: &ExpandedNode) -> bool {
618        !Self::alpha_settings(expanded_node).0 && Self::resolve_mask_path(expanded_node).is_some()
619    }
620
621    fn resolve_debug(
622        &self,
623        f: &mut std::fmt::Formatter,
624        _expanded_node: Option<&ExpandedNode>,
625    ) -> std::fmt::Result {
626        f.debug_struct("Mask").finish()
627    }
628
629    fn base(&self) -> &BaseInstance {
630        &self.base
631    }
632}