Skip to main content

pax_std/drawing/
path.rs

1use kurbo::{Affine, BezPath, Rect, Shape};
2
3use pax_engine::api::{Fill, PathElement};
4use pax_runtime::api as pax_runtime_api;
5use pax_runtime::api::drawing::path_smoothing::smooth_bez_path;
6use pax_runtime::api::drawing::stroke_utils::{stroke_width_pixels, stroked_outline_path};
7use pax_runtime::api::{borrow, borrow_mut, use_RefCell};
8use pax_runtime::api::{Layer, Material, Numeric, PathSmoothing, RenderContext, Stroke, UnitValue};
9use pax_runtime::{
10    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
11};
12
13use crate::common::{begin_canvas_node_with_local_bounds, to_kurbo_point};
14use pax_engine::*;
15
16use_RefCell!();
17use std::collections::HashMap;
18use std::iter;
19use std::rc::Rc;
20
21#[cfg(test)]
22use pax_runtime::api::drawing::path_trim::trim_bez_path as trim_bez_path_to_unit_range;
23
24/// A 2D vector path for arbitrary Bézier and line-segment chains.
25///
26/// `elements` describes the path in local coordinates. `fill` paints the
27/// interior of closed contours, while `stroke` paints the path itself; for
28/// open subpaths, the stroke cap controls the exposed endpoints. Path geometry
29/// may draw outside the element's layout bounds; use a `Frame` or `Mask` when
30/// that overflow should be clipped.
31#[pax]
32#[custom(Default)]
33#[engine_import_path("pax_engine")]
34#[primitive("pax_std::drawing::path::PathInstance")]
35pub struct Path {
36    /// The path commands and control points, expressed in local coordinates.
37    pub elements: Property<Vec<PathElement>>,
38    /// The stroke applied along the path centerline.
39    pub stroke: Property<Stroke>,
40    /// The fill applied to the interior of closed contours.
41    pub fill: Property<Fill>,
42    /// Light-reactive surface response.
43    pub material: Property<Material>,
44    /// Optional curve smoothing applied before rendering path geometry.
45    pub smoothing: Property<PathSmoothing>,
46    /// Start position of the visible stroke range over the path's total length.
47    pub draw_start: Property<UnitValue>,
48    /// End position of the visible stroke range over the path's total length.
49    pub draw_end: Property<UnitValue>,
50}
51
52impl Default for Path {
53    fn default() -> Self {
54        Self {
55            elements: Default::default(),
56            stroke: Default::default(),
57            fill: Default::default(),
58            material: Default::default(),
59            smoothing: Default::default(),
60            draw_start: Property::new(UnitValue::Unitless(Numeric::F64(0.0))),
61            draw_end: Property::new(UnitValue::Unitless(Numeric::F64(1.0))),
62        }
63    }
64}
65
66impl Path {
67    /// Starts a new path at the provided point.
68    pub fn start(x: Size, y: Size) -> Vec<PathElement> {
69        let mut start: Vec<PathElement> = Vec::new();
70        start.push(PathElement::Point(x, y));
71        start
72    }
73
74    /// Appends a straight line segment to the provided point.
75    pub fn line_to(mut path: Vec<PathElement>, x: Size, y: Size) -> Vec<PathElement> {
76        path.push(PathElement::Line);
77        path.push(PathElement::Point(x, y));
78        path
79    }
80
81    /// Appends a quadratic Bézier curve with one control point.
82    pub fn curve_to(
83        mut path: Vec<PathElement>,
84        h_x: Size,
85        h_y: Size,
86        x: Size,
87        y: Size,
88    ) -> Vec<PathElement> {
89        path.push(PathElement::Quadratic(h_x, h_y));
90        path.push(PathElement::Point(x, y));
91        path
92    }
93}
94
95// Runtime instance backing `<Path>`.
96pub struct PathInstance {
97    base: BaseInstance,
98}
99
100impl InstanceNode for PathInstance {
101    fn instantiate(args: InstantiationArgs) -> Rc<Self>
102    where
103        Self: Sized,
104    {
105        Rc::new(Self {
106            base: BaseInstance::new(
107                args,
108                InstanceFlags {
109                    invisible_to_slot: false,
110                    invisible_to_raycasting: false,
111                    layer: Layer::Canvas,
112                    is_component: false,
113                    is_slot: false,
114                },
115            ),
116        })
117    }
118
119    fn handle_mount(
120        self: Rc<Self>,
121        expanded_node: &Rc<ExpandedNode>,
122        context: &Rc<RuntimeContext>,
123    ) {
124        // create a new stack to be able to insert a local store specific for this node and the
125        // ones bellow. If not done, things above this node could potentially access it
126        let env = expanded_node.stack.push(HashMap::new());
127        expanded_node.with_properties_unwrapped(|properties: &mut Path| {
128            env.insert_stack_local_store(PathContext {
129                elements: properties.elements.clone(),
130            });
131            let children = borrow!(self.base().get_instance_children());
132            if !children.is_empty() {
133                let children_with_envs = children.iter().cloned().zip(iter::repeat(env));
134                let new_children = expanded_node.generate_children(
135                    children_with_envs,
136                    context,
137                    &expanded_node.parent_frame,
138                    true,
139                );
140                // Path child nodes write PathElement values into the local PathContext store.
141                *borrow_mut!(expanded_node.expanded_projected_children) =
142                    Some(new_children.clone());
143                expanded_node.children.set(new_children);
144            }
145        });
146
147        let tab = expanded_node.transform_and_bounds.clone();
148        let (elements, stroke, fill, material, smoothing, draw_start, draw_end) = expanded_node
149            .with_properties_unwrapped(|properties: &mut Path| {
150                (
151                    properties.elements.clone(),
152                    properties.stroke.clone(),
153                    properties.fill.clone(),
154                    properties.material.clone(),
155                    properties.smoothing.clone(),
156                    properties.draw_start.clone(),
157                    properties.draw_end.clone(),
158                )
159            });
160
161        let deps = &[
162            tab.untyped(),
163            elements.untyped(),
164            stroke.untyped(),
165            fill.untyped(),
166            material.untyped(),
167            smoothing.untyped(),
168            draw_start.untyped(),
169            draw_end.untyped(),
170            expanded_node.computed_opacity.untyped(),
171        ];
172        let cloned_expanded_node = expanded_node.clone();
173        let cloned_context = context.clone();
174
175        expanded_node
176            .changed_listener
177            .replace_with(Property::computed(
178                move || {
179                    cloned_context.mark_canvas_node_dirty(cloned_expanded_node.id);
180                    cloned_context
181                        .set_canvas_dirty(cloned_expanded_node.occlusion.get().render_layer_id)
182                },
183                deps,
184            ));
185    }
186
187    fn requires_non_reactive_update(&self, expanded_node: &ExpandedNode) -> bool {
188        borrow!(expanded_node.expanded_projected_children).is_some()
189    }
190
191    fn update(self: Rc<Self>, expanded_node: &Rc<ExpandedNode>, _context: &Rc<RuntimeContext>) {
192        if borrow!(expanded_node.expanded_projected_children).is_some() {
193            // Path child nodes can change the path command list, but plain property-backed paths
194            // have no projected child structure to recompute on each tick.
195            expanded_node.compute_flattened_projected_children();
196        }
197    }
198
199    fn resolve_coverage_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
200        expanded_node.with_properties_unwrapped(|properties: &mut Path| {
201            let bounds = expanded_node.transform_and_bounds.get().bounds;
202            let elements = properties.elements.get();
203            let local_path = smooth_bez_path(
204                &build_local_bez_path(&elements, bounds)?,
205                properties.smoothing.get(),
206            );
207            let fill = properties.fill.get();
208            let stroke = properties.stroke.get();
209            let draw_start = properties.draw_start.get();
210            let draw_end = properties.draw_end.get();
211            let draw_start = draw_start.to_clamped_unit_float();
212            let draw_end = draw_end.to_clamped_unit_float();
213            let mut coverage = BezPath::new();
214            if fill.coverage_alpha_0_1() > f64::EPSILON {
215                coverage.extend(local_path.elements().iter().copied());
216            }
217            if stroke.color.get().alpha_0_1() > f64::EPSILON && draw_start < draw_end {
218                if let Some(stroke_outline) = stroked_outline_path(&local_path, &stroke) {
219                    coverage.extend(stroke_outline.elements().iter().copied());
220                }
221            }
222
223            if coverage.elements().is_empty() {
224                return None;
225            }
226            let tab = expanded_node.transform_and_bounds.get();
227            Some(Affine::from(tab.transform) * coverage)
228        })
229    }
230
231    fn resolve_alpha_mask_paints(
232        &self,
233        node: &ExpandedNode,
234    ) -> Vec<pax_runtime_api::AlphaMaskPaint> {
235        node.with_properties_unwrapped(|p: &mut Path| {
236            let Some(path) =
237                build_local_bez_path(&p.elements.get(), node.transform_and_bounds.get().bounds)
238            else {
239                return Vec::new();
240            };
241            let path = smooth_bez_path(&path, p.smoothing.get());
242            let mut paints = crate::common::alpha_mask_paints(
243                node,
244                path.clone(),
245                p.fill.get(),
246                Stroke::default(),
247            );
248            let path = pax_runtime_api::drawing::path_trim::trim_bez_path(
249                &path,
250                p.draw_start.get().to_clamped_unit_float(),
251                p.draw_end.get().to_clamped_unit_float(),
252            );
253            paints.extend(crate::common::alpha_mask_paints(
254                node,
255                path,
256                Fill::Solid(pax_runtime_api::Color::TRANSPARENT),
257                p.stroke.get(),
258            ));
259            paints
260        })
261    }
262
263    fn resolve_occlusion_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
264        expanded_node.with_properties_unwrapped(|properties: &mut Path| {
265            let bounds = expanded_node.transform_and_bounds.get().bounds;
266            let elements = properties.elements.get();
267            let local_path = smooth_bez_path(
268                &build_local_bez_path(&elements, bounds)?,
269                properties.smoothing.get(),
270            );
271            let fill = properties.fill.get();
272            let stroke = properties.stroke.get();
273            let mut coverage = BezPath::new();
274            if fill.coverage_alpha_0_1() > f64::EPSILON {
275                coverage.extend(local_path.elements().iter().copied());
276            }
277            if stroke.color.get().alpha_0_1() > f64::EPSILON {
278                if let Some(stroke_outline) = stroked_outline_path(&local_path, &stroke) {
279                    coverage.extend(stroke_outline.elements().iter().copied());
280                }
281            }
282
283            if coverage.elements().is_empty() {
284                return None;
285            }
286            let tab = expanded_node.transform_and_bounds.get();
287            Some(Affine::from(tab.transform) * coverage)
288        })
289    }
290
291    fn resolve_coverage_opacity(&self, expanded_node: &ExpandedNode) -> f64 {
292        expanded_node.with_properties_unwrapped(|properties: &mut Path| {
293            let fill_alpha = properties.fill.get().coverage_alpha_0_1();
294            let stroke_alpha = properties.stroke.get().color.get().alpha_0_1();
295            (fill_alpha.max(stroke_alpha) * expanded_node.computed_opacity.get()).clamp(0.0, 1.0)
296        })
297    }
298
299    fn property_requires_occlusion_recompute(&self, property_name: &str) -> bool {
300        !matches!(property_name, "draw_start" | "draw_end" | "material")
301    }
302
303    fn render(
304        &self,
305        expanded_node: &ExpandedNode,
306        rtc: &Rc<RuntimeContext>,
307        rc: &mut dyn RenderContext,
308    ) {
309        if !rtc.is_canvas_node_dirty(&expanded_node.id) {
310            return;
311        }
312
313        let bounds = expanded_node.transform_and_bounds.get().bounds;
314        let layout_bounds = Rect::new(0.0, 0.0, bounds.0, bounds.1);
315        let (bez_path, local_coverage_bounds) =
316            expanded_node.with_properties_unwrapped(|properties: &mut Path| {
317                let elements = properties.elements.get();
318                let bez_path = build_local_bez_path(&elements, bounds);
319                let local_coverage_bounds = bez_path
320                    .as_ref()
321                    .filter(|path| !path.elements().is_empty())
322                    .map(|path| {
323                        path_local_coverage_bounds(
324                            path,
325                            properties.smoothing.get(),
326                            stroke_width_pixels(&properties.stroke.get()),
327                        )
328                    })
329                    .unwrap_or(layout_bounds);
330                (bez_path, local_coverage_bounds)
331            });
332
333        let Some(scope) =
334            begin_canvas_node_with_local_bounds(rc, expanded_node, rtc, local_coverage_bounds)
335        else {
336            return;
337        };
338
339        if let Some(bez_path) = bez_path {
340            expanded_node.with_properties_unwrapped(|properties: &mut Path| {
341                let opacity = expanded_node.computed_opacity.get();
342                let fill = properties.fill.get();
343                let stroke = properties.stroke.get();
344                let material = properties.material.get();
345                let smoothing = properties.smoothing.get();
346                let draw_start = properties.draw_start.get();
347                let draw_end = properties.draw_end.get();
348                let draw_start = draw_start.to_clamped_unit_float();
349                let draw_end = draw_end.to_clamped_unit_float();
350                rc.save(scope.layer_id);
351                rc.transform(scope.layer_id, scope.surface_transform);
352                if fill.coverage_alpha_0_1() * opacity > f64::EPSILON {
353                    rc.fill_with_material_and_opacity_and_smoothing(
354                        scope.layer_id,
355                        bez_path.clone(),
356                        &fill,
357                        &material,
358                        opacity,
359                        smoothing,
360                    );
361                }
362                if stroke_width_pixels(&stroke) > f64::EPSILON && draw_start < draw_end {
363                    if draw_start <= f64::EPSILON && draw_end >= 1.0 - f64::EPSILON {
364                        rc.stroke_with_material_and_opacity_and_smoothing(
365                            scope.layer_id,
366                            bez_path,
367                            &stroke,
368                            &material,
369                            opacity,
370                            smoothing,
371                        );
372                    } else {
373                        rc.stroke_with_draw_range_and_material_and_opacity_and_smoothing(
374                            scope.layer_id,
375                            bez_path,
376                            &stroke,
377                            &material,
378                            opacity,
379                            draw_start,
380                            draw_end,
381                            smoothing,
382                        );
383                    }
384                }
385                rc.restore(scope.layer_id);
386            });
387        }
388        if rc.end_node(scope.layer_id, scope.node_id) {
389            rtc.clear_canvas_node_dirty(&expanded_node.id);
390        }
391    }
392
393    fn base(&self) -> &BaseInstance {
394        &self.base
395    }
396
397    fn resolve_debug(
398        &self,
399        f: &mut std::fmt::Formatter,
400        _expanded_node: Option<&ExpandedNode>,
401    ) -> std::fmt::Result {
402        f.debug_struct("Path").finish()
403    }
404}
405
406fn path_local_coverage_bounds(path: &BezPath, smoothing: PathSmoothing, stroke_width: f64) -> Rect {
407    let path = smooth_bez_path(path, smoothing);
408    let stroke_padding = stroke_width.max(0.0);
409    path.bounding_box().inflate(stroke_padding, stroke_padding)
410}
411
412fn build_local_bez_path(elements: &[PathElement], bounds: (f64, f64)) -> Option<BezPath> {
413    let mut bez_path = BezPath::new();
414    let mut itr_elems = elements.iter();
415
416    if let Some(elem) = itr_elems.next() {
417        if let &PathElement::Point(x, y) = elem {
418            bez_path.move_to(to_kurbo_point(x, y, bounds));
419        } else {
420            log::warn!("path must start with point");
421            return None;
422        }
423    }
424
425    while let Some(elem) = itr_elems.next() {
426        match elem {
427            &PathElement::Point(x, y) => {
428                bez_path.move_to(to_kurbo_point(x, y, bounds));
429            }
430            &PathElement::Line => {
431                let Some(&PathElement::Point(x, y)) = itr_elems.next() else {
432                    log::warn!("line expects to be followed by a point");
433                    return None;
434                };
435                bez_path.line_to(to_kurbo_point(x, y, bounds));
436            }
437            &PathElement::Quadratic(h_x, h_y) => {
438                let Some(&PathElement::Point(x, y)) = itr_elems.next() else {
439                    log::warn!("curve expects to be followed by a point");
440                    return None;
441                };
442                bez_path.quad_to(
443                    to_kurbo_point(h_x, h_y, bounds),
444                    to_kurbo_point(x, y, bounds),
445                );
446            }
447            &PathElement::Cubic(v1, v2, v3, v4) => {
448                let Some(&PathElement::Point(x, y)) = itr_elems.next() else {
449                    log::warn!("curve expects to be followed by a point");
450                    return None;
451                };
452                bez_path.curve_to(
453                    to_kurbo_point(v1, v2, bounds),
454                    to_kurbo_point(v3, v4, bounds),
455                    to_kurbo_point(x, y, bounds),
456                );
457            }
458            &PathElement::Close => {
459                bez_path.close_path();
460            }
461            PathElement::Empty => (),
462        }
463    }
464
465    Some(bez_path)
466}
467
468#[cfg(test)]
469fn trim_bez_path(path: &BezPath, draw_start: UnitValue, draw_end: UnitValue) -> BezPath {
470    trim_bez_path_to_unit_range(
471        path,
472        draw_start.to_clamped_unit_float(),
473        draw_end.to_clamped_unit_float(),
474    )
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480    use kurbo::{PathEl, PathSeg};
481
482    fn unit(value: f64) -> UnitValue {
483        UnitValue::Unitless(Numeric::F64(value))
484    }
485
486    fn point_from_move(element: PathEl) -> kurbo::Point {
487        match element {
488            PathEl::MoveTo(point) => point,
489            _ => panic!("expected MoveTo, got {element:?}"),
490        }
491    }
492
493    fn point_from_line(element: PathEl) -> kurbo::Point {
494        match element {
495            PathEl::LineTo(point) => point,
496            _ => panic!("expected LineTo, got {element:?}"),
497        }
498    }
499
500    fn assert_point_near(actual: kurbo::Point, expected: kurbo::Point) {
501        assert!(
502            (actual.x - expected.x).abs() < 1e-6 && (actual.y - expected.y).abs() < 1e-6,
503            "expected {expected:?}, got {actual:?}"
504        );
505    }
506
507    #[test]
508    fn local_coverage_bounds_include_geometry_outside_layout_bounds() {
509        let mut path = BezPath::new();
510        path.move_to((-25.0, -10.0));
511        path.line_to((125.0, 110.0));
512
513        let bounds = path_local_coverage_bounds(&path, PathSmoothing::None, 4.0);
514
515        assert_eq!(bounds, Rect::new(-29.0, -14.0, 129.0, 114.0));
516    }
517
518    #[test]
519    fn trim_empty_path_returns_empty_path() {
520        let path = BezPath::new();
521        let trimmed = trim_bez_path(&path, unit(0.0), unit(1.0));
522
523        assert!(trimmed.elements().is_empty());
524    }
525
526    #[test]
527    fn trim_line_partial_range() {
528        let mut path = BezPath::new();
529        path.move_to((0.0, 0.0));
530        path.line_to((100.0, 0.0));
531
532        let trimmed = trim_bez_path(&path, unit(0.25), unit(0.75));
533        let elements = trimmed.elements();
534
535        assert_eq!(elements.len(), 2);
536        assert_point_near(point_from_move(elements[0]), kurbo::Point::new(25.0, 0.0));
537        assert_point_near(point_from_line(elements[1]), kurbo::Point::new(75.0, 0.0));
538    }
539
540    #[test]
541    fn trim_crosses_line_boundaries_without_internal_moves() {
542        let mut path = BezPath::new();
543        path.move_to((0.0, 0.0));
544        path.line_to((50.0, 0.0));
545        path.line_to((100.0, 0.0));
546
547        let trimmed = trim_bez_path(&path, unit(0.25), unit(0.75));
548        let elements = trimmed.elements();
549
550        assert_eq!(elements.len(), 3);
551        assert!(matches!(elements[0], PathEl::MoveTo(_)));
552        assert!(matches!(elements[1], PathEl::LineTo(_)));
553        assert!(matches!(elements[2], PathEl::LineTo(_)));
554        assert_point_near(point_from_move(elements[0]), kurbo::Point::new(25.0, 0.0));
555        assert_point_near(point_from_line(elements[1]), kurbo::Point::new(50.0, 0.0));
556        assert_point_near(point_from_line(elements[2]), kurbo::Point::new(75.0, 0.0));
557    }
558
559    #[test]
560    fn trim_quadratic_and_cubic_segments() {
561        let mut path = BezPath::new();
562        path.move_to((0.0, 0.0));
563        path.quad_to((50.0, 100.0), (100.0, 0.0));
564        path.curve_to((125.0, -50.0), (175.0, 50.0), (200.0, 0.0));
565
566        let trimmed = trim_bez_path(&path, unit(0.1), unit(0.9));
567
568        assert!(trimmed.elements().len() >= 3);
569        assert!(matches!(trimmed.elements()[0], PathEl::MoveTo(_)));
570        assert!(
571            trimmed
572                .segments()
573                .any(|segment| matches!(segment, PathSeg::Quad(_) | PathSeg::Cubic(_))),
574            "expected at least one curved segment after trimming"
575        );
576    }
577
578    #[test]
579    fn close_path_contributes_to_trimmed_length() {
580        let mut path = BezPath::new();
581        path.move_to((0.0, 0.0));
582        path.line_to((100.0, 0.0));
583        path.close_path();
584
585        let trimmed = trim_bez_path(&path, unit(0.75), unit(1.0));
586        let elements = trimmed.elements();
587
588        assert_eq!(elements.len(), 2);
589        assert_point_near(point_from_move(elements[0]), kurbo::Point::new(50.0, 0.0));
590        assert_point_near(point_from_line(elements[1]), kurbo::Point::new(0.0, 0.0));
591    }
592
593    #[test]
594    fn trim_closes_completed_contours_before_path_end() {
595        let mut path = BezPath::new();
596        path.move_to((0.0, 0.0));
597        path.line_to((10.0, 0.0));
598        path.line_to((10.0, 10.0));
599        path.line_to((0.0, 10.0));
600        path.close_path();
601        path.move_to((100.0, 0.0));
602        path.line_to((200.0, 0.0));
603
604        let trimmed = trim_bez_path(&path, unit(0.0), unit(0.5));
605        let elements = trimmed.elements();
606        let close_index = elements
607            .iter()
608            .position(|element| matches!(element, PathEl::ClosePath))
609            .expect("expected completed first contour to be closed");
610
611        assert!(
612            elements
613                .iter()
614                .skip(close_index + 1)
615                .any(|element| matches!(element, PathEl::MoveTo(_))),
616            "expected later partial contour after completed closed contour"
617        );
618    }
619
620    #[test]
621    fn trim_closes_completed_contours_with_explicit_return_to_start() {
622        let mut path = BezPath::new();
623        path.move_to((0.0, 0.0));
624        path.line_to((10.0, 0.0));
625        path.line_to((0.0, 0.0));
626        path.close_path();
627        path.move_to((100.0, 0.0));
628        path.line_to((200.0, 0.0));
629
630        let trimmed = trim_bez_path(&path, unit(0.0), unit(0.3));
631        let elements = trimmed.elements();
632
633        assert!(
634            elements
635                .iter()
636                .any(|element| matches!(element, PathEl::ClosePath)),
637            "expected zero-length ClosePath to be preserved for the completed contour"
638        );
639    }
640
641    #[test]
642    fn trim_clamps_and_empty_when_start_reaches_end() {
643        let mut path = BezPath::new();
644        path.move_to((0.0, 0.0));
645        path.line_to((100.0, 0.0));
646
647        assert_eq!(
648            trim_bez_path(&path, unit(-1.0), unit(2.0)).elements(),
649            path.elements()
650        );
651        assert!(trim_bez_path(&path, unit(0.5), unit(0.5))
652            .elements()
653            .is_empty());
654        assert!(trim_bez_path(&path, unit(0.75), unit(0.25))
655            .elements()
656            .is_empty());
657    }
658}
659
660use pax_engine::{
661    api::{NodeContext, Size, Store},
662    pax, Property,
663};
664
665// Local store shared by `Path` and its path-builder children.
666pub struct PathContext {
667    // Shared path element list mutated by path-builder child components.
668    pub elements: Property<Vec<PathElement>>,
669}
670
671impl Store for PathContext {}
672
673/// Path child component that inserts a `PathElement::Point`.
674#[pax]
675#[engine_import_path("pax_engine")]
676#[inlined( @settings { @mount: on_mount @pre_render: pre_render @unmount: on_unmount })]
677pub struct PathPoint {
678    /// Point x-coordinate.
679    pub x: Property<Size>,
680    /// Point y-coordinate.
681    pub y: Property<Size>,
682    // Private reactive hook that writes this child into the parent path.
683    pub _on_change: Property<bool>,
684}
685
686impl PathPoint {
687    // Registers this child as a point command in the parent `Path`.
688    pub fn on_mount(&mut self, ctx: &NodeContext) {
689        let path_elems = ctx
690            .peek_local_store(|path_ctx: &mut PathContext| path_ctx.elements.clone())
691            .expect("path point can only exist in <Path> tag");
692
693        let x = self.x.clone();
694        let y = self.y.clone();
695        let id = ctx.slot_index.clone();
696        let deps = [x.untyped(), y.untyped(), id.untyped()];
697        self._on_change.replace_with(Property::computed(
698            move || {
699                path_elems.update(|elems| {
700                    let id = id.get().unwrap();
701                    while elems.len() < id + 1 {
702                        elems.push(PathElement::Close)
703                    }
704                    elems[id] = PathElement::Point(x.get(), y.get());
705                });
706                false
707            },
708            &deps,
709        ));
710    }
711
712    // Removes this child command from the parent `Path`.
713    pub fn on_unmount(&mut self, ctx: &NodeContext) {
714        let path_elems = ctx
715            .peek_local_store(|path_ctx: &mut PathContext| path_ctx.elements.clone())
716            .expect("path point can only exist in <Path> tag");
717        let id = ctx.slot_index.get().unwrap();
718        path_elems.update(|elems| {
719            if id < elems.len() {
720                elems.remove(id);
721            }
722        });
723    }
724
725    // Forces the path-command computed property to run.
726    pub fn pre_render(&mut self, _ctx: &NodeContext) {
727        self._on_change.get();
728    }
729}
730
731/// Path child component that inserts a straight line segment.
732#[pax]
733#[engine_import_path("pax_engine")]
734#[inlined( @settings { @mount: on_mount @pre_render: pre_render @unmount: on_unmount })]
735pub struct PathLine {
736    // Private reactive hook that writes this child into the parent path.
737    pub _on_change: Property<bool>,
738}
739
740impl PathLine {
741    // Registers this child as a line command in the parent `Path`.
742    pub fn on_mount(&mut self, ctx: &NodeContext) {
743        let path_elems = ctx
744            .peek_local_store(|path_ctx: &mut PathContext| path_ctx.elements.clone())
745            .expect("path line can only exist in <Path> tag");
746
747        let id = ctx.slot_index.clone();
748        let deps = [id.untyped()];
749        self._on_change.replace_with(Property::computed(
750            move || {
751                path_elems.update(|elems| {
752                    let id = id.get().unwrap();
753                    while elems.len() < id + 1 {
754                        elems.push(PathElement::Close)
755                    }
756                    elems[id] = PathElement::Line;
757                });
758                false
759            },
760            &deps,
761        ));
762    }
763
764    // Removes this child command from the parent `Path`.
765    pub fn on_unmount(&mut self, ctx: &NodeContext) {
766        let path_elems = ctx
767            .peek_local_store(|path_ctx: &mut PathContext| path_ctx.elements.clone())
768            .expect("path point can only exist in <Path> tag");
769        let id = ctx.slot_index.get().unwrap();
770        path_elems.update(|elems| {
771            if id < elems.len() {
772                elems.remove(id);
773            }
774        });
775    }
776    // Forces the path-command computed property to run.
777    pub fn pre_render(&mut self, _ctx: &NodeContext) {
778        self._on_change.get();
779    }
780}
781
782/// Path child component that closes the current contour.
783#[pax]
784#[engine_import_path("pax_engine")]
785#[inlined( @settings { @mount: on_mount @pre_render: pre_render @unmount: on_unmount })]
786pub struct PathClose {
787    // Private reactive hook that writes this child into the parent path.
788    pub _on_change: Property<bool>,
789}
790
791impl PathClose {
792    // Registers this child as a close-path command in the parent `Path`.
793    pub fn on_mount(&mut self, ctx: &NodeContext) {
794        let path_elems = ctx
795            .peek_local_store(|path_ctx: &mut PathContext| path_ctx.elements.clone())
796            .expect("path line can only exist in <Path> tag");
797
798        let id = ctx.slot_index.clone();
799        let deps = [id.untyped()];
800        self._on_change.replace_with(Property::computed(
801            move || {
802                path_elems.update(|elems| {
803                    let id = id.get().unwrap();
804                    while elems.len() < id + 1 {
805                        elems.push(PathElement::Close)
806                    }
807                    elems[id] = PathElement::Close;
808                });
809                false
810            },
811            &deps,
812        ));
813    }
814    // Removes this child command from the parent `Path`.
815    pub fn on_unmount(&mut self, ctx: &NodeContext) {
816        let path_elems = ctx
817            .peek_local_store(|path_ctx: &mut PathContext| path_ctx.elements.clone())
818            .expect("path point can only exist in <Path> tag");
819        let id = ctx.slot_index.clone();
820        path_elems.update(|elems| {
821            let id = id.get().unwrap();
822            if id < elems.len() {
823                elems.remove(id);
824            }
825        });
826    }
827
828    // Forces the path-command computed property to run.
829    pub fn pre_render(&mut self, _ctx: &NodeContext) {
830        self._on_change.get();
831    }
832}
833
834/// Path child component that inserts a quadratic curve control point.
835#[pax]
836#[engine_import_path("pax_engine")]
837#[inlined( @settings { @mount: on_mount @pre_render: pre_render @unmount: on_unmount })]
838pub struct PathCurve {
839    /// Control point x-coordinate.
840    pub x: Property<Size>,
841    /// Control point y-coordinate.
842    pub y: Property<Size>,
843    // Private reactive hook that writes this child into the parent path.
844    pub _on_change: Property<bool>,
845}
846
847impl PathCurve {
848    // Registers this child as a quadratic curve command in the parent `Path`.
849    pub fn on_mount(&mut self, ctx: &NodeContext) {
850        let path_elems = ctx
851            .peek_local_store(|path_ctx: &mut PathContext| path_ctx.elements.clone())
852            .expect("path point can only exist in <Path> tag");
853
854        let x = self.x.clone();
855        let y = self.y.clone();
856        let id = ctx.slot_index.clone();
857        let deps = [x.untyped(), y.untyped(), id.untyped()];
858        self._on_change.replace_with(Property::computed(
859            move || {
860                path_elems.update(|elems| {
861                    let id = id.get().unwrap();
862                    while elems.len() < id + 1 {
863                        elems.push(PathElement::Close)
864                    }
865                    elems[id] = PathElement::Quadratic(x.get(), y.get());
866                });
867                false
868            },
869            &deps,
870        ));
871    }
872
873    // Removes this child command from the parent `Path`.
874    pub fn on_unmount(&mut self, ctx: &NodeContext) {
875        let path_elems = ctx
876            .peek_local_store(|path_ctx: &mut PathContext| path_ctx.elements.clone())
877            .expect("path point can only exist in <Path> tag");
878        let id = ctx.slot_index.get().unwrap();
879        path_elems.update(|elems| {
880            if id < elems.len() {
881                elems.remove(id);
882            }
883        });
884    }
885
886    // Forces the path-command computed property to run.
887    pub fn pre_render(&mut self, _ctx: &NodeContext) {
888        self._on_change.get();
889    }
890}