tui-lipan 0.2.0

Opinionated, component-based TUI framework for Rust - declarative components, reconciliation, layout engine, focus, overlays, and rich widgets on top of ratatui.
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Tabs widget.

mod layout;
mod node;
mod reconcile;

pub use layout::measure_tabs;
pub use node::TabsNode;
pub use reconcile::reconcile_tabs;

use std::sync::Arc;

use crate::callback::{Callback, KeyHandler};
use crate::core::element::{Element, ElementKind};
use crate::core::event::MouseEvent;
use crate::style::{BorderStyle, Length, Padding, Style, StyleSlot};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

/// Tab overflow policy.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TabsOverflow {
    /// Current behavior: greedily pack tabs from the start.
    #[default]
    Clip,
    /// Keep all tabs visible by allocating per-tab budgets and ellipsizing labels.
    Ellipsis,
}

/// A tab change event.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TabsEvent {
    /// Active tab index.
    pub index: usize,
}

/// A tab title.
#[derive(Clone, Debug)]
pub struct Tab {
    pub(crate) label: Arc<str>,
    pub(crate) style: Style,
    pub(crate) capped: bool,
}

impl Tab {
    /// Create a new tab.
    pub fn new(label: impl Into<Arc<str>>) -> Self {
        Self {
            label: label.into(),
            style: Style::default(),
            capped: false,
        }
    }

    /// Set style.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Draw this tab's end caps even when it is neither active nor hovered.
    ///
    /// [`Tabs::caps`] normally shapes only the active and hovered tabs, because those are the two
    /// the widget knows are emphasized. A tab carrying its own background for an app-specific reason
    /// — an unsaved marker, an error state, a workspace waiting on input — is emphasized too, and
    /// without this reads as a flat colored block beside shaped peers.
    ///
    /// The remaining cap conditions still apply: the tab must be untruncated, its background must
    /// differ from the strip's (there has to be a color to fill the glyph with), and the caps must
    /// fit the padding cells they replace.
    pub fn capped(mut self, capped: bool) -> Self {
        self.capped = capped;
        self
    }
}

impl From<&'static str> for Tab {
    fn from(value: &'static str) -> Self {
        Self::new(value)
    }
}

impl From<String> for Tab {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<Arc<str>> for Tab {
    fn from(value: Arc<str>) -> Self {
        Self::new(value)
    }
}

/// A horizontal tab bar.
#[derive(Clone)]
pub struct Tabs {
    pub(crate) tabs: Arc<[Tab]>,
    pub(crate) active: usize,
    pub(crate) style: Style,
    pub(crate) focus_style: StyleSlot,
    pub(crate) hover_style: StyleSlot,
    pub(crate) tab_hover_style: StyleSlot,
    pub(crate) active_style: StyleSlot,
    pub(crate) divider: char,
    pub(crate) caps: Option<(char, char)>,
    pub(crate) overflow: TabsOverflow,
    pub(crate) border: bool,
    pub(crate) border_style: BorderStyle,
    pub(crate) padding: Padding,
    pub(crate) width: Length,
    pub(crate) height: Length,
    pub(crate) on_change: Option<Callback<TabsEvent>>,
    pub(crate) on_click: Option<Callback<MouseEvent>>,
    pub(crate) on_key: Option<KeyHandler>,
    pub(crate) disabled: bool,
    pub(crate) disabled_style: Style,
    pub(crate) focusable: bool,
    pub(crate) tab_stop: bool,
    pub(crate) on_focus: Option<Callback<()>>,
    pub(crate) on_blur: Option<Callback<()>>,
}

impl Default for Tabs {
    fn default() -> Self {
        Self {
            tabs: Arc::new([]),
            active: 0,
            style: Style::default(),
            focus_style: StyleSlot::Inherit,
            hover_style: StyleSlot::Inherit,
            tab_hover_style: StyleSlot::Inherit,
            active_style: StyleSlot::Inherit,
            divider: '',
            caps: None,
            overflow: TabsOverflow::Clip,
            border: false,
            border_style: BorderStyle::Plain,
            padding: Padding::default(),
            width: Length::Flex(1),
            height: Length::Auto,
            on_change: None,
            on_click: None,
            on_key: None,
            disabled: false,
            disabled_style: Style::default(),
            focusable: false,
            tab_stop: true,
            on_focus: None,
            on_blur: None,
        }
    }
}

impl Tabs {
    /// Create an empty tab bar.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replace tabs.
    pub fn tabs<I>(mut self, tabs: I) -> Self
    where
        I: IntoIterator<Item = Tab>,
    {
        self.tabs = tabs.into_iter().collect::<Vec<_>>().into();
        self
    }

