ftui-widgets 0.11.0

Widget library built on FrankenTUI render and layout.
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
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
// Index walks over parallel slices by a single counter; an iterator rewrite would
// obscure the arithmetic without changing behaviour.
#![allow(clippy::needless_range_loop)]
#![forbid(unsafe_code)]

//! Core widgets for FrankenTUI.
//!
//! This crate provides the [`Widget`] and [`StatefulWidget`] traits, along with
//! a collection of ready-to-use widgets for building terminal UIs.
//!
//! # Widget Trait Design
//!
//! Widgets render into a [`Frame`] rather than directly into a [`Buffer`]. The Frame
//! provides access to several subsystems beyond the cell grid:
//!
//! - **`frame.buffer`** - The cell grid for drawing characters and styles
//! - **`frame.hit_grid`** - Optional mouse hit testing (for interactive widgets)
//! - **`frame.cursor_position`** - Cursor placement (for input widgets)
//! - **`frame.cursor_visible`** - Cursor visibility control
//! - **`frame.degradation`** - Performance budget hints (for adaptive rendering)
//!
//! # Role in FrankenTUI
//! `ftui-widgets` is the standard widget library. It provides the reusable
//! building blocks (tables, lists, inputs, graphs, etc.) that most apps will
//! render inside their `view()` functions.
//!
//! # How it fits in the system
//! Widgets render into `ftui-render::Frame` using `ftui-style` for appearance
//! and `ftui-text` for text measurement and wrapping. The runtime drives these
//! widgets by calling your model's `view()` on each frame.
//!
//! # Widget Categories
//!
//! Widgets fall into four categories based on which Frame features they use:
//!
//! ## Category A: Simple Buffer-Only Widgets
//!
//! Most widgets only need buffer access. These are the simplest to implement:
//!
//! ```ignore
//! impl Widget for MyWidget {
//!     fn render(&self, area: Rect, frame: &mut Frame) {
//!         // Just write to the buffer
//!         frame.buffer.set(area.x, area.y, Cell::from_char('X'));
//!     }
//! }
//! ```
//!
//! Examples: [`block::Block`], [`paragraph::Paragraph`], [`rule::Rule`], [`StatusLine`]
//!
//! ## Category B: Interactive Widgets with Hit Testing
//!
//! Widgets that handle mouse clicks register hit regions:
//!
//! ```ignore
//! impl Widget for ClickableList {
//!     fn render(&self, area: Rect, frame: &mut Frame) {
//!         // Draw items...
//!         for (i, item) in self.items.iter().enumerate() {
//!             let row_area = Rect::new(area.x, area.y + i as u16, area.width, 1);
//!             // Draw item to buffer...
//!
//!             // Register hit region for mouse interaction
//!             if let Some(id) = self.hit_id {
//!                 frame.register_hit(row_area, id, HitRegion::Content, i as u64);
//!             }
//!         }
//!     }
//! }
//! ```
//!
//! Examples: [`list::List`], [`table::Table`], [`scrollbar::Scrollbar`]
//!
//! ## Category C: Input Widgets with Cursor Control
//!
//! Text input widgets need to position the cursor:
//!
//! ```ignore
//! impl Widget for TextInput {
//!     fn render(&self, area: Rect, frame: &mut Frame) {
//!         // Draw the input content...
//!
//!         // Position cursor when focused
//!         if self.focused {
//!             let cursor_x = area.x + self.cursor_offset as u16;
//!             frame.cursor_position = Some((cursor_x, area.y));
//!             frame.cursor_visible = true;
//!         }
//!     }
//! }
//! ```
//!
//! Examples: [`TextInput`](input::TextInput)
//!
//! ## Category D: Adaptive Widgets with Degradation Support
//!
//! Complex widgets can adapt their rendering based on performance budget:
//!
//! ```ignore
//! impl Widget for FancyProgressBar {
//!     fn render(&self, area: Rect, frame: &mut Frame) {
//!         let deg = frame.buffer.degradation;
//!
//!         if !deg.render_decorative() {
//!             // Skip decorative elements at reduced budgets
//!             return;
//!         }
//!
//!         if deg.apply_styling() {
//!             // Use full styling and effects
//!         } else {
//!             // Use simplified ASCII rendering
//!         }
//!     }
//! }
//! ```
//!
//! Examples: [`ProgressBar`](progress::ProgressBar), [`Spinner`](spinner::Spinner)
//!
//! # Essential vs Decorative Widgets
//!
//! The [`Widget::is_essential`] method indicates whether a widget should always render,
//! even at `EssentialOnly` degradation level:
//!
//! - **Essential**: Text inputs, primary content, status information
//! - **Decorative**: Borders, scrollbars, spinners, visual separators
//!
//! [`Frame`]: ftui_render::frame::Frame
//! [`Buffer`]: ftui_render::buffer::Buffer

pub mod adaptive_radix;
pub mod align;
/// Badge widget (status/priority pills).
pub mod badge;
/// Block widget with borders, titles, and padding.
pub mod block;
pub mod borders;
pub mod cached;
pub mod choreography;
pub mod columns;
pub mod command_palette;
pub mod constraint_overlay;
#[cfg(feature = "debug-overlay")]
pub mod debug_overlay;
/// Galaxy-brain decision card widget with progressive-disclosure transparency.
pub mod decision_card;
/// Reusable diagnostic logging and telemetry substrate for JSONL diagnostics.
pub mod diagnostics;
/// Drag-and-drop protocol: [`Draggable`] sources, [`DropTarget`] targets, and [`DragPayload`] payloads.
pub mod drag;
/// Drift-triggered fallback visualization with per-domain confidence sparklines.
pub mod drift_visualization;
/// Elias-Fano encoding for monotone integer sequences (succinct prefix sums).
pub mod elias_fano;
pub mod emoji;
pub mod error_boundary;
/// Fenwick tree (Binary Indexed Tree) for O(log n) prefix sum queries.
pub mod fenwick;
pub mod file_picker;
/// Focus management: navigation graph for keyboard-driven focus traversal.
pub mod focus;
pub mod group;
/// Bayesian height prediction with conformal bounds for virtualized lists.
pub mod height_predictor;
pub mod help;
pub mod help_registry;
/// Utility-based keybinding hint ranking with Bayesian posteriors.
pub mod hint_ranker;
/// Undo/redo history panel widget for displaying command history.
pub mod history_panel;
pub mod input;
/// UI Inspector overlay for debugging widget trees and hit-test regions.
pub mod inspector;
pub mod json_view;
pub mod keyboard_drag;
pub mod layout;
pub mod layout_debugger;
pub mod list;
pub mod log_ring;
pub mod log_viewer;
pub mod louds;
/// Intrinsic sizing support for content-aware layout.
pub mod measurable;
/// Measure cache for memoizing widget measure results.
pub mod measure_cache;
pub mod modal;
/// Shared mouse event result type for widget mouse handling.
pub mod mouse;
/// Notification queue for managing multiple toast notifications.
pub mod notification_queue;
pub mod padding;
pub mod paginator;
pub mod panel;
/// Multi-line styled text paragraph widget.
pub mod paragraph;
pub mod popover;
pub mod pretty;
pub mod progress;
/// Receipt verifier panel — renders signed-decision-receipt verifier verdicts.
pub mod receipt_verifier_panel;
pub mod rule;
pub mod scrollbar;
pub mod sparkline;
pub mod spinner;
/// Opt-in persistable state trait for widgets.
pub mod stateful;
pub mod status_line;
pub mod stopwatch;
/// Table widget with rows, columns, and selection.
pub mod table;
pub mod tabs;
pub mod textarea;
pub mod timer;
/// Toast widget for transient notifications.
pub mod toast;
pub mod tree;
/// Undo support for widgets.
pub mod undo_support;
/// Inline validation error display widget.
pub mod validation_error;
pub mod virtualized;
pub mod voi_debug_overlay;

