pax-std 0.39.1

Standard library for Pax, including layouts, drawing primitives, and form controls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use kurbo::{Affine, RoundedRect, RoundedRectRadii, Shape};
use pax_engine::api::LocalProperty;
use pax_runtime::BaseInstance;
use pax_runtime_api::use_RefCell;

use pax_runtime::{ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext};

use pax_runtime::api as pax_runtime_api;
use pax_runtime::api::{Layer, RenderContext, Stroke};
use_RefCell!();
use pax_engine::{helpers, pax, CoercionRules, PaxValue, Property};
use pax_manifest::pax_runtime_api::Numeric;
use std::rc::Rc;

/// A 2D vector rectangle, which covers its bounding box with the specified fill and stroke.
#[pax]
#[custom(Default)]
#[engine_import_path("pax_engine")]
#[primitive("pax_std::drawing::rectangle::RectangleInstance")]
pub struct Rectangle {
    /// Ordered outline layers above the fills, index zero topmost. Empty by default.
    pub stroke: Property<Vec<Stroke>>,
    /// Paint painted inside the rectangle.
    pub fill: Property<Vec<pax_runtime_api::Fill>>,
    /// Per-corner radii.
    pub corner_radius: Property<CornerRadii>,
}

impl Default for Rectangle {
    fn default() -> Self {
        Self {
            fill: Property::new(vec![pax_runtime_api::Fill::default()]),
            stroke: Default::default(),
            corner_radius: Default::default(),
        }
    }
}

// Runtime instance backing `<Rectangle>`.
pub struct RectangleInstance {
    base: BaseInstance,
}

impl InstanceNode for RectangleInstance {
    fn supports_alpha_source_render(&self) -> bool {
        true
    }

    fn instantiate(args: InstantiationArgs) -> Rc<Self> {
        Rc::new(Self {
            base: BaseInstance::new(
                args,
                InstanceFlags {
                    invisible_to_slot: false,
                    invisible_to_raycasting: false,
                    layer: Layer::Canvas,
                    is_component: false,
                    is_slot: false,
                },
            ),
        })
    }