    /// Set tabs from a shared slice.
    pub fn tabs_arc(mut self, tabs: Arc<[Tab]>) -> Self {
        self.tabs = tabs;
        self
    }

    /// Add a tab.
    pub fn tab(mut self, tab: impl Into<Tab>) -> Self {
        let mut tabs = self.tabs.to_vec();
        tabs.push(tab.into());
        self.tabs = tabs.into();
        self
    }

    /// Set active tab index.
    pub fn active(mut self, active: usize) -> Self {
        self.active = active;
        self
    }

    /// Set base style.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set style when the tabs widget is focused.
    pub fn focus_style(mut self, style: Style) -> Self {
        self.focus_style = StyleSlot::Replace(style);
        self
    }

    /// Extend the active theme's focus style with additional fields.
    pub fn extend_focus_style(mut self, style: Style) -> Self {
        self.focus_style = StyleSlot::Extend(style);
        self
    }

    /// Inherit focus style from the active theme.
    pub fn inherit_focus_style(mut self) -> Self {
        self.focus_style = StyleSlot::Inherit;
        self
    }

    /// Set style when tabs widget is hovered.
    pub fn hover_style(mut self, style: Style) -> Self {
        self.hover_style = StyleSlot::Replace(style);
        self
    }

    /// Extend the active theme's hover style with additional fields.
    pub fn extend_hover_style(mut self, style: Style) -> Self {
        self.hover_style = StyleSlot::Extend(style);
        self
    }

    /// Inherit hover style from the active theme.
    pub fn inherit_hover_style(mut self) -> Self {
        self.hover_style = StyleSlot::Inherit;
        self
    }

    /// Set style for hovered tab.
    pub fn tab_hover_style(mut self, style: Style) -> Self {
        self.tab_hover_style = StyleSlot::Replace(style);
        self
    }

    /// Extend the active theme's tab hover style with additional fields.
    pub fn extend_tab_hover_style(mut self, style: Style) -> Self {
        self.tab_hover_style = StyleSlot::Extend(style);
        self
    }

    /// Inherit tab hover style from the active theme.
    pub fn inherit_tab_hover_style(mut self) -> Self {
        self.tab_hover_style = StyleSlot::Inherit;
        self
    }

    /// Set active tab style.
    pub fn active_style(mut self, style: Style) -> Self {
        self.active_style = StyleSlot::Replace(style);
        self
    }

    /// Extend the active theme's active-tab style with additional fields.
    pub fn extend_active_style(mut self, style: Style) -> Self {
        self.active_style = StyleSlot::Extend(style);
        self
    }

    /// Inherit active-tab style from the active theme.
    pub fn inherit_active_style(mut self) -> Self {
        self.active_style = StyleSlot::Inherit;
        self
    }

    /// Set divider character.
    pub fn divider(mut self, ch: char) -> Self {
        self.divider = ch;
        self
    }