/// Standard style names and conventions for [`StyleSheet`] lookups.
pub mod style_names {
    /// Suffix appended to a block style name to resolve its border style (e.g. `".border"`).
    pub const BLOCK_BORDER_SUFFIX: &str = ".border";

    /// Default prefix for table style roles (e.g. `"table"`).
    pub const TABLE_PREFIX: &str = "table";

    // Standard role names matching TableTheme
    /// Table border role name (`"border"`).
    pub const TABLE_BORDER: &str = "border";
    /// Table header role name (`"header"`).
    pub const TABLE_HEADER: &str = "header";
    /// Table row role name (`"row"`).
    pub const TABLE_ROW: &str = "row";
    /// Table alternating row role name (`"row_alt"`).
    pub const TABLE_ROW_ALT: &str = "row_alt";
    /// Table selected row role name (`"row_selected"`).
    pub const TABLE_ROW_SELECTED: &str = "row_selected";
    /// Table hovered row role name (`"row_hover"`).
    pub const TABLE_ROW_HOVER: &str = "row_hover";
    /// Table divider role name (`"divider"`).
    pub const TABLE_DIVIDER: &str = "divider";
}

#[cfg(all(test, feature = "tracing"))]
pub(crate) mod tracing_test_support {
    use std::sync::{Mutex, MutexGuard, OnceLock};

    /// Serialize tests that install tracing subscribers and rebuild the
    /// callsite interest cache.
    pub(crate) struct TraceTestGuard {
        _lock: MutexGuard<'static, ()>,
    }

    impl Drop for TraceTestGuard {
        fn drop(&mut self) {
            tracing::callsite::rebuild_interest_cache();
        }
    }

    pub(crate) fn acquire() -> TraceTestGuard {
        static TRACE_TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

        // Preserve serialization even if an earlier tracing assertion panicked.
        let lock = TRACE_TEST_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        tracing::callsite::rebuild_interest_cache();
        TraceTestGuard { _lock: lock }
    }
}

pub use align::{Align, VerticalAlignment};
pub use badge::Badge;
pub use cached::{CacheKey, CachedWidget, CachedWidgetState, FnKey, HashKey, NoCacheKey};
pub use columns::{Column, Columns};
pub use constraint_overlay::{ConstraintOverlay, ConstraintOverlayStyle};
#[cfg(feature = "debug-overlay")]
pub use debug_overlay::{
    DebugOverlay, DebugOverlayOptions, DebugOverlayState, DebugOverlayStateful,
    DebugOverlayStatefulState,
};
pub use decision_card::DecisionCard;
pub use ftui_style::StyleSheet;
pub use group::Group;
pub use help_registry::{HelpContent, HelpId, HelpRegistry, Keybinding};
pub use history_panel::{HistoryEntry, HistoryPanel, HistoryPanelMode};
pub use layout_debugger::{LayoutConstraints, LayoutDebugger, LayoutRecord};
pub use log_ring::LogRing;
pub use log_viewer::{LogViewer, LogViewerState, LogWrapMode, SearchConfig, SearchMode};
pub use paginator::{Paginator, PaginatorMode};
pub use panel::Panel;
pub use sparkline::{Sparkline, SparklineMarkers};
pub use status_line::{StatusItem, StatusLine};
pub use table::{ColumnSpec, Row, Table, TableState, Truncate};
pub use tabs::{Tab, Tabs, TabsState};
pub use virtualized::{
    HeightCache, ItemHeight, RenderItem, Virtualized, VirtualizedList, VirtualizedListState,
    VirtualizedStorage,
};
pub use voi_debug_overlay::{
    VoiDebugOverlay, VoiDecisionSummary, VoiLedgerEntry, VoiObservationSummary, VoiOverlayData,
    VoiOverlayStyle, VoiPosteriorSummary,
};

// Toast notification widget
pub use toast::{
    KeyEvent as ToastKeyEvent, Toast, ToastAction, ToastAnimationConfig, ToastAnimationPhase,
    ToastAnimationState, ToastConfig, ToastContent, ToastEasing, ToastEntranceAnimation,
    ToastEvent, ToastExitAnimation, ToastIcon, ToastId, ToastPosition, ToastState, ToastStyle,
};

// Notification queue manager
pub use notification_queue::{
    NotificationPriority, NotificationQueue, QueueAction, QueueConfig, QueueStats,
};

// Re-export accessibility trait and types for widget implementations.
pub use ftui_a11y::Accessible;

// Shared mouse result type for widget mouse handling
pub use mouse::MouseResult;

// Measurable widget support for intrinsic sizing
pub use measurable::{MeasurableWidget, SizeConstraints};

// Measure cache for memoizing measure() results
pub use measure_cache::{CacheStats, MeasureCache, WidgetId};
pub use modal::{
    BackdropConfig, MODAL_HIT_BACKDROP, MODAL_HIT_CONTENT, Modal, ModalAction, ModalConfig,
    ModalPosition, ModalSizeConstraints, ModalState,
};

// UI Inspector for debugging
pub use inspector::{
    DiagnosticEntry, DiagnosticEventKind, DiagnosticLog, HitInfo, InspectorMode, InspectorOverlay,
    InspectorState, InspectorStyle, TelemetryCallback, TelemetryHooks, WidgetInfo,
    diagnostics_enabled, init_diagnostics, is_deterministic_mode, reset_event_counter,
    set_diagnostics_enabled,
};

// Focus management
pub use focus::{
    FocusEvent, FocusGraph, FocusGroup, FocusId, FocusIndicator, FocusIndicatorKind, FocusManager,
    FocusNode, FocusTrap, NavDirection,
};

// Drag-and-drop protocol (source + target)
pub use drag::{DragPayload, DragState, Draggable, DropPosition, DropResult, DropTarget};

// Stateful persistence trait
pub use stateful::{StateKey, Stateful, VersionedState};

// Widget persist state types for state-persistence
pub use list::ListPersistState;
pub use table::TablePersistState;
pub use tree::TreePersistState;
pub use virtualized::VirtualizedListPersistState;

// Undo support for widgets
pub use undo_support::{
    ListOperation, ListUndoExt, SelectionOperation, TableOperation, TableUndoExt,
    TextEditOperation, TextInputUndoExt, TreeOperation, TreeUndoExt, UndoSupport, UndoWidgetId,
    WidgetTextEditCmd,
};

// Inline validation error display
pub use validation_error::{
    ANIMATION_DURATION_MS, ERROR_BG_DEFAULT, ERROR_FG_DEFAULT, ERROR_ICON_DEFAULT,
    ValidationErrorDisplay, ValidationErrorState,
};

use ftui_core::geometry::Rect;
use ftui_render::buffer::Buffer;
use ftui_render::cell::Cell;
use ftui_render::frame::{Frame, WidgetSignal};
use ftui_style::Style;
use ftui_text::grapheme_width;

