teksilo-widgets 0.9.2

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Default `TabStyle` impl driven by paint-recipe data.
//!
//! `RecipeTabStyle` ships the IntUI editor-tab look: an accent
//! indicator on the active tab's outside edge (top for horizontal
//! bars, leading for vertical bars), plus a keyboard focus ring
//! inset from the tab's bounds.
//!
//! The tab's own per-state background (selected / hover / idle,
//! controlled by `TabBar::tab_background` and the per-state overrides)
//! is painted by the surrounding `TabHeader` as separate RectWidget
//! siblings — the trait config doesn't carry the tab-surface roles
//! through the cfg, and pulling them through every consumer would be
//! more disruptive than letting the widget keep those rects.
//!
//! `TabStyle` carries two methods. `make_body` wraps a single tab
//! header: a leaf `TabBodyPainter` (accent indicator + focus ring)
//! sits behind the label / leading / trailing slot composition in a
//! `ZStack`. `make_bar` wraps the whole strip: a `TabBarChrome`
//! container stacks an optional backdrop `RectWidget`, a
//! `TabBarChromePainter` leaf (content-pane separator +
//! drag-reorder drop indicator), and the bar content — sizing to the
//! content under the real proposal so its inner `Expand` fills the
//! bar. Neither painter has an intrinsic size; each fills the bounds
//! its parent hands it.

use teksilo_canvas::{Canvas, Rect, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::binding::BindingLevel;
use teksilo_core::build_context::BuildContext;
use teksilo_core::signal::Signal;
use teksilo_core::styles::{
    TabBarChromeConfig, TabBarOrientation, TabIndicatorPosition, TabStyle, TabStyleConfig,
};
use teksilo_core::widget::{LayoutContext, LayoutResponse, PaintContext, Widget, WidgetPlacement};
use teksilo_core::widget_id::WidgetId;
use teksilo_tokens::CornerRadius;

use crate::primitives::{HStack, RectWidget, ZStack};

// IntUI design tokens for Tab. The recipe and parent TabHeader own
// their own dimensions.
pub const TAB_EDITOR_HEIGHT: f32 = 50.0;
pub const TAB_TOOL_WINDOW_HEIGHT: f32 = 28.0;
pub const TAB_PADDING_HORIZONTAL: f32 = 12.0;
pub const TAB_UNDERLINE_ACTIVE: f32 = 2.0;
pub const TAB_UNDERLINE_HOVER: f32 = 2.0;
pub const TAB_CLOSE_BUTTON_SIZE: f32 = 16.0;
/// Thickness of the drag-reorder drop-indicator line.
const DROP_INDICATOR_WIDTH: f32 = 2.0;

/// Dimension recipe for [`RecipeTabStyle`].
///
/// All fields default to the corresponding `TAB_*` constants so that
/// [`RecipeTabStyle::default()`] reproduces the built-in IntUI look.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TabRecipe {
    pub editor_height: f32,
    pub tool_window_height: f32,
    pub padding_horizontal: f32,
    pub underline_active: f32,
    pub underline_hover: f32,
    pub close_button_size: f32,
}

impl Default for TabRecipe {
    fn default() -> Self {
        Self {
            editor_height: TAB_EDITOR_HEIGHT,
            tool_window_height: TAB_TOOL_WINDOW_HEIGHT,
            padding_horizontal: TAB_PADDING_HORIZONTAL,
            underline_active: TAB_UNDERLINE_ACTIVE,
            underline_hover: TAB_UNDERLINE_HOVER,
            close_button_size: TAB_CLOSE_BUTTON_SIZE,
        }
    }
}

/// Default `TabStyle` shipped with Teksilo.
#[derive(Debug, Default, Clone, Copy)]
pub struct RecipeTabStyle {
    pub recipe: TabRecipe,
}

impl RecipeTabStyle {
    pub fn new(recipe: TabRecipe) -> Self {
        Self { recipe }
    }
}

impl TabStyle for RecipeTabStyle {
    fn make_body(&self, cfg: &TabStyleConfig, ctx: &mut BuildContext) -> WidgetId {
        // Leaf painter for the chrome bits that live at the bounds
        // edges: accent indicator and focus ring.
        let painter = ctx.add(TabBodyPainter {
            is_active: cfg.is_active.clone(),
            is_focused: cfg.is_focused.clone(),
            is_disabled: cfg.is_disabled.clone(),
            orientation: cfg.orientation,
            indicator_position: cfg.indicator_position,
            recipe: self.recipe,
        });

        // Compose the slots. The widget today bundles everything into
        // `label` and passes None for leading/trailing — but custom
        // impls may use the three slots directly, so we honour them.
        let mut row = HStack::new();
        if let Some(id) = cfg.leading {
            row = row.add_child(id);
        }
        row = row.add_child(cfg.label);
        if let Some(id) = cfg.trailing {
            row = row.add_child(id);
        }
        let row_id = ctx.add(row);

        ctx.add(ZStack::new().add_child(painter).add_child(row_id))
    }

