ftui-layout 0.5.1

Flex and grid layout solvers for FrankenTUI.
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
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
//! Canonical keyboard command model and focus-graph semantics for panes
//! (bd-21pbi.1).
//!
//! This module defines a **host-agnostic** keyboard interaction contract for
//! the pane workspace: a normative command vocabulary ([`PaneCommand`]), a
//! deterministic focus graph over the split tree (in-order traversal and
//! spatial/directional navigation with explicit tie-breaks), a pure command
//! resolver ([`resolve`]) that maps each command to a focus change, a list of
//! structural [`PaneOperation`]s, or a transient view-state change, plus
//! explicit repeat/acceleration ([`PaneCommandAcceleration`]) and keymap
//! precedence ([`PaneKeymapPrecedence`]) policies.
//!
//! Why a command layer? Pointer drag-resize already has a first-class semantic
//! pipeline (`PaneSemanticInputEvent` -> `PaneDragResizeMachine` ->
//! `PaneTree::operations_for_transition`). Keyboard interaction needs an
//! equivalent, but its vocabulary is broader than resize (focus navigation,
//! split/close/move/swap, maximize/restore) and must NOT be expressed as
//! host-specific key events. [`PaneCommand`] is that vocabulary: terminal
//! (bd-21pbi.2) and web (bd-21pbi.3) hosts translate raw key events into
//! `PaneCommand`s, and [`resolve`] turns each command into the same outcome on
//! every host. This is the executable form of the normative spec in
//! `docs/spec/pane-keyboard-interaction.md`.
//!
//! Determinism guarantee: for a fixed split-tree topology, layout, and focus
//! context, [`resolve`] is a pure function. Equivalent command streams
//! therefore yield identical pane state (topology hash + active pane) across
//! hosts — the cross-host parity property the pane validation epic requires.

use crate::Rect;
use crate::pane::{
    PANE_SNAP_DEFAULT_HYSTERESIS_BPS, PaneAffordanceMotion, PaneDragResizeMachine, PaneId,
    PaneLayout, PaneLeaf, PaneNodeKind, PaneOperation, PanePlacement, PanePressureSnapProfile,
    PaneResizeDirection, PaneResizeTarget, PaneSemanticInputEvent, PaneSemanticInputEventKind,
    PaneSplitRatio, PaneTree, SplitAxis,
};

/// Neutral snap profile used when lowering keyboard resize commands through the
/// shared drag/resize machine. Keyboard nudges apply a fixed basis-point step
/// and are independent of snap pressure, so any valid profile yields identical
/// operations; this constant keeps the lowering deterministic.
const KEYBOARD_NEUTRAL_PRESSURE: PanePressureSnapProfile = PanePressureSnapProfile {
    strength_bps: 5_000,
    hysteresis_bps: PANE_SNAP_DEFAULT_HYSTERESIS_BPS,
};

/// A cardinal direction for spatial focus and pane movement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PaneCardinalDirection {
    /// Toward smaller x.
    Left,
    /// Toward larger x.
    Right,
    /// Toward smaller y.
    Up,
    /// Toward larger y.
    Down,
}

impl PaneCardinalDirection {
    /// The split axis a move/dock in this direction creates.
    #[must_use]
    pub const fn axis(self) -> SplitAxis {
        match self {
            Self::Left | Self::Right => SplitAxis::Horizontal,
            Self::Up | Self::Down => SplitAxis::Vertical,
        }
    }

    /// Placement of an incoming (moved) pane relative to a dock target in this
    /// direction. Left/Up place the incoming pane first; Right/Down place it
    /// second.
    #[must_use]
    pub const fn incoming_placement(self) -> PanePlacement {
        match self {
            Self::Left | Self::Up => PanePlacement::IncomingFirst,
            Self::Right | Self::Down => PanePlacement::ExistingFirst,
        }
    }
}

/// Cyclic ordinal over the deterministic focus order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PaneFocusOrdinal {
    /// The next leaf in focus order (wraps to the first).
    Next,
    /// The previous leaf in focus order (wraps to the last).
    Previous,
}

/// The canonical, host-agnostic pane keyboard command vocabulary.
///
/// Hosts translate raw key events into these commands; [`resolve`] maps each to
/// a deterministic outcome. Resize unit counts are supplied by the caller
/// (computed via [`PaneCommandAcceleration`]) so the command itself stays a
/// pure intent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaneCommand {
    /// Move focus to the next leaf in deterministic focus order (cyclic).
    FocusNext,
    /// Move focus to the previous leaf in deterministic focus order (cyclic).
    FocusPrevious,
    /// Move focus to the nearest leaf in a direction (spatial).
    FocusDirectional(PaneCardinalDirection),
    /// Move focus to the extreme leaf in a direction (jump to edge).
    FocusEdge(PaneCardinalDirection),
    /// Grow (`Increase`) or shrink (`Decrease`) the active pane by `units`
    /// snap steps, resizing its enclosing split.
    ResizeStep {
        /// `Increase` grows the active pane; `Decrease` shrinks it.
        direction: PaneResizeDirection,
        /// Number of snap steps (one step = `PANE_SNAP_DEFAULT_STEP_BPS`).
        units: u16,
    },
    /// Split the active leaf along `axis`, adding a new sibling leaf.
    Split(SplitAxis),
    /// Close the active leaf, promoting its sibling.
    Close,
    /// Move the active pane to dock against the nearest pane in a direction.
    MovePane(PaneCardinalDirection),
    /// Swap the active pane with its cyclic neighbour.
    SwapPane(PaneFocusOrdinal),
    /// Maximize the active pane (transient view state; no topology change).
    Maximize,
    /// Restore from a maximized state (transient view state).
    Restore,
}

/// Host-owned focus context consumed by [`resolve`]. This is plain input data,
/// not competing persistent state: hosts store the active/maximized pane
/// wherever they like (e.g. `WorkspaceSnapshot::active_pane_id`) and pass a
/// snapshot here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PaneFocusContext {
    /// The currently focused leaf, if any.
    pub active: Option<PaneId>,
    /// The currently maximized leaf, if any.
    pub maximized: Option<PaneId>,
}

impl PaneFocusContext {
    /// Construct a focus context with the given active leaf and no maximized
    /// pane.
    #[must_use]
    pub const fn active(active: PaneId) -> Self {
        Self {
            active: Some(active),
            maximized: None,
        }
    }
}

/// The concrete effect a resolved command produces. Focus changes and maximize
/// state are transient (no tree mutation); structural changes are a list of
/// [`PaneOperation`]s the host applies via `PaneTree::apply_operation`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PaneCommandEffect {
    /// Focus moved from `previous` to `active` with no topology change.
    Focus {
        /// The previously focused leaf, if any.
        previous: Option<PaneId>,
        /// The newly focused leaf.
        active: PaneId,
    },
    /// Apply these structural operations in order.
    Structural(Vec<PaneOperation>),
    /// Enter the maximized view state for `target`.
    Maximize {
        /// The leaf to maximize.
        target: PaneId,
    },
    /// Leave the maximized view state previously held by `previous`.
    Restore {
        /// The leaf that was maximized.
        previous: PaneId,
    },
    /// The command had no effect; see the reason.
    Noop(PaneCommandNoopReason),
}

/// Why a command resolved to a no-op.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaneCommandNoopReason {
    /// No active pane was set in the focus context.
    NoActivePane,
    /// The active pane id was not a leaf in the tree.
    ActiveNotLeaf,
    /// Only one pane exists; navigation/structural change is meaningless.
    OnlyOnePane,
    /// No pane exists in the requested direction.
    NoTargetInDirection,
    /// The active pane is the root and cannot be closed.
    RootCannotClose,
    /// The active leaf has no enclosing split to resize.
    NoEnclosingSplit,
    /// A pane is already maximized (or the active one is).
    AlreadyMaximized,
    /// No pane is currently maximized.
    NotMaximized,
}

