Skip to main content

strata_ui/
canvas.rs

1//! Declarative Immediate-Mode `<Canvas2D>` Component for Strata UI.
2
3#![allow(non_snake_case)]
4
5use std::rc::Rc;
6use std::sync::Arc;
7use strata_dom::{
8    Attribute, ClassList, Event, EventHandlerMarker, EventType, IntoChildren, IntoClassList,
9    IntoOptionalString, NodeBlueprint, Tag, View,
10};
11pub use strata_render::canvas2d::{
12    Canvas2DContext, Canvas2DPaintCallback, CanvasCommand, CanvasLineCap, CanvasLineJoin,
13    CanvasPathVerb, CanvasTextAlign, CanvasTextBaseline, CanvasTextMetrics, IntoRoundRectRadii,
14};
15
16/// Ergonomic conversion into CSS class tokens for `<Canvas2D class={...} />`.
17pub trait IntoCanvasClass {
18    fn into_canvas_class_tokens(self) -> Vec<String>;
19}
20
21impl<T: IntoClassList> IntoCanvasClass for T {
22    fn into_canvas_class_tokens(self) -> Vec<String> {
23        self.into_class_list().iter().map(str::to_string).collect()
24    }
25}
26
27/// Marker conversion for `on_draw={...}` supporting `Rc<dyn Fn(&mut Canvas2DContext)>`,
28/// `Option<Rc<...>>`, and inline closures.
29pub trait IntoCanvasDrawProp<Marker = ()> {
30    fn into_canvas_draw_prop(self) -> Option<Rc<dyn Fn(&mut Canvas2DContext)>>;
31}
32
33impl IntoCanvasDrawProp<()> for Option<Rc<dyn Fn(&mut Canvas2DContext)>> {
34    fn into_canvas_draw_prop(self) -> Option<Rc<dyn Fn(&mut Canvas2DContext)>> {
35        self
36    }
37}
38
39impl IntoCanvasDrawProp<()> for Rc<dyn Fn(&mut Canvas2DContext)> {
40    fn into_canvas_draw_prop(self) -> Option<Rc<dyn Fn(&mut Canvas2DContext)>> {
41        Some(self)
42    }
43}
44
45impl<F: Fn(&mut Canvas2DContext) + 'static> IntoCanvasDrawProp<((),)> for F {
46    fn into_canvas_draw_prop(self) -> Option<Rc<dyn Fn(&mut Canvas2DContext)>> {
47        Some(Rc::new(self))
48    }
49}
50
51/// Marker conversion for post-layout `on_paint={|ctx, width, height| ...}` callbacks.
52pub trait IntoCanvasPaintProp<Marker = ()> {
53    fn into_canvas_paint_prop(self) -> Option<Rc<dyn Fn(&mut Canvas2DContext, f32, f32)>>;
54}
55
56impl IntoCanvasPaintProp<()> for Option<Rc<dyn Fn(&mut Canvas2DContext, f32, f32)>> {
57    fn into_canvas_paint_prop(self) -> Option<Rc<dyn Fn(&mut Canvas2DContext, f32, f32)>> {
58        self
59    }
60}
61
62impl IntoCanvasPaintProp<()> for Rc<dyn Fn(&mut Canvas2DContext, f32, f32)> {
63    fn into_canvas_paint_prop(self) -> Option<Rc<dyn Fn(&mut Canvas2DContext, f32, f32)>> {
64        Some(self)
65    }
66}
67
68impl<F: Fn(&mut Canvas2DContext, f32, f32) + 'static> IntoCanvasPaintProp<((),)> for F {
69    fn into_canvas_paint_prop(self) -> Option<Rc<dyn Fn(&mut Canvas2DContext, f32, f32)>> {
70        Some(Rc::new(self))
71    }
72}
73
74/// Declarative Immediate-Mode 2D Vector Canvas Component.
75///
76/// Supports either fixed-size eager drawing (`width`/`height` + `on_draw`) or responsive
77/// container sizing (`responsive: true` or omitted `width`/`height` with `class="w-full h-full"` /
78/// flex growth) paired with post-layout `on_paint(|ctx, w, h| ...)`.
79#[derive(Default)]
80pub struct Canvas2D {}
81
82impl Canvas2D {
83    pub fn builder() -> Canvas2DBuilder {
84        Canvas2DBuilder::default()
85    }
86}
87
88/// Builder powering `<Canvas2D ... />` in `rsx!`.
89#[derive(Default)]
90pub struct Canvas2DBuilder {
91    pub width: Option<f32>,
92    pub height: Option<f32>,
93    pub responsive: bool,
94    pub class_tokens: Vec<String>,
95    pub style: Option<String>,
96    pub id: Option<String>,
97    pub title: Option<String>,
98    pub __strata_key: Option<String>,
99    pub on_draw: Option<Rc<dyn Fn(&mut Canvas2DContext)>>,
100    pub on_paint: Option<Rc<dyn Fn(&mut Canvas2DContext, f32, f32)>>,
101    pub events: Vec<Attribute>,
102    pub children: Option<Vec<NodeBlueprint>>,
103}
104
105impl Canvas2DBuilder {
106    pub fn width(mut self, width: impl Into<Option<f32>>) -> Self {
107        self.width = width.into();
108        self
109    }
110
111    pub fn height(mut self, height: impl Into<Option<f32>>) -> Self {
112        self.height = height.into();
113        self
114    }
115
116    /// When `true`, omits inline pixel `width`/`height` styles and attributes so CSS/flex classes
117    /// (`w-full h-full`, `flex-1`, split panes) control the resolved viewport size.
118    pub fn responsive(mut self, responsive: bool) -> Self {
119        self.responsive = responsive;
120        self
121    }
122
123    pub fn class(mut self, class: impl IntoCanvasClass) -> Self {
124        self.class_tokens = class.into_canvas_class_tokens();
125        self
126    }
127
128    pub fn style(mut self, style: impl Into<String>) -> Self {
129        self.style = Some(style.into());
130        self
131    }
132
133    pub fn id(mut self, id: impl Into<String>) -> Self {
134        self.id = Some(id.into());
135        self
136    }
137
138    pub fn title(mut self, title: impl IntoOptionalString) -> Self {
139        self.title = title.into_optional_string();
140        self
141    }
142
143    pub fn key(mut self, key: impl std::fmt::Display) -> Self {
144        self.__strata_key = Some(key.to_string());
145        self
146    }
147
148    pub fn children(mut self, children: impl IntoChildren<Vec<NodeBlueprint>>) -> Self {
149        self.children = Some(children.into_children());
150        self
151    }
152
153    pub fn on_draw<M>(mut self, cb: impl IntoCanvasDrawProp<M>) -> Self {
154        self.on_draw = cb.into_canvas_draw_prop();
155        self
156    }
157
158    pub fn on_draw_fn(mut self, cb: impl Fn(&mut Canvas2DContext) + 'static) -> Self {
159        self.on_draw = Some(Rc::new(cb));
160        self
161    }
162
163    /// Registers a post-layout paint hook invoked during display-list compilation with the
164    /// resolved `LayoutNode` dimensions `(width, height)`.
165    pub fn on_paint<M>(mut self, cb: impl IntoCanvasPaintProp<M>) -> Self {
166        self.on_paint = cb.into_canvas_paint_prop();
167        self
168    }
169
170    pub fn on_paint_fn(mut self, cb: impl Fn(&mut Canvas2DContext, f32, f32) + 'static) -> Self {
171        self.on_paint = Some(Rc::new(cb));
172        self
173    }
174
175    fn push_event<Args>(
176        mut self,
177        ty: EventType,
178        handler: impl EventHandlerMarker<Args> + 'static,
179    ) -> Self {
180        self.events.push(Attribute::event_listener(ty, handler));
181        self
182    }
183
184    pub fn onclick<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
185        self.push_event(EventType::Click, handler)
186    }
187
188    pub fn onclick_fn(self, handler: impl Fn() + 'static) -> Self {
189        self.push_event(EventType::Click, handler)
190    }
191
192    pub fn ondblclick<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
193        self.push_event(EventType::DblClick, handler)
194    }
195
196    pub fn ondblclick_fn(self, handler: impl Fn(Event) + 'static) -> Self {
197        self.push_event(EventType::DblClick, handler)
198    }
199
200    pub fn oncontextmenu<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
201        self.push_event(EventType::ContextMenu, handler)
202    }
203
204    pub fn oncontextmenu_fn(self, handler: impl Fn(Event) + 'static) -> Self {
205        self.push_event(EventType::ContextMenu, handler)
206    }
207
208    pub fn onmousedown<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
209        self.push_event(EventType::MouseDown, handler)
210    }
211
212    pub fn onmousedown_fn(self, handler: impl Fn(Event) + 'static) -> Self {
213        self.push_event(EventType::MouseDown, handler)
214    }
215
216    pub fn onmousemove<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
217        self.push_event(EventType::MouseMove, handler)
218    }
219
220    pub fn onmousemove_fn(self, handler: impl Fn(Event) + 'static) -> Self {
221        self.push_event(EventType::MouseMove, handler)
222    }
223
224    pub fn onmouseup<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
225        self.push_event(EventType::MouseUp, handler)
226    }
227
228    pub fn onmouseup_fn(self, handler: impl Fn(Event) + 'static) -> Self {
229        self.push_event(EventType::MouseUp, handler)
230    }
231
232    pub fn onmouseenter<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
233        self.push_event(EventType::MouseEnter, handler)
234    }
235
236    pub fn onmouseenter_fn(self, handler: impl Fn(Event) + 'static) -> Self {
237        self.push_event(EventType::MouseEnter, handler)
238    }
239
240    pub fn onmouseleave<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
241        self.push_event(EventType::MouseLeave, handler)
242    }
243
244    pub fn onmouseleave_fn(self, handler: impl Fn(Event) + 'static) -> Self {
245        self.push_event(EventType::MouseLeave, handler)
246    }
247
248    pub fn onwheel<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
249        self.push_event(EventType::Wheel, handler)
250    }
251
252    pub fn onwheel_fn(self, handler: impl Fn(Event) + 'static) -> Self {
253        self.push_event(EventType::Wheel, handler)
254    }
255
256    pub fn onpointerdown<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
257        self.push_event(EventType::PointerDown, handler)
258    }
259
260    pub fn onpointerdown_fn(self, handler: impl Fn(Event) + 'static) -> Self {
261        self.push_event(EventType::PointerDown, handler)
262    }
263
264    pub fn onpointermove<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
265        self.push_event(EventType::PointerMove, handler)
266    }
267
268    pub fn onpointermove_fn(self, handler: impl Fn(Event) + 'static) -> Self {
269        self.push_event(EventType::PointerMove, handler)
270    }
271
272    pub fn onpointerup<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
273        self.push_event(EventType::PointerUp, handler)
274    }
275
276    pub fn onpointerup_fn(self, handler: impl Fn(Event) + 'static) -> Self {
277        self.push_event(EventType::PointerUp, handler)
278    }
279
280    pub fn onresize<Args>(self, handler: impl EventHandlerMarker<Args> + 'static) -> Self {
281        self.push_event(EventType::Resize, handler)
282    }
283
284    pub fn onresize_fn(self, handler: impl Fn(Event) + 'static) -> Self {
285        self.push_event(EventType::Resize, handler)
286    }
287
288    pub fn build(self) -> View {
289        let render = move || {
290            let _scope = strata_dom::ComponentScopeGuard::enter(concat!(
291                module_path!(),
292                "::Canvas2D"
293            ));
294            let is_responsive = self.responsive || (self.width.is_none() && self.height.is_none());
295
296            let mut attrs = Vec::with_capacity(7 + self.events.len());
297            attrs.push(Attribute::property("data-strata-canvas2d", "true"));
298            if let Some(ref id) = self.id {
299                attrs.push(Attribute::property("id", id.clone()));
300            }
301            if let Some(ref title) = self.title {
302                attrs.push(Attribute::property("title", title.clone()));
303            }
304
305            let mut style_str = String::new();
306            if !is_responsive {
307                if let Some(ew) = self.width {
308                    attrs.push(Attribute::property("width", ew.to_string()));
309                    style_str.push_str(&format!("width: {}px; ", ew));
310                }
311                if let Some(eh) = self.height {
312                    attrs.push(Attribute::property("height", eh.to_string()));
313                    style_str.push_str(&format!("height: {}px; ", eh));
314                }
315            }
316            if let Some(ref extra_style) = self.style {
317                if !extra_style.trim().is_empty() {
318                    style_str.push_str(extra_style.trim());
319                }
320            }
321            if !style_str.trim().is_empty() {
322                attrs.push(Attribute::property("style", style_str.trim()));
323            }
324
325            if let Some(paint_fn) = self.on_paint {
326                let payload: Arc<dyn std::any::Any + Send + Sync> =
327                    Canvas2DPaintCallback::new(paint_fn);
328                attrs.push(Attribute::scene_payload_arc(payload));
329            } else {
330                let w = self.width.unwrap_or(400.0);
331                let h = self.height.unwrap_or(300.0);
332                let mut ctx = Canvas2DContext::new(w, h);
333                if let Some(draw_fn) = &self.on_draw {
334                    draw_fn(&mut ctx);
335                }
336                let commands: Arc<Vec<CanvasCommand>> = Arc::new(ctx.finish());
337                let payload: Arc<dyn std::any::Any + Send + Sync> = commands;
338                attrs.push(Attribute::scene_payload_arc(payload));
339            }
340            attrs.extend(self.events);
341
342            let mut class_vec: Vec<String> = [
343                "relative",
344                "overflow-hidden",
345                "bg-neutral-950",
346                "rounded-xl",
347                "border",
348                "border-neutral-800/80",
349            ]
350            .into_iter()
351            .map(str::to_string)
352            .collect();
353            class_vec.extend(self.class_tokens);
354
355            View::new(NodeBlueprint::element(
356                Tag::Div,
357                ClassList::from(class_vec),
358                attrs,
359                self.children.unwrap_or_default(),
360            ))
361        };
362
363        if let Some(k) = self.__strata_key {
364            strata_dom::with_component_key(k, render)
365        } else {
366            render()
367        }
368    }
369}
370
371/// Declarative Immediate-Mode 2D Vector Canvas Component function entrypoint.
372///
373/// Preserves positional calls `Canvas2D(width, height, class, on_draw)`; for responsive
374/// post-layout sizing (`responsive`, `on_paint`, dynamic `ClassList`/`String` classes), use
375/// `<Canvas2D ... />` or [`Canvas2D::builder`].
376pub fn Canvas2D(
377    width: Option<f32>,
378    height: Option<f32>,
379    class: Option<&'static str>,
380    on_draw: Option<Rc<dyn Fn(&mut Canvas2DContext)>>,
381) -> View {
382    Canvas2D::builder()
383        .width(width)
384        .height(height)
385        .class(class.map(str::to_string))
386        .on_draw(on_draw)
387        .build()
388}