    fn handle_mount(
        self: Rc<Self>,
        expanded_node: &Rc<ExpandedNode>,
        context: &Rc<RuntimeContext>,
    ) {
        let tab = expanded_node.transform_and_bounds.clone();
        let (corner_radius, stroke, fill) =
            expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
                (
                    properties.corner_radius.local(),
                    properties.stroke.local(),
                    properties.fill.local(),
                )
            });

        let appearance =
            crate::common::watch_appearance(expanded_node, context, fill.clone(), stroke.clone());
        let deps = &[
            appearance.untyped(),
            tab.untyped(),
            corner_radius.untyped(),
            stroke.untyped(),
            fill.untyped(),
            expanded_node.computed_opacity.untyped(),
            expanded_node.computed_opacity_scopes.untyped(),
        ];
        let cloned_expanded_node = expanded_node.clone();
        let cloned_context = context.clone();

        expanded_node
            .changed_listener
            .replace_with(LocalProperty::computed(
                move || {
                    appearance.get();
                    cloned_context.mark_canvas_node_dirty(cloned_expanded_node.id);
                    cloned_context
                        .set_canvas_dirty(cloned_expanded_node.occlusion.get().render_layer_id)
                },
                deps,
            ));
    }

    fn resolve_coverage_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
        expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
            let tab = expanded_node.transform_and_bounds.get();
            let (width, height) = tab.bounds;
            let rect = RoundedRect::new(
                0.0,
                0.0,
                width,
                height,
                properties.corner_radius.local().get().resolve_in_graph(),
            );
            Some(
                Affine::from(tab.transform)
                    * crate::common::appearance_coverage_path(
                        &rect.to_path(0.1),
                        &properties.fill.local().get(),
                        &properties.stroke.local().get(),
                    ),
            )
        })
    }

    fn resolve_alpha_mask_paints(
        &self,
        node: &ExpandedNode,
    ) -> Vec<pax_runtime_api::AlphaMaskPaint> {
        node.with_properties_unwrapped(|p: &mut Rectangle| {
            let (w, h) = node.transform_and_bounds.get().bounds;
            crate::common::alpha_mask_paints(
                node,
                RoundedRect::new(
                    0.0,
                    0.0,
                    w,
                    h,
                    p.corner_radius.local().get().resolve_in_graph(),
                )
                .to_path(0.1),
                p.fill.local().get(),
                p.stroke.local().get(),
            )
        })
    }

    fn resolve_coverage_opacity(&self, expanded_node: &ExpandedNode) -> f64 {
        expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
            (crate::common::appearance_coverage_alpha(
                &properties.fill.local().get(),
                &properties.stroke.local().get(),
            ) * expanded_node.computed_opacity.get())
            .clamp(0.0, 1.0)
        })
    }

    fn prepare_canvas_geometry(
        &self,
        node: &ExpandedNode,
    ) -> pax_runtime::scene_geometry::CanvasGeometry {
        let bounds = node.transform_and_bounds.get().bounds;
        let local_bounds = node.with_properties_unwrapped(|p: &mut Rectangle| {
            crate::common::stroke_coverage_bounds(
                kurbo::Rect::new(0.0, 0.0, bounds.0, bounds.1),
                &p.stroke.local().get(),
            )
        });
        pax_runtime::scene_geometry::CanvasGeometry {
            local_bounds: Some(local_bounds),
            path: None,
        }
    }

    fn render(
        &self,
        expanded_node: &ExpandedNode,
        rtc: &Rc<RuntimeContext>,
        rc: &mut dyn RenderContext,
    ) {
        if rc.alpha_source_layer().is_none() && !rtc.is_canvas_node_dirty(&expanded_node.id) {
            return;
        }

        let Some(scope) = crate::common::begin_bounded_canvas_node(rc, expanded_node, rtc) else {
            return;
        };
        let (width, height) = scope.bounds;

        expanded_node.with_properties_unwrapped(|properties: &mut Rectangle| {
            let rect = RoundedRect::new(
                0.0,
                0.0,
                width,
                height,
                properties.corner_radius.local().get().resolve_in_graph(),
            );
            let bez_path = rect.to_path(0.1);
            rc.save(scope.layer_id);
            rc.transform(scope.layer_id, scope.surface_transform);
            crate::common::draw_appearance(
                rc,
                scope.layer_id,
                bez_path,
                &properties.fill.local().get(),
                &properties.stroke.local().get(),
                scope.paint_opacity,
                pax_runtime_api::PathSmoothing::None,
                0.0,
                1.0,
            );
            rc.restore(scope.layer_id);
        });
        if rc.end_node(scope.layer_id, scope.node_id) {
            rtc.clear_canvas_node_dirty(&expanded_node.id);
        }
    }

    fn resolve_debug(
        &self,
        f: &mut std::fmt::Formatter,
        expanded_node: Option<&ExpandedNode>,
    ) -> std::fmt::Result {
        match expanded_node {
            Some(expanded_node) => expanded_node.with_properties_unwrapped(|r: &mut Rectangle| {
                f.debug_struct("Rectangle")
                    .field("fill", &r.fill.local().get())
                    .finish()
            }),
            None => f.debug_struct("Rectangle").finish_non_exhaustive(),
        }
    }

    fn base(&self) -> &BaseInstance {
        &self.base
    }
}