/// The full result of resolving one [`PaneCommand`]: the effect plus the
/// resulting focus context the host should adopt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PaneCommandResolution {
    /// What the command does.
    pub effect: PaneCommandEffect,
    /// The active pane after the command (unchanged on no-op).
    pub next_active: Option<PaneId>,
    /// The maximized pane after the command (unchanged on no-op).
    pub next_maximized: Option<PaneId>,
}

impl PaneCommandResolution {
    fn noop(reason: PaneCommandNoopReason, ctx: PaneFocusContext) -> Self {
        Self {
            effect: PaneCommandEffect::Noop(reason),
            next_active: ctx.active,
            next_maximized: ctx.maximized,
        }
    }

    /// True when the command produced a real effect (not a no-op).
    #[must_use]
    pub const fn is_effective(&self) -> bool {
        !matches!(self.effect, PaneCommandEffect::Noop(_))
    }
}

/// Repeat-key acceleration policy for resize stepping. Explicit and testable:
/// the first `accelerate_after_repeats` presses use `base_units`; sustained
/// repeats escalate to `accelerated_units`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PaneCommandAcceleration {
    /// Snap steps applied on a non-repeated (or early-repeat) press.
    pub base_units: u16,
    /// Snap steps applied once the key has repeated enough.
    pub accelerated_units: u16,
    /// Repeat count at/after which acceleration engages.
    pub accelerate_after_repeats: u16,
}

impl Default for PaneCommandAcceleration {
    fn default() -> Self {
        Self {
            base_units: 1,
            accelerated_units: 5,
            accelerate_after_repeats: 3,
        }
    }
}

impl PaneCommandAcceleration {
    /// Snap steps for a key held with the given repeat count (0 = first press).
    #[must_use]
    pub const fn units_for(&self, repeat_count: u16) -> u16 {
        if repeat_count >= self.accelerate_after_repeats {
            self.accelerated_units
        } else {
            self.base_units
        }
    }
}

/// Conflict precedence between application-level keymaps and the pane manager.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PaneKeymapPrecedence {
    /// The pane manager wins conflicts while it holds focus (default). Apps
    /// must opt specific keys out via [`PaneKeymapPrecedence::ApplicationFirst`]
    /// or by not binding them to pane commands.
    #[default]
    PaneManagerFirst,
    /// The application wins conflicts (e.g. for globally reserved shortcuts).
    ApplicationFirst,
}

/// Who owns a key given its bindings and the active precedence policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaneKeymapOwner {
    /// The application handles the key.
    Application,
    /// The pane manager handles the key.
    PaneManager,
    /// Neither binds the key.
    Unbound,
}

impl PaneKeymapPrecedence {
    /// Resolve which layer owns a key given whether each layer binds it.
    #[must_use]
    pub const fn resolve(self, app_bound: bool, pane_bound: bool) -> PaneKeymapOwner {
        match (app_bound, pane_bound) {
            (false, false) => PaneKeymapOwner::Unbound,
            (true, false) => PaneKeymapOwner::Application,
            (false, true) => PaneKeymapOwner::PaneManager,
            (true, true) => match self {
                Self::PaneManagerFirst => PaneKeymapOwner::PaneManager,
                Self::ApplicationFirst => PaneKeymapOwner::Application,
            },
        }
    }
}

/// Host-agnostic accessibility preferences for pane interaction (bd-21pbi.5).
///
/// These three adaptive modes are applied uniformly across hosts so a
/// pointer-free, low-vision, or touch user gets the same behavior in the
/// terminal and in the browser:
///
/// - **Reduced motion** collapses affordance micro-animations to instant steps
///   (see [`PaneAffordanceMotion`]) — the state change is preserved, the motion
///   is not.
/// - **High contrast** lifts splitter / focus-ring affordance colors to WCAG
///   AAA (applied by the host theme; see `ftui_style::PaneAffordanceTheme`,
///   which takes this flag).
/// - **Large target** enlarges splitter handles / hit regions for precision and
///   touch ergonomics (see [`enlarge_target`](Self::enlarge_target)).
///
/// Crucially, none of these modes changes the keyboard command vocabulary, the
/// focus graph, or announcements — pane *semantics* are mode-invariant. They are
/// not inputs to [`resolve`] at all; they only affect presentation (motion,
/// color, size). This is what keeps keyboard/focus behavior deterministic and
/// identical regardless of the active accessibility modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PaneAccessibilityPreferences {
    /// Collapse affordance micro-animations to instant steps.
    pub reduced_motion: bool,
    /// Use high-contrast (WCAG AAA) affordance colors.
    pub high_contrast: bool,
    /// Enlarge splitter handles / hit regions.
    pub large_target: bool,
}

impl PaneAccessibilityPreferences {
    /// No accessibility modes enabled (equivalent to [`Default`]).
    #[must_use]
    pub const fn none() -> Self {
        Self {
            reduced_motion: false,
            high_contrast: false,
            large_target: false,
        }
    }

    /// All accessibility modes enabled.
    #[must_use]
    pub const fn all() -> Self {
        Self {
            reduced_motion: true,
            high_contrast: true,
            large_target: true,
        }
    }

    /// Set the reduced-motion preference.
    #[must_use]
    pub const fn with_reduced_motion(mut self, on: bool) -> Self {
        self.reduced_motion = on;
        self
    }

    /// Set the high-contrast preference.
    #[must_use]
    pub const fn with_high_contrast(mut self, on: bool) -> Self {
        self.high_contrast = on;
        self
    }

    /// Set the large-target preference.
    #[must_use]
    pub const fn with_large_target(mut self, on: bool) -> Self {
        self.large_target = on;
        self
    }

    /// Whether any adaptive mode is active.
    #[must_use]
    pub const fn any(self) -> bool {
        self.reduced_motion || self.high_contrast || self.large_target
    }

    /// The affordance micro-animation policy implied by these preferences:
    /// the default timing, with motion stepped when reduced-motion is set.
    #[must_use]
    pub fn affordance_motion(self) -> PaneAffordanceMotion {
        PaneAffordanceMotion::default().with_reduced_motion(self.reduced_motion)
    }

    /// The minimum interactive target size (in cells) for a `base` size.
    ///
    /// In large-target mode a base of `n` cells grows to ~150% (rounded up),
    /// with at least a +1-cell bump so even a 1-cell rail becomes easier to hit;
    /// otherwise `base` is returned unchanged. Monotonic non-decreasing in
    /// `base`, and never smaller than `base`.
    #[must_use]
    pub fn enlarge_target(self, base: u16) -> u16 {
        if !self.large_target {
            return base;
        }
        let scaled = (u32::from(base) * 3).div_ceil(2) as u16;
        scaled.max(base.saturating_add(1))
    }
}

// --------------------------------------------------------------------------
// Focus graph
// --------------------------------------------------------------------------

/// Deterministic focus order: leaves in topological depth-first order
/// (`first` child before `second` at every split). This is the canonical "tab
/// order" and is independent of solved geometry, so it is stable for any
/// layout area.
#[must_use]
pub fn focus_order(tree: &PaneTree) -> Vec<PaneId> {
    let mut out = Vec::new();
    let mut stack = vec![tree.root()];
    while let Some(id) = stack.pop() {
        let Some(record) = tree.node(id) else {
            continue;
        };
        match &record.kind {
            PaneNodeKind::Leaf(_) => out.push(id),
            PaneNodeKind::Split(split) => {
                // Push second then first so first is visited first (in-order).
                stack.push(split.second);
                stack.push(split.first);
            }
        }
    }
    out
}

