Skip to main content

teksilo_core/
widget_builder_branching.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Branching widget types and child-insertion trait for the `teksu!` DSL.
5//!
6//! `TeksiBranch{,3,4}` are two-, three-, and four-way sum types over Widget
7//! implementations. They exist so `if`/`else` and small `match` arms in
8//! `teksu!` can yield heterogeneous widget types from the same position
9//! without boxing. Each variant implements Widget by delegating every
10//! method to the active arm.
11//!
12//! `IntoTeksiChild` is the dispatch trait the macro uses when it cannot
13//! decide at expansion time whether a child expression is a widget value
14//! or a pre-registered `WidgetId` (the `#{ expr }` escape case). It
15//! produces a `PendingChild`, which Category A containers already know
16//! how to route through their `child()` / `add_child()` path.
17
18use teksilo_canvas::{Canvas, Point, Rect, SizeProposal};
19
20use crate::accessibility::AccessNodeBuilder;
21use crate::build_context::BuildContext;
22use crate::widget::{
23    LayoutContext, PaintContext, PendingChild, Widget, WidgetPlacement, WidgetTreeView,
24};
25use crate::widget_builder::HandlerSet;
26use crate::widget_id::WidgetId;
27
28// ---------------------------------------------------------------------------
29// The delegation, written once
30// ---------------------------------------------------------------------------
31
32/// Emit `impl Widget` for one branch enum, forwarding every method to the
33/// active arm.
34///
35/// Each branch type occupies its arm's own arena node — the tree never sees the
36/// arm again — so a method absent from this list is not overridden, it is gone:
37/// the trait's default answers in its place and the arm silently loses the
38/// behaviour behind it. The three branch widths would be three copies of that
39/// hazard, so they share one list here, and each generated impl denies
40/// `missing_trait_methods` so a method added to `Widget` fails the lint rather
41/// than the app.
42///
43/// The variant names and the type-parameter names are the same identifiers by
44/// construction (`L`/`R`, `A`/`B`/`C`, …), which is what lets one repetition
45/// serve as both.
46macro_rules! impl_widget_for_branch {
47    ($branch:ident, $($arm:ident),+) => {
48        #[deny(clippy::missing_trait_methods)]
49        impl<$($arm: Widget),+> Widget for $branch<$($arm),+> {
50            fn type_name(&self) -> &'static str {
51                match self { $($branch::$arm(w) => w.type_name()),+ }
52            }
53
54            fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
55                match self { $($branch::$arm(w) => w.build(ctx)),+ }
56            }
57
58            fn layout_response(
59                &self,
60                proposal: SizeProposal,
61                ctx: &LayoutContext,
62            ) -> crate::widget::LayoutResponse {
63                match self { $($branch::$arm(w) => w.layout_response(proposal, ctx)),+ }
64            }
65
66            fn cacheable_layout(&self) -> bool {
67                match self { $($branch::$arm(w) => w.cacheable_layout()),+ }
68            }
69
70            fn place_children(
71                &self,
72                bounds: Rect,
73                proposal: SizeProposal,
74                children: &mut [WidgetPlacement],
75                ctx: &LayoutContext,
76            ) {
77                match self {
78                    $($branch::$arm(w) => w.place_children(bounds, proposal, children, ctx)),+
79                }
80            }
81
82            fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
83                match self { $($branch::$arm(w) => w.paint(bounds, canvas, ctx)),+ }
84            }
85
86            fn wants_after_paint(&self) -> bool {
87                match self { $($branch::$arm(w) => w.wants_after_paint()),+ }
88            }
89
90            fn after_paint(&self, view: &WidgetTreeView<'_>, ctx: &PaintContext) {
91                match self { $($branch::$arm(w) => w.after_paint(view, ctx)),+ }
92            }
93
94            fn wants_post_paint(&self) -> bool {
95                match self { $($branch::$arm(w) => w.wants_post_paint()),+ }
96            }
97
98            fn post_paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
99                match self { $($branch::$arm(w) => w.post_paint(bounds, canvas, ctx)),+ }
100            }
101
102            fn accessibility(&self, builder: &mut AccessNodeBuilder) {
103                match self { $($branch::$arm(w) => w.accessibility(builder)),+ }
104            }
105
106            fn wants_descendant_redirects(&self) -> bool {
107                match self { $($branch::$arm(w) => w.wants_descendant_redirects()),+ }
108            }
109
110            fn a11y_redirect_descendant(
111                &self,
112                self_id: WidgetId,
113                descendant: WidgetId,
114            ) -> Option<accesskit::NodeId> {
115                match self {
116                    $($branch::$arm(w) => w.a11y_redirect_descendant(self_id, descendant)),+
117                }
118            }
119
120            fn accessible_title_hint(&self) -> Option<String> {
121                match self { $($branch::$arm(w) => w.accessible_title_hint()),+ }
122            }
123
124            fn accessible_title_node(&self) -> Option<crate::widget_id::WidgetId> {
125                match self { $($branch::$arm(w) => w.accessible_title_node()),+ }
126            }
127
128            fn initial_focus_hint(&self) -> Option<WidgetId> {
129                match self { $($branch::$arm(w) => w.initial_focus_hint()),+ }
130            }
131
132            fn context_menu_key_target(&self) -> Option<WidgetId> {
133                match self { $($branch::$arm(w) => w.context_menu_key_target()),+ }
134            }
135
136            fn children(&self) -> Vec<WidgetId> {
137                match self { $($branch::$arm(w) => w.children()),+ }
138            }
139
140            fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
141                match self { $($branch::$arm(w) => w.accessibility_children()),+ }
142            }
143
144            fn as_any(&self) -> Option<&dyn std::any::Any> {
145                match self { $($branch::$arm(w) => w.as_any()),+ }
146            }
147
148            fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
149                match self { $($branch::$arm(w) => w.as_any_mut()),+ }
150            }
151
152            fn clips_children(&self) -> bool {
153                match self { $($branch::$arm(w) => w.clips_children()),+ }
154            }
155
156            fn focus_reveal_rect(&self, bounds: Rect) -> Option<Rect> {
157                match self { $($branch::$arm(w) => w.focus_reveal_rect(bounds)),+ }
158            }
159
160            fn hit_shape(&self, local_point: Point, bounds: Rect) -> bool {
161                match self { $($branch::$arm(w) => w.hit_shape(local_point, bounds)),+ }
162            }
163
164            fn hit_outset(
165                &self,
166                kind: teksilo_tokens::PointerKind,
167                tokens: &teksilo_tokens::InputTokens,
168            ) -> teksilo_canvas::EdgeInsets {
169                match self { $($branch::$arm(w) => w.hit_outset(kind, tokens)),+ }
170            }
171
172            fn hit_slop(
173                &self,
174                kind: teksilo_tokens::PointerKind,
175                tokens: &teksilo_tokens::InputTokens,
176            ) -> Option<crate::pointer::hit_slop::HitSlop> {
177                // Named on `WidgetBuilder` too, where it is a consuming builder
178                // method — spelled out so the arm's `Widget` impl is the one
179                // called no matter what is in scope at the expansion site.
180                match self { $($branch::$arm(w) => Widget::hit_slop(w, kind, tokens)),+ }
181            }
182
183            fn hit_distance(&self, local_point: Point, bounds: Rect) -> Option<f32> {
184                match self { $($branch::$arm(w) => w.hit_distance(local_point, bounds)),+ }
185            }
186
187            fn target_regions(&self, bounds: Rect) -> Vec<crate::partition::TargetRegion> {
188                match self { $($branch::$arm(w) => w.target_regions(bounds)),+ }
189            }
190
191            fn preserves_children_on_rebuild(&self) -> bool {
192                match self { $($branch::$arm(w) => w.preserves_children_on_rebuild()),+ }
193            }
194
195            fn tooltip_has_content(&self) -> bool {
196                match self { $($branch::$arm(w) => w.tooltip_has_content()),+ }
197            }
198
199            fn declare_shortcuts(&self) -> Vec<crate::shortcut::Shortcut> {
200                match self { $($branch::$arm(w) => w.declare_shortcuts()),+ }
201            }
202
203            fn take_handler_set(&mut self) -> Option<HandlerSet> {
204                match self { $($branch::$arm(w) => w.take_handler_set()),+ }
205            }
206        }
207    };
208}
209
210// ---------------------------------------------------------------------------
211// TeksiBranch — two-way sum type
212// ---------------------------------------------------------------------------
213
214#[derive(Debug)]
215pub enum TeksiBranch<L: Widget, R: Widget> {
216    L(L),
217    R(R),
218}
219
220impl_widget_for_branch!(TeksiBranch, L, R);
221
222// ---------------------------------------------------------------------------
223// TeksiBranch3 — three-way sum type
224// ---------------------------------------------------------------------------
225
226#[derive(Debug)]
227pub enum TeksiBranch3<A: Widget, B: Widget, C: Widget> {
228    A(A),
229    B(B),
230    C(C),
231}
232
233impl_widget_for_branch!(TeksiBranch3, A, B, C);
234
235// ---------------------------------------------------------------------------
236// TeksiBranch4 — four-way sum type
237// ---------------------------------------------------------------------------
238
239#[derive(Debug)]
240pub enum TeksiBranch4<A: Widget, B: Widget, C: Widget, D: Widget> {
241    A(A),
242    B(B),
243    C(C),
244    D(D),
245}
246
247impl_widget_for_branch!(TeksiBranch4, A, B, C, D);
248
249// ---------------------------------------------------------------------------
250// IntoTeksiChild — widget-or-id dispatch for #{ expr } child positions
251// ---------------------------------------------------------------------------
252
253/// Dispatch trait the `teksu!` macro uses to route child expressions whose
254/// static type isn't known at expansion time (the `#{ expr }` escape).
255/// `impl Widget + 'static` values lower to `PendingChild::Deferred`;
256/// pre-registered `WidgetId` values lower to `PendingChild::Id`.
257pub trait IntoTeksiChild {
258    fn into_pending(self) -> PendingChild;
259}
260
261impl<W: Widget + 'static> IntoTeksiChild for W {
262    fn into_pending(self) -> PendingChild {
263        PendingChild::Deferred(Box::new(self))
264    }
265}
266
267impl IntoTeksiChild for WidgetId {
268    fn into_pending(self) -> PendingChild {
269        PendingChild::Id(self)
270    }
271}
272
273// ---------------------------------------------------------------------------
274// IntoTeksiCondition — reactive/static dispatch for `if bare_ident { ... }`
275// ---------------------------------------------------------------------------
276
277/// Dispatch trait the `teksu!` macro uses for `if bare_ident { Element }`
278/// — the `teksu!` "reactive conditionals" pattern. The bare-identifier form
279/// lowers to a call on this trait; which impl fires (and thus whether
280/// the element is conditionally built or always built with bound
281/// visibility) is decided at monomorphization.
282///
283/// - `bool`: static — the element is built only when the flag is true.
284///   Returns `Some(id)` if built, `None` if skipped.
285/// - `Signal<bool>` / `Prop<bool>`: reactive — the element is always
286///   built, and its visibility is bound to the signal via
287///   `BuildContext::visible_when`. Returns `Some(id)` unconditionally.
288///
289/// The return type is `Option<WidgetId>` so the macro can use a single
290/// lowering shape (`if let Some(id) = ... { parent.add_child(id) }`)
291/// that works for both cases.
292pub trait IntoTeksiCondition {
293    fn teksilo_into_conditional_child<W: crate::widget::Widget + 'static>(
294        self,
295        child: W,
296        ctx: &mut crate::build_context::BuildContext,
297    ) -> Option<WidgetId>;
298}
299
300impl IntoTeksiCondition for bool {
301    fn teksilo_into_conditional_child<W: crate::widget::Widget + 'static>(
302        self,
303        child: W,
304        ctx: &mut crate::build_context::BuildContext,
305    ) -> Option<WidgetId> {
306        if self { Some(ctx.add(child)) } else { None }
307    }
308}
309
310impl IntoTeksiCondition for crate::signal::Signal<bool> {
311    fn teksilo_into_conditional_child<W: crate::widget::Widget + 'static>(
312        self,
313        child: W,
314        ctx: &mut crate::build_context::BuildContext,
315    ) -> Option<WidgetId> {
316        let id = ctx.add(child);
317        ctx.visible_when(id, self);
318        Some(id)
319    }
320}
321
322impl IntoTeksiCondition for crate::signal::Prop<bool> {
323    fn teksilo_into_conditional_child<W: crate::widget::Widget + 'static>(
324        self,
325        child: W,
326        ctx: &mut crate::build_context::BuildContext,
327    ) -> Option<WidgetId> {
328        let id = ctx.add(child);
329        ctx.visible_when(id, self);
330        Some(id)
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337    use crate::test_widgets::FillWidget;
338    use crate::widget_tree::WidgetTree;
339    use teksilo_canvas::SizeProposal;
340    use teksilo_tokens::Color;
341
342    #[test]
343    fn teksilo_branch_dispatches_to_active_variant() {
344        // Build two trees, one with each variant, confirm each variant's
345        // widget actually runs its own build/size/paint path.
346        let mut tree_l = WidgetTree::new();
347        let id_l = tree_l.add(TeksiBranch::<FillWidget, FillWidget>::L(
348            FillWidget::new().background(Color::RED),
349        ));
350        tree_l.layout(SizeProposal::exact(100.0, 50.0));
351        assert!((tree_l.bounds(id_l).width - 100.0).abs() < 0.01);
352
353        let mut tree_r = WidgetTree::new();
354        let id_r = tree_r.add(TeksiBranch::<FillWidget, FillWidget>::R(
355            FillWidget::new().background(Color::BLUE),
356        ));
357        tree_r.layout(SizeProposal::exact(80.0, 40.0));
358        assert!((tree_r.bounds(id_r).width - 80.0).abs() < 0.01);
359    }
360
361    #[test]
362    fn teksilo_branch3_dispatches_to_active_variant() {
363        let mut tree = WidgetTree::new();
364        let id = tree.add(TeksiBranch3::<FillWidget, FillWidget, FillWidget>::B(
365            FillWidget::new(),
366        ));
367        tree.layout(SizeProposal::exact(120.0, 60.0));
368        assert!((tree.bounds(id).width - 120.0).abs() < 0.01);
369    }
370
371    #[test]
372    fn into_teksilo_child_routes_widget_to_deferred() {
373        let pending = FillWidget::new().into_pending();
374        assert!(matches!(pending, PendingChild::Deferred(_)));
375    }
376
377    #[test]
378    fn into_teksilo_child_routes_widget_id_to_id() {
379        let mut tree = WidgetTree::new();
380        let leaf = tree.add(FillWidget::new());
381        let pending = leaf.into_pending();
382        match pending {
383            PendingChild::Id(id) => assert_eq!(id, leaf),
384            _ => panic!("expected PendingChild::Id"),
385        }
386    }
387}