/// Corner radii, ordered clockwise from top-left.
///
/// Pax templates canonically use a list of one to four values such as
/// `corner_radius=[12, 8, 4]`. Lists expand using the same clockwise arity rules
/// as CSS `border-radius`; a uniform radius may elide the brackets as
/// `corner_radius=12`.
///
/// The zero-based positional ("magic index") contract depends on list arity:
///
/// - `[all]`
/// - `[top-left/bottom-right, top-right/bottom-left]`
/// - `[top-left, top-right/bottom-left, bottom-right]`
/// - `[top-left, top-right, bottom-right, bottom-left]`
///
/// A contextual named object remains available as explicit longhand:
/// `corner_radius={ top_left: 12 top_right: 8 bottom_right: 4 bottom_left: 2 }`.
/// The fully type-qualified constructor also remains valid when explicit type
/// syntax is useful: `corner_radius=CornerRadii { top_left: 12 top_right: 8
/// bottom_right: 4 bottom_left: 2 }`.
/// Interpolation treats each radius independently; zero produces an angular corner.
#[pax]
#[engine_import_path("pax_engine")]
#[has_helpers]
#[custom(CoercionRules, Interpolatable)]
pub struct CornerRadii {
    /// Top-left corner radius.
    pub top_left: Property<Numeric>,
    /// Top-right corner radius.
    pub top_right: Property<Numeric>,
    /// Bottom-right corner radius.
    pub bottom_right: Property<Numeric>,
    /// Bottom-left corner radius.
    pub bottom_left: Property<Numeric>,
}

impl pax_engine::api::Interpolatable for CornerRadii {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        Self::radii(
            self.top_left.get().interpolate(&other.top_left.get(), t),
            self.top_right.get().interpolate(&other.top_right.get(), t),
            self.bottom_right
                .get()
                .interpolate(&other.bottom_right.get(), t),
            self.bottom_left
                .get()
                .interpolate(&other.bottom_left.get(), t),
        )
    }
}

impl CoercionRules for CornerRadii {
    fn try_coerce(value: PaxValue) -> Result<Self, String> {
        match value {
            PaxValue::Vec(values) => Self::from_css_values(values),
            PaxValue::Object(values) => {
                let mut radii = Self::default();
                for (name, value) in values {
                    match name.as_str() {
                        "top_left" => radii.top_left = Property::new(Numeric::try_coerce(value)?),
                        "top_right" => radii.top_right = Property::new(Numeric::try_coerce(value)?),
                        "bottom_right" => {
                            radii.bottom_right = Property::new(Numeric::try_coerce(value)?)
                        }
                        "bottom_left" => {
                            radii.bottom_left = Property::new(Numeric::try_coerce(value)?)
                        }
                        _ => {}
                    }
                }
                Ok(radii)
            }
            PaxValue::Option(value) => match *value {
                Some(value) => Self::try_coerce(value),
                None => Err("None can't be coerced into CornerRadii".to_string()),
            },
            value => {
                let radius = Numeric::try_coerce(value).map_err(|error| {
                    format!("failed to coerce a uniform rectangle corner radius: {error}")
                })?;
                Ok(Self::radii(
                    radius.clone(),
                    radius.clone(),
                    radius.clone(),
                    radius,
                ))
            }
        }
    }
}

impl CornerRadii {
    /// Resolves corner radii from the entered UI graph's settled projections.
    pub fn resolve_in_graph(&self) -> RoundedRectRadii {
        RoundedRectRadii::new(
            self.top_left.local().get().to_float(),
            self.top_right.local().get().to_float(),
            self.bottom_right.local().get().to_float(),
            self.bottom_left.local().get().to_float(),
        )
    }
}

impl Into<RoundedRectRadii> for &CornerRadii {
    fn into(self) -> RoundedRectRadii {
        RoundedRectRadii::new(
            self.top_left.get().to_float(),
            self.top_right.get().to_float(),
            self.bottom_right.get().to_float(),
            self.bottom_left.get().to_float(),
        )
    }
}

#[helpers]
impl CornerRadii {
    /// Constructs a `CornerRadii` value from clockwise corner radii.
    pub fn radii(
        top_left: Numeric,
        top_right: Numeric,
        bottom_right: Numeric,
        bottom_left: Numeric,
    ) -> Self {
        CornerRadii {
            top_left: Property::new(top_left),
            top_right: Property::new(top_right),
            bottom_right: Property::new(bottom_right),
            bottom_left: Property::new(bottom_left),
        }
    }

