Skip to main content

oxframe_2d/
builder.rs

1use kurbo::{BezPath, Vec2};
2use oxframe_core::{BlendMode, Color, Gradient, Signal};
3use oxframe_text::TextStyle;
4
5use crate::draw::{LineCap, LineJoin};
6use crate::graph::{Direction, Justify, LayoutAlign, NodeId, NodeKind, SceneGraph, with_graph};
7use crate::handles::{
8    Circle, Code, Grid, Group, Img, Layout, Line, Path, Polygon, Rect, Star, Txt,
9};
10use crate::image::ImageSource;
11use crate::place::{self, Axis, Edge, Place, Side, Span};
12use crate::text::{CodeTheme, RichSpan};
13use crate::theme::{self, Corner, IntoPaint, Len, Step, TypeRole};
14
15/// Initial values shared by every node; set through [`NodeBuilder`] methods.
16#[doc(hidden)]
17#[derive(Debug)]
18pub struct BaseProps {
19    pub name: Option<String>,
20    pub x: f64,
21    pub y: f64,
22    pub rotation: f64,
23    pub scale: Vec2,
24    pub opacity: f64,
25    pub fill: Color,
26    /// Set when `fill` was chosen explicitly. Text leaves this false and
27    /// takes the theme's text color at build time.
28    pub fill_explicit: bool,
29    pub stroke: Color,
30    pub line_width: f64,
31    pub start: f64,
32    pub end: f64,
33    pub fill_gradient: Option<Gradient>,
34    pub stroke_gradient: Option<Gradient>,
35    pub dash: Vec<f64>,
36    pub dash_offset: f64,
37    pub line_cap: LineCap,
38    pub line_join: LineJoin,
39    pub blur: f64,
40    pub shadow_color: Color,
41    pub shadow_blur: f64,
42    pub shadow_offset: Vec2,
43    pub clip: bool,
44    pub blend: BlendMode,
45    pub z_index: f64,
46    pub anchor: Vec2,
47    pub grow: f64,
48    pub shrink: f64,
49    pub basis: Option<f64>,
50    pub margin: f64,
51    pub align_self: Option<LayoutAlign>,
52    pub children: Vec<ChildBuilder>,
53    /// Resolved every frame. Set by `next_to`, `align_to`, `to_edge`, `center_in`.
54    pub place: Option<Place>,
55}
56
57impl Default for BaseProps {
58    fn default() -> Self {
59        Self {
60            name: None,
61            x: 0.0,
62            y: 0.0,
63            rotation: 0.0,
64            scale: Vec2::new(1.0, 1.0),
65            opacity: 1.0,
66            fill: Color::TRANSPARENT,
67            fill_explicit: false,
68            stroke: Color::TRANSPARENT,
69            line_width: 0.0,
70            start: 0.0,
71            end: 1.0,
72            fill_gradient: None,
73            stroke_gradient: None,
74            dash: Vec::new(),
75            dash_offset: 0.0,
76            line_cap: LineCap::Round,
77            line_join: LineJoin::Round,
78            blur: 0.0,
79            shadow_color: Color::TRANSPARENT,
80            shadow_blur: 0.0,
81            shadow_offset: Vec2::ZERO,
82            clip: false,
83            blend: BlendMode::Normal,
84            z_index: 0.0,
85            anchor: Vec2::ZERO,
86            grow: 0.0,
87            shrink: 0.0,
88            basis: None,
89            margin: 0.0,
90            align_self: None,
91            children: Vec::new(),
92            place: None,
93        }
94    }
95}
96
97/// A type-erased child added with [`NodeBuilder::child`].
98type BuildFn = Box<dyn FnOnce(&SceneGraph, NodeId)>;
99
100/// A child declared with [`NodeBuilder::child`], built together with its parent.
101pub struct ChildBuilder(BuildFn);
102
103impl std::fmt::Debug for ChildBuilder {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.write_str("ChildBuilder")
106    }
107}
108
109/// Describes a node before it is added to the scene.
110pub trait NodeBuilder: Sized + 'static {
111    /// Handle returned by [`Node::add`](crate::Node::add).
112    type Handle;
113
114    #[doc(hidden)]
115    fn base(&mut self) -> &mut BaseProps;
116
117    #[doc(hidden)]
118    fn build(self, graph: &SceneGraph, parent: NodeId) -> Self::Handle;
119
120    /// Name shown in the editor and in `oxframe check` / `oxframe inspect`.
121    /// Without it, the node is labeled by the `add` call site (`src/main.rs:42`).
122    fn name(mut self, v: impl Into<String>) -> Self {
123        self.base().name = Some(v.into());
124        self
125    }
126    /// Horizontal position; 0 is the parent's center, positive is right.
127    fn x(mut self, v: f64) -> Self {
128        self.base().x = v;
129        self
130    }
131    /// Vertical position; 0 is the parent's center, positive is down.
132    fn y(mut self, v: f64) -> Self {
133        self.base().y = v;
134        self
135    }
136    /// Sets `x` and `y` together, e.g. `.position((100.0, -50.0))`.
137    fn position(mut self, v: impl Into<Vec2>) -> Self {
138        let v = v.into();
139        let b = self.base();
140        (b.x, b.y) = (v.x, v.y);
141        self
142    }
143    /// Degrees, clockwise.
144    fn rotation(mut self, v: f64) -> Self {
145        self.base().rotation = v;
146        self
147    }
148    /// Uniform scale; 1 is the natural size.
149    fn scale(mut self, v: f64) -> Self {
150        self.base().scale = Vec2::new(v, v);
151        self
152    }
153    /// Separate horizontal and vertical scale.
154    fn scale_xy(mut self, v: impl Into<Vec2>) -> Self {
155        self.base().scale = v.into();
156        self
157    }
158    /// Opacity of the node and its children, 0 (invisible) to 1.
159    fn opacity(mut self, v: f64) -> Self {
160        self.base().opacity = v;
161        self
162    }
163    /// Fill color: a [`Color`](oxframe_core::Color) or a theme role such as `Accent`.
164    /// Default: transparent, except text, which uses the theme's text color.
165    fn fill(mut self, v: impl IntoPaint) -> Self {
166        let b = self.base();
167        b.fill = v.into_paint();
168        b.fill_explicit = true;
169        self
170    }
171    /// Outline color; also set `line_width`. A theme role works the same as a color.
172    /// Default: transparent.
173    fn stroke(mut self, v: impl IntoPaint) -> Self {
174        self.base().stroke = v.into_paint();
175        self
176    }
177    /// Outline width in pixels. Default: 0 (no outline).
178    fn line_width(mut self, v: f64) -> Self {
179        self.base().line_width = v;
180        self
181    }
182    /// Start of the drawn part of the outline, fraction of its length.
183    fn start(mut self, v: f64) -> Self {
184        self.base().start = v;
185        self
186    }
187    /// End of the drawn part of the outline; animate 0 → 1 to draw it on.
188    fn end(mut self, v: f64) -> Self {
189        self.base().end = v;
190        self
191    }
192    /// Gradient fill (local coordinates, origin at the node center);
193    /// overrides `fill`.
194    fn fill_gradient(mut self, g: Gradient) -> Self {
195        self.base().fill_gradient = Some(g);
196        self
197    }
198    /// Gradient outline; overrides `stroke`.
199    fn stroke_gradient(mut self, g: Gradient) -> Self {
200        self.base().stroke_gradient = Some(g);
201        self
202    }
203    /// Dash pattern: on, off, on, … lengths. Animate `dash_offset` for
204    /// marching ants.
205    fn dash(mut self, pattern: impl Into<Vec<f64>>) -> Self {
206        self.base().dash = pattern.into();
207        self
208    }
209    /// Shifts the dash pattern along the outline.
210    fn dash_offset(mut self, v: f64) -> Self {
211        self.base().dash_offset = v;
212        self
213    }
214    /// Shape of outline ends. Default: round.
215    fn line_cap(mut self, v: LineCap) -> Self {
216        self.base().line_cap = v;
217        self
218    }
219    /// Shape of outline corners. Default: round.
220    fn line_join(mut self, v: LineJoin) -> Self {
221        self.base().line_join = v;
222        self
223    }
224    /// Gaussian blur of the node and its children (standard deviation, in
225    /// the node's units).
226    fn blur(mut self, v: f64) -> Self {
227        self.base().blur = v;
228        self
229    }
230    /// Drop shadow under the node and its children.
231    fn shadow(mut self, color: impl IntoPaint, blur: f64, offset: impl Into<Vec2>) -> Self {
232        let b = self.base();
233        (b.shadow_color, b.shadow_blur, b.shadow_offset) =
234            (color.into_paint(), blur, offset.into());
235        self
236    }
237    /// The theme's shadow for this step (`Xs` and `Sm` are the small one, `Xl` the large).
238    fn elevation(self, step: Step) -> Self {
239        let s = theme::current().shadow(step);
240        self.shadow(s.color, s.blur, s.offset)
241    }
242    /// A shadow without offset.
243    fn glow(self, color: impl IntoPaint, blur: f64) -> Self {
244        self.shadow(color, blur, Vec2::ZERO)
245    }
246    /// Clip children to this node's outline (or box).
247    fn clip(mut self, v: bool) -> Self {
248        self.base().clip = v;
249        self
250    }
251    /// How the node is composited onto what is below it.
252    fn blend(mut self, v: BlendMode) -> Self {
253        self.base().blend = v;
254        self
255    }
256    /// Paint order among siblings; higher is on top.
257    fn z_index(mut self, v: f64) -> Self {
258        self.base().z_index = v;
259        self
260    }
261    /// Pivot and placement point: (-1, -1) top-left … (1, 1) bottom-right.
262    fn anchor(mut self, v: impl Into<Vec2>) -> Self {
263        self.base().anchor = v.into();
264        self
265    }
266    /// Inside a `Layout`: share of the free space this node takes.
267    fn grow(mut self, v: f64) -> Self {
268        self.base().grow = v;
269        self
270    }
271    /// Inside a `Layout`: how much this node gives up when space is short.
272    fn shrink(mut self, v: f64) -> Self {
273        self.base().shrink = v;
274        self
275    }
276    /// Inside a `Layout`: main-axis size before growing/shrinking.
277    fn basis(mut self, v: f64) -> Self {
278        self.base().basis = Some(v);
279        self
280    }
281    /// Inside a `Layout`: space around this node, in pixels or a theme step (`.margin(Md)`).
282    fn margin(mut self, v: impl Len) -> Self {
283        self.base().margin = v.px();
284        self
285    }
286    /// Inside a `Layout`: overrides the layout's cross-axis alignment.
287    fn align_self(mut self, v: LayoutAlign) -> Self {
288        self.base().align_self = Some(v);
289        self
290    }
291    /// Sits just outside `other`, on `side`. The gap is the theme's `Md`
292    /// step. Recomputed every frame, so this node follows `other`.
293    fn next_to(mut self, other: impl Into<crate::Node>, side: Side) -> Self {
294        self.base().place = Some(Place::next_to(other.into().id(), side));
295        self
296    }
297    /// Lines this node's `edge` up with the same edge of `other`.
298    fn align_to(mut self, other: impl Into<crate::Node>, edge: Edge) -> Self {
299        self.base().place = Some(Place::align_to(other.into().id(), edge));
300        self
301    }
302    /// Pins one edge to the safe area (not the raw frame edge). The other
303    /// axis stays at `x` or `y`.
304    fn to_edge(mut self, edge: Edge) -> Self {
305        self.base().place = Some(Place::to_edge(edge));
306        self
307    }
308    /// Same center as `other`. Pass the view to center in the frame.
309    fn center_in(mut self, other: impl Into<crate::Node>) -> Self {
310        self.base().place = Some(Place::center_in(other.into().id()));
311        self
312    }
313    /// Adds a child created together with this node. Use `Node::add` when
314    /// you need the child's handle.
315    fn child<C: NodeBuilder>(mut self, child: C) -> Self {
316        self.base()
317            .children
318            .push(ChildBuilder(Box::new(move |g, parent| {
319                child.build(g, parent);
320            })));
321        self
322    }
323}
324
325pub(crate) fn add<B: NodeBuilder>(parent: NodeId, builder: B) -> B::Handle {
326    with_graph(|g| builder.build(g, parent))
327}
328
329/// Inserts the node and then its declared children.
330fn insert(graph: &SceneGraph, parent: NodeId, kind: NodeKind, mut base: BaseProps) -> NodeId {
331    let children = std::mem::take(&mut base.children);
332    let id = graph.insert(Some(parent), kind, base);
333    for c in children {
334        (c.0)(graph, id);
335    }
336    id
337}
338
339fn sig<T: Clone + 'static>(graph: &SceneGraph, kind: &str, field: &str, v: T) -> Signal<T> {
340    Signal::new(v).with_name(format!("{kind}#{}.{field}", graph.next_id()))
341}
342
343macro_rules! builder {
344    (
345        $(#[$doc:meta])*
346        $builder:ident => $handle:ident, kind $kind:literal, defaults { $($bf:ident: $bv:expr),* $(,)? },
347        fields { $($field:ident: $ty:ty = $default:expr),* $(,)? }
348    ) => {
349        $(#[$doc])*
350        #[doc = ""]
351        #[doc = concat!("Builder for a [`", stringify!($handle), "`] node: set the initial values, then")]
352        #[doc = "pass it to `add`."]
353        #[derive(Debug)]
354        #[must_use = "a builder does nothing until it is passed to `add`"]
355        pub struct $builder {
356            base: BaseProps,
357            $(pub(crate) $field: $ty,)*
358        }
359
360        impl Default for $builder {
361            fn default() -> Self {
362                Self {
363                    base: BaseProps { $($bf: $bv,)* ..Default::default() },
364                    $($field: $default,)*
365                }
366            }
367        }
368
369        impl $builder {
370            #[allow(dead_code)]
371            const KIND: &'static str = $kind;
372        }
373    };
374}
375
376macro_rules! setters {
377    ($builder:ident { $($(#[$doc:meta])* $field:ident: $ty:ty),* $(,)? }) => {
378        impl $builder {
379            $(
380                $(#[$doc])*
381                #[doc = ""]
382                #[doc = concat!("Sets the initial `", stringify!($field), "`.")]
383                pub fn $field(mut self, v: impl Into<$ty>) -> Self {
384                    self.$field = v.into();
385                    self
386                }
387            )*
388        }
389    };
390}
391
392macro_rules! base_accessor {
393    () => {
394        fn base(&mut self) -> &mut BaseProps {
395            &mut self.base
396        }
397    };
398}
399
400// ------------------------------------------------------------------ Group
401
402builder!(GroupBuilder => Group, kind "Group", defaults {}, fields {});
403
404impl NodeBuilder for GroupBuilder {
405    type Handle = Group;
406    base_accessor!();
407    fn build(self, graph: &SceneGraph, parent: NodeId) -> Group {
408        Group::from_id(insert(graph, parent, NodeKind::Group, self.base))
409    }
410}
411
412// ------------------------------------------------------------------- Rect
413
414builder!(RectBuilder => Rect, kind "Rect", defaults { fill: Color::WHITE, fill_explicit: true },
415    fields { width: Span = Span::Px(100.0), height: Span = Span::Px(100.0), radius: f64 = 0.0 });
416
417impl RectBuilder {
418    /// Width in pixels, or [`pct`](crate::pct)`(80)` for a fraction of the frame.
419    pub fn width(mut self, v: impl Into<Span>) -> Self {
420        self.width = v.into();
421        self
422    }
423    /// Height in pixels, or a percentage of the frame.
424    pub fn height(mut self, v: impl Into<Span>) -> Self {
425        self.height = v.into();
426        self
427    }
428    /// Corner radius, in pixels or a theme step (`.radius(Md)`).
429    /// Clamped to half of the shorter side when drawn.
430    pub fn radius(mut self, v: impl Corner) -> Self {
431        self.radius = v.radius();
432        self
433    }
434    /// Sets width and height to the same pixel size.
435    pub fn size(mut self, v: f64) -> Self {
436        (self.width, self.height) = (Span::Px(v), Span::Px(v));
437        self
438    }
439}
440
441impl NodeBuilder for RectBuilder {
442    type Handle = Rect;
443    base_accessor!();
444    fn build(self, g: &SceneGraph, parent: NodeId) -> Rect {
445        let k = Self::KIND;
446        let n = g.next_id();
447        let kind = NodeKind::Rect {
448            width: place::span_signal(g, parent, Axis::X, self.width, format!("{k}#{n}.width")),
449            height: place::span_signal(g, parent, Axis::Y, self.height, format!("{k}#{n}.height")),
450            radius: sig(g, k, "radius", self.radius),
451        };
452        Rect::from_id(insert(g, parent, kind, self.base))
453    }
454}
455
456// ----------------------------------------------------------------- Circle
457
458builder!(CircleBuilder => Circle, kind "Circle", defaults { fill: Color::WHITE, fill_explicit: true },
459    fields { size: f64 = 100.0, start_angle: f64 = 0.0, end_angle: f64 = 360.0, pie: bool = false });
460setters!(CircleBuilder {
461    /// Diameter.
462    size: f64,
463    /// Degrees clockwise from 12 o'clock.
464    start_angle: f64,
465    end_angle: f64,
466    /// Close the arc through the center (pie slice).
467    pie: bool
468});
469
470impl NodeBuilder for CircleBuilder {
471    type Handle = Circle;
472    base_accessor!();
473    fn build(self, g: &SceneGraph, parent: NodeId) -> Circle {
474        let k = Self::KIND;
475        let kind = NodeKind::Circle {
476            size: sig(g, k, "size", self.size),
477            start_angle: sig(g, k, "start_angle", self.start_angle),
478            end_angle: sig(g, k, "end_angle", self.end_angle),
479            pie: self.pie,
480        };
481        Circle::from_id(insert(g, parent, kind, self.base))
482    }
483}
484
485// ---------------------------------------------------------------- Polygon
486
487builder!(PolygonBuilder => Polygon, kind "Polygon", defaults { fill: Color::WHITE, fill_explicit: true },
488    fields { sides: f64 = 6.0, size: f64 = 100.0 });
489setters!(PolygonBuilder {
490    /// Number of sides (rounded; animatable as a number).
491    sides: f64,
492    /// Diameter of the circumscribed circle.
493    size: f64
494});
495
496impl NodeBuilder for PolygonBuilder {
497    type Handle = Polygon;
498    base_accessor!();
499    fn build(self, g: &SceneGraph, parent: NodeId) -> Polygon {
500        let k = Self::KIND;
501        let kind = NodeKind::Polygon {
502            sides: sig(g, k, "sides", self.sides),
503            size: sig(g, k, "size", self.size),
504        };
505        Polygon::from_id(insert(g, parent, kind, self.base))
506    }
507}
508
509// ------------------------------------------------------------------- Star
510
511builder!(StarBuilder => Star, kind "Star", defaults { fill: Color::WHITE, fill_explicit: true },
512    fields { points: f64 = 5.0, size: f64 = 100.0, inner: f64 = 0.45 });
513setters!(StarBuilder {
514    points: f64,
515    /// Outer diameter.
516    size: f64,
517    /// Inner radius as a fraction of the outer one.
518    inner: f64
519});
520
521impl NodeBuilder for StarBuilder {
522    type Handle = Star;
523    base_accessor!();
524    fn build(self, g: &SceneGraph, parent: NodeId) -> Star {
525        let k = Self::KIND;
526        let kind = NodeKind::Star {
527            points: sig(g, k, "points", self.points),
528            size: sig(g, k, "size", self.size),
529            inner: sig(g, k, "inner", self.inner),
530        };
531        Star::from_id(insert(g, parent, kind, self.base))
532    }
533}
534
535// ------------------------------------------------------------------- Path
536
537builder!(PathBuilder => Path, kind "Path", defaults { fill: Color::WHITE, fill_explicit: true },
538    fields { data: BezPath = BezPath::new() });
539setters!(PathBuilder { data: BezPath });
540
541impl PathBuilder {
542    /// Path from SVG path syntax (`"M0 0 L10 0 Z"`).
543    ///
544    /// # Panics
545    ///
546    /// If `d` is not valid SVG path data.
547    pub fn svg(mut self, d: &str) -> Self {
548        self.data = BezPath::from_svg(d).unwrap_or_else(|e| panic!("invalid SVG path {d:?}: {e}"));
549        self
550    }
551}
552
553impl NodeBuilder for PathBuilder {
554    type Handle = Path;
555    base_accessor!();
556    fn build(self, g: &SceneGraph, parent: NodeId) -> Path {
557        let kind = NodeKind::Path {
558            data: sig(g, Self::KIND, "data", self.data),
559        };
560        Path::from_id(insert(g, parent, kind, self.base))
561    }
562}
563
564// ------------------------------------------------------------------- Line
565
566builder!(LineBuilder => Line, kind "Line",
567    defaults { stroke: Color::WHITE, line_width: 4.0 },
568    fields { points: Vec<Vec2> = Vec::new(), closed: bool = false, smooth: bool = false,
569             start_arrow: bool = false, end_arrow: bool = false, arrow_size: f64 = 24.0 });
570setters!(LineBuilder {
571    closed: bool,
572    /// Smooth curve through the points instead of straight segments.
573    smooth: bool,
574    start_arrow: bool,
575    end_arrow: bool,
576    arrow_size: f64
577});
578
579impl LineBuilder {
580    /// Points the line passes through, in local coordinates.
581    pub fn points<P: Into<Vec2>>(mut self, pts: impl IntoIterator<Item = P>) -> Self {
582        self.points = pts.into_iter().map(Into::into).collect();
583        self
584    }
585}
586
587impl NodeBuilder for LineBuilder {
588    type Handle = Line;
589    base_accessor!();
590    fn build(self, g: &SceneGraph, parent: NodeId) -> Line {
591        let kind = NodeKind::Line {
592            points: sig(g, Self::KIND, "points", self.points),
593            closed: self.closed,
594            smooth: self.smooth,
595            start_arrow: self.start_arrow,
596            end_arrow: self.end_arrow,
597            arrow_size: sig(g, Self::KIND, "arrow_size", self.arrow_size),
598        };
599        Line::from_id(insert(g, parent, kind, self.base))
600    }
601}
602
603// -------------------------------------------------------------------- Txt
604
605builder!(TxtBuilder => Txt, kind "Txt", defaults { fill: Color::WHITE },
606    fields { text: String = String::new(), spans: Vec<RichSpan> = Vec::new(),
607             style: TextStyle = TextStyle::default() });
608
609impl TxtBuilder {
610    /// The text to show.
611    pub fn text(mut self, v: impl Into<String>) -> Self {
612        self.text = v.into();
613        self
614    }
615    /// Styled runs instead of plain text: `[span("Hello "), span("world").bold()]`.
616    pub fn rich(mut self, spans: impl IntoIterator<Item = RichSpan>) -> Self {
617        self.spans = spans.into_iter().collect();
618        self
619    }
620    /// Font size in pixels. Default: 48.
621    pub fn font_size(mut self, v: f64) -> Self {
622        self.style.size = v;
623        self
624    }
625    /// 100..=900.
626    pub fn weight(mut self, v: f64) -> Self {
627        self.style.weight = v;
628        self
629    }
630    /// [`SANS`](crate::SANS), [`MONO`](crate::MONO) or a family registered
631    /// with `oxframe_text::register_font`.
632    pub fn family(mut self, v: impl Into<String>) -> Self {
633        self.style.family = v.into();
634        self
635    }
636    /// Italic style.
637    pub fn italic(mut self, v: bool) -> Self {
638        self.style.italic = v;
639        self
640    }
641    /// Multiple of the font size.
642    pub fn line_height(mut self, v: f64) -> Self {
643        self.style.line_height = v;
644        self
645    }
646    /// Extra space between letters, in pixels.
647    pub fn letter_spacing(mut self, v: f64) -> Self {
648        self.style.letter_spacing = v;
649        self
650    }
651    /// Alignment of lines within the text block.
652    pub fn align(mut self, v: crate::TextAlign) -> Self {
653        self.style.align = v;
654        self
655    }
656    /// Wrap width.
657    pub fn max_width(mut self, v: f64) -> Self {
658        self.style.max_width = Some(v);
659        self
660    }
661    /// Largest title from the theme.
662    pub fn display(self) -> Self {
663        self.role(TypeRole::Display)
664    }
665    /// Page title from the theme.
666    pub fn h1(self) -> Self {
667        self.role(TypeRole::H1)
668    }
669    /// Section title from the theme.
670    pub fn h2(self) -> Self {
671        self.role(TypeRole::H2)
672    }
673    /// Running text from the theme.
674    pub fn body(self) -> Self {
675        self.role(TypeRole::Body)
676    }
677    /// Secondary text from the theme.
678    pub fn caption(self) -> Self {
679        self.role(TypeRole::Caption)
680    }
681    /// Monospace text from the theme.
682    pub fn code(self) -> Self {
683        self.family(crate::MONO).role(TypeRole::Code)
684    }
685
686    fn role(mut self, role: TypeRole) -> Self {
687        let r = theme::current().role(role);
688        self.style.size = r.size;
689        self.style.weight = r.weight;
690        self.style.line_height = r.line_height;
691        self
692    }
693}
694
695impl NodeBuilder for TxtBuilder {
696    type Handle = Txt;
697    base_accessor!();
698    fn build(mut self, g: &SceneGraph, parent: NodeId) -> Txt {
699        if !self.base.fill_explicit {
700            self.base.fill = theme::current().text;
701        }
702        let k = Self::KIND;
703        let kind = NodeKind::Txt {
704            text: sig(g, k, "text", self.text),
705            spans: sig(g, k, "spans", self.spans),
706            font_size: sig(g, k, "font_size", self.style.size),
707            weight: sig(g, k, "weight", self.style.weight),
708            style: self.style,
709            morph: sig(g, k, "morph", None),
710            morph_t: sig(g, k, "morph_t", 0.0),
711        };
712        Txt::from_id(insert(g, parent, kind, self.base))
713    }
714}
715
716// ------------------------------------------------------------------- Code
717
718builder!(CodeBuilder => Code, kind "Code", defaults {},
719    fields { code: String = String::new(), lang: oxframe_text::Lang = oxframe_text::Lang::Rust,
720             theme: CodeTheme = CodeTheme::dark(), theme_set: bool = false, style: TextStyle = TextStyle {
721                 family: oxframe_text::MONO.to_owned(), size: 32.0, line_height: 1.45, ..TextStyle::default()
722             }, focus: Vec2 = Vec2::ZERO, dim: f64 = 0.3 });
723
724impl CodeBuilder {
725    /// The source code to show.
726    pub fn code(mut self, v: impl Into<String>) -> Self {
727        self.code = v.into();
728        self
729    }
730    /// "rust", "js", "ts", "python", "json", "toml", "shell"; anything else
731    /// is plain text.
732    pub fn language(mut self, name: &str) -> Self {
733        self.lang = oxframe_text::Lang::parse(name);
734        self
735    }
736    /// Syntax highlighting colors. Without this, a light project theme uses
737    /// [`CodeTheme::light`] and a dark one uses [`CodeTheme::dark`].
738    pub fn theme(mut self, t: CodeTheme) -> Self {
739        self.theme = t;
740        self.theme_set = true;
741        self
742    }
743    /// Font size in pixels.
744    pub fn font_size(mut self, v: f64) -> Self {
745        self.style.size = v;
746        self
747    }
748    /// Line height as a multiple of the font size.
749    pub fn line_height(mut self, v: f64) -> Self {
750        self.style.line_height = v;
751        self
752    }
753    /// Highlight lines `first..=last` (1-based); others are dimmed.
754    pub fn focus(mut self, first: usize, last: usize) -> Self {
755        self.focus = Vec2::new(first as f64, last as f64);
756        self
757    }
758    /// Alpha of unfocused lines (default 0.3).
759    pub fn dim(mut self, v: f64) -> Self {
760        self.dim = v;
761        self
762    }
763}
764
765impl NodeBuilder for CodeBuilder {
766    type Handle = Code;
767    base_accessor!();
768    fn build(self, g: &SceneGraph, parent: NodeId) -> Code {
769        let k = Self::KIND;
770        let theme = if self.theme_set {
771            self.theme
772        } else if theme::current().is_light() {
773            CodeTheme::light()
774        } else {
775            CodeTheme::dark()
776        };
777        let kind = NodeKind::Code {
778            code: sig(g, k, "code", self.code),
779            lang: self.lang,
780            theme,
781            font_size: sig(g, k, "font_size", self.style.size),
782            style: self.style,
783            focus: sig(g, k, "focus", self.focus),
784            dim: sig(g, k, "dim", self.dim),
785        };
786        Code::from_id(insert(g, parent, kind, self.base))
787    }
788}
789
790// -------------------------------------------------------------------- Img
791
792builder!(ImgBuilder => Img, kind "Img", defaults {},
793    fields { source: Option<ImageSource> = None, width: Option<f64> = None, height: Option<f64> = None });
794
795impl ImgBuilder {
796    /// PNG, JPEG or SVG bytes, typically `include_bytes!("../assets/x.png")`
797    /// — the only option under wasm.
798    ///
799    /// # Panics
800    ///
801    /// If the bytes are not a PNG, JPEG or SVG image.
802    pub fn src(mut self, bytes: &[u8]) -> Self {
803        self.source =
804            Some(ImageSource::decode(bytes).unwrap_or_else(|e| panic!("cannot decode image: {e}")));
805        self
806    }
807
808    /// Reads an image file (native only).
809    ///
810    /// # Panics
811    ///
812    /// If the file cannot be read or decoded.
813    #[cfg(not(target_arch = "wasm32"))]
814    pub fn file(self, path: impl AsRef<std::path::Path>) -> Self {
815        let path = path.as_ref();
816        let bytes =
817            std::fs::read(path).unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));
818        self.src(&bytes)
819    }
820
821    /// Width; height follows the aspect ratio unless also set.
822    pub fn width(mut self, v: f64) -> Self {
823        self.width = Some(v);
824        self
825    }
826
827    /// Height; width follows the aspect ratio unless also set.
828    pub fn height(mut self, v: f64) -> Self {
829        self.height = Some(v);
830        self
831    }
832}
833
834impl NodeBuilder for ImgBuilder {
835    type Handle = Img;
836    base_accessor!();
837    fn build(self, g: &SceneGraph, parent: NodeId) -> Img {
838        let source = self
839            .source
840            .expect("Img needs a source: call .src(bytes) or .file(path)");
841        let (nw, nh) = source.natural_size();
842        let aspect = if nh > 0.0 { nw / nh } else { 1.0 };
843        let (w, h) = match (self.width, self.height) {
844            (Some(w), Some(h)) => (w, h),
845            (Some(w), None) => (w, w / aspect),
846            (None, Some(h)) => (h * aspect, h),
847            (None, None) => (nw, nh),
848        };
849        let k = Self::KIND;
850        let kind = NodeKind::Img {
851            source,
852            width: sig(g, k, "width", w),
853            height: sig(g, k, "height", h),
854        };
855        Img::from_id(insert(g, parent, kind, self.base))
856    }
857}
858
859// ----------------------------------------------------------------- Layout
860
861builder!(
862    /// Places children in a row or column. Children's `x`/`y` become offsets
863    /// from their layout position.
864    LayoutBuilder => Layout, kind "Layout", defaults {},
865    fields { direction: Direction = Direction::Row, align: LayoutAlign = LayoutAlign::Center,
866             justify: Justify = Justify::Center, wrap: bool = false, columns: Option<u16> = None,
867             gap: f64 = 0.0, padding: f64 = 0.0,
868             width: Option<Span> = None, height: Option<Span> = None, radius: f64 = 0.0 });
869setters!(LayoutBuilder {
870    direction: Direction,
871    align: LayoutAlign,
872    justify: Justify
873});
874
875impl LayoutBuilder {
876    /// Space between children, in pixels or a theme step (`.gap(Sm)`).
877    pub fn gap(mut self, v: impl Len) -> Self {
878        self.gap = v.px();
879        self
880    }
881    /// Space inside the edges, in pixels or a theme step (`.padding(Md)`).
882    pub fn padding(mut self, v: impl Len) -> Self {
883        self.padding = v.px();
884        self
885    }
886    /// Corner radius, in pixels or a theme step.
887    pub fn radius(mut self, v: impl Corner) -> Self {
888        self.radius = v.radius();
889        self
890    }
891}
892
893impl LayoutBuilder {
894    /// Wrap children onto several lines when they do not fit.
895    pub fn wrap(mut self, v: bool) -> Self {
896        self.wrap = v;
897        self
898    }
899    /// CSS grid with `n` equal columns instead of a row/column.
900    pub fn grid(mut self, columns: u16) -> Self {
901        self.columns = Some(columns.max(1));
902        self
903    }
904    /// Children side by side (the default).
905    pub fn row(self) -> Self {
906        self.direction(Direction::Row)
907    }
908    /// Children stacked top to bottom.
909    pub fn column(self) -> Self {
910        self.direction(Direction::Column)
911    }
912    /// Fixed width in pixels or [`pct`](crate::pct)`(80)` (otherwise sized to content).
913    pub fn width(mut self, v: impl Into<Span>) -> Self {
914        self.width = Some(v.into());
915        self
916    }
917    /// Fixed height in pixels or a percentage (otherwise sized to content).
918    pub fn height(mut self, v: impl Into<Span>) -> Self {
919        self.height = Some(v.into());
920        self
921    }
922}
923
924impl NodeBuilder for LayoutBuilder {
925    type Handle = Layout;
926    base_accessor!();
927    fn build(self, g: &SceneGraph, parent: NodeId) -> Layout {
928        let k = Self::KIND;
929        let kind = NodeKind::Layout {
930            direction: self.direction,
931            align: self.align,
932            justify: self.justify,
933            wrap: self.wrap,
934            columns: self.columns,
935            gap: sig(g, k, "gap", self.gap),
936            padding: sig(g, k, "padding", self.padding),
937            width: place::span_option(
938                g,
939                parent,
940                Axis::X,
941                self.width,
942                format!("{k}#{}.width", g.next_id()),
943            ),
944            height: place::span_option(
945                g,
946                parent,
947                Axis::Y,
948                self.height,
949                format!("{k}#{}.height", g.next_id()),
950            ),
951            radius: sig(g, k, "radius", self.radius),
952        };
953        Layout::from_id(insert(g, parent, kind, self.base))
954    }
955}
956
957// ------------------------------------------------------------------- Grid
958
959builder!(GridBuilder => Grid, kind "Grid",
960    defaults { stroke: Color::rgba(1.0, 1.0, 1.0, 0.15), line_width: 1.0 },
961    fields { width: f64 = 1920.0, height: f64 = 1080.0, spacing: f64 = 80.0 });
962setters!(GridBuilder {
963    width: f64,
964    height: f64,
965    spacing: f64
966});
967
968impl NodeBuilder for GridBuilder {
969    type Handle = Grid;
970    base_accessor!();
971    fn build(self, g: &SceneGraph, parent: NodeId) -> Grid {
972        let k = Self::KIND;
973        let kind = NodeKind::Grid {
974            width: sig(g, k, "width", self.width),
975            height: sig(g, k, "height", self.height),
976            spacing: sig(g, k, "spacing", self.spacing),
977        };
978        Grid::from_id(insert(g, parent, kind, self.base))
979    }
980}