/// The cyclic neighbour of `active` in [`focus_order`]. Returns `None` when
/// `active` is absent from the order or the tree has fewer than two leaves.
#[must_use]
pub fn focus_cyclic(tree: &PaneTree, active: PaneId, ordinal: PaneFocusOrdinal) -> Option<PaneId> {
    let order = focus_order(tree);
    if order.len() < 2 {
        return None;
    }
    let index = order.iter().position(|&id| id == active)?;
    let len = order.len();
    let next = match ordinal {
        PaneFocusOrdinal::Next => (index + 1) % len,
        PaneFocusOrdinal::Previous => (index + len - 1) % len,
    };
    Some(order[next])
}

fn center(rect: Rect) -> (i32, i32) {
    (
        i32::from(rect.x) + i32::from(rect.width) / 2,
        i32::from(rect.y) + i32::from(rect.height) / 2,
    )
}

/// Overlap length of two half-open intervals `[a0, a1)` and `[b0, b1)`.
fn overlap_1d(a0: u16, a1: u16, b0: u16, b1: u16) -> i32 {
    let lo = a0.max(b0);
    let hi = a1.min(b1);
    i32::from(hi.saturating_sub(lo))
}

/// The nearest leaf to `active` in a cardinal direction, using solved geometry.
///
/// Tie-break order (all deterministic): smallest primary-axis center distance,
/// then largest perpendicular overlap, then earliest [`focus_order`] index.
/// Returns `None` when no leaf lies in the direction.
#[must_use]
pub fn focus_directional(
    tree: &PaneTree,
    layout: &PaneLayout,
    active: PaneId,
    direction: PaneCardinalDirection,
) -> Option<PaneId> {
    let order = focus_order(tree);
    let active_rect = layout.rect(active)?;
    let (acx, acy) = center(active_rect);

    let mut best: Option<((i32, i32, usize), PaneId)> = None;
    for (index, &leaf) in order.iter().enumerate() {
        if leaf == active {
            continue;
        }
        let Some(rect) = layout.rect(leaf) else {
            continue;
        };
        let (cx, cy) = center(rect);
        // Pane layouts are guillotine splits (axis-aligned tilings), so the
        // correct "in direction" test is by EDGE, not center: a candidate must
        // lie wholly on the requested side of the active pane. This excludes
        // diagonal neighbours that merely have a more extreme center.
        let in_direction = match direction {
            PaneCardinalDirection::Left => rect.right() <= active_rect.left(),
            PaneCardinalDirection::Right => rect.left() >= active_rect.right(),
            PaneCardinalDirection::Up => rect.bottom() <= active_rect.top(),
            PaneCardinalDirection::Down => rect.top() >= active_rect.bottom(),
        };
        if !in_direction {
            continue;
        }
        let primary = match direction {
            PaneCardinalDirection::Left | PaneCardinalDirection::Right => (cx - acx).abs(),
            PaneCardinalDirection::Up | PaneCardinalDirection::Down => (cy - acy).abs(),
        };
        let overlap = match direction {
            PaneCardinalDirection::Left | PaneCardinalDirection::Right => overlap_1d(
                active_rect.top(),
                active_rect.bottom(),
                rect.top(),
                rect.bottom(),
            ),
            PaneCardinalDirection::Up | PaneCardinalDirection::Down => overlap_1d(
                active_rect.left(),
                active_rect.right(),
                rect.left(),
                rect.right(),
            ),
        };
        // Minimize primary distance, then maximize overlap (store negated),
        // then minimize focus-order index.
        let key = (primary, -overlap, index);
        if best.as_ref().is_none_or(|(best_key, _)| key < *best_key) {
            best = Some((key, leaf));
        }
    }
    best.map(|(_, leaf)| leaf)
}

/// The extreme leaf in a cardinal direction (jump to edge). Returns the active
/// leaf's own id when it is already the extreme, so callers can treat that as a
/// no-op.
#[must_use]
pub fn focus_edge(
    tree: &PaneTree,
    layout: &PaneLayout,
    direction: PaneCardinalDirection,
) -> Option<PaneId> {
    let order = focus_order(tree);
    let mut best: Option<((i32, i32, usize), PaneId)> = None;
    for (index, &leaf) in order.iter().enumerate() {
        let Some(rect) = layout.rect(leaf) else {
            continue;
        };
        let (cx, cy) = center(rect);
        // Sort key: the primary coordinate oriented so the extreme is the
        // minimum, then a stable secondary coordinate, then focus-order index.
        let key = match direction {
            PaneCardinalDirection::Left => (cx, cy, index),
            PaneCardinalDirection::Right => (-cx, cy, index),
            PaneCardinalDirection::Up => (cy, cx, index),
            PaneCardinalDirection::Down => (-cy, cx, index),
        };
        if best.as_ref().is_none_or(|(best_key, _)| key < *best_key) {
            best = Some((key, leaf));
        }
    }
    best.map(|(_, leaf)| leaf)
}

// --------------------------------------------------------------------------
// Resolution
// --------------------------------------------------------------------------

/// Resolve a single [`PaneCommand`] against the current tree, solved layout,
/// and focus context. Pure and deterministic: identical inputs always yield an
/// identical [`PaneCommandResolution`], which is what makes equivalent command
/// streams produce identical pane state across hosts.
#[must_use]
pub fn resolve(
    tree: &PaneTree,
    layout: &PaneLayout,
    ctx: PaneFocusContext,
    command: PaneCommand,
) -> PaneCommandResolution {
    match command {
        PaneCommand::FocusNext => resolve_cyclic(tree, ctx, PaneFocusOrdinal::Next),
        PaneCommand::FocusPrevious => resolve_cyclic(tree, ctx, PaneFocusOrdinal::Previous),
        PaneCommand::FocusDirectional(direction) => {
            resolve_focus(tree, ctx, focus_dir(tree, layout, ctx, direction))
        }
        PaneCommand::FocusEdge(direction) => {
            resolve_focus(tree, ctx, focus_edge(tree, layout, direction))
        }
        PaneCommand::ResizeStep { direction, units } => {
            resolve_resize(tree, layout, ctx, direction, units)
        }
        PaneCommand::Split(axis) => resolve_split(tree, ctx, axis),
        PaneCommand::Close => resolve_close(tree, ctx),
        PaneCommand::MovePane(direction) => resolve_move(tree, layout, ctx, direction),
        PaneCommand::SwapPane(ordinal) => resolve_swap(tree, ctx, ordinal),
        PaneCommand::Maximize => resolve_maximize(tree, ctx),
        PaneCommand::Restore => resolve_restore(ctx),
    }
}

/// The active leaf id, if present and actually a leaf.
fn active_leaf(tree: &PaneTree, ctx: PaneFocusContext) -> Result<PaneId, PaneCommandNoopReason> {
    let active = ctx.active.ok_or(PaneCommandNoopReason::NoActivePane)?;
    match tree.node(active).map(|record| &record.kind) {
        Some(PaneNodeKind::Leaf(_)) => Ok(active),
        _ => Err(PaneCommandNoopReason::ActiveNotLeaf),
    }
}

fn focus_dir(
    tree: &PaneTree,
    layout: &PaneLayout,
    ctx: PaneFocusContext,
    direction: PaneCardinalDirection,
) -> Option<PaneId> {
    let active = ctx.active?;
    focus_directional(tree, layout, active, direction)
}