/// Render a widget's own [`Block`](block::Block) without letting it contribute
/// an accessibility node.
///
/// A widget that owns a block folds the block's title into its *own* node -
/// `Paragraph`, `Table`, `List` and `Progress` all do - so the block's `Group`
/// is redundant semantics. It is worse than redundant. `Block`'s node and the
/// widget's both take their id from [`a11y_node_id`], which is a function of
/// the rect alone, and the widget renders its block at the very rect it just
/// pushed its own node for. `A11yTreeBuilder::add_node` replaces on a
/// duplicate id, and the block renders second - so the `Group` silently
/// overwrote the widget. A `Paragraph::new("hello").block(..)` reached the
/// screen reader as an empty group with its text gone.
///
/// Lifting the builder out for the duration is how `List` already handled
/// this; this is that, in one place. `catch_unwind` because a panic mid-render
/// must not leave the frame without its builder.
///
/// This does not make [`a11y_node_id`] collision-proof - two *sibling* widgets
/// at the same rect would still land on one id. It removes the case that is
/// structural rather than accidental: a widget and the block it draws around
/// itself always share a rect.
pub(crate) fn render_block_without_a11y(block: &block::Block<'_>, area: Rect, frame: &mut Frame) {
    if !frame.a11y_enabled() {
        block.render(area, frame);
        return;
    }
    let builder = frame.a11y.take();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        block.render(area, frame);
    }));
    frame.a11y = builder;
    if let Err(payload) = result {
        std::panic::resume_unwind(payload);
    }
}

/// Generate a deterministic accessibility node ID from a widget's bounding rect.
///
/// Uses FNV-1a to hash the area coordinates. Stable across frames for widgets
/// rendered at the same position, enabling efficient A11yTree diffing.
///
/// The id depends on the rect and nothing else, so two nodes pushed for the
/// same rect in one frame collide and the later one wins - see
/// [`render_block_without_a11y`].
#[must_use]
pub(crate) fn a11y_node_id(area: Rect) -> u64 {
    // FNV-1a 64-bit
    const FNV_OFFSET: u64 = 14_695_981_039_346_656_037;
    const FNV_PRIME: u64 = 1_099_511_628_211;
    let mut h = FNV_OFFSET;
    for byte in area
        .x
        .to_le_bytes()
        .iter()
        .chain(&area.y.to_le_bytes())
        .chain(&area.width.to_le_bytes())
        .chain(&area.height.to_le_bytes())
    {
        h ^= u64::from(*byte);
        h = h.wrapping_mul(FNV_PRIME);
    }
    h
}

/// A widget that can render itself into a [`Frame`].
///
/// # Frame vs Buffer
///
/// Widgets render into a `Frame` rather than directly into a `Buffer`. This provides:
///
/// - **Buffer access**: `frame.buffer` for drawing cells
/// - **Hit testing**: `frame.register_hit()` for mouse interaction
/// - **Cursor control**: `frame.cursor_position` for input widgets
/// - **Performance hints**: `frame.buffer.degradation` for adaptive rendering
///
/// # Implementation Guide
///
/// Most widgets only need buffer access:
///
/// ```ignore
/// fn render(&self, area: Rect, frame: &mut Frame) {
///     for y in area.y..area.bottom() {
///         for x in area.x..area.right() {
///             frame.buffer.set(x, y, Cell::from_char('.'));
///         }
///     }
/// }
/// ```
///
/// Interactive widgets should register hit regions when a `hit_id` is set.
/// Input widgets should set `frame.cursor_position` when focused.
///
/// # Degradation Levels
///
/// Check `frame.buffer.degradation` to adapt rendering:
///
/// - `Full`: All features enabled
/// - `SimpleBorders`: Skip fancy borders, use ASCII
/// - `NoStyling`: Skip colors and attributes
/// - `EssentialOnly`: Only render essential widgets
/// - `Skeleton`: Minimal placeholder rendering
///
/// [`Frame`]: ftui_render::frame::Frame
pub trait Widget {
    /// Render the widget into the frame at the given area.
    ///
    /// The `area` defines the bounding rectangle within which the widget
    /// should render. Widgets should respect the area bounds and not
    /// draw outside them (the buffer's scissor stack enforces this).
    fn render(&self, area: Rect, frame: &mut Frame);

    /// Whether this widget is essential and should always render.
    ///
    /// Essential widgets render even at `EssentialOnly` degradation level.
    /// Override this to return `true` for:
    ///
    /// - Text inputs (user needs to see what they're typing)
    /// - Primary content areas (main information display)
    /// - Critical status indicators
    ///
    /// Returns `false` by default, appropriate for decorative widgets.
    fn is_essential(&self) -> bool {
        false
    }
}

/// Frame-side rendering helpers so `view()` code reads top-down:
/// `frame.render_widget(&sidebar, left)` instead of `sidebar.render(left, frame)`.
///
/// This is an extension trait because [`Frame`] lives in `ftui-render`, which
/// does not know the widget traits; import it through `ftui::prelude::*` or
/// `use ftui_widgets::FrameExt`.
pub trait FrameExt {
    /// Render a stateless widget into `area`.
    fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect);

    /// Render a stateful widget into `area`, giving it mutable access to its
    /// state for the duration of the render.
    fn render_stateful_widget<W: StatefulWidget + ?Sized>(
        &mut self,
        widget: &W,
        area: Rect,
        state: &mut W::State,
    );
}

impl FrameExt for Frame<'_> {
    #[inline]
    fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect) {
        widget.render(area, self);
    }

    #[inline]
    fn render_stateful_widget<W: StatefulWidget + ?Sized>(
        &mut self,
        widget: &W,
        area: Rect,
        state: &mut W::State,
    ) {
        widget.render(area, self, state);
    }
}

/// Budget-aware wrapper that registers widget signals and respects refresh budgets.
pub struct Budgeted<W> {
    widget_id: u64,
    signal: WidgetSignal,
    inner: W,
}

impl<W> Budgeted<W> {
    /// Wrap a widget with a stable identifier and default signal values.
    #[must_use]
    pub fn new(widget_id: u64, inner: W) -> Self {
        Self {
            widget_id,
            signal: WidgetSignal::new(widget_id),
            inner,
        }
    }

    /// Override the widget signal template.
    #[must_use]
    pub fn with_signal(mut self, mut signal: WidgetSignal) -> Self {
        signal.widget_id = self.widget_id;
        self.signal = signal;
        self
    }

    /// Access the wrapped widget.
    #[must_use]
    pub fn inner(&self) -> &W {
        &self.inner
    }
}

impl<W: Widget> Widget for Budgeted<W> {
    fn render(&self, area: Rect, frame: &mut Frame) {
        let mut signal = self.signal.clone();
        signal.widget_id = self.widget_id;
        signal.essential = self.inner.is_essential();
        signal.area_cells = area.width as u32 * area.height as u32;
        frame.register_widget_signal(signal);

        if frame.should_render_budgeted_widget(self.widget_id, self.inner.is_essential()) {
            self.inner.render(area, frame);
        }
    }

    fn is_essential(&self) -> bool {
        self.inner.is_essential()
    }
}

impl<W: StatefulWidget + Widget> StatefulWidget for Budgeted<W> {
    type State = W::State;

    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
        let mut signal = self.signal.clone();
        signal.widget_id = self.widget_id;
        signal.essential = self.inner.is_essential();
        signal.area_cells = area.width as u32 * area.height as u32;
        frame.register_widget_signal(signal);

        if frame.should_render_budgeted_widget(self.widget_id, self.inner.is_essential()) {
            StatefulWidget::render(&self.inner, area, frame, state);
        }
    }
}

