svg.rs

 1use crate::{
 2    Bounds, Element, ElementId, InteractiveElement, InteractiveElementState, Interactivity,
 3    IntoElement, LayoutId, Pixels, SharedString, StyleRefinement, Styled, WindowContext,
 4};
 5use util::ResultExt;
 6
 7pub struct Svg {
 8    interactivity: Interactivity,
 9    path: Option<SharedString>,
10}
11
12pub fn svg() -> Svg {
13    Svg {
14        interactivity: Interactivity::default(),
15        path: None,
16    }
17}
18
19impl Svg {
20    pub fn path(mut self, path: impl Into<SharedString>) -> Self {
21        self.path = Some(path.into());
22        self
23    }
24}
25
26impl Element for Svg {
27    type State = InteractiveElementState;
28
29    fn layout(
30        &mut self,
31        element_state: Option<Self::State>,
32        cx: &mut WindowContext,
33    ) -> (LayoutId, Self::State) {
34        self.interactivity.layout(element_state, cx, |style, cx| {
35            cx.request_layout(&style, None)
36        })
37    }
38
39    fn paint(
40        &mut self,
41        bounds: Bounds<Pixels>,
42        element_state: &mut Self::State,
43        cx: &mut WindowContext,
44    ) where
45        Self: Sized,
46    {
47        self.interactivity
48            .paint(bounds, bounds.size, element_state, cx, |style, _, cx| {
49                if let Some((path, color)) = self.path.as_ref().zip(style.text.color) {
50                    cx.paint_svg(bounds, path.clone(), color).log_err();
51                }
52            })
53    }
54}
55
56impl IntoElement for Svg {
57    type Element = Self;
58
59    fn element_id(&self) -> Option<ElementId> {
60        self.interactivity.element_id.clone()
61    }
62
63    fn into_element(self) -> Self::Element {
64        self
65    }
66}
67
68impl Styled for Svg {
69    fn style(&mut self) -> &mut StyleRefinement {
70        &mut self.interactivity.base_style
71    }
72}
73
74impl InteractiveElement for Svg {
75    fn interactivity(&mut self) -> &mut Interactivity {
76        &mut self.interactivity
77    }
78}