fn resolve_cyclic(
    tree: &PaneTree,
    ctx: PaneFocusContext,
    ordinal: PaneFocusOrdinal,
) -> PaneCommandResolution {
    let active = match active_leaf(tree, ctx) {
        Ok(active) => active,
        Err(reason) => return PaneCommandResolution::noop(reason, ctx),
    };
    match focus_cyclic(tree, active, ordinal) {
        Some(next) => focus_changed(ctx, next),
        None => PaneCommandResolution::noop(PaneCommandNoopReason::OnlyOnePane, ctx),
    }
}

fn resolve_focus(
    tree: &PaneTree,
    ctx: PaneFocusContext,
    target: Option<PaneId>,
) -> PaneCommandResolution {
    if active_leaf(tree, ctx).is_err() && ctx.active.is_some() {
        return PaneCommandResolution::noop(PaneCommandNoopReason::ActiveNotLeaf, ctx);
    }
    match target {
        Some(next) if Some(next) != ctx.active => focus_changed(ctx, next),
        _ => PaneCommandResolution::noop(PaneCommandNoopReason::NoTargetInDirection, ctx),
    }
}

fn focus_changed(ctx: PaneFocusContext, next: PaneId) -> PaneCommandResolution {
    PaneCommandResolution {
        effect: PaneCommandEffect::Focus {
            previous: ctx.active,
            active: next,
        },
        next_active: Some(next),
        next_maximized: ctx.maximized,
    }
}

fn structural(
    ctx: PaneFocusContext,
    operations: Vec<PaneOperation>,
    next_active: Option<PaneId>,
) -> PaneCommandResolution {
    PaneCommandResolution {
        effect: PaneCommandEffect::Structural(operations),
        next_active,
        next_maximized: ctx.maximized,
    }
}

/// Enclosing split of a leaf: its parent, when that parent is a split.
fn enclosing_split(tree: &PaneTree, leaf: PaneId) -> Option<PaneId> {
    let parent = tree.node(leaf)?.parent?;
    match &tree.node(parent)?.kind {
        PaneNodeKind::Split(_) => Some(parent),
        PaneNodeKind::Leaf(_) => None,
    }
}

fn resolve_resize(
    tree: &PaneTree,
    layout: &PaneLayout,
    ctx: PaneFocusContext,
    direction: PaneResizeDirection,
    units: u16,
) -> PaneCommandResolution {
    let active = match active_leaf(tree, ctx) {
        Ok(active) => active,
        Err(reason) => return PaneCommandResolution::noop(reason, ctx),
    };
    let Some(split_id) = enclosing_split(tree, active) else {
        return PaneCommandResolution::noop(PaneCommandNoopReason::NoEnclosingSplit, ctx);
    };
    let Some(PaneNodeKind::Split(split)) = tree.node(split_id).map(|record| &record.kind) else {
        return PaneCommandResolution::noop(PaneCommandNoopReason::NoEnclosingSplit, ctx);
    };
    // The command direction is active-pane-relative (grow/shrink the active
    // pane). Translate to the split's first-share direction: growing the
    // first child increases first-share; growing the second decreases it.
    let split_direction = if split.first == active {
        direction
    } else {
        flip_direction(direction)
    };
    let target = PaneResizeTarget {
        split_id,
        axis: split.axis,
    };
    // Lower through the shared resize machine so keyboard resize uses the exact
    // same nudge math as pointer/wheel resize (no duplicated logic).
    let event = PaneSemanticInputEvent::new(
        1,
        PaneSemanticInputEventKind::KeyboardResize {
            target,
            direction: split_direction,
            units,
        },
    );
    let mut machine = PaneDragResizeMachine::default();
    let Ok(transition) = machine.apply_event(&event) else {
        return PaneCommandResolution::noop(PaneCommandNoopReason::NoEnclosingSplit, ctx);
    };
    let operations = tree.operations_for_transition(&transition, layout, KEYBOARD_NEUTRAL_PRESSURE);
    structural(ctx, operations, ctx.active)
}

const fn flip_direction(direction: PaneResizeDirection) -> PaneResizeDirection {
    match direction {
        PaneResizeDirection::Increase => PaneResizeDirection::Decrease,
        PaneResizeDirection::Decrease => PaneResizeDirection::Increase,
    }
}

fn resolve_split(tree: &PaneTree, ctx: PaneFocusContext, axis: SplitAxis) -> PaneCommandResolution {
    let active = match active_leaf(tree, ctx) {
        Ok(active) => active,
        Err(reason) => return PaneCommandResolution::noop(reason, ctx),
    };
    let surface_key = leaf_surface_key(tree, active).unwrap_or_default();
    let new_leaf = PaneLeaf::new(format!("{surface_key}#split"));
    let ratio = PaneSplitRatio::default();
    let op = PaneOperation::SplitLeaf {
        target: active,
        axis,
        ratio,
        placement: PanePlacement::ExistingFirst,
        new_leaf,
    };
    // The new leaf id is allocated by `apply_operation`, so focus stays on the
    // existing pane; hosts may refocus the new leaf after applying.
    structural(ctx, vec![op], ctx.active)
}

fn leaf_surface_key(tree: &PaneTree, leaf: PaneId) -> Option<String> {
    match &tree.node(leaf)?.kind {
        PaneNodeKind::Leaf(record) => Some(record.surface_key.clone()),
        PaneNodeKind::Split(_) => None,
    }
}

fn resolve_close(tree: &PaneTree, ctx: PaneFocusContext) -> PaneCommandResolution {
    let active = match active_leaf(tree, ctx) {
        Ok(active) => active,
        Err(reason) => return PaneCommandResolution::noop(reason, ctx),
    };
    if active == tree.root() {
        return PaneCommandResolution::noop(PaneCommandNoopReason::RootCannotClose, ctx);
    }
    let order = focus_order(tree);
    if order.len() < 2 {
        return PaneCommandResolution::noop(PaneCommandNoopReason::OnlyOnePane, ctx);
    }
    // Focus the deterministic survivor: the next leaf in focus order, or the
    // previous when the active pane was last.
    let next_active = focus_cyclic(tree, active, PaneFocusOrdinal::Next)
        .filter(|&id| id != active)
        .or_else(|| focus_cyclic(tree, active, PaneFocusOrdinal::Previous))
        .filter(|&id| id != active);
    let mut resolution = structural(
        ctx,
        vec![PaneOperation::CloseNode { target: active }],
        next_active,
    );
    // Closing the maximized pane must clear the maximize state — carrying it
    // forward would leave a dangling id pointing at a removed node.
    if ctx.maximized == Some(active) {
        resolution.next_maximized = None;
    }
    resolution
}

fn resolve_move(
    tree: &PaneTree,
    layout: &PaneLayout,
    ctx: PaneFocusContext,
    direction: PaneCardinalDirection,
) -> PaneCommandResolution {
    let active = match active_leaf(tree, ctx) {
        Ok(active) => active,
        Err(reason) => return PaneCommandResolution::noop(reason, ctx),
    };
    let Some(target) = focus_directional(tree, layout, active, direction) else {
        return PaneCommandResolution::noop(PaneCommandNoopReason::NoTargetInDirection, ctx);
    };
    let ratio = PaneSplitRatio::default();
    let op = PaneOperation::MoveSubtree {
        source: active,
        target,
        axis: direction.axis(),
        ratio,
        placement: direction.incoming_placement(),
    };
    structural(ctx, vec![op], ctx.active)
}