/// A widget that renders based on mutable state.
///
/// Use `StatefulWidget` when the widget needs to:
///
/// - Update scroll position during render
/// - Track selection state
/// - Cache computed layout information
/// - Synchronize view with external model
///
/// # Example
///
/// ```ignore
/// pub struct ListState {
///     pub selected: Option<usize>,
///     pub offset: usize,
/// }
///
/// impl StatefulWidget for List<'_> {
///     type State = ListState;
///
///     fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
///         // Adjust offset to keep selection visible
///         if let Some(sel) = state.selected {
///             if sel < state.offset {
///                 state.offset = sel;
///             }
///         }
///         // Render items starting from offset...
///     }
/// }
/// ```
///
/// # Stateful vs Stateless
///
/// Prefer stateless [`Widget`] when possible. Use `StatefulWidget` only when
/// the render pass genuinely needs to modify state (e.g., scroll adjustment).
pub trait StatefulWidget {
    /// The state type associated with this widget.
    type State;

    /// Render the widget into the frame, potentially modifying state.
    ///
    /// State modifications should be limited to:
    /// - Scroll offset adjustments
    /// - Selection clamping
    /// - Layout caching
    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State);
}

/// Merge a [`Style`] into a cell, preserving existing properties for unset fields.
///
/// - **Foreground / Background:** Only overwritten when the style explicitly sets
///   the field (`Some`).  Background colours with alpha < 255 are composited via
///   Porter-Duff SourceOver so semi-transparent overlays blend correctly.
/// - **Attributes:** New flags are OR-ed on top of existing flags (never cleared).
pub(crate) fn apply_style(cell: &mut Cell, style: Style) {
    if let Some(fg) = style.fg {
        cell.fg = fg;
    }
    if let Some(bg) = style.bg {
        match bg.a() {
            0 => {}                          // Fully transparent: no-op
            255 => cell.bg = bg,             // Fully opaque: replace
            _ => cell.bg = bg.over(cell.bg), // Composite src-over-dst
        }
    }
    if let Some(attrs) = style.attrs {
        let cell_flags: ftui_render::cell::StyleFlags = attrs.into();
        cell.attrs = cell.attrs.merged_flags(cell_flags);
    }
}

/// Apply a style to all cells in a rectangular area using **merge** semantics.
///
/// Only fields that are explicitly set in `style` (i.e. `Some`) are applied;
/// unset fields leave the existing cell values intact.  This is the correct
/// behaviour for selection / highlight overlays that specify only a background
/// colour — per-cell foreground colours from earlier text rendering are preserved.
///
/// - **Background:** Alpha-aware compositing (Porter-Duff SourceOver).
/// - **Attributes:** OR-ed on top of existing flags (never cleared).
pub(crate) fn set_style_area(buf: &mut Buffer, area: Rect, style: Style) {
    if style.is_empty() {
        return;
    }
    let clipped = area.intersection(&buf.current_scissor());
    if clipped.is_empty() {
        return;
    }

    let opacity = buf.current_opacity();
    let fg = style.fg.map(|fg| fg.with_opacity(opacity));
    let bg = style.bg.map(|bg| bg.with_opacity(opacity));
    let attrs = style.attrs.map(ftui_render::cell::StyleFlags::from);
    for y in clipped.y..clipped.bottom() {
        let Some(row) = buf.row_cells_mut_span(y, clipped.x, clipped.right()) else {
            continue;
        };
        for cell in row {
            if let Some(fg) = fg {
                cell.fg = fg;
            }
            if let Some(bg) = bg {
                match bg.a() {
                    0 => {}                          // Fully transparent: no-op
                    255 => cell.bg = bg,             // Fully opaque: replace
                    _ => cell.bg = bg.over(cell.bg), // Composite src-over-dst
                }
            }
            if let Some(attrs) = attrs {
                cell.attrs = cell.attrs.merged_flags(attrs);
            }
        }
    }
}

/// Clear a text area with styled spaces before rendering new content.
pub(crate) fn clear_text_area(frame: &mut Frame, area: Rect, style: Style) {
    if area.width == 0 || area.height == 0 {
        return;
    }

    let mut cell = Cell::from_char(' ');
    apply_style(&mut cell, style);
    frame.buffer.fill(area, cell);
}

/// Clear a single text row with styled spaces before rendering new content.
pub(crate) fn clear_text_row(frame: &mut Frame, area: Rect, style: Style) {
    clear_text_area(frame, Rect::new(area.x, area.y, area.width, 1), style);
}

/// Build a text cell that inherits existing visual styling from the buffer.
///
/// This preserves foreground/background/style flags applied by prior area-wide
/// overlays (for example selection/highlight passes) while intentionally
/// dropping any stale hyperlink ID before new text is written.
fn inherited_text_cell(
    frame: &Frame,
    x: u16,
    y: u16,
    content: ftui_render::cell::CellContent,
) -> Cell {
    let mut cell = frame.buffer.get(x, y).copied().unwrap_or_default();
    cell.content = content;
    cell.attrs = ftui_render::cell::CellAttrs::new(cell.attrs.flags(), 0);
    cell
}

/// Draw a text span into a frame at the given position.
///
/// Returns the x position after the last drawn character.
/// Stops at `max_x` (exclusive).
pub(crate) fn draw_text_span(
    frame: &mut Frame,
    mut x: u16,
    y: u16,
    content: &str,
    style: Style,
    max_x: u16,
) -> u16 {
    use unicode_segmentation::UnicodeSegmentation;

    for grapheme in content.graphemes(true) {
        if x >= max_x {
            break;
        }
        let w = grapheme_width(grapheme);
        if w == 0 {
            continue;
        }
        if x.saturating_add(w as u16) > max_x {
            break;
        }

        // Intern grapheme if needed
        let cell_content = if w > 1 || grapheme.chars().count() > 1 {
            let id = frame.intern_with_width(grapheme, w as u8);
            ftui_render::cell::CellContent::from_grapheme(id)
        } else if let Some(c) = grapheme.chars().next() {
            ftui_render::cell::CellContent::from_char(c)
        } else {
            continue;
        };

        let mut cell = inherited_text_cell(frame, x, y, cell_content);
        apply_style(&mut cell, style);

        // set_fast() skips scissor/opacity/compositing checks for common
        // single-width opaque cells; falls back to set() otherwise.
        frame.buffer.set_fast(x, y, cell);

        x = x.saturating_add(w as u16);
    }
    x
}

/// Draw a text span, optionally attaching a hyperlink.
#[allow(dead_code)]
pub(crate) fn draw_text_span_with_link(
    frame: &mut Frame,
    x: u16,
    y: u16,
    content: &str,
    style: Style,
    max_x: u16,
    link_url: Option<&str>,
) -> u16 {
    draw_text_span_scrolled(frame, x, y, content, style, max_x, 0, link_url)
}