    /// Set the `(left, right)` end-cap glyphs drawn around the active and hovered tabs.
    ///
    /// Each cap replaces one of the tab's two padding cells, so the tab keeps its
    /// measured width and hit region. The glyphs are painted in the tab's own
    /// background color over the strip background, so the tab reads as a rounded or
    /// pointed pill (pass powerline separators for that look). `None` (the default)
    /// keeps flat space padding on every tab.
    ///
    /// A tab falls back to flat padding when it is truncated by the overflow policy,
    /// when its background matches the strip's (leaving nothing to fill the glyph
    /// with), or when either cap is not exactly one cell wide. Caps must be
    /// single-width because a wider glyph would push later tabs off the columns the
    /// widget hit-tests against.
    pub fn caps(mut self, caps: Option<(char, char)>) -> Self {
        self.caps = caps;
        self
    }

    /// Set overflow policy.
    pub fn overflow(mut self, overflow: TabsOverflow) -> Self {
        self.overflow = overflow;
        self
    }

    /// Draw a border.
    pub fn border(mut self, border: bool) -> Self {
        self.border = border;
        self
    }

    /// Set border style.
    pub fn border_style(mut self, border_style: BorderStyle) -> Self {
        self.border_style = border_style;
        self
    }

    /// Set padding.
    pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
        self.padding = padding.into();
        self
    }

    /// Override requested width.
    pub fn width(mut self, width: Length) -> Self {
        self.width = width;
        self
    }

    /// Override requested height.
    pub fn height(mut self, height: Length) -> Self {
        self.height = height;
        self
    }

    /// Callback fired when the active tab changes.
    pub fn on_change(mut self, cb: Callback<TabsEvent>) -> Self {
        self.on_change = Some(cb);
        self
    }

    /// Set on-click handler.
    pub fn on_click(mut self, cb: Callback<MouseEvent>) -> Self {
        self.on_click = Some(cb);
        self
    }

    /// Set on-key handler.
    pub fn on_key(mut self, handler: KeyHandler) -> Self {
        self.on_key = Some(handler);
        self
    }

    /// Set disabled state.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Set disabled style.
    pub fn disabled_style(mut self, style: Style) -> Self {
        self.disabled_style = style;
        self
    }

    /// Control whether the node is focusable.
    pub fn focusable(mut self, focusable: bool) -> Self {
        self.focusable = focusable;
        self
    }

    /// Control whether the tabs participate in sequential focus navigation.
    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
        self.tab_stop = tab_stop;
        self
    }

    /// Set the callback fired when the tabs receive focus.
    pub fn on_focus(mut self, cb: Callback<()>) -> Self {
        self.on_focus = Some(cb);
        self
    }

    /// Set the callback fired when the tabs lose focus.
    pub fn on_blur(mut self, cb: Callback<()>) -> Self {
        self.on_blur = Some(cb);
        self
    }

    pub(crate) fn index_at_col(
        tabs: &[Tab],
        divider: char,
        overflow: TabsOverflow,
        inner_w: usize,
        col: usize,
    ) -> Option<usize> {
        let budgets = tab_width_budgets(tabs, divider, inner_w, overflow);
        let mut used = 0usize;

        for (i, tab) in tabs.iter().enumerate() {
            if used >= inner_w {
                break;
            }

            let remaining = budgets.as_ref().map_or_else(
                || inner_w.saturating_sub(used).min(u16::MAX as usize),
                |budgets| budgets.get(i).copied().unwrap_or(0) as usize,
            );
            let tab_width = tab_segment_width(tab.label.as_ref(), remaining);
            if col < used.saturating_add(tab_width) {
                return Some(i);
            }
            used = used.saturating_add(tab_width);

            if used >= inner_w {
                break;
            }

            if i + 1 < tabs.len() {
                let remaining = inner_w.saturating_sub(used);
                let divider_width = tab_divider_width(divider, remaining);
                if col < used.saturating_add(divider_width) {
                    return None;
                }
                used = used.saturating_add(divider_width);
            }
        }

        None
    }
}

impl From<Tabs> for Element {
    fn from(value: Tabs) -> Self {
        Element::new(ElementKind::Tabs(value))
    }
}