    fn make_bar(&self, cfg: &TabBarChromeConfig, ctx: &mut BuildContext) -> WidgetId {
        // Bar chrome z-order (back → front): optional backdrop fill,
        // the separator + drop-indicator leaf painter, then the bar
        // content. This mirrors the old `TabBar::paint` order, where
        // the widget painted backdrop/separator/indicator before its
        // children drew on top.
        //
        // A plain `ZStack` won't do here: it sizes itself by querying
        // children with an *unspecified* proposal, which collapses the
        // content's inner `Expand` to zero width. `TabBarChrome`
        // instead sizes to the content child under the *real*
        // proposal and places every layer at the full bar bounds.
        let painter = ctx.add(TabBarChromePainter {
            orientation: cfg.orientation,
            show_separator: cfg.show_separator,
            drop_indicator: cfg.drop_indicator.clone(),
        });

        let mut layers = Vec::with_capacity(3);
        if let Some(role) = &cfg.surface_role {
            // A `RectWidget` (not a painted fill in the leaf) so the
            // backdrop tracks `ColorProp` bindings — static role,
            // `Signal<Color>`, or `Signal<Role>` — correctly.
            let backdrop = ctx.add(RectWidget::new().background(role.clone()));
            layers.push(backdrop);
        }
        layers.push(painter);
        layers.push(cfg.content);

        ctx.add(TabBarChrome {
            layers,
            content: cfg.content,
        })
    }
}

/// Bar-chrome container produced by [`RecipeTabStyle::make_bar`].
/// Stacks the backdrop / chrome-painter / content layers at the full
/// bar bounds, but — unlike `ZStack` — sizes itself to the content
/// child under the real layout proposal so the content's inner
/// `Expand` fills the bar instead of collapsing to zero.
#[derive(Debug)]
struct TabBarChrome {
    /// Back-to-front: `[backdrop?, painter, content]`.
    layers: Vec<WidgetId>,
    /// The layer that drives the bar's size.
    content: WidgetId,
}

impl Widget for TabBarChrome {
    fn build(&mut self, _ctx: &mut BuildContext) -> Vec<WidgetId> {
        self.layers.clone()
    }

    fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
        ctx.child_size(self.content, proposal)
            .unwrap_or_else(|| proposal.resolve(0.0, 0.0))
            .into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        builder.set_role(teksilo_core::accesskit::Role::GenericContainer);
    }

    fn children(&self) -> Vec<WidgetId> {
        self.layers.clone()
    }
}

/// Internal leaf widget that paints the bar-level chrome at the
/// strip's bounds: the content-pane separator and the drag-reorder
/// drop indicator. The backdrop fill is a sibling `RectWidget`, not
/// painted here, so `ColorProp` bindings resolve correctly.
struct TabBarChromePainter {
    orientation: TabBarOrientation,
    show_separator: bool,
    drop_indicator: Signal<Option<f32>>,
}

impl std::fmt::Debug for TabBarChromePainter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TabBarChromePainter")
            .field("orientation", &self.orientation)
            .field("show_separator", &self.show_separator)
            .finish()
    }
}

