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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech
//! Tabbed-container widgets.
//!
//! Two public entry points:
//!
//! - [`TabBar<T>`] — a header strip driven by a `ListModel<T>` /
//! [`ListDataSource`](teksilo_data::ListDataSource) and a
//! [`TabDelegate<T>`]. Use it stand-alone when you want only the
//! tab strip (e.g., a document tab strip whose content lives in a
//! different panel or window).
//!
//! - [`TabWidget`] — the all-in-one composition: bar above, content
//! `Switcher` below, sharing one selection signal. Two
//! construction flavors:
//! - [`static_tab(info, content)`](TabWidget::static_tab) —
//! fixed tabs accumulated at construction.
//! - [`dynamic_tab::<S>(kind, factory)`](TabWidget::dynamic_tab) +
//! [`dynamic_model(model)`](TabWidget::dynamic_model) — apps
//! register a content factory per tab `kind` (`"plain-text-doc"`,
//! `"image"`, …); the live tab list is a mutable
//! `ListModel<TabHandle>` mutated at runtime (open / close /
//! reorder).
//!
//! Static tabs always render first, in declaration order; dynamic
//! tabs follow. Selection is by stable [`TabId`] — drag-reorder and
//! model mutations never silently send the active selection to a
//! different tab.
//!
//! ## Activating a tab scrolls it into view
//!
//! When more tabs are open than the strip can show, activating one
//! always reveals it — including when the activation is programmatic
//! (writing the selection signal, the "show all tabs" overflow
//! dropdown, an assistive-technology click). Pointer and keyboard
//! activation move focus and would be revealed by the framework's focus
//! follow anyway; the other paths move no focus, so the bar scrolls the
//! header in itself, by the minimum needed to bring it fully inside the
//! viewport.
//!
//! The reveal is edge-triggered on the selection changing, not an
//! invariant re-asserted every layout pass: once the reader has scrolled
//! away from the active tab by hand, a rebuild for an unrelated reason —
//! a retitled tab, a locale change, a tab opened elsewhere in the strip —
//! leaves the viewport where they left it.
//!
//! ## Accessibility
//!
//! Both [`TabWidget`] and [`TabBar`] emit `Role::TabList` on the bar
//! and `Role::Tab` on each header. ARIA APG ([tabs
//! pattern](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/))
//! recommends providing an accessible name for the tab list
//! whenever a page hosts more than one — call
//! [`.access_label(tr!(editor_tabs()))`](teksilo_core::widget_builder::WidgetBuilder::access_label)
//! on the widget so screen readers can distinguish "editor tabs"
//! from "tool tabs":
//!
//! ```ignore
//! TabWidget::new(selected)
//! .static_tab(TabInfo::new().title(tr!(welcome())), welcome_panel)
//! // ...
//! .access_label(tr!(editor_tabs()))
//! ```
//!
//! Panels with no focusable descendants (a static text-only "About"
//! tab, a chart-only metrics tab) are unreachable by Tab key unless
//! opted in via [`TabInfo::focusable_panel(true)`](TabInfo::focusable_panel).
use std::any::Any;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use teksilo_i18n::lit;
use teksilo_canvas::{Rect, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::binding::BindingLevel;
use teksilo_core::build_context::BuildContext;
use teksilo_core::drag_payload::DragPayload;
use teksilo_core::signal::{Prop, Signal};
use teksilo_core::widget::{
EventContext, LayoutContext, LayoutResponse, PendingChild, Widget, WidgetPlacement,
};
use teksilo_core::widget_id::WidgetId;
use teksilo_data::ListModel;
use crate::primitives::{Expand, Switcher, VStack};
mod bar;
mod delegate;
mod handle;
mod header;
mod id;
mod info;
#[cfg(test)]
mod a11y_tests;
#[cfg(test)]
mod tests;
pub use bar::{
DEFAULT_BAR_SLOT_SPACING, DEFAULT_MAX_TAB_WIDTH, DEFAULT_MIN_TAB_WIDTH,
DEFAULT_PINNED_TAB_WIDTH, DEFAULT_TAB_SPACING, TabBar, TabBarDragData,
};
pub use delegate::{
ContextMenuFactory, TabBarOrientation, TabDelegate, TabDisplayMode, TabOverflowButton,
TabSizing,
};
pub use handle::{STATIC_KIND, TabHandle};
pub use id::TabId;
pub use info::{IconFactory, TabInfo};
use teksilo_i18n::LocalizedString;
// ─── Static + dynamic content factory types ─────────────────────────
/// Closure that builds a static tab's content widget. Called once
/// per static tab — on the [`TabWidget`]'s first build that includes
/// it. The resulting pane is then memoized: rebuilds caused by
/// adjacent dynamic-model mutations reuse the same pane WidgetId, so
/// internal state (focus, scroll, animation progress, …) survives.
pub type StaticContentFactory = Rc<dyn Fn(&TabHandle) -> Box<dyn Widget>>;
/// Closure that builds a dynamic tab's content widget from its
/// handle and downcast typed payload. Internal — apps register via
/// [`TabWidget::dynamic_tab::<S>`](TabWidget::dynamic_tab) which
/// hides the `Any` downcast behind the type parameter.
pub(crate) type DynamicContentFactory = Rc<dyn Fn(&TabHandle, &dyn Any) -> Box<dyn Widget>>;
// ─── Static-tab content shapes ──────────────────────────────────────
/// One static tab's content + presentation. Three shapes:
///
/// - `Owned`: a one-shot `Box<dyn Widget>` from `static_tab(impl Widget)`.
/// Consumed on the slot's first registration.
/// - `Factory`: a `Fn(&TabHandle) -> Box<dyn Widget>` from
/// `static_tab_factory`. Called once on the slot's first
/// registration.
/// - `PreId`: a pre-registered `WidgetId` from `static_tab_id`,
/// wrapped in an alias on first registration. Stable for the
/// widget's lifetime.
enum StaticContentSource {
Owned(Option<Box<dyn Widget>>),
Factory(StaticContentFactory),
PreId(Option<WidgetId>),
}
impl StaticContentSource {
#[allow(clippy::wrong_self_convention)]
fn into_widget(&mut self, handle: &TabHandle) -> Box<dyn Widget> {
match self {
StaticContentSource::Owned(opt) => opt
.take()
.expect("static tab content has already been consumed"),
StaticContentSource::Factory(f) => f(handle),
StaticContentSource::PreId(opt) => {
let id = opt
.take()
.expect("static tab pre-registered id has already been consumed");
Box::new(AliasWidget {
target: Some(id),
child_id: None,
})
}
}
}
}
/// One static tab slot. The `pane_id` is `None` until the slot's
/// first build and stable thereafter — that's what makes static
/// content survive sibling rebuilds.
struct StaticTabSlot {
handle: TabHandle,
source: StaticContentSource,
pane_id: Option<WidgetId>,
}
/// One bar slot (leading or trailing). Memoized: registered on
/// first build via [`Self::resolve`], reused on subsequent builds.
struct BarSlot {
pending: Option<PendingChild>,
resolved: Option<WidgetId>,
}
impl BarSlot {
fn new(child: PendingChild) -> Self {
Self {
pending: Some(child),
resolved: None,
}
}
/// Resolve the slot to a stable WidgetId, registering the pending
/// widget on first call. Subsequent calls return the same id.
fn resolve(&mut self, ctx: &mut BuildContext) -> WidgetId {
if let Some(id) = self.resolved {
return id;
}
let id = match self
.pending
.take()
.expect("bar slot already resolved without id")
{
PendingChild::Id(id) => id,
PendingChild::Deferred(w) => ctx.add_boxed(w),
};
self.resolved = Some(id);
id
}
}
// ─── TabWidget — the public composition ─────────────────────────────
/// All-in-one tabbed container. Builds a [`TabBar`] above a
/// `Switcher` of content panes, sharing one selection signal.
pub struct TabWidget {
selected_id: Signal<Option<TabId>>,
/// Internal index signal driving the inner `Switcher`'s
/// visibility. Self-owned (persists across rebuilds) and kept in
/// sync with `selected_id` via a single one-way effect installed
/// in [`build`](Widget::build) — the bar manages its own id↔index
/// bridge for keyboard / click / scroll, so this is just the
/// content-pane mirror.
switcher_index: Signal<usize>,
/// Bar orientation — **reactive**. `Horizontal` (default) places
/// the bar above the content; `Vertical` places it on the leading
/// edge with content on the trailing side. Bound at
/// [`BindingLevel::Rebuild`]
/// in [`build`](Widget::build), so flipping it from outside the
/// widget re-runs the build with the new layout (the inner
/// content panes are memoized across this rebuild — their
/// internal state is preserved).
orientation: Signal<TabBarOrientation>,
static_tabs: Vec<StaticTabSlot>,
dynamic_registry: HashMap<&'static str, DynamicContentFactory>,
dynamic_model: Option<ListModel<TabHandle>>,
/// Lazily-populated map from a dynamic tab's stable [`TabId`] to
/// its content-pane WidgetId. Lets pane widgets (with their
/// internal mutable state — focus, scroll, animation, …) survive
/// across rebuilds caused by reorder, pin/unpin toggles, or
/// adjacent insertions / removals. Pruned every build to drop
/// entries whose tab is no longer in the model.
dyn_pane_ids: HashMap<TabId, WidgetId>,
// Bar configuration — forwarded to the inner TabBar.
/// Optional tab-strip height override (the strip's cross-axis extent).
/// `None` keeps the style's `editor_tab_height`. Set via
/// [`Self::tab_bar_height`] / [`Self::compact_bar`].
tab_bar_height: Option<f32>,
/// Reactive sizing strategy. `None` until `.tab_sizing(...)`
/// or `.sizing(...)` is called; defaulted by the bar
/// (`TabSizing::Shared`) otherwise. `TabSizing::Fill` stretches the
/// tabs across the bar (the nav-rail look). When a signal is bound,
/// the [`TabWidget`] also binds it at
/// [`BindingLevel::Rebuild`]
/// so toggling the signal swaps the sizing mode live.
sizing: Option<Signal<TabSizing>>,
/// Reactive tab display mode (icon / text / icon+text). `None` until
/// `.tab_display(...)` is called; defaulted by the bar
/// ([`TabDisplayMode::Auto`]) otherwise. Bound at [`BindingLevel::Rebuild`]
/// like `sizing`, so flipping it swaps what the tabs show live.
tab_display: Option<Signal<TabDisplayMode>>,
/// All-states per-tab background shorthand. Set via
/// [`Self::tab_background`]. `None` (default) means transparent.
tab_background: Option<teksilo_core::color_prop::ColorProp>,
/// Background for the selected tab. Set via [`Self::selected_tab_background`].
selected_tab_background: Option<teksilo_core::color_prop::ColorProp>,
/// Background for the hovered (non-selected) tab. Set via
/// [`Self::hover_tab_background`].
hover_tab_background: Option<teksilo_core::color_prop::ColorProp>,
/// Background for idle tabs. Set via [`Self::idle_tab_background`].
idle_tab_background: Option<teksilo_core::color_prop::ColorProp>,
/// Bar-strip backdrop fill. Set via [`Self::bar_background`].
bar_background: Option<teksilo_core::color_prop::ColorProp>,
/// Draw a divider between consecutive tabs. Set via [`Self::tab_dividers`].
tab_dividers: bool,
/// Colour for the inter-tab dividers. Set via [`Self::tab_divider_color`].
tab_divider_color: Option<teksilo_core::color_prop::ColorProp>,
/// Active-tab highlight edge. Set via [`Self::active_indicator`].
active_indicator: Option<teksilo_core::styles::TabIndicatorPosition>,
/// Text role used for the label (and matching icon tint) on the
/// selected tab. Set via [`Self::selected_text_role`]. `None`
/// defaults to [`teksilo_tokens::TextRole::Primary`] (Int UI
/// editor-strip convention).
selected_text_role: Option<teksilo_tokens::TextRole>,
/// Text role used for the label (and matching icon tint) on idle
/// tabs. Set via [`Self::idle_text_role`]. `None` defaults to
/// [`teksilo_tokens::TextRole::Secondary`].
idle_text_role: Option<teksilo_tokens::TextRole>,
min_tab_width: Option<f32>,
max_tab_width: Option<f32>,
pinned_tab_width: Option<f32>,
show_scroll_arrows: Option<bool>,
overflow_button: Option<TabOverflowButton>,
reorderable: bool,
on_close: Option<Rc<dyn Fn(TabId, &mut EventContext)>>,
on_reorder: Option<Rc<dyn Fn(TabId, usize, &mut EventContext)>>,
on_pin_toggle: Option<Rc<dyn Fn(TabId, bool, &mut EventContext)>>,
/// Cross-bar transfer opt-in. Enables this `TabWidget` to both
/// hand its (dynamic) tabs to other accepting `TabWidget`s and
/// receive tabs from them.
accept_external_tabs: bool,
/// Target-side override: insert a received tab. Receives the moved
/// [`TabHandle`] and the insertion index *within the dynamic
/// region*. Defaults to inserting into [`dynamic_model`](Self::dynamic_model).
on_tab_received: Option<Rc<dyn Fn(TabHandle, usize, &mut EventContext)>>,
/// Source-side override: one of this widget's tabs was accepted by
/// another `TabWidget`. Receives the transferred [`TabId`].
/// Defaults to removing it from [`dynamic_model`](Self::dynamic_model).
on_transfer_out: Option<Rc<dyn Fn(TabId, &mut EventContext)>>,
/// Handler for **non-tab** drops (an in-app foreign drag carrying
/// app data, or an OS file/text/URL drop). Receives the raw
/// payload and the insertion index *within the dynamic region*.
on_external_drop: Option<Rc<dyn Fn(&DragPayload, usize, &mut EventContext) -> bool>>,
bar_leading_slot: Option<BarSlot>,
bar_trailing_slot: Option<BarSlot>,
/// Tab-strip visibility policy, statically or reactively. See
/// [`TabBarVisibility`]. Bound at [`BindingLevel::Rebuild`] so a flip
/// re-runs `build` and re-derives `show_bar`.
bar_visibility: Prop<TabBarVisibility>,
root_child_id: Option<WidgetId>,
/// Whole-widget enabled state, statically or reactively. Forwarded to
/// the arena via `ctx.enabled_when(self_id, self.enabled.clone())` at
/// build time; a disabled `TabWidget` greys out and stops accepting
/// focus / selection / keyboard input (arena-gated). Distinct from
/// per-tab `TabInfo::enabled`.
enabled: Prop<bool>,
}
/// Controls whether a [`TabWidget`]'s tab strip is shown.
///
/// The default is [`Always`](TabBarVisibility::Always) — fully
/// back-compatible with the historical behaviour. [`WhenMultiple`](
/// TabBarVisibility::WhenMultiple) hides the strip while a single tab
/// is present (the content fills the whole area) and shows it again
/// once a second tab appears; the evaluation is reactive because a
/// dynamic-model mutation already rebuilds the `TabWidget`.
/// [`Never`](TabBarVisibility::Never) always hides the strip (the
/// selector lives elsewhere — e.g. a docking activity rail).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TabBarVisibility {
/// Always render the tab strip (historical default).
#[default]
Always,
/// Show the strip only when two or more tabs are present.
WhenMultiple,
/// Never render the strip; the content fills the whole area.
Never,
}
impl std::fmt::Debug for TabWidget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TabWidget")
.field("selected", &self.selected_id.get())
.field("static_tabs", &self.static_tabs.len())
.field(
"dynamic_registry",
&self.dynamic_registry.keys().collect::<Vec<_>>(),
)
.field("has_dynamic_model", &self.dynamic_model.is_some())
.finish()
}
}
impl TabWidget {
/// Construct an empty `TabWidget`. Selection is `None` until
/// the first `static_tab(...)` / `dynamic_model(...)` adds a
/// tab and the framework activates it.
pub fn new(selected: Signal<Option<TabId>>) -> Self {
Self {
selected_id: selected,
switcher_index: Signal::new(0_usize),
orientation: Signal::new(TabBarOrientation::Horizontal),
static_tabs: Vec::new(),
dynamic_registry: HashMap::new(),
dynamic_model: None,
dyn_pane_ids: HashMap::new(),
sizing: None,
tab_display: None,
tab_background: None,
selected_tab_background: None,
hover_tab_background: None,
idle_tab_background: None,
bar_background: None,
tab_dividers: false,
tab_divider_color: None,
active_indicator: None,
selected_text_role: None,
idle_text_role: None,
min_tab_width: None,
max_tab_width: None,
pinned_tab_width: None,
show_scroll_arrows: None,
overflow_button: None,
reorderable: false,
on_close: None,
on_reorder: None,
on_pin_toggle: None,
accept_external_tabs: false,
on_tab_received: None,
on_transfer_out: None,
on_external_drop: None,
bar_leading_slot: None,
bar_trailing_slot: None,
tab_bar_height: None,
bar_visibility: Prop::Static(TabBarVisibility::Always),
root_child_id: None,
enabled: Prop::Static(true),
}
}
/// Enable or disable the whole widget. A disabled `TabWidget` greys out
/// and stops accepting focus / selection / keyboard input
/// (arena-gated). Distinct from per-tab `TabInfo::enabled`.
pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
self.enabled = enabled.into();
self
}
/// Set the tab-strip visibility policy (default
/// [`TabBarVisibility::Always`]). Use [`TabBarVisibility::WhenMultiple`]
/// to hide the strip while a single tab is present, or
/// [`TabBarVisibility::Never`] when an external selector (e.g. a
/// docking activity rail) drives selection.
///
/// Accepts a plain [`TabBarVisibility`] or a `Signal<TabBarVisibility>`.
/// Bound reactively, the strip appears and disappears in place — the
/// `TabWidget` itself is never torn down, so per-tab content state
/// (caret, scroll offset, focus) survives the flip. That is the point
/// of binding rather than swapping two `TabWidget`s in a `Switcher`:
/// an app-level "hide the chrome" mode must not cost the user their
/// place in the document.
///
/// A derived signal (`.map(..)` / `.zip(..)`) is fine here: binding
/// resolves through to the mutable roots and never calls `observe`.
pub fn bar_visibility(mut self, visibility: impl Into<Prop<TabBarVisibility>>) -> Self {
self.bar_visibility = visibility.into();
self
}
/// Override the tab-strip height (its cross-axis extent). `None` /
/// unset keeps the style's `editor_tab_height` (50 dp). Use for a denser
/// strip — e.g. dock side panels.
pub fn tab_bar_height(mut self, dp: f32) -> Self {
self.tab_bar_height = Some(dp.max(0.0));
self
}
/// Shorthand for a **compact** (38 dp) tab strip — denser than the standard
/// 50 dp editor strip. Equivalent to `self.tab_bar_height(38.0)`.
pub fn compact_bar(self) -> Self {
self.tab_bar_height(38.0)
}
/// Configure the bar to render vertically — pills stacked
/// top-to-bottom on the leading edge, content fills the trailing
/// area (sidebar / IDE-perspective convention). Equivalent to
/// `self.orientation(TabBarOrientation::Vertical)`.
pub fn vertical(self) -> Self {
self.orientation.set(TabBarOrientation::Vertical);
self
}
/// Configure the bar to render horizontally — pills laid out
/// left-to-right above the content (browser tab convention).
/// This is the default.
pub fn horizontal(self) -> Self {
self.orientation.set(TabBarOrientation::Horizontal);
self
}
/// Set the bar orientation, statically or reactively. Passing a
/// `Signal<TabBarOrientation>` replaces the internal orientation
/// signal with the external one — lets a parent widget toggle
/// orientation reactively (e.g. a "View → Vertical Tabs" toolbar
/// button) without recreating the `TabWidget`.
pub fn orientation(mut self, orientation: impl Into<Prop<TabBarOrientation>>) -> Self {
self.orientation = orientation.into().as_signal();
self
}
/// Add a static tab — fixed for the widget's lifetime, with a
/// pre-built content widget. The content is registered in the
/// arena on the [`TabWidget`]'s first build and **memoized** —
/// subsequent rebuilds (caused by adjacent dynamic-model
/// mutations) reuse the same pane WidgetId, preserving any
/// internal state the content owns.
pub fn static_tab(mut self, info: TabInfo, content: impl Widget + 'static) -> Self {
let handle = TabHandle::static_handle(TabId::fresh(), info);
self.static_tabs.push(StaticTabSlot {
handle,
source: StaticContentSource::Owned(Some(Box::new(content))),
pane_id: None,
});
self
}
/// Ergonomic shorthand for a title-only static tab:
/// `tab(label, content)` is `static_tab(TabInfo::new().title(label),
/// content)`. `label` accepts `tr!(...)` (translated) or `lit!(...)`.
/// This is the method the `teksu!` `tab:` slot lowers to
/// (`tab: lit!("Overview"), Card { … }`).
pub fn tab(self, label: impl Into<LocalizedString>, content: impl Widget + 'static) -> Self {
self.static_tab(TabInfo::new().title(label), content)
}
/// `WidgetId` twin of [`tab`](Self::tab) — `tab_id(label, id)` is
/// `static_tab_id(TabInfo::new().title(label), id)`. This is what the
/// `teksu!` `tab:` slot lowers to when its content is an id binding
/// (`#{…}` / `name = Element`).
pub fn tab_id(self, label: impl Into<LocalizedString>, id: WidgetId) -> Self {
self.static_tab_id(TabInfo::new().title(label), id)
}
/// Add a static tab whose content is constructed by a factory
/// closure. The factory is called once — on the slot's first
/// build — and the resulting pane is memoized just like
/// [`static_tab`](Self::static_tab).
pub fn static_tab_factory(
mut self,
info: TabInfo,
factory: impl Fn(&TabHandle) -> Box<dyn Widget> + 'static,
) -> Self {
let handle = TabHandle::static_handle(TabId::fresh(), info);
self.static_tabs.push(StaticTabSlot {
handle,
source: StaticContentSource::Factory(Rc::new(factory)),
pane_id: None,
});
self
}
/// Element-valued slot variant for the `teksu!` DSL — accepts a
/// pre-registered widget id rather than a `Box<dyn Widget>`.
/// Equivalent to [`static_tab`](Self::static_tab) with an
/// already-built child; the id is wrapped in a tab pane on
/// first build and the pane id is memoized thereafter.
pub fn static_tab_id(mut self, info: TabInfo, content_id: WidgetId) -> Self {
let handle = TabHandle::static_handle(TabId::fresh(), info);
self.static_tabs.push(StaticTabSlot {
handle,
source: StaticContentSource::PreId(Some(content_id)),
pane_id: None,
});
self
}
/// Add a static tab with a caller-provided [`TabId`] — useful
/// when external code (an app-event handler, a session-restore
/// path, a deep link) needs to flip selection to this tab by id.
/// The pane is memoized like [`static_tab`](Self::static_tab).
pub fn static_tab_with_id(
mut self,
id: TabId,
info: TabInfo,
content: impl Widget + 'static,
) -> Self {
let handle = TabHandle::static_handle(id, info);
self.static_tabs.push(StaticTabSlot {
handle,
source: StaticContentSource::Owned(Some(Box::new(content))),
pane_id: None,
});
self
}
/// Factory variant of [`static_tab_with_id`](Self::static_tab_with_id).
pub fn static_tab_factory_with_id(
mut self,
id: TabId,
info: TabInfo,
factory: impl Fn(&TabHandle) -> Box<dyn Widget> + 'static,
) -> Self {
let handle = TabHandle::static_handle(id, info);
self.static_tabs.push(StaticTabSlot {
handle,
source: StaticContentSource::Factory(Rc::new(factory)),
pane_id: None,
});
self
}
/// Register a dynamic-tab content factory keyed by `kind`. The
/// `<S>` type parameter pins the payload type — the framework
/// downcasts `handle.payload` to `S` before calling the
/// factory and panics with a clear message on kind/payload
/// mismatch, so `Any` never leaks into app code.
pub fn dynamic_tab<S: Any + 'static>(
mut self,
kind: &'static str,
factory: impl Fn(&TabHandle, &S) -> Box<dyn Widget> + 'static,
) -> Self {
assert!(
kind != STATIC_KIND,
"tab kind '{}' is reserved by the framework for static tabs",
STATIC_KIND
);
debug_assert!(
!self.dynamic_registry.contains_key(kind),
"dynamic_tab kind '{kind}' is already registered — duplicate registration"
);
let kind_for_panic = kind;
let typed_factory: DynamicContentFactory = Rc::new(move |handle, payload| {
let typed = payload.downcast_ref::<S>().unwrap_or_else(|| {
panic!(
"tab kind '{}' was registered for {} but the handle's \
payload has a different type",
kind_for_panic,
std::any::type_name::<S>(),
)
});
factory(handle, typed)
});
self.dynamic_registry.insert(kind, typed_factory);
self
}
/// Connect the dynamic-tab data source. Mutations rebuild the
/// dynamic-tab subtree; static tabs are unaffected.
pub fn dynamic_model(mut self, model: ListModel<TabHandle>) -> Self {
self.dynamic_model = Some(model);
self
}
// ── Bar configuration (forwarded to inner TabBar) ──────────────
/// Set the per-tab sizing strategy as a static value. Internally
/// stores it as a `Signal<TabSizing>` so the widget can be
/// retrofitted to reactive control via [`Self::sizing`]
/// without breaking existing call sites.
pub fn tab_sizing(mut self, mode: TabSizing) -> Self {
self.sizing = Some(Signal::new(mode));
self
}
/// Bind the per-tab sizing strategy, statically or reactively —
/// flipping a bound signal swaps between Shared / Independent / Fill
/// live, with no rebuild on the parent's part. The signal is bound at
/// `BindingLevel::Rebuild` inside [`build`](Widget::build);
/// memoized panes survive the rebuild so per-tab state is
/// preserved.
pub fn sizing(mut self, sizing: impl Into<Prop<TabSizing>>) -> Self {
self.sizing = Some(sizing.into().as_signal());
self
}
/// Choose what every tab shows — icon, label, or both
/// ([`TabDisplayMode`]), statically or reactively. A bound signal can be
/// flipped to swap icon / text / icon+text live (the bar rebuilds,
/// memoized panes survive), with no rebuild on the parent's part. Bound
/// at `BindingLevel::Rebuild`.
pub fn tab_display(mut self, mode: impl Into<Prop<TabDisplayMode>>) -> Self {
self.tab_display = Some(mode.into().as_signal());
self
}
/// All-states shorthand for the per-tab background — every tab
/// (selected, idle, hovered) paints this unless a per-state override
/// is set. Accepts any `Color`, `SurfaceRole`, or `Signal<Color>` (via
/// [`ColorProp`](teksilo_core::color_prop::ColorProp)). Default is
/// transparent. To tint the bar's backdrop instead, use
/// [`bar_background`](Self::bar_background).
pub fn tab_background(mut self, color: impl Into<teksilo_core::color_prop::ColorProp>) -> Self {
self.tab_background = Some(color.into());
self
}
/// Background for the **selected** tab. Falls back to
/// [`tab_background`](Self::tab_background), then transparent.
pub fn selected_tab_background(
mut self,
color: impl Into<teksilo_core::color_prop::ColorProp>,
) -> Self {
self.selected_tab_background = Some(color.into());
self
}
/// Background for the **hovered** (non-selected) tab. Falls back to
/// [`tab_background`](Self::tab_background), then transparent.
pub fn hover_tab_background(
mut self,
color: impl Into<teksilo_core::color_prop::ColorProp>,
) -> Self {
self.hover_tab_background = Some(color.into());
self
}
/// Background for **idle** tabs (not selected, not hovered). Falls back
/// to [`tab_background`](Self::tab_background), then transparent.
pub fn idle_tab_background(
mut self,
color: impl Into<teksilo_core::color_prop::ColorProp>,
) -> Self {
self.idle_tab_background = Some(color.into());
self
}
/// Set the bar-strip backdrop fill (behind headers, slots, arrows),
/// independent of the per-tab backgrounds. Default transparent.
pub fn bar_background(mut self, color: impl Into<teksilo_core::color_prop::ColorProp>) -> Self {
self.bar_background = Some(color.into());
self
}
/// Draw a 1 dp divider between consecutive tabs. Off by default.
pub fn tab_dividers(mut self) -> Self {
self.tab_dividers = true;
self
}
/// Like [`tab_dividers`](Self::tab_dividers) with an explicit colour
/// (`Color`, [`BorderRole`](teksilo_tokens::BorderRole), or
/// `Signal<Color>`). Implies `tab_dividers()`.
pub fn tab_divider_color(
mut self,
color: impl Into<teksilo_core::color_prop::ColorProp>,
) -> Self {
self.tab_dividers = true;
self.tab_divider_color = Some(color.into());
self
}
/// Choose which edge the active-tab highlight indicator hugs. Default
/// [`TabIndicatorPosition::OuterEdge`](teksilo_core::styles::TabIndicatorPosition);
/// [`InnerEdge`](teksilo_core::styles::TabIndicatorPosition::InnerEdge)
/// puts it below the label (horizontal) / trailing edge (vertical).
pub fn active_indicator(
mut self,
position: teksilo_core::styles::TabIndicatorPosition,
) -> Self {
self.active_indicator = Some(position);
self
}
/// Set the text role used for the label (and matching icon tint)
/// on the **selected** tab. Default: [`teksilo_tokens::TextRole::Primary`]
/// — the Int UI editor-strip convention. Override to e.g.
/// [`teksilo_tokens::TextRole::Accent`] when the strip sits over a
/// tinted surface.
pub fn selected_text_role(mut self, role: teksilo_tokens::TextRole) -> Self {
self.selected_text_role = Some(role);
self
}
/// Set the text role used for the label (and matching icon tint)
/// on **idle** tabs (not selected, not disabled). Default:
/// [`teksilo_tokens::TextRole::Secondary`]. Disabled tabs always read
/// as [`teksilo_tokens::TextRole::Disabled`] regardless of this
/// setting.
pub fn idle_text_role(mut self, role: teksilo_tokens::TextRole) -> Self {
self.idle_text_role = Some(role);
self
}
/// Minimum scrollable-tab width in logical pixels. Default
/// [`DEFAULT_MIN_TAB_WIDTH`].
pub fn min_tab_width(mut self, dp: f32) -> Self {
self.min_tab_width = Some(dp);
self
}
/// Maximum scrollable-tab width in logical pixels. Default
/// [`DEFAULT_MAX_TAB_WIDTH`].
pub fn max_tab_width(mut self, dp: f32) -> Self {
self.max_tab_width = Some(dp);
self
}
/// Fixed width for pinned (icon-only) tabs in logical pixels. Default
/// [`DEFAULT_PINNED_TAB_WIDTH`].
pub fn pinned_tab_width(mut self, dp: f32) -> Self {
self.pinned_tab_width = Some(dp);
self
}
/// Show or hide the leading/trailing scroll-arrow buttons when tabs overflow.
/// Default (unset) uses the style's preference.
pub fn show_scroll_arrows(mut self, on: bool) -> Self {
self.show_scroll_arrows = Some(on);
self
}
/// When the trailing "show all tabs" overflow dropdown appears. Default
/// (unset) is [`TabOverflowButton::Auto`] — shown only when the tab headers
/// overflow the bar's viewport. See [`TabOverflowButton`] for
/// `Always` / `Never`.
pub fn overflow_button(mut self, mode: TabOverflowButton) -> Self {
self.overflow_button = Some(mode);
self
}
/// Convenience over [`overflow_button`](Self::overflow_button): `true` maps
/// to [`TabOverflowButton::Always`], `false` to [`TabOverflowButton::Never`].
pub fn show_overflow_dropdown(mut self, on: bool) -> Self {
self.overflow_button = Some(if on {
TabOverflowButton::Always
} else {
TabOverflowButton::Never
});
self
}
/// Allow drag-to-reorder of tabs within the bar. Default `false`.
/// Setting [`on_reorder`](Self::on_reorder) implies `reorderable(true)`.
pub fn reorderable(mut self, on: bool) -> Self {
self.reorderable = on;
self
}
/// Install a close-tab handler. Receives the [`TabId`] of the
/// closed tab (not its index — indices are presentation-only)
/// and the firing [`EventContext`]. The latter lets the handler
/// open a confirmation dialog
/// (`ctx.present_modal(MessageBox::confirm(...))`), dispatch an
/// intent, or otherwise route the close request before mutating
/// the underlying model. To veto, do nothing in the handler; to
/// confirm-then-close, only call the model mutator on accept.
///
/// If unset, the default behavior is to remove the tab from
/// [`dynamic_model`](Self::dynamic_model) without a prompt
/// (static tabs cannot be closed by default).
pub fn on_close(mut self, f: impl Fn(TabId, &mut EventContext) + 'static) -> Self {
self.on_close = Some(Rc::new(f));
self
}
/// Install a reorder handler. Receives `(moved_tab_id,
/// destination_index, ctx)` in the unified static-then-dynamic
/// ordering. The firing [`EventContext`] lets the handler
/// confirm or dispatch the reorder via a dialog / intent
/// before mutating the model. If unset, the default behavior
/// is to reorder within the dynamic region of
/// [`dynamic_model`](Self::dynamic_model). Implies
/// [`reorderable(true)`](Self::reorderable).
pub fn on_reorder(mut self, f: impl Fn(TabId, usize, &mut EventContext) + 'static) -> Self {
self.on_reorder = Some(Rc::new(f));
self.reorderable = true;
self
}
/// Install a pin-toggle handler — receives `(tab_id,
/// new_pinned_flag, ctx)` when the user drags a tab across the
/// pinned ↔ unpinned boundary. The firing [`EventContext`]
/// lets the handler confirm or dispatch the transition via a
/// dialog / intent. Apps decide whether to actually mutate the
/// tab's `info.pinned`.
pub fn on_pin_toggle(mut self, f: impl Fn(TabId, bool, &mut EventContext) + 'static) -> Self {
self.on_pin_toggle = Some(Rc::new(f));
self
}
/// Opt into cross-`TabWidget` tab transfer (app-internal
/// drag-and-drop between two tabbed containers). When enabled,
/// this widget's **dynamic** tabs can be dragged out to any other
/// accepting `TabWidget`, and it accepts tabs dragged in from one,
/// painting an insertion-line indicator between its tabs.
///
/// The dragged [`TabHandle`] moves intact — its `Rc<dyn Any>`
/// payload (the heavy per-tab state) is preserved, not rebuilt —
/// so the receiving widget must register a content factory for the
/// tab's `kind` via [`dynamic_tab`](Self::dynamic_tab).
///
/// **Static tabs are excluded**: they have no factory on a
/// receiving widget, so they can never be transferred out (they
/// still reorder in place if [`reorderable`](Self::reorderable)).
///
/// By default, accepting a tab inserts it into this widget's
/// [`dynamic_model`](Self::dynamic_model) and transferring one out
/// removes it from this widget's model. Override either side with
/// [`on_tab_received`](Self::on_tab_received) /
/// [`on_transfer_out`](Self::on_transfer_out). Default: off.
pub fn accept_external_tabs(mut self, on: bool) -> Self {
self.accept_external_tabs = on;
self
}
/// Override the target-side behaviour when a foreign tab is
/// dropped onto this widget. Receives `(handle, insertion_index,
/// ctx)` where `insertion_index` is within the **dynamic** tab
/// region. The app inserts the handle into its own model. Implies
/// [`accept_external_tabs(true)`](Self::accept_external_tabs).
///
/// If unset, the default inserts the handle into
/// [`dynamic_model`](Self::dynamic_model) at the drop position.
pub fn on_tab_received(
mut self,
f: impl Fn(TabHandle, usize, &mut EventContext) + 'static,
) -> Self {
self.on_tab_received = Some(Rc::new(f));
self.accept_external_tabs = true;
self
}
/// Override the source-side behaviour after one of this widget's
/// tabs has been accepted by another `TabWidget`. Receives the
/// transferred [`TabId`]; the app removes it from its own model.
/// Implies [`accept_external_tabs(true)`](Self::accept_external_tabs).
///
/// If unset, the default removes the tab from
/// [`dynamic_model`](Self::dynamic_model).
pub fn on_transfer_out(mut self, f: impl Fn(TabId, &mut EventContext) + 'static) -> Self {
self.on_transfer_out = Some(Rc::new(f));
self.accept_external_tabs = true;
self
}
/// Accept **non-tab** drops onto the tab bar — an in-app foreign
/// drag (e.g. a file dragged from a `TreeView`, carrying app data)
/// or an OS file/text/URL drop. The bar shows an insertion-line
/// indicator while such a payload hovers; on drop, `f` runs with
/// the raw [`DragPayload`], the insertion index *within the dynamic
/// region*, and the firing context. Inspect the payload
/// (`get_typed::<T>()` / `files()` / `text()` / `uris()`) and, e.g.,
/// push a new `TabHandle` into your [`dynamic_model`](Self::dynamic_model);
/// return `true` if accepted.
///
/// This is the "open a dropped file as a tab" hook (VS Code style).
/// Independent of [`accept_external_tabs`](Self::accept_external_tabs).
/// OS drops also require `TeksiloAppBuilder::install_external_dnd()`.
pub fn on_external_drop(
mut self,
f: impl Fn(&DragPayload, usize, &mut EventContext) -> bool + 'static,
) -> Self {
self.on_external_drop = Some(Rc::new(f));
self
}
/// Place a widget on the leading edge of the tab strip (before the first
/// tab). Memoized: registered once on first build, reused on rebuilds.
pub fn bar_leading_slot(mut self, w: impl Widget + 'static) -> Self {
self.bar_leading_slot = Some(BarSlot::new(PendingChild::Deferred(Box::new(w))));
self
}
/// Place a widget on the trailing edge of the tab strip (after the last
/// tab and overflow button). Memoized like
/// [`bar_leading_slot`](Self::bar_leading_slot).
pub fn bar_trailing_slot(mut self, w: impl Widget + 'static) -> Self {
self.bar_trailing_slot = Some(BarSlot::new(PendingChild::Deferred(Box::new(w))));
self
}
/// Element-valued variant of
/// [`bar_leading_slot`](Self::bar_leading_slot) accepting a
/// pre-registered `WidgetId` (for the `teksu!` DSL).
pub fn bar_leading_slot_id(mut self, id: WidgetId) -> Self {
self.bar_leading_slot = Some(BarSlot::new(PendingChild::Id(id)));
self
}
/// Element-valued variant of
/// [`bar_trailing_slot`](Self::bar_trailing_slot).
pub fn bar_trailing_slot_id(mut self, id: WidgetId) -> Self {
self.bar_trailing_slot = Some(BarSlot::new(PendingChild::Id(id)));
self
}
}
impl TabWidget {
// ── build() helpers ────────────────────────────────────────────
//
// `build()` is decomposed into three self-contained steps so the
// method body reads as orchestration rather than implementation.
// Each helper captures only `&self` (plus the build-local lookup
// tables it needs) and has no side effects beyond the arena
// registrations it performs through `ctx`.
/// Translate `TabInfo` fields into the [`TabDelegate`]'s
/// closure-shaped accessors. Pure — captures nothing from the
/// surrounding `build()`.
fn build_delegate(&self) -> TabDelegate<TabHandle> {
let mut delegate =
TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| lit!("")))
.icon(|_, h: &TabHandle| h.info.icon.as_ref().map(|f| f()))
.closable(|_, h: &TabHandle| h.info.closable)
.pinned(|_, h: &TabHandle| h.info.pinned)
.enabled(|_, h: &TabHandle| h.info.initial_enabled.get())
.tooltip(|_, h: &TabHandle| {
// Pinned tabs render icon-only; promote `title` to the
// tooltip if the caller didn't set one explicitly so
// the user can still identify the tab on hover.
if h.info.pinned
&& h.info.tooltip.is_none()
&& h.info.rich_tooltip.is_none()
&& h.info.composite_tooltip.is_none()
{
h.info.title.clone()
} else {
h.info.tooltip.clone()
}
});
// Bypass the tooltip-clearing setters here: TabInfo already
// enforces mutual exclusion across plain / rich / composite,
// so each closure returns `Some` only for its flavor.
delegate.rich_tooltip_key = Some(Box::new(|_, h: &TabHandle| match &h.info.rich_tooltip {
Some(crate::tooltip::RichTooltipSource::Key(k)) => Some(k.clone()),
_ => None,
}));
delegate.rich_tooltip_content =
Some(Box::new(|_, h: &TabHandle| match &h.info.rich_tooltip {
Some(crate::tooltip::RichTooltipSource::Content(c)) => Some(c.clone()),
_ => None,
}));
delegate.composite_tooltip = Some(Box::new(|_, h: &TabHandle| {
h.info.composite_tooltip.as_ref().map(|factory| factory())
}));
delegate = delegate.context_menu(|_, h: &TabHandle| h.info.context_menu.clone());
delegate
}
/// Wrap the bar's index-shaped callbacks (close / reorder / pin /
/// cross-bar transfer / non-tab drop) into the app's id-shaped
/// callbacks, translating at the boundary via `index_to_id` and
/// `saturating_sub(static_count)` for the unified→dynamic index map.
fn wire_bar_callbacks(
&self,
mut bar: TabBar<TabHandle>,
index_to_id: &Rc<Vec<TabId>>,
static_count: usize,
) -> TabBar<TabHandle> {
// Wrap callbacks: bar speaks in indices, app speaks in
// TabIds. We translate at the boundary using the
// `index_to_id` lookup captured at build time.
let close_cb = self.on_close.clone();
let dyn_model_for_close = self.dynamic_model.clone();
let idx_to_id_for_close = index_to_id.clone();
bar = bar.on_close(move |i: usize, ctx: &mut EventContext| {
if let Some(&id) = idx_to_id_for_close.get(i) {
if let Some(ref f) = close_cb {
f(id, ctx);
} else if i >= static_count {
// Default: remove from dynamic_model. Static
// tabs are not auto-closable.
if let Some(ref model) = dyn_model_for_close {
let dyn_idx = i - static_count;
if dyn_idx < model.len() {
let _ = model.remove(dyn_idx);
}
}
}
}
});
// `on_reorder(...)` setter sets `reorderable = true`, so the
// single `self.reorderable` flag is the only gate we need.
let reorder_cb = self.on_reorder.clone();
let dyn_model_for_reorder = self.dynamic_model.clone();
let idx_to_id_for_reorder = index_to_id.clone();
if self.reorderable {
bar = bar.on_reorder(move |from: usize, to: usize, ctx: &mut EventContext| {
if let Some(&id) = idx_to_id_for_reorder.get(from) {
if let Some(ref f) = reorder_cb {
f(id, to, ctx);
} else if from >= static_count && to >= static_count {
// Default: reorder within the dynamic region
// only. Static tabs are pinned in place.
if let Some(ref model) = dyn_model_for_reorder {
let from_dyn = from - static_count;
let to_dyn = to - static_count;
if from_dyn < model.len() && to_dyn < model.len() {
model.move_item(from_dyn, to_dyn);
}
}
} else {
// Cross-boundary reorder: silently rejected
// by the default handler. Surface it once
// per process so developers don't chase a
// ghost — install an explicit `on_reorder`
// to interleave static and dynamic tabs.
warn_cross_boundary_reorder_once(from, to, static_count);
}
}
});
}
if let Some(f) = self.on_pin_toggle.clone() {
let idx_to_id = index_to_id.clone();
bar = bar.on_pin_toggle(move |i: usize, pinned: bool, ctx: &mut EventContext| {
if let Some(&id) = idx_to_id.get(i) {
f(id, pinned, ctx);
}
});
}
// Cross-bar transfer wiring. The bar speaks in unified model
// indices (static tabs first, then dynamic); the app speaks in
// dynamic-region indices and TabIds. Static tabs are excluded
// from transfer — they have no factory on a receiving widget.
if self.accept_external_tabs {
bar = bar
.accept_external_tabs(true)
.with_transferable_predicate(|_, h: &TabHandle| h.kind != STATIC_KIND);
// Target side: insert the received handle. The bar's
// insertion index is in unified model space; translate to
// a dynamic-region index for the app / default model.
let received_cb = self.on_tab_received.clone();
let dyn_model_for_recv = self.dynamic_model.clone();
bar = bar.on_tab_received_rc(Rc::new(
move |handle: TabHandle, to_model: usize, ctx: &mut EventContext| {
let dyn_index = to_model.saturating_sub(static_count);
if let Some(ref f) = received_cb {
f(handle, dyn_index, ctx);
} else if let Some(ref model) = dyn_model_for_recv {
let idx = dyn_index.min(model.len());
model.insert(idx, handle);
}
},
));
// Source side: remove the transferred tab by id.
let transfer_out_cb = self.on_transfer_out.clone();
let dyn_model_for_out = self.dynamic_model.clone();
bar = bar.on_transfer_out_rc(Rc::new(move |tab_id: TabId, ctx: &mut EventContext| {
if let Some(ref f) = transfer_out_cb {
f(tab_id, ctx);
} else if let Some(ref model) = dyn_model_for_out {
let pos =
(0..model.len()).find(|&i| model.with_item(i, |h| h.id) == Some(tab_id));
if let Some(pos) = pos {
let _ = model.remove(pos);
}
}
}));
}
// Non-tab drops (foreign in-app drag / OS file drop). Translate
// the bar's unified model index to a dynamic-region index for
// the app callback. Independent of `accept_external_tabs`.
if let Some(external_cb) = self.on_external_drop.clone() {
bar = bar.on_external_drop_rc(Rc::new(
move |payload: &DragPayload, to_model: usize, ctx: &mut EventContext| {
let dyn_index = to_model.saturating_sub(static_count);
(external_cb)(payload, dyn_index, ctx)
},
));
}
bar
}
/// Build (or reuse) the content panes. Static and dynamic panes
/// both memoize their pane `WidgetId` — once registered, the pane
/// outlives sibling rebuilds (caused by dynamic-model mutations) so
/// internal state survives. Static panes cache in
/// [`StaticTabSlot::pane_id`]; dynamic panes cache in
/// [`Self::dyn_pane_ids`] keyed by [`TabId`], pruned at the end to
/// drop tabs no longer in the model.
fn build_panes(
&mut self,
ctx: &mut BuildContext,
all_handles: &[TabHandle],
static_count: usize,
dyn_count: usize,
panel_ids: &Rc<RefCell<Vec<WidgetId>>>,
header_ids: &Rc<RefCell<Vec<WidgetId>>>,
) -> Vec<WidgetId> {
let mut pane_ids: Vec<WidgetId> = Vec::with_capacity(static_count + dyn_count);
for slot in self.static_tabs.iter_mut() {
let pane_id = match slot.pane_id {
Some(id) => id,
None => {
let content = slot.source.into_widget(&slot.handle);
let id = ctx.add(TabPane::new(
slot.handle.clone(),
content,
panel_ids.clone(),
header_ids.clone(),
));
slot.pane_id = Some(id);
id
}
};
pane_ids.push(pane_id);
}
let mut alive_dyn: HashSet<TabId> = HashSet::with_capacity(dyn_count);
for handle in all_handles.iter().skip(static_count) {
alive_dyn.insert(handle.id);
let pane_id = match self.dyn_pane_ids.get(&handle.id) {
Some(&id) => id,
None => {
let factory = self.dynamic_registry.get(handle.kind).unwrap_or_else(|| {
panic!(
"tab kind '{}' has no registered content factory — \
add a `dynamic_tab::<S>(\"{}\", |handle, state| ...)` \
registration before connecting the model",
handle.kind, handle.kind,
)
});
let content = factory(handle, handle.payload.as_ref());
let id = ctx.add(TabPane::new(
handle.clone(),
content,
panel_ids.clone(),
header_ids.clone(),
));
self.dyn_pane_ids.insert(handle.id, id);
id
}
};
pane_ids.push(pane_id);
}
// Prune dynamic-pane memo entries for tabs the model no longer
// carries. Their pane widgets are absent from the children this
// rebuild returns, so the reconciling rebuild path (TabWidget is
// `preserves_children_on_rebuild`) destroys them — they are not left
// as stranded, still-active orphans.
self.dyn_pane_ids.retain(|id, _| alive_dyn.contains(id));
pane_ids
}
}
impl Widget for TabWidget {
fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
let self_id = ctx.self_id();
ctx.enabled_when(self_id, self.enabled.clone());
// Bind orientation at Rebuild level — toggling the signal
// (e.g. via a toolbar button) rebuilds TabWidget with the
// new outer layout (HStack ↔ VStack) and a fresh TabBar in
// the new orientation. Memoized panes survive the rebuild.
self.orientation
.bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
let orientation = self.orientation.get();
// Subscribe to dynamic-model mutations so add / remove /
// reorder triggers a TabWidget rebuild that picks up the
// new tab list.
if let Some(model) = &self.dynamic_model {
let version = ctx.signal(0_u64);
version.bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
let observer = model.observe_changes({
let v = version.clone();
move |_change| v.set(v.get().wrapping_add(1))
});
ctx.own_handle(observer);
}
// Snapshot static + dynamic into a single ordered handle
// list. Static tabs come first, in declaration order.
let static_count = self.static_tabs.len();
let dyn_count = self.dynamic_model.as_ref().map(|m| m.len()).unwrap_or(0);
let total = static_count + dyn_count;
let mut all_handles: Vec<TabHandle> = Vec::with_capacity(total);
for slot in &self.static_tabs {
all_handles.push(slot.handle.clone());
}
if let Some(model) = &self.dynamic_model {
for i in 0..dyn_count {
if let Some(h) = model.with_item(i, |h| h.clone()) {
all_handles.push(h);
}
}
}
// Index → id lookup table. Used by the close / reorder /
// pin callback wrappers below to translate the bar's
// index-shaped events into id-shaped app callbacks. The
// id ↔ selection bridge itself lives inside [`TabBar`] now;
// TabWidget hands the bar `selected_id` and `id_of` directly.
let index_to_id: Rc<Vec<TabId>> = Rc::new(all_handles.iter().map(|h| h.id).collect());
let id_to_index: Rc<HashMap<TabId, usize>> = Rc::new(
index_to_id
.iter()
.copied()
.enumerate()
.map(|(i, id)| (id, i))
.collect(),
);
// Drive `switcher_index` from `selected_id`. One-way only:
// the inner `Switcher` reads the index to pick which pane is
// visible, but never writes back — selection mutations all
// flow through `selected_id` (the bar updates it on click,
// app code may set it externally). Pre-sync handles the
// initial state and stale-id cases without needing a
// bidirectional effect.
if total > 0 {
let target_idx = self
.selected_id
.get()
.and_then(|id| id_to_index.get(&id).copied())
.unwrap_or_else(|| self.switcher_index.get().min(total - 1));
if self.switcher_index.get() != target_idx {
self.switcher_index.set(target_idx);
}
}
let id_to_idx = id_to_index.clone();
let switcher_idx = self.switcher_index.clone();
ctx.effect(&self.selected_id, move |maybe_id| {
if let Some(id) = maybe_id
&& let Some(&i) = id_to_idx.get(id)
&& switcher_idx.get() != i
{
switcher_idx.set(i);
}
});
// Internal model fed to the inner TabBar — a snapshot of
// the unified handle list (built inside the `show_bar` block
// below, since it is consumed only by the bar).
// Shared panel-id buffer: the Switcher writes panel widget
// ids into it as panes are added; the bar's headers read
// it to publish the Tab → TabPanel `controls()`
// accessibility relation.
let panel_ids = Rc::new(RefCell::new(Vec::with_capacity(total)));
// Shared header-id buffer: the bar populates this with each
// tab header's WidgetId in tab order; each TabPane reads it
// to publish the TabPanel → Tab `aria-labelledby` relation.
let header_ids: Rc<RefCell<Vec<WidgetId>>> =
Rc::new(RefCell::new(Vec::with_capacity(total)));
// Bind the visibility policy itself before reading it, so a bound
// policy flipping (e.g. an app-level distraction-free mode swapping
// `Always` for `Never`) rebuilds this widget and re-derives
// `show_bar` below. Registered unconditionally — outside the
// `show_bar` block, for the same reason as `sizing` / `tab_display`
// further down: while the strip is hidden there is no bar widget to
// carry the binding, so a hidden strip could never learn it should
// come back.
self.bar_visibility.register_if_bound(
self_id,
ctx.binding_registry(),
BindingLevel::Rebuild,
);
// Decide whether the tab strip is shown this build. Reactive
// for `WhenMultiple`: a dynamic-model mutation rebuilds the
// widget (the version observer above), so `total` is current.
let show_bar = match self.bar_visibility.get() {
TabBarVisibility::Always => true,
TabBarVisibility::Never => false,
TabBarVisibility::WhenMultiple => total >= 2,
};
// Bind the sizing signal at the TabWidget level (not inside the
// `show_bar` block) so a sizing change still rebuilds the widget even
// while the strip is hidden (`WhenMultiple` with a single tab) — the
// new mode is then applied the moment the bar reappears.
if let Some(ref sizing) = self.sizing {
sizing.bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
}
// Same treatment for the display mode: a flip rebuilds the widget so the
// bar re-derives its headers (icon ↔ text) even while the strip is
// hidden, applying the moment it reappears.
if let Some(ref display) = self.tab_display {
display.bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);
}
// Build + configure the inner TabBar — only when the strip is
// shown (`bar_visibility`). Skipped entirely otherwise so the
// bar's slot widgets aren't allocated as orphans. `internal_model`
// and `delegate` are constructed here because they are consumed
// only by the bar.
let bar_id: Option<WidgetId> = if show_bar {
let internal_model = ListModel::from_vec(all_handles.clone());
let delegate = self.build_delegate();
// Selection is plumbed through as id-based — the bar
// maintains its own private index-side signal and bridges
// the two internally.
let mut bar = match orientation {
TabBarOrientation::Horizontal => TabBar::horizontal(
internal_model,
delegate,
self.selected_id.clone(),
|_, h: &TabHandle| h.id,
),
TabBarOrientation::Vertical => TabBar::vertical(
internal_model,
delegate,
self.selected_id.clone(),
|_, h: &TabHandle| h.id,
),
}
.with_panel_ids(panel_ids.clone())
.with_header_ids(header_ids.clone());
if let Some(ref sizing) = self.sizing {
// The rebuild-triggering binding is installed above (outside
// this block); here we just apply the current mode to the bar.
bar = bar.tab_sizing(sizing.get());
}
if let Some(ref display) = self.tab_display {
bar = bar.tab_display(display.get());
}
if let Some(ref bg) = self.tab_background {
bar = bar.tab_background(bg.clone());
}
if let Some(ref bg) = self.selected_tab_background {
bar = bar.selected_tab_background(bg.clone());
}
if let Some(ref bg) = self.hover_tab_background {
bar = bar.hover_tab_background(bg.clone());
}
if let Some(ref bg) = self.idle_tab_background {
bar = bar.idle_tab_background(bg.clone());
}
if let Some(ref bg) = self.bar_background {
bar = bar.bar_background(bg.clone());
}
if self.tab_dividers {
bar = match self.tab_divider_color {
Some(ref c) => bar.tab_divider_color(c.clone()),
None => bar.tab_dividers(),
};
}
if let Some(pos) = self.active_indicator {
bar = bar.active_indicator(pos);
}
if let Some(role) = self.selected_text_role {
bar = bar.selected_text_role(role);
}
if let Some(role) = self.idle_text_role {
bar = bar.idle_text_role(role);
}
if let Some(h) = self.tab_bar_height {
bar = bar.tab_bar_height(h);
}
if let Some(w) = self.min_tab_width {
bar = bar.min_tab_width(w);
}
if let Some(w) = self.max_tab_width {
bar = bar.max_tab_width(w);
}
if let Some(w) = self.pinned_tab_width {
bar = bar.pinned_tab_width(w);
}
if let Some(s) = self.show_scroll_arrows {
bar = bar.show_scroll_arrows(s);
}
if let Some(mode) = self.overflow_button {
bar = bar.overflow_button(mode);
}
if self.reorderable {
bar = bar.reorderable(true);
}
// Wrap the bar's index-shaped callbacks into the app's
// id-shaped callbacks (close / reorder / pin / transfer / drop).
bar = self.wire_bar_callbacks(bar, &index_to_id, static_count);
if let Some(ref mut slot) = self.bar_leading_slot {
let id = slot.resolve(ctx);
bar = bar.bar_leading_slot_id(id);
}
if let Some(ref mut slot) = self.bar_trailing_slot {
let id = slot.resolve(ctx);
bar = bar.bar_trailing_slot_id(id);
}
Some(ctx.add(bar))
} else {
None
};
// Build (or reuse) the content panes — static + dynamic, both
// memoized so internal state survives sibling rebuilds.
let pane_ids = self.build_panes(
ctx,
&all_handles,
static_count,
dyn_count,
&panel_ids,
&header_ids,
);
let mut switcher =
Switcher::new(self.switcher_index.clone()).capture_child_ids_into(panel_ids);
for &pane_id in &pane_ids {
switcher = switcher.child_id(pane_id);
}
let switcher_id = ctx.add(switcher);
// Tab content area must claim BOTH axes: full panel width
// (so per-tab content fills the bounds, not just its natural
// width) AND full panel height (slack below the tab bar).
// `respect_intrinsic` makes the cross-axis fall back to the
// switcher's intrinsic when a parent queries us with an
// unspecified proposal, instead of reporting 0.
let content_id = ctx.add(Expand::new().respect_intrinsic().child_id(switcher_id));
// When the strip is hidden (`bar_visibility`), the content
// fills the whole area — no bar/content stack is needed.
let root_id = match (bar_id, orientation) {
(None, _) => content_id,
(Some(bar_id), TabBarOrientation::Horizontal) => {
ctx.add(VStack::new().add_child(bar_id).add_child(content_id))
}
(Some(bar_id), TabBarOrientation::Vertical) => ctx.add(
crate::primitives::HStack::new()
.add_child(bar_id)
.add_child(content_id),
),
};
self.root_child_id = Some(root_id);
vec![root_id]
}
fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
self.root_child_id
.and_then(|id| ctx.child_size(id, 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.root_child_id.into_iter().collect()
}
/// TabWidget memoizes the WidgetIds of its static-tab panes,
/// dynamic-tab panes (keyed by [`TabId`]), and bar slots across
/// rebuilds — internal mutable state (focus, scroll, animation,
/// rich-text editor history, …) survives sibling mutations
/// (dynamic-model push / remove / reorder, locale or theme
/// changes that retitle live tabs). Without this opt-in, the
/// framework's default `destroy_subtree` step on rebuild would
/// reap those memoized panes and the user would see static-tab
/// content vanish the first time they opened or closed a
/// dynamic tab.
fn preserves_children_on_rebuild(&self) -> bool {
true
}
}
// ─── Once-per-process developer warning ─────────────────────────────
/// Print a developer-aid warning the first time a cross-boundary
/// reorder is rejected by the default handler. Suppressed on
/// subsequent calls so high-frequency drag events don't spam stderr.
fn warn_cross_boundary_reorder_once(from: usize, to: usize, static_count: usize) {
use std::sync::Once;
static WARNED: Once = Once::new();
WARNED.call_once(|| {
eprintln!(
"[teksilo-widgets::tab_widget] default on_reorder rejected a \
cross-boundary move (from={from}, to={to}, \
static_count={static_count}). Install an explicit \
`on_reorder(...)` handler if you want to interleave \
static and dynamic tabs."
);
});
}
// ─── TabPane (internal content-pane wrapper) ────────────────────────
/// Wraps each tab's content widget so the `Switcher` can attach a
/// stable accessibility name (the tab's title) and the framework's
/// dormancy bookkeeping (`controls` relation, `is_visible` flag)
/// has a consistent target.
#[derive(Debug)]
struct TabPane {
handle: TabHandle,
child_id: Option<WidgetId>,
pending_child: Option<Box<dyn Widget>>,
/// Captured during `build()` so `accessibility()` can find this
/// pane's position in `panel_ids` (and thereby look up the
/// corresponding tab header in `header_ids`) — surviving
/// reorders without needing the parent to update memoized
/// state.
self_id: Option<WidgetId>,
/// Shared buffer the parent `TabWidget` populates (via the
/// inner `Switcher::capture_child_ids_into`) with each pane's
/// `WidgetId` in tab order. The pane reads it to discover its
/// own current index.
panel_ids: Rc<RefCell<Vec<WidgetId>>>,
/// Shared buffer the bar populates with each header's
/// `WidgetId` in tab order. Read at `accessibility()` time to
/// resolve the labelling tab.
header_ids: Rc<RefCell<Vec<WidgetId>>>,
/// When true, the pane attaches a `focusable(true)` handler to
/// itself at build time AND advertises `Action::Focus` from
/// `accessibility()`. Apps opt in via
/// [`TabInfo::focusable_panel`] for panels containing no
/// focusable descendants (an empty "About" tab, a chart-only
/// metrics tab) so keyboard users can reach them.
self_focusable: bool,
}
impl TabPane {
fn new(
handle: TabHandle,
content: Box<dyn Widget>,
panel_ids: Rc<RefCell<Vec<WidgetId>>>,
header_ids: Rc<RefCell<Vec<WidgetId>>>,
) -> Self {
let self_focusable = handle.info.focusable_panel;
Self {
handle,
child_id: None,
pending_child: Some(content),
self_id: None,
panel_ids,
header_ids,
self_focusable,
}
}
}
impl Widget for TabPane {
fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
self.self_id = Some(ctx.self_id());
if let Some(child) = self.pending_child.take() {
self.child_id = Some(ctx.add_boxed(child));
}
if self.self_focusable {
// Apply self-handlers so the framework treats this pane
// as a Tab-key stop, allowing Tab from the selected tab
// header to land inside an otherwise-empty panel.
ctx.apply_self_handlers(
teksilo_core::widget_builder::HandlerSet::new().focusable(true),
);
}
self.child_id.into_iter().collect()
}
fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
self.child_id
.and_then(|id| ctx.child_size(id, 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::TabPanel);
if let Some(ref title) = self.handle.info.title {
let resolved: String = title.clone().into();
builder.set_name(&resolved);
}
// ARIA aria-labelledby — point to the tab header that
// controls this panel. Look up *current* index by finding
// self_id in panel_ids (which the Switcher repopulates each
// build, so this auto-corrects on reorder), then map that
// to the header at the same position. Skip the relation —
// no dangling — when self_id or the header for that index
// isn't yet available (e.g. mid-rebuild after a model
// mutation).
if let Some(self_id) = self.self_id {
let panel_ids = self.panel_ids.borrow();
if let Some(pos) = panel_ids.iter().position(|&id| id == self_id) {
if let Some(&header_id) = self.header_ids.borrow().get(pos) {
builder.push_labelled_by(teksilo_core::accessibility::widget_id_to_node_id(
header_id,
));
}
}
}
// Opt-in panel focusability (TabInfo::focusable_panel).
// AccessKit has no `tabindex` field; `Action::Focus` is the
// canonical way to signal focusability to AT, matching how
// TabHeader::accessibility advertises focusability.
if self.self_focusable {
builder.add_action(teksilo_core::accesskit::Action::Focus);
}
}
fn children(&self) -> Vec<WidgetId> {
self.child_id.into_iter().collect()
}
}
// ─── AliasWidget: thin wrapper exposing a pre-registered widget id ──
/// One-shot wrapper that "absorbs" a pre-registered `WidgetId` on
/// first build, returning it as the wrapper's only child. Used by
/// [`TabWidget::static_tab_id`] to bridge the
/// `teksu!` DSL's element-valued-slot pattern (which pre-registers
/// the inner widget and hands the parent its id) into the factory
/// shape `static_tab_factory` expects.
#[derive(Debug)]
struct AliasWidget {
target: Option<WidgetId>,
child_id: Option<WidgetId>,
}
impl Widget for AliasWidget {
fn build(&mut self, _ctx: &mut BuildContext) -> Vec<WidgetId> {
if let Some(id) = self.target.take() {
self.child_id = Some(id);
}
self.child_id.into_iter().collect()
}
fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
self.child_id
.and_then(|id| ctx.child_size(id, 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 children(&self) -> Vec<WidgetId> {
self.child_id.into_iter().collect()
}
}