impl crate::layout::hash::LayoutHash for Tabs {
    fn layout_hash(
        &self,
        hasher: &mut impl std::hash::Hasher,
        _recurse: &dyn Fn(&Element) -> Option<u64>,
    ) -> Option<()> {
        use std::hash::Hash;
        self.width.hash(hasher);
        self.height.hash(hasher);
        self.border.hash(hasher);
        self.border_style.hash(hasher);
        self.padding.hash(hasher);
        self.tabs.len().hash(hasher);
        self.active.hash(hasher);
        self.divider.hash(hasher);
        self.overflow.hash(hasher);
        Some(())
    }
}

/// Return rendered width budget per tab for the given available width.
///
/// For `TabsOverflow::Clip`, returns `None` so callers keep the greedy path.
pub(crate) fn tab_width_budgets(
    tabs: &[Tab],
    divider: char,
    max_w: usize,
    overflow: TabsOverflow,
) -> Option<Vec<u16>> {
    if overflow == TabsOverflow::Clip {
        return None;
    }

    if tabs.is_empty() {
        return Some(Vec::new());
    }

    let n = tabs.len();
    let div_w = UnicodeWidthChar::width(divider).unwrap_or(1);
    let divider_budget = div_w.saturating_mul(n.saturating_sub(1));
    let usable = max_w.saturating_sub(divider_budget);

    let nat: Vec<usize> = tabs
        .iter()
        .map(|tab| UnicodeWidthStr::width(tab.label.as_ref()).saturating_add(2))
        .collect();
    let nat_sum = nat.iter().copied().sum::<usize>();
    if nat_sum <= usable {
        return Some(
            nat.into_iter()
                .map(|w| w.min(u16::MAX as usize) as u16)
                .collect(),
        );
    }

    const MIN_TAB_CELLS: usize = 3;
    let min_total = MIN_TAB_CELLS.saturating_mul(n);
    if usable < min_total {
        let each = (usable / n).max(1).min(u16::MAX as usize) as u16;
        return Some(vec![each; n]);
    }

    let mut alloc = vec![MIN_TAB_CELLS; n];
    let mut caps: Vec<usize> = nat
        .iter()
        .map(|&w| w.saturating_sub(MIN_TAB_CELLS))
        .collect();
    let mut extra = usable.saturating_sub(min_total);

    let pass1 = allocate_proportional(&caps, &nat, extra);
    for i in 0..n {
        alloc[i] = alloc[i].saturating_add(pass1[i]);
        caps[i] = caps[i].saturating_sub(pass1[i]);
    }
    extra = extra.saturating_sub(pass1.iter().copied().sum::<usize>());

    if extra > 0 {
        let pass2 = allocate_proportional(&caps, &nat, extra);
        for i in 0..n {
            alloc[i] = alloc[i].saturating_add(pass2[i]);
        }
    }

    Some(
        alloc
            .into_iter()
            .map(|w| w.min(u16::MAX as usize) as u16)
            .collect(),
    )
}

fn allocate_proportional(caps: &[usize], weights: &[usize], budget: usize) -> Vec<usize> {
    let n = caps.len();
    if budget == 0 || n == 0 {
        return vec![0; n];
    }

    let active_weight_sum = caps
        .iter()
        .zip(weights.iter())
        .filter(|(cap, _)| **cap > 0)
        .map(|(_, w)| *w)
        .sum::<usize>();
    if active_weight_sum == 0 {
        return vec![0; n];
    }

    let mut out = vec![0usize; n];
    let mut fracs = Vec::with_capacity(n);

    for i in 0..n {
        if caps[i] == 0 {
            fracs.push((i, -1.0_f64));
            continue;
        }

        let exact = (budget as f64) * (weights[i] as f64) / (active_weight_sum as f64);
        let grant = (exact.floor() as usize).min(caps[i]);
        out[i] = grant;
        fracs.push((i, exact - (grant as f64)));
    }

    let mut leftover = budget
        .saturating_sub(out.iter().copied().sum::<usize>())
        .min(caps.iter().copied().sum::<usize>());

    fracs.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

    while leftover > 0 {
        let mut progressed = false;
        for (idx, _) in &fracs {
            if leftover == 0 {
                break;
            }
            if out[*idx] < caps[*idx] {
                out[*idx] += 1;
                leftover -= 1;
                progressed = true;
            }
        }
        if !progressed {
            break;
        }
    }

    out
}