fn resolve_swap(
    tree: &PaneTree,
    ctx: PaneFocusContext,
    ordinal: PaneFocusOrdinal,
) -> PaneCommandResolution {
    let active = match active_leaf(tree, ctx) {
        Ok(active) => active,
        Err(reason) => return PaneCommandResolution::noop(reason, ctx),
    };
    match focus_cyclic(tree, active, ordinal) {
        Some(other) if other != active => structural(
            ctx,
            vec![PaneOperation::SwapNodes {
                first: active,
                second: other,
            }],
            ctx.active,
        ),
        _ => PaneCommandResolution::noop(PaneCommandNoopReason::OnlyOnePane, ctx),
    }
}

fn resolve_maximize(tree: &PaneTree, ctx: PaneFocusContext) -> PaneCommandResolution {
    let active = match active_leaf(tree, ctx) {
        Ok(active) => active,
        Err(reason) => return PaneCommandResolution::noop(reason, ctx),
    };
    if ctx.maximized == Some(active) {
        return PaneCommandResolution::noop(PaneCommandNoopReason::AlreadyMaximized, ctx);
    }
    PaneCommandResolution {
        effect: PaneCommandEffect::Maximize { target: active },
        next_active: Some(active),
        next_maximized: Some(active),
    }
}

fn resolve_restore(ctx: PaneFocusContext) -> PaneCommandResolution {
    match ctx.maximized {
        Some(previous) => PaneCommandResolution {
            effect: PaneCommandEffect::Restore { previous },
            next_active: ctx.active,
            next_maximized: None,
        },
        None => PaneCommandResolution::noop(PaneCommandNoopReason::NotMaximized, ctx),
    }
}

// --------------------------------------------------------------------------
// Accessible announcements (bd-21pbi.4)
// --------------------------------------------------------------------------

/// Category of a pane state-change announcement (for host channel routing and
/// coalescing).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaneAnnouncementCategory {
    /// Focus moved to a different pane.
    Focus,
    /// A pane was resized.
    Resize,
    /// A pane was split.
    Split,
    /// A pane was closed.
    Close,
    /// A pane was moved/docked.
    Move,
    /// Two panes were swapped.
    Swap,
    /// A pane was maximized.
    Maximize,
    /// The layout was restored from maximized.
    Restore,
}

/// A concise, host-agnostic accessibility announcement for a pane state change.
/// The web host renders `text` into an `aria-live` region; the terminal host
/// surfaces it via a status line / log hook.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PaneAnnouncement {
    /// The human-readable announcement text.
    pub text: String,
    /// The announcement category.
    pub category: PaneAnnouncementCategory,
}

impl PaneAnnouncement {
    fn new(category: PaneAnnouncementCategory, text: impl Into<String>) -> Self {
        Self {
            category,
            text: text.into(),
        }
    }
}

const fn cardinal_label(direction: PaneCardinalDirection) -> &'static str {
    match direction {
        PaneCardinalDirection::Left => "left",
        PaneCardinalDirection::Right => "right",
        PaneCardinalDirection::Up => "up",
        PaneCardinalDirection::Down => "down",
    }
}

const fn axis_label(axis: SplitAxis) -> &'static str {
    match axis {
        SplitAxis::Horizontal => "horizontal",
        SplitAxis::Vertical => "vertical",
    }
}

/// The active pane's own share of its enclosing split, as a percentage.
fn active_pane_share_pct(tree: &PaneTree, active: PaneId) -> Option<u16> {
    let split_id = enclosing_split(tree, active)?;
    let PaneNodeKind::Split(split) = &tree.node(split_id)?.kind else {
        return None;
    };
    // u64 arithmetic: `num + den` can overflow u32 (any nonzero pair is a
    // valid PaneSplitRatio, e.g. u32::MAX:1), which would wrap into a
    // division by zero in release builds.
    let num = u64::from(split.ratio.numerator());
    let den = u64::from(split.ratio.denominator());
    let first_share = num * 100 / (num + den);
    let share = if split.first == active {
        first_share
    } else {
        100 - first_share
    };
    u16::try_from(share).ok()
}

/// Generate a concise accessibility announcement for a resolved command.
///
/// Returns `None` for no-ops (nothing changed). `tree` MUST be the post-apply
/// state, so counts and ratios reflect the result.
#[must_use]
pub fn announce_command(
    command: PaneCommand,
    resolution: &PaneCommandResolution,
    tree: &PaneTree,
) -> Option<PaneAnnouncement> {
    if matches!(resolution.effect, PaneCommandEffect::Noop(_)) {
        return None;
    }
    let leaf_count = focus_order(tree).len();
    match command {
        PaneCommand::FocusNext
        | PaneCommand::FocusPrevious
        | PaneCommand::FocusDirectional(_)
        | PaneCommand::FocusEdge(_) => {
            let active = resolution.next_active?;
            let label = leaf_surface_key(tree, active).unwrap_or_else(|| "pane".to_owned());
            Some(PaneAnnouncement::new(
                PaneAnnouncementCategory::Focus,
                format!("Focused pane {label}"),
            ))
        }
        PaneCommand::ResizeStep { .. } => {
            let active = resolution.next_active?;
            let pct = active_pane_share_pct(tree, active)?;
            Some(PaneAnnouncement::new(
                PaneAnnouncementCategory::Resize,
                format!("Resized pane to {pct} percent"),
            ))
        }
        PaneCommand::Split(axis) => Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Split,
            format!("Split pane {}, {leaf_count} panes", axis_label(axis)),
        )),
        PaneCommand::Close => Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Close,
            format!("Closed pane, {leaf_count} remaining"),
        )),
        PaneCommand::MovePane(dir) => Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Move,
            format!("Moved pane {}", cardinal_label(dir)),
        )),
        PaneCommand::SwapPane(_) => Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Swap,
            "Swapped pane",
        )),
        PaneCommand::Maximize => Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Maximize,
            "Maximized pane",
        )),
        PaneCommand::Restore => Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Restore,
            "Restored pane",
        )),
    }
}

/// Coalescing announcer that keeps host live regions / status lines bounded and
/// non-spammy: the latest offered announcement wins (so a burst of resize/repeat
/// announcements collapses to one), and consecutive identical text is
/// suppressed. Hosts call [`PaneAnnouncer::take`] once per render / live-region
/// update.
#[derive(Debug, Clone, Default)]
pub struct PaneAnnouncer {
    pending: Option<PaneAnnouncement>,
    last_spoken: Option<String>,
}

impl PaneAnnouncer {
    /// Create an empty announcer.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Offer an announcement; the most recent non-empty offer is retained, so
    /// rapid bursts coalesce to the final state.
    pub fn offer(&mut self, announcement: Option<PaneAnnouncement>) {
        if announcement.is_some() {
            self.pending = announcement;
        }
    }

    /// Take the pending announcement to speak now, suppressing an exact repeat
    /// of the previously spoken text.
    pub fn take(&mut self) -> Option<PaneAnnouncement> {
        let pending = self.pending.take()?;
        if self.last_spoken.as_deref() == Some(pending.text.as_str()) {
            return None;
        }
        self.last_spoken = Some(pending.text.clone());
        Some(pending)
    }

    /// Peek the pending announcement without consuming it.
    #[must_use]
    pub fn pending(&self) -> Option<&PaneAnnouncement> {
        self.pending.as_ref()
    }

