1use kurbo::{Affine, RoundedRect, RoundedRectRadii, Shape};
2use pax_engine::api::LocalProperty;
3use pax_runtime::BaseInstance;
4use pax_runtime_api::use_RefCell;
5
6use pax_runtime::{ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext};
7
8use pax_runtime::api as pax_runtime_api;
9use pax_runtime::api::{Layer, 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#[pax]
17#[custom(Default)]
18#[engine_import_path("pax_engine")]
19#[primitive("pax_std::drawing::rectangle::RectangleInstance")]
20pub struct Rectangle {
21 pub stroke: Property<Vec<Stroke>>,
23 pub fill: Property<Vec<pax_runtime_api::Fill>>,
25 pub corner_radius: Property<CornerRadii>,
27}
28
29impl Default for Rectangle {
30 fn default() -> Self {
31 Self {
32 fill: Property::new(vec![pax_runtime_api::Fill::default()]),
33 stroke: Default::default(),
34 corner_radius: Default::default(),
35 }
36 }
37}
38
39pub struct RectangleInstance {
41 base: BaseInstance,
42}
43
44impl InstanceNode for RectangleInstance {
45 fn supports_alpha_source_render(&self) -> bool {
46 true
47 }
48
49 fn instantiate(args: InstantiationArgs) -> Rc<Self> {
50 Rc::new(Self {
51 base: BaseInstance::new(
52 args,
53 InstanceFlags {
54 invisible_to_slot: false,
55 invisible_to_raycasting: false,
56 layer: Layer::Canvas,
57 is_component: false,
58 is_slot: false,
59 },
60 ),
61 })
62 }
63
64 fn handle_mount(
65 self: Rc<Self>,
66 expanded_node: &Rc<ExpandedNode>,
67 context: &Rc<RuntimeContext>,
68 ) {
69 let tab = expanded_node.transform_and_bounds.clone();
70 let (corner_radius, stroke, fill) =
71 expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
72 (
73 properties.corner_radius.local(),
74 properties.stroke.local(),
75 properties.fill.local(),
76 )
77 });
78
79 let appearance =
80 crate::common::watch_appearance(expanded_node, context, fill.clone(), stroke.clone());
81 let deps = &[
82 appearance.untyped(),
83 tab.untyped(),
84 corner_radius.untyped(),
85 stroke.untyped(),
86 fill.untyped(),
87 expanded_node.computed_opacity.untyped(),
88 expanded_node.computed_opacity_scopes.untyped(),
89 ];
90 let cloned_expanded_node = expanded_node.clone();
91 let cloned_context = context.clone();
92
93 expanded_node
94 .changed_listener
95 .replace_with(LocalProperty::computed(
96 move || {
97 appearance.get();
98 cloned_context.mark_canvas_node_dirty(cloned_expanded_node.id);
99 cloned_context
100 .set_canvas_dirty(cloned_expanded_node.occlusion.get().render_layer_id)
101 },
102 deps,
103 ));
104 }
105
106 fn resolve_coverage_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
107 expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
108 let tab = expanded_node.transform_and_bounds.get();
109 let (width, height) = tab.bounds;
110 let rect = RoundedRect::new(
111 0.0,
112 0.0,
113 width,
114 height,
115 properties.corner_radius.local().get().resolve_in_graph(),
116 );
117 Some(
118 Affine::from(tab.transform)
119 * crate::common::appearance_coverage_path(
120 &rect.to_path(0.1),
121 &properties.fill.local().get(),
122 &properties.stroke.local().get(),
123 ),
124 )
125 })
126 }
127
128 fn resolve_alpha_mask_paints(
129 &self,
130 node: &ExpandedNode,
131 ) -> Vec<pax_runtime_api::AlphaMaskPaint> {
132 node.with_properties_unwrapped(|p: &mut Rectangle| {
133 let (w, h) = node.transform_and_bounds.get().bounds;
134 crate::common::alpha_mask_paints(
135 node,
136 RoundedRect::new(
137 0.0,
138 0.0,
139 w,
140 h,
141 p.corner_radius.local().get().resolve_in_graph(),
142 )
143 .to_path(0.1),
144 p.fill.local().get(),
145 p.stroke.local().get(),
146 )
147 })
148 }
149
150 fn resolve_coverage_opacity(&self, expanded_node: &ExpandedNode) -> f64 {
151 expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
152 (crate::common::appearance_coverage_alpha(
153 &properties.fill.local().get(),
154 &properties.stroke.local().get(),
155 ) * expanded_node.computed_opacity.get())
156 .clamp(0.0, 1.0)
157 })
158 }
159
160 fn prepare_canvas_geometry(
161 &self,
162 node: &ExpandedNode,
163 ) -> pax_runtime::scene_geometry::CanvasGeometry {
164 let bounds = node.transform_and_bounds.get().bounds;
165 let local_bounds = node.with_properties_unwrapped(|p: &mut Rectangle| {
166 crate::common::stroke_coverage_bounds(
167 kurbo::Rect::new(0.0, 0.0, bounds.0, bounds.1),
168 &p.stroke.local().get(),
169 )
170 });
171 pax_runtime::scene_geometry::CanvasGeometry {
172 local_bounds: Some(local_bounds),
173 path: None,
174 }
175 }
176
177 fn render(
178 &self,
179 expanded_node: &ExpandedNode,
180 rtc: &Rc<RuntimeContext>,
181 rc: &mut dyn RenderContext,
182 ) {
183 if rc.alpha_source_layer().is_none() && !rtc.is_canvas_node_dirty(&expanded_node.id) {
184 return;
185 }
186
187 let Some(scope) = crate::common::begin_bounded_canvas_node(rc, expanded_node, rtc) else {
188 return;
189 };
190 let (width, height) = scope.bounds;
191
192 expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
193 let rect = RoundedRect::new(
194 0.0,
195 0.0,
196 width,
197 height,
198 properties.corner_radius.local().get().resolve_in_graph(),
199 );
200 let bez_path = rect.to_path(0.1);
201 rc.save(scope.layer_id);
202 rc.transform(scope.layer_id, scope.surface_transform);
203 crate::common::draw_appearance(
204 rc,
205 scope.layer_id,
206 bez_path,
207 &properties.fill.local().get(),
208 &properties.stroke.local().get(),
209 scope.paint_opacity,
210 pax_runtime_api::PathSmoothing::None,
211 0.0,
212 1.0,
213 );
214 rc.restore(scope.layer_id);
215 });
216 if rc.end_node(scope.layer_id, scope.node_id) {
217 rtc.clear_canvas_node_dirty(&expanded_node.id);
218 }
219 }
220
221 fn resolve_debug(
222 &self,
223 f: &mut std::fmt::Formatter,
224 expanded_node: Option<&ExpandedNode>,
225 ) -> std::fmt::Result {
226 match expanded_node {
227 Some(expanded_node) => expanded_node.with_properties_unwrapped(|r: &mut Rectangle| {
228 f.debug_struct("Rectangle")
229 .field("fill", &r.fill.local().get())
230 .finish()
231 }),
232 None => f.debug_struct("Rectangle").finish_non_exhaustive(),
233 }
234 }
235
236 fn base(&self) -> &BaseInstance {
237 &self.base
238 }
239}
240
241#[pax]
262#[engine_import_path("pax_engine")]
263#[has_helpers]
264#[custom(CoercionRules, Interpolatable)]
265pub struct CornerRadii {
266 pub top_left: Property<Numeric>,
268 pub top_right: Property<Numeric>,
270 pub bottom_right: Property<Numeric>,
272 pub bottom_left: Property<Numeric>,
274}
275
276impl pax_engine::api::Interpolatable for CornerRadii {
277 fn interpolate(&self, other: &Self, t: f64) -> Self {
278 Self::radii(
279 self.top_left.get().interpolate(&other.top_left.get(), t),
280 self.top_right.get().interpolate(&other.top_right.get(), t),
281 self.bottom_right
282 .get()
283 .interpolate(&other.bottom_right.get(), t),
284 self.bottom_left
285 .get()
286 .interpolate(&other.bottom_left.get(), t),
287 )
288 }
289}
290
291impl CoercionRules for CornerRadii {
292 fn try_coerce(value: PaxValue) -> Result<Self, String> {
293 match value {
294 PaxValue::Vec(values) => Self::from_css_values(values),
295 PaxValue::Object(values) => {
296 let mut radii = Self::default();
297 for (name, value) in values {
298 match name.as_str() {
299 "top_left" => radii.top_left = Property::new(Numeric::try_coerce(value)?),
300 "top_right" => radii.top_right = Property::new(Numeric::try_coerce(value)?),
301 "bottom_right" => {
302 radii.bottom_right = Property::new(Numeric::try_coerce(value)?)
303 }
304 "bottom_left" => {
305 radii.bottom_left = Property::new(Numeric::try_coerce(value)?)
306 }
307 _ => {}
308 }
309 }
310 Ok(radii)
311 }
312 PaxValue::Option(value) => match *value {
313 Some(value) => Self::try_coerce(value),
314 None => Err("None can't be coerced into CornerRadii".to_string()),
315 },
316 value => {
317 let radius = Numeric::try_coerce(value).map_err(|error| {
318 format!("failed to coerce a uniform rectangle corner radius: {error}")
319 })?;
320 Ok(Self::radii(
321 radius.clone(),
322 radius.clone(),
323 radius.clone(),
324 radius,
325 ))
326 }
327 }
328 }
329}
330
331impl CornerRadii {
332 pub fn resolve_in_graph(&self) -> RoundedRectRadii {
334 RoundedRectRadii::new(
335 self.top_left.local().get().to_float(),
336 self.top_right.local().get().to_float(),
337 self.bottom_right.local().get().to_float(),
338 self.bottom_left.local().get().to_float(),
339 )
340 }
341}
342
343impl Into<RoundedRectRadii> for &CornerRadii {
344 fn into(self) -> RoundedRectRadii {
345 RoundedRectRadii::new(
346 self.top_left.get().to_float(),
347 self.top_right.get().to_float(),
348 self.bottom_right.get().to_float(),
349 self.bottom_left.get().to_float(),
350 )
351 }
352}
353
354#[helpers]
355impl CornerRadii {
356 pub fn radii(
358 top_left: Numeric,
359 top_right: Numeric,
360 bottom_right: Numeric,
361 bottom_left: Numeric,
362 ) -> Self {
363 CornerRadii {
364 top_left: Property::new(top_left),
365 top_right: Property::new(top_right),
366 bottom_right: Property::new(bottom_right),
367 bottom_left: Property::new(bottom_left),
368 }
369 }
370
371 fn from_css_values(values: Vec<PaxValue>) -> Result<Self, String> {
372 if !(1..=4).contains(&values.len()) {
373 return Err(format!(
374 "rectangle corner radii require 1 to 4 values, got {}",
375 values.len()
376 ));
377 }
378
379 let values = values
380 .into_iter()
381 .enumerate()
382 .map(|(index, value)| {
383 Numeric::try_coerce(value).map_err(|error| {
384 format!("failed to coerce rectangle corner radius {index}: {error}")
385 })
386 })
387 .collect::<Result<Vec<_>, _>>()?;
388
389 let (top_left, top_right, bottom_right, bottom_left) = match values.as_slice() {
390 [all] => (all.clone(), all.clone(), all.clone(), all.clone()),
391 [top_left_bottom_right, top_right_bottom_left] => (
392 top_left_bottom_right.clone(),
393 top_right_bottom_left.clone(),
394 top_left_bottom_right.clone(),
395 top_right_bottom_left.clone(),
396 ),
397 [top_left, top_right_bottom_left, bottom_right] => (
398 top_left.clone(),
399 top_right_bottom_left.clone(),
400 bottom_right.clone(),
401 top_right_bottom_left.clone(),
402 ),
403 [top_left, top_right, bottom_right, bottom_left] => (
404 top_left.clone(),
405 top_right.clone(),
406 bottom_right.clone(),
407 bottom_left.clone(),
408 ),
409 _ => unreachable!("corner radius arity was validated above"),
410 };
411
412 Ok(Self::radii(top_left, top_right, bottom_right, bottom_left))
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 #[test]
419 fn corners_interpolate_independently_through_zero() {
420 use pax_engine::api::Interpolatable;
421 let from = super::CornerRadii::radii(0.into(), 20.into(), 10.into(), 30.into());
422 let to = super::CornerRadii::radii(20.into(), 0.into(), 30.into(), 10.into());
423 let mid = from.interpolate(&to, 0.5);
424 assert_eq!(mid.top_left.get().to_float(), 10.0);
425 assert_eq!(mid.top_right.get().to_float(), 10.0);
426 assert_eq!(mid.bottom_right.get().to_float(), 20.0);
427 assert_eq!(mid.bottom_left.get().to_float(), 20.0);
428 to.top_left.set(100.into());
429 assert_eq!(mid.top_left.get().to_float(), 10.0);
430 }
431 use super::*;
432
433 fn numeric(value: i64) -> PaxValue {
434 PaxValue::Numeric(value.into())
435 }
436
437 fn assert_radii(radii: CornerRadii, expected: [f64; 4]) {
438 assert_eq!(radii.top_left.get().to_float(), expected[0]);
439 assert_eq!(radii.top_right.get().to_float(), expected[1]);
440 assert_eq!(radii.bottom_right.get().to_float(), expected[2]);
441 assert_eq!(radii.bottom_left.get().to_float(), expected[3]);
442 }
443
444 #[test]
445 fn corner_radius_lists_follow_css_arity() {
446 for (values, expected) in [
447 (vec![1], [1.0, 1.0, 1.0, 1.0]),
448 (vec![1, 2], [1.0, 2.0, 1.0, 2.0]),
449 (vec![1, 2, 3], [1.0, 2.0, 3.0, 2.0]),
450 (vec![1, 2, 3, 4], [1.0, 2.0, 3.0, 4.0]),
451 ] {
452 let value = PaxValue::Vec(values.into_iter().map(numeric).collect());
453 assert_radii(CornerRadii::try_coerce(value).unwrap(), expected);
454 }
455 }
456
457 #[test]
458 fn bare_corner_radius_is_uniform() {
459 assert_radii(CornerRadii::try_coerce(numeric(12)).unwrap(), [12.0; 4]);
460 }
461
462 #[test]
463 fn object_corner_radius_remains_supported() {
464 let value = PaxValue::Object(vec![
465 ("top_left".to_string(), numeric(7)),
466 ("top_right".to_string(), numeric(6)),
467 ("bottom_right".to_string(), numeric(5)),
468 ("bottom_left".to_string(), numeric(4)),
469 (
470 "unknown".to_string(),
471 PaxValue::String("ignored".to_string()),
472 ),
473 ]);
474
475 assert_radii(
476 CornerRadii::try_coerce(value).unwrap(),
477 [7.0, 6.0, 5.0, 4.0],
478 );
479 }
480
481 #[test]
482 fn corner_radius_lists_reject_invalid_arities() {
483 for values in [vec![], vec![1, 2, 3, 4, 5]] {
484 let value = PaxValue::Vec(values.into_iter().map(numeric).collect());
485 assert!(CornerRadii::try_coerce(value).is_err());
486 }
487 }
488}