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::{Attribute, ClassList, NodeBlueprint, Tag, View};
8use strata_macro::component;
9pub use strata_render::canvas2d::{Canvas2DContext, CanvasCommand, CanvasPathVerb};
10
11/// Declarative Immediate-Mode 2D Vector Canvas Component.
12///
13/// Executes an immediate-mode drawing closure `on_draw` via `Canvas2DContext`
14/// with subpixel anti-aliasing and affine transforms.
15#[component]
16pub fn Canvas2D(
17    width: Option<f32>,
18    height: Option<f32>,
19    class: Option<&'static str>,
20    on_draw: Option<Rc<dyn Fn(&mut Canvas2DContext)>>,
21) -> View {
22    let w = width.unwrap_or(400.0);
23    let h = height.unwrap_or(300.0);
24    let custom = class.unwrap_or("");
25
26    let mut ctx = Canvas2DContext::new(w, h);
27    if let Some(draw_fn) = &on_draw {
28        draw_fn(&mut ctx);
29    }
30    let commands: Arc<Vec<CanvasCommand>> = Arc::new(ctx.finish());
31    let payload: Arc<dyn std::any::Any + Send + Sync> = commands;
32
33    let mut attrs = Vec::with_capacity(4);
34    attrs.push(Attribute::property("width", w.to_string()));
35    attrs.push(Attribute::property("height", h.to_string()));
36    let mut style_str = String::new();
37    if let Some(ew) = width {
38        style_str.push_str(&format!("width: {}px; ", ew));
39    }
40    if let Some(eh) = height {
41        style_str.push_str(&format!("height: {}px; ", eh));
42    }
43    if !style_str.is_empty() {
44        attrs.push(Attribute::property("style", style_str.trim()));
45    }
46    attrs.push(Attribute::scene_payload_arc(payload));
47
48    let class_str = if custom.is_empty() {
49        "relative overflow-hidden bg-neutral-950 rounded-xl border border-neutral-800/80".to_string()
50    } else {
51        format!(
52            "relative overflow-hidden bg-neutral-950 rounded-xl border border-neutral-800/80 {}",
53            custom
54        )
55    };
56
57    View::new(NodeBlueprint::element(
58        Tag::Div,
59        ClassList::from(vec![class_str]),
60        attrs,
61        Vec::new(),
62    ))
63}