    /// The most recently spoken announcement text.
    #[must_use]
    pub fn last_spoken(&self) -> Option<&str> {
        self.last_spoken.as_deref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pane::{
        PANE_SNAP_DEFAULT_STEP_BPS, PANE_TREE_SCHEMA_VERSION, PaneNodeRecord, PaneSplit,
        PaneTreeSnapshot,
    };
    use std::collections::BTreeMap;

    fn pid(raw: u64) -> PaneId {
        PaneId::new(raw).expect("non-zero id")
    }

    #[test]
    fn accessibility_preferences_constructors() {
        assert_eq!(
            PaneAccessibilityPreferences::none(),
            PaneAccessibilityPreferences::default()
        );
        assert!(!PaneAccessibilityPreferences::none().any());
        let all = PaneAccessibilityPreferences::all();
        assert!(all.reduced_motion && all.high_contrast && all.large_target);
        assert!(all.any());
        // Builder setters are independent.
        let only_hc = PaneAccessibilityPreferences::none().with_high_contrast(true);
        assert!(only_hc.high_contrast && !only_hc.reduced_motion && !only_hc.large_target);
        assert!(only_hc.any());
    }

    #[test]
    fn affordance_motion_reflects_reduced_motion_preference() {
        let on = PaneAccessibilityPreferences::none().with_reduced_motion(true);
        assert!(on.affordance_motion().reduced_motion);
        // Stepped: full emphasis on frame 0.
        assert_eq!(
            on.affordance_motion().hover_emphasis_bps(0),
            crate::pane::PANE_AFFORDANCE_EMPHASIS_FULL_BPS
        );
        let off = PaneAccessibilityPreferences::none();
        assert!(!off.affordance_motion().reduced_motion);
        // Animated: frame 0 is below full when not reduced.
        assert!(
            off.affordance_motion().hover_emphasis_bps(0)
                < crate::pane::PANE_AFFORDANCE_EMPHASIS_FULL_BPS
        );
    }

    #[test]
    fn enlarge_target_grows_only_in_large_target_mode_and_is_monotonic() {
        let normal = PaneAccessibilityPreferences::none();
        let large = PaneAccessibilityPreferences::none().with_large_target(true);
        let mut prev_normal = 0u16;
        let mut prev_large = 0u16;
        for base in 0..=20u16 {
            // Default mode is identity.
            assert_eq!(normal.enlarge_target(base), base);
            let grown = large.enlarge_target(base);
            // Large target never shrinks, and strictly grows any positive base.
            assert!(grown >= base, "large target must not shrink base {base}");
            if base > 0 {
                assert!(grown > base, "large target must grow base {base}");
            }
            // Both functions are monotonic non-decreasing in base.
            assert!(normal.enlarge_target(base) >= prev_normal);
            assert!(grown >= prev_large);
            prev_normal = normal.enlarge_target(base);
            prev_large = grown;
        }
        // Concrete ergonomics: a 1-cell rail becomes 2, a 2-cell rail becomes 3.
        assert_eq!(large.enlarge_target(1), 2);
        assert_eq!(large.enlarge_target(2), 3);
        // Saturating: a max base does not overflow.
        assert!(large.enlarge_target(u16::MAX) >= u16::MAX - 1);
    }

    #[test]
    fn accessibility_preferences_are_not_an_input_to_resolution() {
        // The modes are presentation-only: resolve() takes no preferences, so a
        // fixed command resolves to byte-identical effects regardless of which
        // modes a host has enabled. We demonstrate this by resolving the same
        // command and confirming the resolution is independent of any prefs the
        // caller might be tracking alongside it.
        let tree = nested();
        let layout = tree.solve_layout(Rect::new(0, 0, 80, 24)).expect("solves");
        let ctx = PaneFocusContext {
            active: Some(pid(2)),
            maximized: None,
        };
        let baseline = resolve(&tree, &layout, ctx, PaneCommand::FocusNext);
        for prefs in [
            PaneAccessibilityPreferences::none(),
            PaneAccessibilityPreferences::all(),
            PaneAccessibilityPreferences::none().with_large_target(true),
        ] {
            // prefs deliberately do not participate in resolution.
            let _ = prefs;
            let again = resolve(&tree, &layout, ctx, PaneCommand::FocusNext);
            assert_eq!(again.next_active, baseline.next_active);
            assert_eq!(again.next_maximized, baseline.next_maximized);
        }
    }

    /// First-child share of a split node in basis points.
    fn first_share_bps(tree: &PaneTree, split: PaneId) -> u32 {
        match &tree.node(split).expect("split present").kind {
            PaneNodeKind::Split(node) => {
                node.ratio.numerator() * 10_000
                    / (node.ratio.numerator() + node.ratio.denominator())
            }
            PaneNodeKind::Leaf(_) => panic!("expected split node"),
        }
    }

    /// Single leaf root.
    fn single() -> PaneTree {
        let snapshot = PaneTreeSnapshot {
            schema_version: PANE_TREE_SCHEMA_VERSION,
            root: pid(1),
            next_id: pid(2),
            nodes: vec![PaneNodeRecord::leaf(pid(1), None, PaneLeaf::new("only"))],
            extensions: BTreeMap::new(),
        };
        PaneTree::from_snapshot(snapshot).expect("valid single tree")
    }

    /// Horizontal root: left(2) | right-column where right is vertical
    /// top(4)/bottom(5). Leaves in focus order: [2, 4, 5].
    fn nested() -> PaneTree {
        let snapshot = PaneTreeSnapshot {
            schema_version: PANE_TREE_SCHEMA_VERSION,
            root: pid(1),
            next_id: pid(6),
            nodes: vec![
                PaneNodeRecord::split(
                    pid(1),
                    None,
                    PaneSplit {
                        axis: SplitAxis::Horizontal,
                        ratio: PaneSplitRatio::new(1, 1).unwrap(),
                        first: pid(2),
                        second: pid(3),
                    },
                ),
                PaneNodeRecord::leaf(pid(2), Some(pid(1)), PaneLeaf::new("left")),
                PaneNodeRecord::split(
                    pid(3),
                    Some(pid(1)),
                    PaneSplit {
                        axis: SplitAxis::Vertical,
                        ratio: PaneSplitRatio::new(1, 1).unwrap(),
                        first: pid(4),
                        second: pid(5),
                    },
                ),
                PaneNodeRecord::leaf(pid(4), Some(pid(3)), PaneLeaf::new("right_top")),
                PaneNodeRecord::leaf(pid(5), Some(pid(3)), PaneLeaf::new("right_bottom")),
            ],
            extensions: BTreeMap::new(),
        };
        PaneTree::from_snapshot(snapshot).expect("valid nested tree")
    }

    fn solved(tree: &PaneTree) -> PaneLayout {
        tree.solve_layout(Rect::new(0, 0, 80, 24))
            .expect("layout solves")
    }

    #[test]
    fn closing_the_maximized_pane_clears_maximize_state() {
        let tree = nested();
        let layout = solved(&tree);
        let res = resolve(
            &tree,
            &layout,
            PaneFocusContext {
                active: Some(pid(4)),
                maximized: Some(pid(4)),
            },
            PaneCommand::Close,
        );
        assert!(matches!(res.effect, PaneCommandEffect::Structural(_)));
        assert_eq!(
            res.next_maximized, None,
            "a closed pane must not remain the maximize target"
        );
        // Closing a non-maximized pane keeps the maximize state.
        let res2 = resolve(
            &tree,
            &layout,
            PaneFocusContext {
                active: Some(pid(4)),
                maximized: Some(pid(2)),
            },
            PaneCommand::Close,
        );
        assert_eq!(res2.next_maximized, Some(pid(2)));
    }

    #[test]
    fn share_pct_survives_extreme_ratios() {
        // Any nonzero u32 pair is a valid ratio; u32 math would overflow (or
        // divide by zero on wrap) for u32::MAX:1.
        let snapshot = PaneTreeSnapshot {
            schema_version: PANE_TREE_SCHEMA_VERSION,
            root: pid(1),
            next_id: pid(4),
            nodes: vec![
                PaneNodeRecord::split(
                    pid(1),
                    None,
                    PaneSplit {
                        axis: SplitAxis::Horizontal,
                        ratio: PaneSplitRatio::new(u32::MAX, 1).unwrap(),
                        first: pid(2),
                        second: pid(3),
                    },
                ),
                PaneNodeRecord::leaf(pid(2), Some(pid(1)), PaneLeaf::new("a")),
                PaneNodeRecord::leaf(pid(3), Some(pid(1)), PaneLeaf::new("b")),
            ],
            extensions: BTreeMap::new(),
        };
        let tree = PaneTree::from_snapshot(snapshot).expect("valid tree");
        assert_eq!(active_pane_share_pct(&tree, pid(2)), Some(99));
        assert_eq!(active_pane_share_pct(&tree, pid(3)), Some(1));
    }

    #[test]
    fn focus_order_is_topological_in_order() {
        assert_eq!(focus_order(&single()), vec![pid(1)]);
        assert_eq!(focus_order(&nested()), vec![pid(2), pid(4), pid(5)]);
    }

    #[test]
    fn focus_cyclic_wraps_both_directions() {
        let tree = nested();
        assert_eq!(
            focus_cyclic(&tree, pid(2), PaneFocusOrdinal::Next),
            Some(pid(4))
        );
        assert_eq!(
            focus_cyclic(&tree, pid(5), PaneFocusOrdinal::Next),
            Some(pid(2))
        );
        assert_eq!(
            focus_cyclic(&tree, pid(2), PaneFocusOrdinal::Previous),
            Some(pid(5))
        );
        assert_eq!(
            focus_cyclic(&single(), pid(1), PaneFocusOrdinal::Next),
            None
        );
    }

    #[test]
    fn focus_directional_uses_geometry() {
        let tree = nested();
        let layout = solved(&tree);
        // left(2) is to the LEFT of the right column; right of left is top(4)
        // (nearest by overlap/order among 4,5).
        assert_eq!(
            focus_directional(&tree, &layout, pid(2), PaneCardinalDirection::Right),
            Some(pid(4))
        );
        // From top(4), down -> bottom(5); left -> left(2).
        assert_eq!(
            focus_directional(&tree, &layout, pid(4), PaneCardinalDirection::Down),
            Some(pid(5))
        );
        assert_eq!(
            focus_directional(&tree, &layout, pid(4), PaneCardinalDirection::Left),
            Some(pid(2))
        );
        // Nothing to the left of the leftmost pane.
        assert_eq!(
            focus_directional(&tree, &layout, pid(2), PaneCardinalDirection::Left),
            None
        );
    }

    #[test]
    fn focus_edge_jumps_to_extremes() {
        let tree = nested();
        let layout = solved(&tree);
        assert_eq!(
            focus_edge(&tree, &layout, PaneCardinalDirection::Left),
            Some(pid(2))
        );
        assert_eq!(
            focus_edge(&tree, &layout, PaneCardinalDirection::Down),
            Some(pid(5))
        );
    }

    #[test]
    fn resolve_focus_next_changes_active() {
        let tree = nested();
        let layout = solved(&tree);
        let res = resolve(
            &tree,
            &layout,
            PaneFocusContext::active(pid(2)),
            PaneCommand::FocusNext,
        );
        assert_eq!(
            res.effect,
            PaneCommandEffect::Focus {
                previous: Some(pid(2)),
                active: pid(4)
            }
        );
        assert_eq!(res.next_active, Some(pid(4)));
    }

    #[test]
    fn resolve_no_active_is_noop() {
        let tree = nested();
        let layout = solved(&tree);
        let res = resolve(
            &tree,
            &layout,
            PaneFocusContext::default(),
            PaneCommand::FocusNext,
        );
        assert_eq!(
            res.effect,
            PaneCommandEffect::Noop(PaneCommandNoopReason::NoActivePane)
        );
        assert!(!res.is_effective());
    }

    #[test]
    fn resolve_resize_grows_active_via_existing_nudge() {
        let tree = nested();
        let layout = solved(&tree);
        // left(2) is the FIRST child of root split: grow active => increase
        // first-share by 2 steps.
        let res = resolve(
            &tree,
            &layout,
            PaneFocusContext::active(pid(2)),
            PaneCommand::ResizeStep {
                direction: PaneResizeDirection::Increase,
                units: 2,
            },
        );
        let PaneCommandEffect::Structural(ops) = &res.effect else {
            panic!("expected structural effect, got {:?}", res.effect);
        };
        assert_eq!(ops.len(), 1);
        // Apply and confirm the root first-share grew by 2 * step.
        let mut applied = tree.clone();
        let before = first_share_bps(&applied, pid(1));
        for (idx, op) in ops.iter().enumerate() {
            applied
                .apply_operation(idx as u64, op.clone())
                .expect("op applies");
        }
        let after = first_share_bps(&applied, pid(1));
        assert_eq!(after, before + 2 * u32::from(PANE_SNAP_DEFAULT_STEP_BPS));
    }

    #[test]
    fn resolve_resize_second_child_flips_direction() {
        let tree = nested();
        let layout = solved(&tree);
        // bottom(5) is the SECOND child of the vertical split(3): growing it
        // must DECREASE that split's first-share.
        let res = resolve(
            &tree,
            &layout,
            PaneFocusContext::active(pid(5)),
            PaneCommand::ResizeStep {
                direction: PaneResizeDirection::Increase,
                units: 1,
            },
        );
        let PaneCommandEffect::Structural(ops) = &res.effect else {
            panic!("expected structural effect");
        };
        let mut applied = tree.clone();
        let before = first_share_bps(&applied, pid(3));
        for (idx, op) in ops.iter().enumerate() {
            applied
                .apply_operation(idx as u64, op.clone())
                .expect("applies");
        }
        let after = first_share_bps(&applied, pid(3));
        assert_eq!(after, before - u32::from(PANE_SNAP_DEFAULT_STEP_BPS));
    }

    #[test]
    fn resolve_close_picks_deterministic_survivor() {
        let tree = nested();
        let layout = solved(&tree);
        let res = resolve(
            &tree,
            &layout,
            PaneFocusContext::active(pid(2)),
            PaneCommand::Close,
        );
        assert!(matches!(res.effect, PaneCommandEffect::Structural(_)));
        // Closing left(2): next survivor in focus order is top(4).
        assert_eq!(res.next_active, Some(pid(4)));
        // Root cannot be closed.
        let single_tree = single();
        let single_layout = solved(&single_tree);
        let res = resolve(
            &single_tree,
            &single_layout,
            PaneFocusContext::active(pid(1)),
            PaneCommand::Close,
        );
        assert_eq!(
            res.effect,
            PaneCommandEffect::Noop(PaneCommandNoopReason::RootCannotClose)
        );
    }

    #[test]
    fn resolve_maximize_and_restore_roundtrip() {
        let tree = nested();
        let layout = solved(&tree);
        let max = resolve(
            &tree,
            &layout,
            PaneFocusContext::active(pid(4)),
            PaneCommand::Maximize,
        );
        assert_eq!(max.effect, PaneCommandEffect::Maximize { target: pid(4) });
        assert_eq!(max.next_maximized, Some(pid(4)));
        // Maximizing again is a no-op.
        let again = resolve(
            &tree,
            &layout,
            PaneFocusContext {
                active: Some(pid(4)),
                maximized: Some(pid(4)),
            },
            PaneCommand::Maximize,
        );
        assert_eq!(
            again.effect,
            PaneCommandEffect::Noop(PaneCommandNoopReason::AlreadyMaximized)
        );
        // Restore clears it.
        let restore = resolve(
            &tree,
            &layout,
            PaneFocusContext {
                active: Some(pid(4)),
                maximized: Some(pid(4)),
            },
            PaneCommand::Restore,
        );
        assert_eq!(
            restore.effect,
            PaneCommandEffect::Restore { previous: pid(4) }
        );
        assert_eq!(restore.next_maximized, None);
    }

    #[test]
    fn acceleration_policy_is_explicit() {
        let accel = PaneCommandAcceleration::default();
        assert_eq!(accel.units_for(0), 1);
        assert_eq!(accel.units_for(2), 1);
        assert_eq!(accel.units_for(3), 5);
        assert_eq!(accel.units_for(50), 5);
    }

    #[test]
    fn precedence_policy_resolves_conflicts() {
        use PaneKeymapOwner::{Application, PaneManager, Unbound};
        let pm = PaneKeymapPrecedence::PaneManagerFirst;
        let app = PaneKeymapPrecedence::ApplicationFirst;
        assert_eq!(pm.resolve(false, false), Unbound);
        assert_eq!(pm.resolve(true, false), Application);
        assert_eq!(pm.resolve(false, true), PaneManager);
        assert_eq!(pm.resolve(true, true), PaneManager);
        assert_eq!(app.resolve(true, true), Application);
    }

    /// Cross-host equivalence + determinism: a fixed command stream, applied
    /// via the resolver, produces an identical final topology hash and active
    /// pane regardless of which host emitted the commands. Running twice must
    /// match byte-for-byte.
    #[test]
    fn command_stream_is_deterministic_and_host_agnostic() {
        fn run_stream() -> (u64, Option<PaneId>) {
            let mut tree = nested();
            let mut ctx = PaneFocusContext::active(pid(2));
            let stream = [
                PaneCommand::FocusNext,
                PaneCommand::ResizeStep {
                    direction: PaneResizeDirection::Increase,
                    units: 2,
                },
                PaneCommand::FocusDirectional(PaneCardinalDirection::Down),
                PaneCommand::SwapPane(PaneFocusOrdinal::Previous),
                PaneCommand::FocusEdge(PaneCardinalDirection::Left),
            ];
            let mut op_id = 0u64;
            for command in stream {
                let layout = tree.solve_layout(Rect::new(0, 0, 80, 24)).expect("solves");
                let res = resolve(&tree, &layout, ctx, command);
                if let PaneCommandEffect::Structural(ops) = &res.effect {
                    for op in ops {
                        tree.apply_operation(op_id, op.clone()).expect("applies");
                        op_id += 1;
                    }
                }
                ctx.active = res.next_active;
                ctx.maximized = res.next_maximized;
            }
            (tree.state_hash(), ctx.active)
        }

        let first = run_stream();
        let second = run_stream();
        assert_eq!(first, second, "command stream must be deterministic");
        // Active pane must be a real leaf after the stream.
        let tree = nested();
        assert!(focus_order(&tree).contains(&first.1.expect("active set")));
    }

    fn announce(
        tree: &PaneTree,
        layout: &PaneLayout,
        ctx: PaneFocusContext,
        command: PaneCommand,
    ) -> Option<PaneAnnouncement> {
        let res = resolve(tree, layout, ctx, command);
        announce_command(command, &res, tree)
    }

    #[test]
    fn announcements_describe_each_transition() {
        let tree = nested();
        let layout = solved(&tree);
        // Focus.
        let a = announce(
            &tree,
            &layout,
            PaneFocusContext::active(pid(2)),
            PaneCommand::FocusNext,
        )
        .unwrap();
        assert_eq!(a.category, PaneAnnouncementCategory::Focus);
        assert_eq!(a.text, "Focused pane right_top");
        // Maximize / restore.
        let a = announce(
            &tree,
            &layout,
            PaneFocusContext::active(pid(2)),
            PaneCommand::Maximize,
        )
        .unwrap();
        assert_eq!(a.text, "Maximized pane");
        let restore_ctx = PaneFocusContext {
            active: Some(pid(2)),
            maximized: Some(pid(2)),
        };
        let a = announce(&tree, &layout, restore_ctx, PaneCommand::Restore).unwrap();
        assert_eq!(a.text, "Restored pane");
    }

    #[test]
    fn announcement_reports_split_and_close_counts() {
        // Split grows the leaf count to 4; the announcement reflects the AFTER tree.
        let mut tree = nested();
        let layout = solved(&tree);
        let res = resolve(
            &tree,
            &layout,
            PaneFocusContext::active(pid(2)),
            PaneCommand::Split(SplitAxis::Vertical),
        );
        if let PaneCommandEffect::Structural(ops) = &res.effect {
            for (i, op) in ops.iter().enumerate() {
                tree.apply_operation(i as u64, op.clone()).unwrap();
            }
        }
        let a = announce_command(PaneCommand::Split(SplitAxis::Vertical), &res, &tree).unwrap();
        assert_eq!(a.category, PaneAnnouncementCategory::Split);
        assert_eq!(a.text, "Split pane vertical, 4 panes");
    }

    #[test]
    fn resize_announcement_reports_active_share() {
        // left(2) is the first child of the 1:1 root; grow by 1 step (+500 bps = +5%).
        let mut tree = nested();
        let layout = solved(&tree);
        let res = resolve(
            &tree,
            &layout,
            PaneFocusContext::active(pid(2)),
            PaneCommand::ResizeStep {
                direction: PaneResizeDirection::Increase,
                units: 1,
            },
        );
        if let PaneCommandEffect::Structural(ops) = &res.effect {
            for (i, op) in ops.iter().enumerate() {
                tree.apply_operation(i as u64, op.clone()).unwrap();
            }
        }
        let a = announce_command(
            PaneCommand::ResizeStep {
                direction: PaneResizeDirection::Increase,
                units: 1,
            },
            &res,
            &tree,
        )
        .unwrap();
        assert_eq!(a.category, PaneAnnouncementCategory::Resize);
        assert_eq!(a.text, "Resized pane to 55 percent");
    }

    #[test]
    fn noop_command_is_not_announced() {
        let tree = nested();
        let layout = solved(&tree);
        // No active pane -> FocusNext is a no-op -> no announcement.
        let a = announce(
            &tree,
            &layout,
            PaneFocusContext::default(),
            PaneCommand::FocusNext,
        );
        assert!(a.is_none());
    }

    #[test]
    fn announcer_coalesces_bursts_and_dedupes() {
        let mut announcer = PaneAnnouncer::new();
        // A burst of resize announcements coalesces to the latest on take().
        announcer.offer(Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Resize,
            "Resized pane to 55 percent",
        )));
        announcer.offer(Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Resize,
            "Resized pane to 60 percent",
        )));
        announcer.offer(Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Resize,
            "Resized pane to 65 percent",
        )));
        let spoken = announcer.take().unwrap();
        assert_eq!(spoken.text, "Resized pane to 65 percent");
        // Nothing pending now.
        assert!(announcer.take().is_none());
        // Offering the same text again is suppressed (dedupe).
        announcer.offer(Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Resize,
            "Resized pane to 65 percent",
        )));
        assert!(announcer.take().is_none());
        // A different text is spoken.
        announcer.offer(Some(PaneAnnouncement::new(
            PaneAnnouncementCategory::Focus,
            "Focused pane left",
        )));
        assert_eq!(announcer.take().unwrap().text, "Focused pane left");
        // Offering None does not disturb state.
        announcer.offer(None);
        assert!(announcer.take().is_none());
    }
}