    fn from_css_values(values: Vec<PaxValue>) -> Result<Self, String> {
        if !(1..=4).contains(&values.len()) {
            return Err(format!(
                "rectangle corner radii require 1 to 4 values, got {}",
                values.len()
            ));
        }

        let values = values
            .into_iter()
            .enumerate()
            .map(|(index, value)| {
                Numeric::try_coerce(value).map_err(|error| {
                    format!("failed to coerce rectangle corner radius {index}: {error}")
                })
            })
            .collect::<Result<Vec<_>, _>>()?;

        let (top_left, top_right, bottom_right, bottom_left) = match values.as_slice() {
            [all] => (all.clone(), all.clone(), all.clone(), all.clone()),
            [top_left_bottom_right, top_right_bottom_left] => (
                top_left_bottom_right.clone(),
                top_right_bottom_left.clone(),
                top_left_bottom_right.clone(),
                top_right_bottom_left.clone(),
            ),
            [top_left, top_right_bottom_left, bottom_right] => (
                top_left.clone(),
                top_right_bottom_left.clone(),
                bottom_right.clone(),
                top_right_bottom_left.clone(),
            ),
            [top_left, top_right, bottom_right, bottom_left] => (
                top_left.clone(),
                top_right.clone(),
                bottom_right.clone(),
                bottom_left.clone(),
            ),
            _ => unreachable!("corner radius arity was validated above"),
        };

        Ok(Self::radii(top_left, top_right, bottom_right, bottom_left))
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn corners_interpolate_independently_through_zero() {
        use pax_engine::api::Interpolatable;
        let from = super::CornerRadii::radii(0.into(), 20.into(), 10.into(), 30.into());
        let to = super::CornerRadii::radii(20.into(), 0.into(), 30.into(), 10.into());
        let mid = from.interpolate(&to, 0.5);
        assert_eq!(mid.top_left.get().to_float(), 10.0);
        assert_eq!(mid.top_right.get().to_float(), 10.0);
        assert_eq!(mid.bottom_right.get().to_float(), 20.0);
        assert_eq!(mid.bottom_left.get().to_float(), 20.0);
        to.top_left.set(100.into());
        assert_eq!(mid.top_left.get().to_float(), 10.0);
    }
    use super::*;

    fn numeric(value: i64) -> PaxValue {
        PaxValue::Numeric(value.into())
    }

    fn assert_radii(radii: CornerRadii, expected: [f64; 4]) {
        assert_eq!(radii.top_left.get().to_float(), expected[0]);
        assert_eq!(radii.top_right.get().to_float(), expected[1]);
        assert_eq!(radii.bottom_right.get().to_float(), expected[2]);
        assert_eq!(radii.bottom_left.get().to_float(), expected[3]);
    }

    #[test]
    fn corner_radius_lists_follow_css_arity() {
        for (values, expected) in [
            (vec![1], [1.0, 1.0, 1.0, 1.0]),
            (vec![1, 2], [1.0, 2.0, 1.0, 2.0]),
            (vec![1, 2, 3], [1.0, 2.0, 3.0, 2.0]),
            (vec![1, 2, 3, 4], [1.0, 2.0, 3.0, 4.0]),
        ] {
            let value = PaxValue::Vec(values.into_iter().map(numeric).collect());
            assert_radii(CornerRadii::try_coerce(value).unwrap(), expected);
        }
    }

    #[test]
    fn bare_corner_radius_is_uniform() {
        assert_radii(CornerRadii::try_coerce(numeric(12)).unwrap(), [12.0; 4]);
    }

    #[test]
    fn object_corner_radius_remains_supported() {
        let value = PaxValue::Object(vec![
            ("top_left".to_string(), numeric(7)),
            ("top_right".to_string(), numeric(6)),
            ("bottom_right".to_string(), numeric(5)),
            ("bottom_left".to_string(), numeric(4)),
            (
                "unknown".to_string(),
                PaxValue::String("ignored".to_string()),
            ),
        ]);

        assert_radii(
            CornerRadii::try_coerce(value).unwrap(),
            [7.0, 6.0, 5.0, 4.0],
        );
    }

    #[test]
    fn corner_radius_lists_reject_invalid_arities() {
        for values in [vec![], vec![1, 2, 3, 4, 5]] {
            let value = PaxValue::Vec(values.into_iter().map(numeric).collect());
            assert!(CornerRadii::try_coerce(value).is_err());
        }
    }
}