Skip to main content

pax_std/drawing/
path.rs

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