/// Draw a text span with horizontal scrolling (skip first `scroll_x` visual cells).
#[allow(dead_code, clippy::too_many_arguments)]
pub(crate) fn draw_text_span_scrolled(
    frame: &mut Frame,
    mut x: u16,
    y: u16,
    content: &str,
    style: Style,
    max_x: u16,
    scroll_x: u16,
    link_url: Option<&str>,
) -> u16 {
    use unicode_segmentation::UnicodeSegmentation;

    // Register link if present
    let link_id = if let Some(url) = link_url {
        frame.register_link(url)
    } else {
        0
    };

    // The logical span may extend beyond the terminal coordinate range.
    let scroll_x = usize::from(scroll_x);
    let mut visual_pos: usize = 0;

    for grapheme in content.graphemes(true) {
        if x >= max_x {
            break;
        }
        let w = grapheme_width(grapheme);
        if w == 0 {
            continue;
        }

        let next_visual_pos = visual_pos.saturating_add(w);

        // Check if this grapheme is visible
        if next_visual_pos <= scroll_x {
            // Fully scrolled out
            visual_pos = next_visual_pos;
            continue;
        }

        if visual_pos < scroll_x {
            // Partially scrolled out (e.g. wide char starting at scroll_x - 1)
            // We skip the whole character because we can't render half a cell.
            visual_pos = next_visual_pos;
            continue;
        }

        if x.saturating_add(w as u16) > max_x {
            break;
        }

        // Intern grapheme if needed
        let cell_content = if w > 1 || grapheme.chars().count() > 1 {
            let id = frame.intern_with_width(grapheme, w as u8);
            ftui_render::cell::CellContent::from_grapheme(id)
        } else if let Some(c) = grapheme.chars().next() {
            ftui_render::cell::CellContent::from_char(c)
        } else {
            continue;
        };

        let mut cell = inherited_text_cell(frame, x, y, cell_content);
        apply_style(&mut cell, style);

        // Apply link ID if present
        if link_id != 0 {
            cell.attrs = cell.attrs.with_link(link_id);
        }

        frame.buffer.set_fast(x, y, cell);

        x = x.saturating_add(w as u16);
        visual_pos = next_visual_pos;
    }
    x
}

/// Helper for allocation-free case-insensitive containment check.
pub(crate) fn contains_ignore_case(haystack: &str, needle_lower: &str) -> bool {
    if needle_lower.is_empty() {
        return true;
    }
    // Fast path for ASCII
    if haystack.is_ascii() && needle_lower.is_ascii() {
        let haystack_bytes = haystack.as_bytes();
        let needle_bytes = needle_lower.as_bytes();
        if needle_bytes.len() > haystack_bytes.len() {
            return false;
        }
        // Naive byte-by-byte scan is fast enough for short strings (UI labels)
        for i in 0..=haystack_bytes.len() - needle_bytes.len() {
            let mut match_found = true;
            for (j, &b) in needle_bytes.iter().enumerate() {
                if haystack_bytes[i + j].to_ascii_lowercase() != b {
                    match_found = false;
                    break;
                }
            }
            if match_found {
                return true;
            }
        }
        return false;
    }
    // Fallback for Unicode (allocates, but correct)
    haystack.to_lowercase().contains(needle_lower)
}

#[cfg(test)]
mod tests {
    use super::*;
    use ftui_render::cell::PackedRgba;
    use ftui_render::grapheme_pool::GraphemePool;

    /// `frame.render_widget(&w, area)` must be exactly `w.render(area, frame)`:
    /// same cells, same clipping, no extra state.
    #[test]
    fn frame_ext_render_widget_matches_direct_render() {
        struct Fill(char);
        impl Widget for Fill {
            fn render(&self, area: Rect, frame: &mut Frame) {
                for y in area.y..area.y + area.height {
                    for x in area.x..area.x + area.width {
                        frame.buffer.set_raw(x, y, Cell::from_char(self.0));
                    }
                }
            }
        }

        let mut pool_a = GraphemePool::new();
        let mut direct = Frame::new(6, 2, &mut pool_a);
        Fill('d').render(Rect::new(1, 0, 3, 2), &mut direct);

        let mut pool_b = GraphemePool::new();
        let mut via_ext = Frame::new(6, 2, &mut pool_b);
        via_ext.render_widget(&Fill('d'), Rect::new(1, 0, 3, 2));
        assert_eq!(via_ext.area(), Rect::new(0, 0, 6, 2));

        for y in 0..2 {
            for x in 0..6 {
                assert_eq!(
                    direct.buffer.get(x, y).map(|cell| cell.content),
                    via_ext.buffer.get(x, y).map(|cell| cell.content),
                    "cell ({x},{y}) differs between direct render and FrameExt"
                );
            }
        }
        assert_eq!(
            via_ext.buffer.get(1, 0).map(|cell| cell.content),
            Some(Cell::from_char('d').content)
        );
        assert_eq!(
            via_ext.buffer.get(0, 0).map(|cell| cell.content),
            Some(Cell::default().content)
        );
    }

    /// With a tree builder attached to the frame, rendering an `Accessible`
    /// widget pushes its nodes (a list with items, a titled block, a
    /// paragraph) so the runtime can build the tree; without one nothing is
    /// collected and rendering is unchanged.
    #[test]
    fn rendering_accessible_widgets_pushes_their_nodes_into_the_frame() {
        use crate::block::Block;
        use crate::list::{List, ListState};
        use crate::paragraph::Paragraph;
        use ftui_a11y::node::A11yRole;
        use ftui_a11y::tree::A11yTreeBuilder;

        let mut pool = GraphemePool::new();
        let mut builder = A11yTreeBuilder::new();
        let mut frame = Frame::new(30, 8, &mut pool);
        frame.set_a11y(&mut builder);

        let mut list_state = ListState::default();
        let list = List::new(["alpha", "beta"]);
        StatefulWidget::render(&list, Rect::new(0, 0, 30, 3), &mut frame, &mut list_state);
        Block::new()
            .title("Details")
            .render(Rect::new(0, 3, 30, 3), &mut frame);
        Paragraph::new("hello").render(Rect::new(0, 6, 30, 1), &mut frame);
        frame.finish_a11y();
        let order = frame.take_a11y_order();
        drop(frame);

        let tree = builder.build();
        assert_eq!(order.len(), tree.node_count());
        assert!(
            order.len() >= 5,
            "list + 2 items + block + paragraph: {order:?}"
        );
        let roles: Vec<A11yRole> = order
            .iter()
            .filter_map(|id| tree.node(*id).map(|n| n.role))
            .collect();
        assert_eq!(roles[0], A11yRole::List);
        assert_eq!(roles[1], A11yRole::ListItem);
        assert_eq!(roles[2], A11yRole::ListItem);
        assert!(roles.contains(&A11yRole::Group), "{roles:?}");
        let list_id = order[0];
        assert_eq!(
            tree.node(list_id).map(|n| n.children.len()),
            Some(2),
            "list items are the list's children"
        );
        assert_eq!(
            tree.root_id(),
            Some(list_id),
            "first parentless node is the root"
        );
        let text = tree.dump_text(&order);
        assert!(text.contains("ListItem \"alpha\""), "{text}");
        assert!(text.contains("Group \"Details\""), "{text}");

        // No builder: nothing collected, rendering still works.
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(30, 8, &mut pool);
        Paragraph::new("hello").render(Rect::new(0, 0, 30, 1), &mut frame);
        assert!(frame.a11y_order().is_empty());
    }

    /// The stateful helper hands the widget its state and keeps mutations.
    #[test]
    fn frame_ext_render_stateful_widget_passes_state() {
        struct Counter;
        impl StatefulWidget for Counter {
            type State = u32;
            fn render(&self, _area: Rect, _frame: &mut Frame, state: &mut u32) {
                *state += 1;
            }
        }
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(4, 1, &mut pool);
        let mut count = 0;
        frame.render_stateful_widget(&Counter, frame.area(), &mut count);
        frame.render_stateful_widget(&Counter, Rect::new(0, 0, 1, 1), &mut count);
        assert_eq!(count, 2);
    }

    #[test]
    fn apply_style_sets_fg() {
        let mut cell = Cell::default();
        let style = Style::new().fg(PackedRgba::rgb(255, 0, 0));
        apply_style(&mut cell, style);
        assert_eq!(cell.fg, PackedRgba::rgb(255, 0, 0));
    }

    #[test]
    fn apply_style_sets_bg() {
        let mut cell = Cell::default();
        let style = Style::new().bg(PackedRgba::rgb(0, 255, 0));
        apply_style(&mut cell, style);
        assert_eq!(cell.bg, PackedRgba::rgb(0, 255, 0));
    }