/// Width of the segment rendered from one tab label, without allocating its text.
pub(crate) fn tab_segment_width(label: &str, max_w: usize) -> usize {
    let full_w = UnicodeWidthStr::width(label).saturating_add(2);
    if full_w <= max_w {
        return full_w;
    }
    if max_w == 0 {
        return 0;
    }

    let ellipsis_w = UnicodeWidthChar::width('').unwrap_or(1).max(1);
    if max_w <= ellipsis_w {
        return ellipsis_w;
    }

    let target = max_w.saturating_sub(ellipsis_w);
    let mut consumed: usize = 1; // The leading padding cell always fits because target is non-zero.
    let mut label_end = 0;
    let mut label_complete = true;
    for (offset, ch) in label.char_indices() {
        let char_w = crate::utils::text::char_visual_width(ch, None);
        if consumed.saturating_add(char_w) > target {
            label_complete = false;
            break;
        }
        consumed = consumed.saturating_add(char_w);
        label_end = offset.saturating_add(ch.len_utf8());
    }

    let trailing_padding = label_complete && consumed < target;
    1usize
        .saturating_add(UnicodeWidthStr::width(&label[..label_end]))
        .saturating_add(usize::from(trailing_padding))
        .saturating_add(ellipsis_w)
}

pub(crate) fn tab_divider_width(divider: char, max_w: usize) -> usize {
    let divider_w = UnicodeWidthChar::width(divider).unwrap_or(1);
    if divider_w <= max_w {
        return divider_w;
    }
    if max_w == 0 {
        return 0;
    }
    UnicodeWidthChar::width('').unwrap_or(1).max(1)
}

#[cfg(test)]
mod tests {
    use super::{Tab, Tabs, TabsOverflow, tab_divider_width, tab_segment_width, tab_width_budgets};
    use unicode_width::UnicodeWidthStr;

    fn mk_tabs(labels: &[&str]) -> Vec<Tab> {
        labels.iter().map(|l| Tab::new(*l)).collect()
    }

