Skip to main content

pax_std/drawing/
rectangle.rs

1use kurbo::{Affine, RoundedRect, RoundedRectRadii, Shape};
2use pax_runtime::{api::Fill, BaseInstance};
3use pax_runtime_api::use_RefCell;
4
5use crate::common::begin_bounded_canvas_node;
6use pax_runtime::{ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext};
7
8use pax_runtime::api as pax_runtime_api;
9use pax_runtime::api::{Layer, Material, RenderContext, Stroke};
10use_RefCell!();
11use pax_engine::{helpers, pax, CoercionRules, PaxValue, Property};
12use pax_manifest::pax_runtime_api::Numeric;
13use std::rc::Rc;
14
15/// A 2D vector rectangle, which covers its bounding box with the specified fill and stroke.
16#[pax]
17#[engine_import_path("pax_engine")]
18#[primitive("pax_std::drawing::rectangle::RectangleInstance")]
19pub struct Rectangle {
20    /// Stroke drawn around the rectangle.
21    pub stroke: Property<Stroke>,
22    /// Fill painted inside the rectangle.
23    pub fill: Property<Fill>,
24    /// Light-reactive surface response.
25    pub material: Property<Material>,
26    /// Per-corner radii.
27    pub corner_radius: Property<CornerRadii>,
28}
29
30// Runtime instance backing `<Rectangle>`.
31pub struct RectangleInstance {
32    base: BaseInstance,
33}
34
35impl InstanceNode for RectangleInstance {
36    fn instantiate(args: InstantiationArgs) -> Rc<Self> {
37        Rc::new(Self {
38            base: BaseInstance::new(
39                args,
40                InstanceFlags {
41                    invisible_to_slot: false,
42                    invisible_to_raycasting: false,
43                    layer: Layer::Canvas,
44                    is_component: false,
45                    is_slot: false,
46                },
47            ),
48        })
49    }
50
51    fn handle_mount(
52        self: Rc<Self>,
53        expanded_node: &Rc<ExpandedNode>,
54        context: &Rc<RuntimeContext>,
55    ) {
56        let tab = expanded_node.transform_and_bounds.clone();
57        let (corner_radius, stroke, fill, material) =
58            expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
59                (
60                    properties.corner_radius.clone(),
61                    properties.stroke.clone(),
62                    properties.fill.clone(),
63                    properties.material.clone(),
64                )
65            });
66
67        let deps = &[
68            tab.untyped(),
69            corner_radius.untyped(),
70            stroke.untyped(),
71            fill.untyped(),
72            material.untyped(),
73            expanded_node.computed_opacity.untyped(),
74        ];
75        let cloned_expanded_node = expanded_node.clone();
76        let cloned_context = context.clone();
77
78        expanded_node
79            .changed_listener
80            .replace_with(Property::computed(
81                move || {
82                    cloned_context.mark_canvas_node_dirty(cloned_expanded_node.id);
83                    cloned_context
84                        .set_canvas_dirty(cloned_expanded_node.occlusion.get().render_layer_id)
85                },
86                deps,
87            ));
88    }
89
90    fn resolve_coverage_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
91        expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
92            let tab = expanded_node.transform_and_bounds.get();
93            let (width, height) = tab.bounds;
94            let rect = RoundedRect::new(0.0, 0.0, width, height, &properties.corner_radius.get());
95            Some(Affine::from(tab.transform) * rect.to_path(0.1))
96        })
97    }
98
99    fn resolve_alpha_mask_paints(
100        &self,
101        node: &ExpandedNode,
102    ) -> Vec<pax_runtime_api::AlphaMaskPaint> {
103        node.with_properties_unwrapped(|p: &mut Rectangle| {
104            let (w, h) = node.transform_and_bounds.get().bounds;
105            crate::common::alpha_mask_paints(
106                node,
107                RoundedRect::new(0.0, 0.0, w, h, &p.corner_radius.get()).to_path(0.1),
108                p.fill.get(),
109                p.stroke.get(),
110            )
111        })
112    }
113
114    fn resolve_coverage_opacity(&self, expanded_node: &ExpandedNode) -> f64 {
115        expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
116            (properties.fill.get().coverage_alpha_0_1() * expanded_node.computed_opacity.get())
117                .clamp(0.0, 1.0)
118        })
119    }
120
121    fn render(
122        &self,
123        expanded_node: &ExpandedNode,
124        rtc: &Rc<RuntimeContext>,
125        rc: &mut dyn RenderContext,
126    ) {
127        if !rtc.is_canvas_node_dirty(&expanded_node.id) {
128            return;
129        }
130
131        let Some(scope) = begin_bounded_canvas_node(rc, expanded_node, rtc) else {
132            return;
133        };
134        let (width, height) = scope.bounds;
135
136        expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
137            let rect = RoundedRect::new(0.0, 0.0, width, height, &properties.corner_radius.get());
138            let bez_path = rect.to_path(0.1);
139            let opacity = expanded_node.computed_opacity.get();
140            let fill = properties.fill.get();
141            let stroke = properties.stroke.get();
142            let material = properties.material.get();
143            rc.save(scope.layer_id);
144            rc.transform(scope.layer_id, scope.surface_transform);
145            rc.fill_with_material_and_opacity(
146                scope.layer_id,
147                bez_path.clone(),
148                &fill,
149                &material,
150                opacity,
151            );
152            //hack to address "phantom stroke" bug on Web
153            let width: f64 = stroke.width.get().expect_pixels().to_float();
154            if width > f64::EPSILON {
155                rc.stroke_with_material_and_opacity(
156                    scope.layer_id,
157                    bez_path,
158                    &stroke,
159                    &material,
160                    opacity,
161                );
162            }
163            rc.restore(scope.layer_id);
164        });
165        if rc.end_node(scope.layer_id, scope.node_id) {
166            rtc.clear_canvas_node_dirty(&expanded_node.id);
167        }
168    }
169
170    fn resolve_debug(
171        &self,
172        f: &mut std::fmt::Formatter,
173        expanded_node: Option<&ExpandedNode>,
174    ) -> std::fmt::Result {
175        match expanded_node {
176            Some(expanded_node) => expanded_node.with_properties_unwrapped(|r: &mut Rectangle| {
177                f.debug_struct("Rectangle")
178                    .field("fill", &r.fill.get())
179                    .finish()
180            }),
181            None => f.debug_struct("Rectangle").finish_non_exhaustive(),
182        }
183    }
184
185    fn base(&self) -> &BaseInstance {
186        &self.base
187    }
188}
189
190/// Corner radii, ordered clockwise from top-left.
191///
192/// Pax templates canonically use a list of one to four values such as
193/// `corner_radius=[12, 8, 4]`. Lists expand using the same clockwise arity rules
194/// as CSS `border-radius`; a uniform radius may elide the brackets as
195/// `corner_radius=12`.
196///
197/// The zero-based positional ("magic index") contract depends on list arity:
198///
199/// - `[all]`
200/// - `[top-left/bottom-right, top-right/bottom-left]`
201/// - `[top-left, top-right/bottom-left, bottom-right]`
202/// - `[top-left, top-right, bottom-right, bottom-left]`
203///
204/// A contextual named object remains available as explicit longhand:
205/// `corner_radius={ top_left: 12 top_right: 8 bottom_right: 4 bottom_left: 2 }`.
206/// The fully type-qualified constructor also remains valid when explicit type
207/// syntax is useful: `corner_radius=CornerRadii { top_left: 12 top_right: 8
208/// bottom_right: 4 bottom_left: 2 }`.
209#[pax]
210#[engine_import_path("pax_engine")]
211#[has_helpers]
212#[custom(CoercionRules)]
213pub struct CornerRadii {
214    /// Top-left corner radius.
215    pub top_left: Property<Numeric>,
216    /// Top-right corner radius.
217    pub top_right: Property<Numeric>,
218    /// Bottom-right corner radius.
219    pub bottom_right: Property<Numeric>,
220    /// Bottom-left corner radius.
221    pub bottom_left: Property<Numeric>,
222}
223
224impl CoercionRules for CornerRadii {
225    fn try_coerce(value: PaxValue) -> Result<Self, String> {
226        match value {
227            PaxValue::Vec(values) => Self::from_css_values(values),
228            PaxValue::Object(values) => {
229                let mut radii = Self::default();
230                for (name, value) in values {
231                    match name.as_str() {
232                        "top_left" => radii.top_left = Property::new(Numeric::try_coerce(value)?),
233                        "top_right" => radii.top_right = Property::new(Numeric::try_coerce(value)?),
234                        "bottom_right" => {
235                            radii.bottom_right = Property::new(Numeric::try_coerce(value)?)
236                        }
237                        "bottom_left" => {
238                            radii.bottom_left = Property::new(Numeric::try_coerce(value)?)
239                        }
240                        _ => {}
241                    }
242                }
243                Ok(radii)
244            }
245            PaxValue::Option(value) => match *value {
246                Some(value) => Self::try_coerce(value),
247                None => Err("None can't be coerced into CornerRadii".to_string()),
248            },
249            value => {
250                let radius = Numeric::try_coerce(value).map_err(|error| {
251                    format!("failed to coerce a uniform rectangle corner radius: {error}")
252                })?;
253                Ok(Self::radii(
254                    radius.clone(),
255                    radius.clone(),
256                    radius.clone(),
257                    radius,
258                ))
259            }
260        }
261    }
262}
263
264impl Into<RoundedRectRadii> for &CornerRadii {
265    fn into(self) -> RoundedRectRadii {
266        RoundedRectRadii::new(
267            self.top_left.get().to_float(),
268            self.top_right.get().to_float(),
269            self.bottom_right.get().to_float(),
270            self.bottom_left.get().to_float(),
271        )
272    }
273}
274
275#[helpers]
276impl CornerRadii {
277    /// Constructs a `CornerRadii` value from clockwise corner radii.
278    pub fn radii(
279        top_left: Numeric,
280        top_right: Numeric,
281        bottom_right: Numeric,
282        bottom_left: Numeric,
283    ) -> Self {
284        CornerRadii {
285            top_left: Property::new(top_left),
286            top_right: Property::new(top_right),
287            bottom_right: Property::new(bottom_right),
288            bottom_left: Property::new(bottom_left),
289        }
290    }
291
292    fn from_css_values(values: Vec<PaxValue>) -> Result<Self, String> {
293        if !(1..=4).contains(&values.len()) {
294            return Err(format!(
295                "rectangle corner radii require 1 to 4 values, got {}",
296                values.len()
297            ));
298        }
299
300        let values = values
301            .into_iter()
302            .enumerate()
303            .map(|(index, value)| {
304                Numeric::try_coerce(value).map_err(|error| {
305                    format!("failed to coerce rectangle corner radius {index}: {error}")
306                })
307            })
308            .collect::<Result<Vec<_>, _>>()?;
309
310        let (top_left, top_right, bottom_right, bottom_left) = match values.as_slice() {
311            [all] => (all.clone(), all.clone(), all.clone(), all.clone()),
312            [top_left_bottom_right, top_right_bottom_left] => (
313                top_left_bottom_right.clone(),
314                top_right_bottom_left.clone(),
315                top_left_bottom_right.clone(),
316                top_right_bottom_left.clone(),
317            ),
318            [top_left, top_right_bottom_left, bottom_right] => (
319                top_left.clone(),
320                top_right_bottom_left.clone(),
321                bottom_right.clone(),
322                top_right_bottom_left.clone(),
323            ),
324            [top_left, top_right, bottom_right, bottom_left] => (
325                top_left.clone(),
326                top_right.clone(),
327                bottom_right.clone(),
328                bottom_left.clone(),
329            ),
330            _ => unreachable!("corner radius arity was validated above"),
331        };
332
333        Ok(Self::radii(top_left, top_right, bottom_right, bottom_left))
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    fn numeric(value: i64) -> PaxValue {
342        PaxValue::Numeric(value.into())
343    }
344
345    fn assert_radii(radii: CornerRadii, expected: [f64; 4]) {
346        assert_eq!(radii.top_left.get().to_float(), expected[0]);
347        assert_eq!(radii.top_right.get().to_float(), expected[1]);
348        assert_eq!(radii.bottom_right.get().to_float(), expected[2]);
349        assert_eq!(radii.bottom_left.get().to_float(), expected[3]);
350    }
351
352    #[test]
353    fn corner_radius_lists_follow_css_arity() {
354        for (values, expected) in [
355            (vec![1], [1.0, 1.0, 1.0, 1.0]),
356            (vec![1, 2], [1.0, 2.0, 1.0, 2.0]),
357            (vec![1, 2, 3], [1.0, 2.0, 3.0, 2.0]),
358            (vec![1, 2, 3, 4], [1.0, 2.0, 3.0, 4.0]),
359        ] {
360            let value = PaxValue::Vec(values.into_iter().map(numeric).collect());
361            assert_radii(CornerRadii::try_coerce(value).unwrap(), expected);
362        }
363    }
364
365    #[test]
366    fn bare_corner_radius_is_uniform() {
367        assert_radii(CornerRadii::try_coerce(numeric(12)).unwrap(), [12.0; 4]);
368    }
369
370    #[test]
371    fn object_corner_radius_remains_supported() {
372        let value = PaxValue::Object(vec![
373            ("top_left".to_string(), numeric(7)),
374            ("top_right".to_string(), numeric(6)),
375            ("bottom_right".to_string(), numeric(5)),
376            ("bottom_left".to_string(), numeric(4)),
377            (
378                "unknown".to_string(),
379                PaxValue::String("ignored".to_string()),
380            ),
381        ]);
382
383        assert_radii(
384            CornerRadii::try_coerce(value).unwrap(),
385            [7.0, 6.0, 5.0, 4.0],
386        );
387    }
388
389    #[test]
390    fn corner_radius_lists_reject_invalid_arities() {
391        for values in [vec![], vec![1, 2, 3, 4, 5]] {
392            let value = PaxValue::Vec(values.into_iter().map(numeric).collect());
393            assert!(CornerRadii::try_coerce(value).is_err());
394        }
395    }
396}