    #[test]
    fn apply_style_preserves_content() {
        let mut cell = Cell::from_char('Z');
        let style = Style::new().fg(PackedRgba::rgb(1, 2, 3));
        apply_style(&mut cell, style);
        assert_eq!(cell.content.as_char(), Some('Z'));
    }

    #[test]
    fn apply_style_empty_is_noop() {
        let original = Cell::default();
        let mut cell = Cell::default();
        apply_style(&mut cell, Style::default());
        assert_eq!(cell.fg, original.fg);
        assert_eq!(cell.bg, original.bg);
    }

    #[test]
    fn apply_style_bg_only_preserves_fg() {
        // Simulate: cell already has syntax-highlighted fg, selection overlay sets only bg.
        let mut cell = Cell::from_char('x').with_fg(PackedRgba::rgb(0, 200, 0));
        let selection = Style::new().bg(PackedRgba::rgb(0, 0, 180));
        apply_style(&mut cell, selection);
        // fg must survive — the selection style didn't set a fg.
        assert_eq!(cell.fg, PackedRgba::rgb(0, 200, 0));
        assert_eq!(cell.bg, PackedRgba::rgb(0, 0, 180));
    }

    #[test]
    fn apply_style_composites_alpha_bg() {
        let base_bg = PackedRgba::rgb(200, 0, 0);
        let mut cell = Cell::default().with_bg(base_bg);
        let overlay = PackedRgba::rgba(0, 0, 200, 128);
        apply_style(&mut cell, Style::new().bg(overlay));
        assert_eq!(cell.bg, overlay.over(base_bg));
    }

    #[test]
    fn apply_style_transparent_bg_is_noop() {
        let base_bg = PackedRgba::rgb(100, 100, 100);
        let mut cell = Cell::default().with_bg(base_bg);
        apply_style(&mut cell, Style::new().bg(PackedRgba::rgba(255, 0, 0, 0)));
        assert_eq!(cell.bg, base_bg);
    }

    #[test]
    fn apply_style_merges_attrs_not_replaces() {
        use ftui_render::cell::StyleFlags as CellFlags;
        // Cell starts with BOLD.
        let mut cell = Cell::default();
        cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
        // Overlay adds ITALIC — should NOT clear BOLD.
        let overlay = Style::new().italic();
        apply_style(&mut cell, overlay);
        assert!(cell.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
        assert!(
            cell.attrs.has_flag(CellFlags::ITALIC),
            "ITALIC must be added"
        );
    }

    #[test]
    fn set_style_area_bg_only_preserves_per_cell_fg() {
        // A 3-cell buffer where each cell has a distinct fg.
        let mut buf = Buffer::new(3, 1);
        buf.set(0, 0, Cell::from_char('R').with_fg(PackedRgba::RED));
        buf.set(1, 0, Cell::from_char('G').with_fg(PackedRgba::GREEN));
        buf.set(2, 0, Cell::from_char('B').with_fg(PackedRgba::BLUE));

        // Selection highlight sets only bg.
        let highlight = Style::new().bg(PackedRgba::rgb(40, 40, 40));
        set_style_area(&mut buf, Rect::new(0, 0, 3, 1), highlight);

        // All fg colours must be preserved.
        assert_eq!(buf.get(0, 0).unwrap().fg, PackedRgba::RED);
        assert_eq!(buf.get(1, 0).unwrap().fg, PackedRgba::GREEN);
        assert_eq!(buf.get(2, 0).unwrap().fg, PackedRgba::BLUE);
        // bg should be the highlight colour.
        assert_eq!(buf.get(0, 0).unwrap().bg, PackedRgba::rgb(40, 40, 40));
    }

    #[test]
    fn set_style_area_merges_attrs_not_replaces() {
        use ftui_render::cell::StyleFlags as CellFlags;
        let mut buf = Buffer::new(1, 1);
        let mut cell = Cell::from_char('X');
        cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
        buf.set(0, 0, cell);

        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().italic());

        let result = buf.get(0, 0).unwrap();
        assert!(result.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
        assert!(
            result.attrs.has_flag(CellFlags::ITALIC),
            "ITALIC must be added"
        );
    }

    #[test]
    fn set_style_area_applies_to_all_cells() {
        let mut buf = Buffer::new(3, 2);
        let area = Rect::new(0, 0, 3, 2);
        let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
        set_style_area(&mut buf, area, style);

        for y in 0..2 {
            for x in 0..3 {
                assert_eq!(
                    buf.get(x, y).unwrap().bg,
                    PackedRgba::rgb(10, 20, 30),
                    "cell ({x},{y}) should have style applied"
                );
            }
        }
    }

    #[test]
    fn set_style_area_composites_alpha_bg_over_existing_bg() {
        let mut buf = Buffer::new(1, 1);
        let base = PackedRgba::rgb(200, 0, 0);
        buf.set(0, 0, Cell::default().with_bg(base));

        let overlay = PackedRgba::rgba(0, 0, 200, 128);
        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(overlay));

        let expected = overlay.over(base);
        assert_eq!(buf.get(0, 0).unwrap().bg, expected);
    }

    #[test]
    fn set_style_area_partial_rect() {
        let mut buf = Buffer::new(5, 5);
        let area = Rect::new(1, 1, 2, 2);
        let style = Style::new().fg(PackedRgba::rgb(99, 99, 99));
        set_style_area(&mut buf, area, style);

        // Inside area should be styled
        assert_eq!(buf.get(1, 1).unwrap().fg, PackedRgba::rgb(99, 99, 99));
        assert_eq!(buf.get(2, 2).unwrap().fg, PackedRgba::rgb(99, 99, 99));

        // Outside area should be default
        assert_ne!(buf.get(0, 0).unwrap().fg, PackedRgba::rgb(99, 99, 99));
    }

    #[test]
    fn set_style_area_empty_style_is_noop() {
        let mut buf = Buffer::new(3, 3);
        buf.set(0, 0, Cell::from_char('A'));
        let original_fg = buf.get(0, 0).unwrap().fg;

        set_style_area(&mut buf, Rect::new(0, 0, 3, 3), Style::default());

        // Should not have changed
        assert_eq!(buf.get(0, 0).unwrap().fg, original_fg);
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
    }