    #[test]
    fn index_at_col_rejects_divider_cells_for_clip_and_ellipsis() {
        let tabs = mk_tabs(&["a", "b"]);

        // Each tab is three cells wide; the wide divider occupies columns 3 and 4.
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Clip, 8, 2),
            Some(0)
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Clip, 8, 3),
            None
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Clip, 8, 4),
            None
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Clip, 8, 5),
            Some(1)
        );

        // With ellipsis budgets below the minimum tab width, the clipped divider remains inert.
        let tabs = mk_tabs(&["a", "b", "c"]);
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Ellipsis, 5, 0),
            Some(0)
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Ellipsis, 5, 1),
            None
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Ellipsis, 5, 2),
            None
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Ellipsis, 5, 3),
            Some(1)
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '', TabsOverflow::Ellipsis, 5, 4),
            None
        );
    }

    #[test]
    fn index_at_col_uses_actual_width_of_wide_segments() {
        let tabs = mk_tabs(&["", "b"]);

        // Clip truncates the wide label to " …", leaving the divider at column 2.
        assert_eq!(
            Tabs::index_at_col(&tabs, '|', TabsOverflow::Clip, 3, 1),
            Some(0)
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '|', TabsOverflow::Clip, 3, 2),
            None
        );

        let tabs = mk_tabs(&["你好", "你好"]);

        // The first budget is five cells, but " 你好 " truncates to " 你…" at four cells.
        // The rendered divider is therefore at column 4, not at the nominal budget boundary 5.
        assert_eq!(
            Tabs::index_at_col(&tabs, '|', TabsOverflow::Ellipsis, 10, 4),
            None
        );
        assert_eq!(
            Tabs::index_at_col(&tabs, '|', TabsOverflow::Ellipsis, 10, 5),
            Some(1)
        );
    }

    #[test]
    fn allocation_free_segment_widths_match_materialized_truncation() {
        for label in ["a", "", "你好", "e\u{301}", "👩‍💻"] {
            for width in 0..=8 {
                let full = format!(" {label} ");
                let rendered = crate::utils::text::truncate_end_with_ellipsis(&full, width);
                assert_eq!(
                    tab_segment_width(label, width),
                    UnicodeWidthStr::width(rendered.as_ref()),
                    "segment width mismatch for {label:?} at width {width}"
                );
            }
        }

        for divider in ['|', '', '\u{301}'] {
            let text = divider.to_string();
            for width in 0..=3 {
                let rendered = crate::utils::text::truncate_end_with_ellipsis(&text, width);
                assert_eq!(
                    tab_divider_width(divider, width),
                    UnicodeWidthStr::width(rendered.as_ref()),
                    "divider width mismatch for {divider:?} at width {width}"
                );
            }
        }
    }

    #[test]
    fn budgets_equal_labels_exact_fit_under_and_over() {
        let tabs = mk_tabs(&["aa", "bb", "cc"]);

        assert_eq!(
            tab_width_budgets(&tabs, '|', 14, TabsOverflow::Ellipsis),
            Some(vec![4, 4, 4])
        );
        assert_eq!(
            tab_width_budgets(&tabs, '|', 11, TabsOverflow::Ellipsis),
            Some(vec![3, 3, 3])
        );
        assert_eq!(
            tab_width_budgets(&tabs, '|', 20, TabsOverflow::Ellipsis),
            Some(vec![4, 4, 4])
        );
    }

    #[test]
    fn budgets_long_label_eats_slack_first() {
        let tabs = mk_tabs(&["x", "super-long-label", "y"]);
        let budgets = tab_width_budgets(&tabs, '|', 20, TabsOverflow::Ellipsis).unwrap();

        assert_eq!(budgets.len(), 3);
        assert_eq!(budgets[0], 3);
        assert_eq!(budgets[2], 3);
        assert!(budgets[1] > budgets[0]);
    }

    #[test]
    fn budgets_single_tab() {
        let tabs = mk_tabs(&["hello"]);
        assert_eq!(
            tab_width_budgets(&tabs, '|', 7, TabsOverflow::Ellipsis),
            Some(vec![7])
        );
        assert_eq!(
            tab_width_budgets(&tabs, '|', 3, TabsOverflow::Ellipsis),
            Some(vec![3])
        );
    }

    #[test]
    fn budgets_zero_tabs_and_zero_width() {
        let tabs = mk_tabs(&[]);
        assert_eq!(
            tab_width_budgets(&tabs, '|', 0, TabsOverflow::Ellipsis),
            Some(vec![])
        );

        let one = mk_tabs(&["a", "b", "c"]);
        assert_eq!(
            tab_width_budgets(&one, '|', 0, TabsOverflow::Ellipsis),
            Some(vec![1, 1, 1])
        );
    }

    #[test]
    fn budgets_with_wide_divider() {
        let tabs = mk_tabs(&["aa", "bb"]);
        // Divider '好' has width 2, so max_w=8 leaves usable=6.
        assert_eq!(
            tab_width_budgets(&tabs, '', 8, TabsOverflow::Ellipsis),
            Some(vec![3, 3])
        );
    }

    #[test]
    fn tabs_arc_preserves_shared_slice() {
        use super::Tabs;
        use std::sync::Arc;

        let tabs: Arc<[Tab]> = Arc::from([Tab::new("one"), Tab::new("two")]);
        let bar = Tabs::new().tabs_arc(Arc::clone(&tabs));
        assert!(Arc::ptr_eq(&bar.tabs, &tabs));
    }
}