impl Widget for TabBarChromePainter {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        self.drop_indicator.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::RepaintOnly,
        );
        vec![]
    }

    fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        // Leaf painter — no intrinsic size, so accept whatever the
        // parent proposes. ZStack/TabBarChrome propose the full bar
        // bounds, then use the returned size as the placement. If we
        // returned ZERO here, the painter would be placed at zero
        // bounds and the separator + drop indicator would never show.
        proposal.resolve(0.0, 0.0).into()
    }

    fn place_children(
        &self,
        _bounds: Rect,
        _proposal: SizeProposal,
        _children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
    }

    fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
        if self.show_separator {
            // 1 dp separator: bottom in horizontal mode, trailing
            // edge (right) in vertical mode. Painted *inside* the
            // focus-ring envelope reserved by each header so the
            // selected header's `surface_content` fill overpaints
            // the separator in its own column (the "tab merges into
            // content pane" effect).
            let border_width = ctx.theme.shape.border_width;
            let envelope = ctx.theme.shape.focus_ring_offset + ctx.theme.shape.focus_ring_width;
            let separator = match self.orientation {
                TabBarOrientation::Horizontal => Rect::new(
                    bounds.x,
                    (bounds.bottom() - envelope - border_width).max(bounds.y),
                    bounds.width,
                    border_width,
                ),
                TabBarOrientation::Vertical => Rect::new(
                    (bounds.right() - envelope - border_width).max(bounds.x),
                    bounds.y,
                    border_width,
                    bounds.height,
                ),
            };
            canvas.fill_rect(separator, ctx.theme.colors.border);
        }

        // Drop indicator: a vertical accent-color line at the
        // would-be insertion x in horizontal mode, a horizontal line
        // at the insertion y in vertical mode. The position is the
        // layout-axis offset stored in bar-local coords by the bar's
        // `on_drag_hover` handler.
        if let Some(local_pos) = self.drop_indicator.get() {
            let indicator = match self.orientation {
                TabBarOrientation::Horizontal => {
                    let world_x = bounds.x + local_pos;
                    Rect::new(
                        (world_x - DROP_INDICATOR_WIDTH * 0.5).max(bounds.x),
                        bounds.y,
                        DROP_INDICATOR_WIDTH,
                        bounds.height,
                    )
                }
                TabBarOrientation::Vertical => {
                    let world_y = bounds.y + local_pos;
                    Rect::new(
                        bounds.x,
                        (world_y - DROP_INDICATOR_WIDTH * 0.5).max(bounds.y),
                        bounds.width,
                        DROP_INDICATOR_WIDTH,
                    )
                }
            };
            canvas.fill_rect(indicator, ctx.theme.colors.accent);
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        // Presentational only — the parent TabBar carries Role::TabList.
        builder.set_hidden();
    }
}

/// Internal leaf widget that paints the per-state chrome bits at the
/// edges of the tab's bounds. Not exposed publicly because custom
/// `TabStyle` impls compose their own body.
struct TabBodyPainter {
    is_active: Signal<bool>,
    is_focused: Signal<bool>,
    is_disabled: Signal<bool>,
    orientation: TabBarOrientation,
    indicator_position: TabIndicatorPosition,
    recipe: TabRecipe,
}

impl std::fmt::Debug for TabBodyPainter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TabBodyPainter")
            .field("orientation", &self.orientation)
            .field("indicator_position", &self.indicator_position)
            .finish()
    }
}

impl TabBodyPainter {
    /// The active-tab highlight rect for a tab at `bounds`, given the bar
    /// orientation, the configured indicator edge, and the layout
    /// direction (for the RTL-dependent vertical edges).
    ///
    /// Horizontal: `OuterEdge` → top, `InnerEdge` → bottom (RTL-invariant).
    /// Vertical: `OuterEdge` → leading, `InnerEdge` → trailing — leading is
    /// the left edge in LTR and the right edge in RTL.
    fn indicator_rect(&self, bounds: Rect, thickness: f32, rtl: bool) -> Rect {
        match self.orientation {
            TabBarOrientation::Horizontal => match self.indicator_position {
                TabIndicatorPosition::OuterEdge => {
                    Rect::new(bounds.x, bounds.y, bounds.width, thickness)
                }
                TabIndicatorPosition::InnerEdge => Rect::new(
                    bounds.x,
                    bounds.bottom() - thickness,
                    bounds.width,
                    thickness,
                ),
            },
            TabBarOrientation::Vertical => {
                // Leading edge = left in LTR / right in RTL; trailing is the
                // opposite. OuterEdge hugs leading, InnerEdge hugs trailing.
                let on_left = match self.indicator_position {
                    TabIndicatorPosition::OuterEdge => !rtl,
                    TabIndicatorPosition::InnerEdge => rtl,
                };
                let x = if on_left {
                    bounds.x
                } else {
                    bounds.right() - thickness
                };
                Rect::new(x, bounds.y, thickness, bounds.height)
            }
        }
    }
}