    #[test]
    fn set_style_area_respects_scissor() {
        let mut buf = Buffer::new(3, 3);
        let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));

        buf.push_scissor(Rect::new(1, 1, 1, 1));
        set_style_area(&mut buf, Rect::new(0, 0, 3, 3), style);

        assert_eq!(buf.get(1, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
        assert_ne!(buf.get(0, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
        assert_ne!(buf.get(1, 0).unwrap().bg, PackedRgba::rgb(10, 20, 30));
        assert_ne!(buf.get(2, 2).unwrap().bg, PackedRgba::rgb(10, 20, 30));
    }

    #[test]
    fn set_style_area_respects_opacity_stack() {
        let mut buf = Buffer::new(1, 1);
        let base_fg = PackedRgba::rgb(20, 30, 40);
        let base_bg = PackedRgba::rgb(50, 60, 70);
        buf.set(0, 0, Cell::from_char('X').with_fg(base_fg).with_bg(base_bg));

        let overlay_fg = PackedRgba::rgb(200, 100, 0);
        let overlay_bg = PackedRgba::rgb(0, 0, 200);
        buf.push_opacity(0.5);
        set_style_area(
            &mut buf,
            Rect::new(0, 0, 1, 1),
            Style::new().fg(overlay_fg).bg(overlay_bg),
        );

        let cell = buf.get(0, 0).unwrap();
        assert_eq!(cell.fg, overlay_fg.with_opacity(0.5));
        assert_eq!(cell.bg, overlay_bg.with_opacity(0.5).over(base_bg));
    }

    #[test]
    fn draw_text_span_basic() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 1, &mut pool);
        let end_x = draw_text_span(&mut frame, 0, 0, "ABC", Style::default(), 10);

        assert_eq!(end_x, 3);
        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
    }

    #[test]
    fn draw_text_span_clipped_at_max_x() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 1, &mut pool);
        let end_x = draw_text_span(&mut frame, 0, 0, "ABCDEF", Style::default(), 3);

        assert_eq!(end_x, 3);
        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
        // 'D' should not be drawn
        assert!(frame.buffer.get(3, 0).unwrap().is_empty());
    }

    #[test]
    fn draw_text_span_starts_at_offset() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 1, &mut pool);
        let end_x = draw_text_span(&mut frame, 5, 0, "XY", Style::default(), 10);

        assert_eq!(end_x, 7);
        assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('X'));
        assert_eq!(frame.buffer.get(6, 0).unwrap().content.as_char(), Some('Y'));
        assert!(frame.buffer.get(4, 0).unwrap().is_empty());
    }

    #[test]
    fn draw_text_span_empty_string() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(5, 1, &mut pool);
        let end_x = draw_text_span(&mut frame, 0, 0, "", Style::default(), 5);
        assert_eq!(end_x, 0);
    }

    #[test]
    fn draw_text_span_applies_style() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(5, 1, &mut pool);
        let style = Style::new().fg(PackedRgba::rgb(255, 128, 0));
        draw_text_span(&mut frame, 0, 0, "A", style, 5);

        assert_eq!(
            frame.buffer.get(0, 0).unwrap().fg,
            PackedRgba::rgb(255, 128, 0)
        );
    }

    #[test]
    fn draw_text_span_preserves_existing_overlay_fg_and_bg() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(3, 1, &mut pool);
        frame.buffer.set(
            0,
            0,
            Cell::from_char('x').with_fg(PackedRgba::rgb(200, 40, 10)),
        );
        set_style_area(
            &mut frame.buffer,
            Rect::new(0, 0, 1, 1),
            Style::new().bg(PackedRgba::rgb(20, 30, 40)),
        );

        draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);

        let cell = frame.buffer.get(0, 0).unwrap();
        assert_eq!(cell.content.as_char(), Some('A'));
        assert_eq!(cell.fg, PackedRgba::rgb(200, 40, 10));
        assert_eq!(cell.bg, PackedRgba::rgb(20, 30, 40));
    }

    #[test]
    fn draw_text_span_drops_stale_link_id_but_keeps_style_flags() {
        use ftui_render::cell::{CellAttrs, StyleFlags as CellFlags};

        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(3, 1, &mut pool);
        frame.buffer.set(
            0,
            0,
            Cell::from_char('x').with_attrs(CellAttrs::new(CellFlags::UNDERLINE, 42)),
        );

        draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);

        let cell = frame.buffer.get(0, 0).unwrap();
        assert_eq!(cell.content.as_char(), Some('A'));
        assert!(cell.attrs.has_flag(CellFlags::UNDERLINE));
        assert_eq!(cell.attrs.link_id(), 0);
    }

    #[test]
    fn draw_text_span_max_x_at_start_draws_nothing() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(5, 1, &mut pool);
        let end_x = draw_text_span(&mut frame, 3, 0, "ABC", Style::default(), 3);
        assert_eq!(end_x, 3);
        assert!(frame.buffer.get(3, 0).unwrap().is_empty());
    }

    #[test]
    fn widget_is_essential_default_false() {
        struct DummyWidget;
        impl Widget for DummyWidget {
            fn render(&self, _: Rect, _: &mut Frame) {}
        }
        assert!(!DummyWidget.is_essential());
    }

    #[test]
    fn budgeted_new_and_inner() {
        struct TestW;
        impl Widget for TestW {
            fn render(&self, _: Rect, _: &mut Frame) {}
        }
        let b = Budgeted::new(42, TestW);
        assert_eq!(b.widget_id, 42);
        let _ = b.inner(); // Should not panic
    }

    #[test]
    fn budgeted_with_signal() {
        struct TestW;
        impl Widget for TestW {
            fn render(&self, _: Rect, _: &mut Frame) {}
        }
        let sig = WidgetSignal::new(99);
        let b = Budgeted::new(42, TestW).with_signal(sig);
        // with_signal should override the signal's widget_id to match
        assert_eq!(b.signal.widget_id, 42);
    }

    #[test]
    fn set_style_area_transparent_bg_is_noop() {
        let mut buf = Buffer::new(1, 1);
        let base = PackedRgba::rgb(100, 100, 100);
        buf.set(0, 0, Cell::default().with_bg(base));

        // Alpha=0 means fully transparent, should leave bg unchanged
        let transparent = PackedRgba::rgba(255, 0, 0, 0);
        set_style_area(
            &mut buf,
            Rect::new(0, 0, 1, 1),
            Style::new().bg(transparent),
        );
        assert_eq!(buf.get(0, 0).unwrap().bg, base);
    }

    #[test]
    fn set_style_area_opaque_bg_replaces() {
        let mut buf = Buffer::new(1, 1);
        buf.set(
            0,
            0,
            Cell::default().with_bg(PackedRgba::rgb(100, 100, 100)),
        );

        let opaque = PackedRgba::rgba(0, 255, 0, 255);
        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(opaque));
        assert_eq!(buf.get(0, 0).unwrap().bg, opaque);
    }

    #[test]
    fn draw_text_span_scrolled_skips_chars() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 1, &mut pool);
        // Scroll past first 2 chars of "ABCDE"
        let end_x =
            draw_text_span_scrolled(&mut frame, 0, 0, "ABCDE", Style::default(), 10, 2, None);

        assert_eq!(end_x, 3);
        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('C'));
        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('D'));
        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('E'));
    }

    fn collect_a11y_from_render<F>(width: u16, height: u16, render: F) -> ftui_a11y::tree::A11yTree
    where
        F: FnOnce(&mut Frame),
    {
        let mut pool = GraphemePool::new();
        let mut builder = ftui_a11y::tree::A11yTreeBuilder::new();
        {
            let mut frame = Frame::new(width, height, &mut pool);
            frame.set_a11y(&mut builder);
            render(&mut frame);
            frame.finish_a11y();
        }
        builder.build()
    }

    #[test]
    fn block_render_pushes_a11y_nodes() {
        use crate::block::Block;
        use crate::borders::Borders;

        let block = Block::new().borders(Borders::ALL).title("Panel");
        let area = Rect::new(0, 0, 20, 6);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&block, area);
        let tree = collect_a11y_from_render(20, 6, |frame| {
            block.render(area, frame);
        });
        assert_eq!(tree.node_count(), expected.len());
        let root = tree.node(expected[0].id).expect("block node present");
        assert_eq!(root.role, ftui_a11y::node::A11yRole::Group);
        assert_eq!(root.name.as_deref(), Some("Panel"));
    }

    #[test]
    fn tabs_render_pushes_a11y_nodes() {
        use crate::tabs::{Tab, Tabs, TabsState};

        let tabs = Tabs::new(vec![Tab::new("General"), Tab::new("Advanced")]);
        let area = Rect::new(0, 0, 30, 1);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&tabs, area);
        let tree = collect_a11y_from_render(30, 1, |frame| {
            let mut state = TabsState::default();
            StatefulWidget::render(&tabs, area, frame, &mut state);
        });
        assert_eq!(tree.node_count(), expected.len());
        for node in &expected {
            assert!(tree.node(node.id).is_some(), "missing tab node {}", node.id);
        }
    }

    #[test]
    fn progress_render_pushes_a11y_nodes() {
        use crate::progress::ProgressBar;

        let bar = ProgressBar::new().ratio(0.6).label("60%");
        let area = Rect::new(0, 0, 20, 1);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&bar, area);
        let tree = collect_a11y_from_render(20, 1, |frame| {
            bar.render(area, frame);
        });
        assert_eq!(tree.node_count(), expected.len());
        let node = tree.node(expected[0].id).expect("progress node present");
        assert_eq!(node.role, ftui_a11y::node::A11yRole::ProgressBar);
        assert_eq!(node.state.value_text.as_deref(), Some("60%"));
    }

    #[test]
    fn input_render_pushes_a11y_nodes() {
        use crate::input::TextInput;

        let input = TextInput::new()
            .with_value("alice")
            .with_placeholder("Username")
            .with_focused(true);
        let area = Rect::new(0, 0, 20, 1);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&input, area);
        let tree = collect_a11y_from_render(20, 1, |frame| {
            input.render(area, frame);
        });
        assert_eq!(tree.node_count(), expected.len());
        let node = tree.node(expected[0].id).expect("input node present");
        assert_eq!(node.role, ftui_a11y::node::A11yRole::TextInput);
        assert!(node.state.focused);
        assert_eq!(tree.focused_id(), Some(expected[0].id));
    }

    #[test]
    fn list_render_pushes_a11y_nodes() {
        use crate::list::{List, ListItem, ListState};

        let list = List::new([ListItem::new("First"), ListItem::new("Second")]);
        let area = Rect::new(0, 0, 20, 4);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&list, area);
        let tree = collect_a11y_from_render(20, 4, |frame| {
            let mut state = ListState::default();
            state.select(Some(1));
            StatefulWidget::render(&list, area, frame, &mut state);
        });
        assert_eq!(tree.node_count(), expected.len());
        let list_node = tree.node(expected[0].id).expect("list node present");
        assert_eq!(list_node.role, ftui_a11y::node::A11yRole::List);
        let second_child = tree
            .node(list_node.children[1])
            .expect("second list item node present");
        assert_eq!(second_child.name.as_deref(), Some("Second"));
        assert!(second_child.state.selected);
    }

    #[test]
    fn table_render_pushes_a11y_nodes() {
        use crate::table::{Row, Table, TableState};
        use ftui_layout::Constraint;

        let table = Table::new(
            [Row::new(["a", "1"]), Row::new(["b", "2"])],
            [Constraint::Fixed(8), Constraint::Fixed(8)],
        );
        let area = Rect::new(0, 0, 20, 4);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&table, area);
        let tree = collect_a11y_from_render(20, 4, |frame| {
            let mut state = TableState::default();
            state.select(Some(0));
            StatefulWidget::render(&table, area, frame, &mut state);
        });
        assert_eq!(tree.node_count(), expected.len());
        let table_node = tree.node(expected[0].id).expect("table node present");
        assert_eq!(table_node.role, ftui_a11y::node::A11yRole::Table);
    }

    #[test]
    fn spinner_render_pushes_a11y_nodes() {
        use crate::spinner::{Spinner, SpinnerState};

        let spinner = Spinner::new().label("Loading");
        let area = Rect::new(0, 0, 20, 1);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&spinner, area);
        let tree = collect_a11y_from_render(20, 1, |frame| {
            let mut state = SpinnerState::default();
            StatefulWidget::render(&spinner, area, frame, &mut state);
        });
        assert_eq!(tree.node_count(), expected.len());
        let node = tree.node(expected[0].id).expect("spinner node present");
        assert_eq!(node.name, expected[0].name);
        assert!(node.state.busy);
    }

    #[test]
    fn scrollbar_render_pushes_a11y_nodes() {
        use crate::scrollbar::{Scrollbar, ScrollbarOrientation, ScrollbarState};

        let sb = Scrollbar::new(ScrollbarOrientation::VerticalRight);
        let area = Rect::new(0, 0, 1, 10);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&sb, area);
        let tree = collect_a11y_from_render(1, 10, |frame| {
            let mut state = ScrollbarState::new(100, 20, 10);
            StatefulWidget::render(&sb, area, frame, &mut state);
        });
        assert_eq!(tree.node_count(), expected.len());
        let node = tree.node(expected[0].id).expect("scrollbar node present");
        assert_eq!(node.role, ftui_a11y::node::A11yRole::ScrollBar);
    }

    #[test]
    fn paragraph_render_pushes_a11y_nodes() {
        use crate::paragraph::Paragraph;

        let p = Paragraph::new("Hello world");
        let area = Rect::new(0, 0, 20, 2);
        let expected = ftui_a11y::Accessible::accessibility_nodes(&p, area);
        let tree = collect_a11y_from_render(20, 2, |frame| {
            p.render(area, frame);
        });
        assert_eq!(tree.node_count(), expected.len());
        let node = tree.node(expected[0].id).expect("paragraph node present");
        assert_eq!(node.role, ftui_a11y::node::A11yRole::Label);
        assert_eq!(node.name.as_deref(), Some("Hello world"));
    }

    #[test]
    fn block_render_with_children_nests_child_nodes() {
        use crate::block::Block;
        use crate::borders::Borders;
        use crate::input::TextInput;
        use crate::paragraph::Paragraph;

        let block = Block::new().borders(Borders::ALL).title("Outer");
        let outer_area = Rect::new(0, 0, 30, 8);
        let inner_area = block.inner(outer_area);
        let p_area = Rect::new(inner_area.x, inner_area.y, inner_area.width, 1);
        let i_area = Rect::new(inner_area.x, inner_area.y + 1, inner_area.width, 1);

        let tree = collect_a11y_from_render(30, 8, |frame| {
            block.render_with_children(outer_area, frame, |inner, frame| {
                assert_eq!(inner, inner_area);
                Paragraph::new("Prompt").render(p_area, frame);
                TextInput::new().with_value("abc").render(i_area, frame);
            });
        });

        let block_id = a11y_node_id(outer_area);
        let p_id = a11y_node_id(p_area);
        let i_id = a11y_node_id(i_area);
        let block_node = tree.node(block_id).expect("block node");
        assert_eq!(block_node.children, vec![p_id, i_id]);
        assert_eq!(
            tree.node(p_id).expect("paragraph node").parent,
            Some(block_id)
        );
        assert_eq!(tree.node(i_id).expect("input node").parent, Some(block_id));
    }

    #[test]
    fn render_without_builder_allocates_nothing() {
        use crate::block::Block;
        use crate::borders::Borders;
        use crate::input::TextInput;
        use crate::paragraph::Paragraph;

        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(30, 8, &mut pool);
        assert!(!frame.a11y_enabled());

        let block = Block::new().borders(Borders::ALL).title("Outer");
        block.render_with_children(Rect::new(0, 0, 30, 8), &mut frame, |inner, frame| {
            Paragraph::new("Prompt").render(Rect::new(inner.x, inner.y, inner.width, 1), frame);
            TextInput::new()
                .with_value("abc")
                .render(Rect::new(inner.x, inner.y + 1, inner.width, 1), frame);
        });
        frame.finish_a11y();
        assert!(frame.take_a11y_order().is_empty());
    }
}