impl Widget for TabBodyPainter {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let id = ctx.self_id();
        let registry = ctx.binding_registry();
        self.is_active
            .bind_to(id, registry, BindingLevel::RepaintOnly);
        self.is_focused
            .bind_to(id, registry, BindingLevel::RepaintOnly);
        self.is_disabled
            .bind_to(id, registry, BindingLevel::RepaintOnly);
        vec![]
    }

    fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        // Leaf painter — no intrinsic size, so accept whatever the
        // parent ZStack proposes. ZStack proposes the full tab
        // bounds, then uses the returned size as the placement. If we
        // returned ZERO here, the painter would be placed at zero
        // bounds and both the accent indicator and the focus ring
        // would never show.
        proposal.resolve(0.0, 0.0).into()
    }

    fn place_children(
        &self,
        _bounds: Rect,
        _proposal: SizeProposal,
        _children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
    }

    fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
        let colors = &ctx.theme.colors;
        let shape = &ctx.theme.shape;
        let active = self.is_active.get();
        let focused = self.is_focused.get();
        let disabled = self.is_disabled.get();

        // Accent indicator on the selected, enabled tab. The edge is
        // chosen by `indicator_position` (default `OuterEdge`):
        //   - Horizontal bar → TOP for OuterEdge (browser-tab look, the
        //     selected tab "merges" into the content panel below) or
        //     BOTTOM for InnerEdge (the indicator sits below the label).
        //   - Vertical bar → LEADING edge for OuterEdge (IDE perspective
        //     look) or TRAILING for InnerEdge. Leading/trailing follow the
        //     layout direction.
        let indicator_thickness = self.recipe.underline_active;
        if active && !disabled {
            let rtl = matches!(
                ctx.layout_direction,
                teksilo_core::environment::LayoutDirection::RightToLeft
            );
            let indicator = self.indicator_rect(bounds, indicator_thickness, rtl);
            canvas.fill_rect(indicator, colors.accent);
        }

        // Focus ring — keyboard focus only. Drawn inside `bounds`
        // (inset by `focus_ring_width / 2 + focus_ring_offset`) so
        // adjacent tabs aren't visually overlapped by the ring.
        if focused {
            let half_stroke = shape.focus_ring_width * 0.5;
            let inset = half_stroke + shape.focus_ring_offset;
            let ring_rect = Rect::new(
                bounds.x + inset,
                bounds.y + inset,
                (bounds.width - inset * 2.0).max(0.0),
                (bounds.height - inset * 2.0).max(0.0),
            );
            canvas.stroke_rounded_rect(
                ring_rect,
                CornerRadius::uniform(shape.radius_control),
                colors.focus_ring,
                shape.focus_ring_width,
            );
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        // The parent TabHeader carries the Role::Tab. This painter is
        // presentational only.
        builder.set_hidden();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn painter(
        orientation: TabBarOrientation,
        indicator_position: TabIndicatorPosition,
    ) -> TabBodyPainter {
        TabBodyPainter {
            is_active: Signal::new(true),
            is_focused: Signal::new(false),
            is_disabled: Signal::new(false),
            orientation,
            indicator_position,
            recipe: TabRecipe::default(),
        }
    }

    // 100×40 tab, 3 dp indicator.
    const B: Rect = Rect {
        x: 10.0,
        y: 20.0,
        width: 100.0,
        height: 40.0,
    };
    const T: f32 = TAB_UNDERLINE_ACTIVE;

    #[test]
    fn horizontal_outer_edge_is_top_and_rtl_invariant() {
        let p = painter(
            TabBarOrientation::Horizontal,
            TabIndicatorPosition::OuterEdge,
        );
        let expected = Rect::new(B.x, B.y, B.width, T);
        assert_eq!(p.indicator_rect(B, T, false), expected);
        assert_eq!(
            p.indicator_rect(B, T, true),
            expected,
            "top edge is RTL-invariant"
        );
    }

    #[test]
    fn horizontal_inner_edge_is_bottom() {
        let p = painter(
            TabBarOrientation::Horizontal,
            TabIndicatorPosition::InnerEdge,
        );
        let expected = Rect::new(B.x, B.bottom() - T, B.width, T);
        assert_eq!(p.indicator_rect(B, T, false), expected);
        assert_eq!(p.indicator_rect(B, T, true), expected);
    }

    #[test]
    fn vertical_outer_edge_is_leading() {
        let p = painter(TabBarOrientation::Vertical, TabIndicatorPosition::OuterEdge);
        // LTR leading = left, RTL leading = right.
        assert_eq!(
            p.indicator_rect(B, T, false),
            Rect::new(B.x, B.y, T, B.height)
        );
        assert_eq!(
            p.indicator_rect(B, T, true),
            Rect::new(B.right() - T, B.y, T, B.height)
        );
    }

    #[test]
    fn vertical_inner_edge_is_trailing() {
        let p = painter(TabBarOrientation::Vertical, TabIndicatorPosition::InnerEdge);
        // LTR trailing = right, RTL trailing = left.
        assert_eq!(
            p.indicator_rect(B, T, false),
            Rect::new(B.right() - T, B.y, T, B.height)
        );
        assert_eq!(
            p.indicator_rect(B, T, true),
            Rect::new(B.x, B.y, T, B.height)
        );
    }
}