ps-blitz-dom 0.3.0-beta.4

Blitz DOM implementation
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
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
use blitz_traits::{
    events::{BlitzImeEvent, BlitzKeyEvent},
    node_id::NodeId,
    shell::ShellProvider,
};
use keyboard_types::{Code, Key, Modifiers};
use parley::{ContentWidths, FontContext, LayoutContext};

use crate::util::{ACTION_MOD, has_clipboard_modifier};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ClipboardCommand {
    Copy,
    Cut,
    Paste,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HistoryCommand {
    Undo,
    Redo,
}

/// Ctrl/Cmd+Z undoes, and Shift+Z or Ctrl+Y redoes.
///
/// Ctrl+Y is the Windows redo and is accepted everywhere rather than gated on
/// the platform: it costs one arm, and a user who reaches for it on macOS gets
/// a redo instead of a `y`.
fn history_command(event: &BlitzKeyEvent) -> Option<HistoryCommand> {
    if !has_clipboard_modifier(event.modifiers) {
        return None;
    }
    let shift = event.modifiers.contains(Modifiers::SHIFT);
    let is = |code: Code, ch: &str| {
        event.code == code || matches!(&event.key, Key::Character(c) if c.eq_ignore_ascii_case(ch))
    };

    if is(Code::KeyZ, "z") {
        return Some(if shift {
            HistoryCommand::Redo
        } else {
            HistoryCommand::Undo
        });
    }
    if is(Code::KeyY, "y") {
        return Some(HistoryCommand::Redo);
    }
    None
}

/// One point a text input can be returned to.
///
/// The whole value, not a diff. A text input holds a single line or a short
/// message rather than a document, so the simplest thing that is always correct
/// beats a delta encoding that has to be right about every mutation path —
/// typing, IME preedit, paste, cut, drag, and the Apple standard keybindings
/// all reach the buffer through parley's driver, and a snapshot cannot miss one.
///
/// The selection travels with the text because restoring one without the other
/// is the wrong behaviour: undoing a paste has to put the caret back where the
/// text was inserted, not leave it wherever the caret happened to be.
#[derive(Clone, Debug, PartialEq, Eq)]
struct TextEditSnapshot {
    text: String,
    /// Byte offsets, in the order the selection was made, so an undone
    /// selection keeps the end the user was extending from.
    anchor: usize,
    focus: usize,
}

/// Undo and redo for one text input.
///
/// # Why this is here and not a crate
///
/// The obvious candidates do not fit. `undo` and `undoredo` are command-pattern
/// or delta libraries: they want to own the mutation so they can invert it, but
/// every mutation here already goes through `parley::PlainEditor`'s driver, so
/// adopting one means rerouting every edit site through command objects to buy
/// back what a snapshot gives for free. `loro`'s `UndoManager` is built for
/// CRDT documents that have to skip *remote* peers' edits; a text field has no
/// peers, and it costs 144 transitive crates and a second source of truth for
/// the text. Snapshot-based crates are ruled out at the source: `PlainEditor`
/// does not implement `Clone`.
///
/// So this is what a browser does, which is also what WebKit hands a normal
/// Tauri app for free: remember the value and the selection, coalesce a run of
/// typing into one entry, and cap the depth.
#[derive(Debug, Default)]
pub struct TextEditHistory {
    /// States that can be returned to, oldest first. The last entry is the one
    /// an undo restores; the state being left is pushed on the way out.
    undo: Vec<TextEditSnapshot>,
    /// States undone and not yet re-applied, most recently undone last.
    redo: Vec<TextEditSnapshot>,
    /// Where the editor was at the last recorded point, so the next edit can be
    /// tested against it for continuation. Follows the editor.
    current: Option<TextEditSnapshot>,
    /// The state the in-flight run of typing began from, held still while the
    /// run continues. This, not [`Self::current`], is what an undo restores —
    /// otherwise undo walks back one character at a time.
    burst: Option<TextEditSnapshot>,
    /// Set while an undo or redo is applying, so restoring a snapshot cannot
    /// record itself as a fresh edit.
    applying: bool,
}

/// Deep enough that a session's editing is recoverable, bounded so a long-lived
/// input cannot grow without limit. Chrome and Firefox both cap in this region.
const MAX_UNDO_DEPTH: usize = 200;

impl TextEditHistory {
    /// Whether `next` continues the burst that produced `previous`.
    ///
    /// Typing is coalesced so one undo removes a word or a run, not a single
    /// character: an undo per keystroke is technically faithful and unusable.
    /// A run continues while text is only being appended at the caret and the
    /// character added is not whitespace — a space or a newline ends the run,
    /// which is what makes undo land on word and line boundaries.
    ///
    /// Anything else — a deletion, a paste, a caret move, a selection replaced —
    /// starts a new entry, because those are the edits a user thinks of as one
    /// action.
    fn continues_burst(previous: &TextEditSnapshot, next: &TextEditSnapshot) -> bool {
        // Only ever appending, and only at the caret.
        if next.text.len() <= previous.text.len() {
            return false;
        }
        if previous.anchor != previous.focus || next.anchor != next.focus {
            return false;
        }
        // The insertion has to be at the previous caret, with everything before
        // and after it untouched.
        let caret = previous.focus;
        if caret > previous.text.len() || next.focus <= caret {
            return false;
        }
        let added = next.focus - caret;
        if next.text.len() != previous.text.len() + added {
            return false;
        }
        if previous.text.get(..caret) != next.text.get(..caret) {
            return false;
        }
        if previous.text.get(caret..) != next.text.get(next.focus..) {
            return false;
        }

        // A word or line boundary closes the run, so undo stops at one.
        !next.text[caret..next.focus]
            .chars()
            .any(|c| c.is_whitespace())
    }

    /// Record the state the editor is in *before* an edit is applied.
    ///
    /// Called on the way into every mutation. The first call seeds `current`
    /// without pushing, because there is nothing to return to yet; after that,
    /// a state that does not continue the current burst is pushed as its own
    /// undo entry.
    fn record(&mut self, snapshot: TextEditSnapshot) {
        if self.applying {
            return;
        }

        let Some(previous) = self.current.clone() else {
            // Nothing to return to yet: this is the state the first edit will
            // be applied to, so it becomes the burst start.
            self.current = Some(snapshot);
            return;
        };
        if previous == snapshot {
            return;
        }

        // Any real edit ends the redo branch, including one that merely
        // continues a run of typing. Clearing this only when a run *ended* let
        // a redo after "undo, then keep typing" resurrect the text that was
        // typed over.
        self.redo.clear();

        // `burst` is the state the current run of typing began from, and it is
        // what an undo has to restore. Advancing it per keystroke — which is
        // what overwriting `current` here used to do — is why undo removed a
        // single character instead of the whole word.
        let burst = self.burst.as_ref().unwrap_or(&previous);
        if Self::continues_burst(burst, &snapshot) {
            // Still the same run. Hold the start, and let `current` follow the
            // editor so the next keystroke is compared against where it is now.
            self.burst = Some(burst.clone());
            self.current = Some(snapshot);
            return;
        }

        // The run ended, so the state it started from becomes an undo entry.
        let entry = self.burst.take().unwrap_or(previous);
        self.current = Some(snapshot);
        self.undo.push(entry);
        if self.undo.len() > MAX_UNDO_DEPTH {
            self.undo.remove(0);
        }
    }

    /// The state to restore for an undo, given where the editor is now.
    fn undo(&mut self, now: TextEditSnapshot) -> Option<TextEditSnapshot> {
        // A run of typing that has not been closed yet is still undoable, and
        // the state to return to is where that run began. Without this, typing
        // a word and pressing undo would skip over it to the entry before.
        if let Some(burst) = self.burst.take() {
            if burst != now {
                self.undo.push(burst);
            }
        }
        let restore = self.undo.pop()?;
        self.redo.push(now);
        self.current = Some(restore.clone());
        Some(restore)
    }

    /// The state to restore for a redo, given where the editor is now.
    fn redo(&mut self, now: TextEditSnapshot) -> Option<TextEditSnapshot> {
        let restore = self.redo.pop()?;
        self.undo.push(now);
        // A redo lands on a settled state, so there is no run in flight.
        self.burst = None;
        self.current = Some(restore.clone());
        Some(restore)
    }
}

fn clipboard_command(event: &BlitzKeyEvent) -> Option<ClipboardCommand> {
    if !has_clipboard_modifier(event.modifiers) {
        return None;
    }
    match event.code {
        Code::KeyC => Some(ClipboardCommand::Copy),
        Code::KeyX => Some(ClipboardCommand::Cut),
        Code::KeyV => Some(ClipboardCommand::Paste),
        _ => match &event.key {
            Key::Character(c) if c.eq_ignore_ascii_case("c") => Some(ClipboardCommand::Copy),
            Key::Character(c) if c.eq_ignore_ascii_case("x") => Some(ClipboardCommand::Cut),
            Key::Character(c) if c.eq_ignore_ascii_case("v") => Some(ClipboardCommand::Paste),
            _ => None,
        },
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
/// Parley Brush type for Blitz which contains the Blitz node id
pub struct TextBrush {
    /// The node id for the span
    pub id: NodeId,
}

impl TextBrush {
    pub(crate) fn from_id(id: NodeId) -> Self {
        Self { id }
    }
}

/// A [`ContentWidths`] result together with the inline box widths it was derived from.
///
/// Only ever produced by [`TextLayout::content_widths`]. Invalidation sites set
/// [`TextLayout::content_widths`] to `None` rather than constructing this.
#[derive(Clone, Debug)]
pub struct CachedContentWidths {
    /// The `width` of every inline box in the layout, as raw bit patterns, at the moment
    /// `widths` was computed. Stored as bits so the comparison is exact rather than
    /// approximate, and boxed so that the overwhelmingly common "no inline boxes" case does
    /// not allocate.
    inline_box_widths: Box<[u32]>,
    widths: ContentWidths,
}

#[derive(Clone, Default)]
pub struct TextLayout {
    pub text: String,
    pub content_widths: Option<CachedContentWidths>,
    pub layout: parley::layout::Layout<TextBrush>,
    /// The width the lines were last broken at *by a layout pass*, in device
    /// pixels.
    ///
    /// Measuring re-breaks the same layout at trial widths and stores the
    /// result back on the node, so the state left behind belongs to whichever
    /// pass ran last, and that is often a max-content measurement rather than
    /// the layout. Non-atomic inline elements read their geometry straight out
    /// of this layout, so they then report boxes from a line that is not on
    /// screen: measured on a live transcript as a block 713px wide and three
    /// lines tall sitting over a single line 1,742px wide, with its `<code>`
    /// and `<strong>` boxes up to 987px outside the pane.
    ///
    /// Recording it lets a measuring pass put the lines back where layout left
    /// them.
    pub laid_out_at: Option<f32>,
}

impl TextLayout {
    pub fn new() -> Self {
        Default::default()
    }

    /// The layout's min-content and max-content widths, recomputed only when the inputs to
    /// that computation have actually changed.
    ///
    /// WHY this is cached: `Layout::calculate_content_widths` walks every shaped cluster in
    /// the layout, and block layout asks for the content widths two or three times per pass
    /// (once under a min-content constraint, once under max-content, then again for the
    /// definite measure), so the same scan is repeated over the same data.
    ///
    /// WHY it is safe: the result is a pure function of exactly two things, the shaped runs
    /// and the current width of each inline box.
    ///
    /// The shaped runs only change when the inline layout is rebuilt, and every rebuild goes
    /// through `build_inline_layout_into`, which clears this cache. Damage propagation clears
    /// it too, in the same places it clears the Taffy layout cache, so a text edit or a style
    /// change affecting font, size, weight, letter/word spacing or white-space collapsing
    /// always re-measures.
    ///
    /// The inline box widths are the reason this cannot be a plain one-shot cache: they are
    /// re-measured on every pass, and an inline box legitimately measures differently under a
    /// min-content constraint than under a max-content one, so the same shaped text can yield
    /// different content widths from one call to the next. Rather than guess which constraint
    /// a cached entry belongs to, we record the box widths the entry was computed from and
    /// reuse it only when they are bit-for-bit identical. A layout containing no inline
    /// boxes, which is the common case and where the scan cost is concentrated, therefore
    /// hits the cache on every pass after the first.
    pub fn content_widths(&mut self) -> ContentWidths {
        // `InlineBox::kind` is fixed when the layout is built (and a change to it goes via a
        // rebuild, which invalidates this cache), so the widths alone identify the inline box
        // state that `calculate_content_widths` reads.
        let inline_box_widths: Box<[u32]> = self
            .layout
            .inline_boxes()
            .iter()
            .map(|ibox| ibox.width.to_bits())
            .collect();

        if let Some(cached) = &self.content_widths
            && cached.inline_box_widths == inline_box_widths
        {
            return cached.widths;
        }

        let widths = self.layout.calculate_content_widths();
        self.content_widths = Some(CachedContentWidths {
            inline_box_widths,
            widths,
        });
        widths
    }
}

impl std::fmt::Debug for TextLayout {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "TextLayout")
    }
}

// TODO: support keypress events
pub enum GeneratedTextInputEvent {
    Input,
    Select,
    PreEditChange,
    Submit,
}

pub struct TextInputData {
    /// A parley TextEditor instance
    pub editor: Box<parley::PlainEditor<TextBrush>>,
    /// Shaped placeholder text, painted only while the editable value is empty.
    pub placeholder_editor: Option<Box<parley::PlainEditor<TextBrush>>>,
    /// Undo and redo for this input. Parley has no history of its own, so
    /// without this Cmd+Z reached no handler and did nothing at all.
    history: TextEditHistory,
    /// Whether the input is a singleline or multiline input
    pub is_multiline: bool,
    /// The scroll offset of the text content within the input, in CSS (unscaled) pixels.
    ///
    /// For single-line inputs this is a horizontal offset; for multi-line inputs it is a
    /// vertical offset. It is kept up to date so that the caret remains visible within the
    /// input's content box.
    pub scroll_offset: f32,
    pub layout_width: Option<f32>,
}

// FIXME: Implement Clone for PlainEditor
impl Clone for TextInputData {
    fn clone(&self) -> Self {
        TextInputData::new(self.is_multiline)
    }
}

impl TextInputData {
    pub fn new(is_multiline: bool) -> Self {
        let editor = Box::new(parley::PlainEditor::new(16.0));
        Self {
            editor,
            placeholder_editor: None,
            history: TextEditHistory::default(),
            is_multiline,
            scroll_offset: 0.0,
            layout_width: None,
        }
    }

    /// The editor's current value and selection, as an undo entry.
    fn snapshot(&self) -> TextEditSnapshot {
        let selection = self.editor.raw_selection();
        TextEditSnapshot {
            text: self.editor.raw_text().to_string(),
            anchor: selection.anchor().index(),
            focus: selection.focus().index(),
        }
    }

    /// Remember where the editor is, before an edit changes it.
    fn record_history(&mut self) {
        let snapshot = self.snapshot();
        self.history.record(snapshot);
    }

    /// Put the editor back to `snapshot`, text and selection together.
    ///
    /// `applying` is held for the duration so the restore cannot be recorded as
    /// a new edit, which would make undo a no-op that toggles between two
    /// states.
    fn restore(
        &mut self,
        font_ctx: &mut FontContext,
        layout_ctx: &mut LayoutContext<TextBrush>,
        snapshot: &TextEditSnapshot,
    ) {
        self.history.applying = true;
        self.editor.set_text(&snapshot.text);
        let mut driver = self.editor.driver(font_ctx, layout_ctx);
        // Byte offsets from a snapshot of this same buffer, but the text has
        // just been replaced, so clamp rather than trust them: parley ignores a
        // non-boundary index and the caret would silently stay put.
        let len = snapshot.text.len();
        let anchor = snapshot.anchor.min(len);
        let focus = snapshot.focus.min(len);
        if anchor == focus {
            driver.move_to_byte(focus);
        } else {
            driver.select_byte_range(anchor, focus);
        }
        self.history.applying = false;
    }

    /// Apply an undo or a redo, if there is one to apply.
    fn apply_history_command(
        &mut self,
        font_ctx: &mut FontContext,
        layout_ctx: &mut LayoutContext<TextBrush>,
        command: HistoryCommand,
    ) -> Option<GeneratedTextInputEvent> {
        let now = self.snapshot();
        let restore = match command {
            HistoryCommand::Undo => self.history.undo(now),
            HistoryCommand::Redo => self.history.redo(now),
        }?;
        self.restore(font_ctx, layout_ctx, &restore);
        Some(GeneratedTextInputEvent::Input)
    }

    /// The height of the laid out text, in CSS (unscaled) pixels.
    ///
    /// Parley lays out at the editor's scale, so `Layout::height` is device
    /// pixels. Everything outside this type speaks CSS pixels, so the division
    /// belongs here rather than at each call site: two of them forgot it, and
    /// the result was a textarea that measured four times too tall on a retina
    /// display.
    pub fn content_height(&self) -> Option<f32> {
        self.editor
            .try_layout()
            .map(|layout| layout.height() / layout.scale())
    }

    /// Push [`Self::layout_width`] into the editors, converting to their space.
    ///
    /// The remembered width is CSS pixels, because that is what layout hands
    /// in. Parley wraps against its own scaled layout, so a width passed
    /// straight through wraps at `width / scale`: on a 2x display a textarea
    /// broke its text at half the box, and an autosizing composer grew to a
    /// second line after half a line of typing.
    fn apply_layout_width(&mut self) {
        let Some(width) = self.layout_width else {
            return;
        };
        self.editor.set_width(Some(width * self.editor.get_scale()));
        if let Some(placeholder) = self.placeholder_editor.as_mut() {
            placeholder.set_width(Some(width * placeholder.get_scale()));
        }
    }

    pub fn sync_multiline_width(
        &mut self,
        font_ctx: &mut FontContext,
        layout_ctx: &mut LayoutContext<TextBrush>,
        width: f32,
    ) {
        if !self.is_multiline || width <= 0.0 {
            return;
        }
        if self
            .layout_width
            .is_some_and(|current| (current - width).abs() < 0.01)
        {
            return;
        }
        self.layout_width = Some(width);
        self.apply_layout_width();
        self.editor.driver(font_ctx, layout_ctx).refresh_layout();
        if let Some(placeholder) = self.placeholder_editor.as_mut() {
            placeholder.driver(font_ctx, layout_ctx).refresh_layout();
        }
    }

    pub fn set_text(
        &mut self,
        font_ctx: &mut FontContext,
        layout_ctx: &mut LayoutContext<TextBrush>,
        text: &str,
    ) {
        if self.editor.text() != text {
            self.editor.set_text(text);
            // Put the wrap width back before re-laying out.
            //
            // `PlainEditor::set_text` rebuilds the layout without a width, so
            // new text would otherwise be laid out on one endless line and walk
            // out of the box. `sync_multiline_width` would normally restore it,
            // but it returns early when the width it remembers already matches
            // the one being asked for, and it does match: only the text
            // changed. The remembered width is a claim about the *layout*, so
            // it has to be re-applied whenever the layout is thrown away.
            //
            // Re-applying here rather than waiting for the next measure is also
            // what lets `scrollHeight` be answered without resolving the whole
            // document, which typing does on every keystroke.
            self.apply_layout_width();
            self.editor.driver(font_ctx, layout_ctx).refresh_layout();
            // Put the caret at the end, where the value setter is specified to
            // leave it.
            //
            // `PlainEditor::set_text` rebuilds the buffer and leaves the
            // selection collapsed at offset 0. HTML says assigning `value`
            // must "move the text entry cursor position to the end of the text
            // control", so without this any page that writes back to an input
            // while someone is typing throws their caret to the front of the
            // field. An address bar that rewrites `example.com` as
            // `https://example.com` on submit is the case that found it.
            //
            // After `refresh_layout`, not before: the cursor is resolved
            // against the layout that call rebuilds.
            self.editor.driver(font_ctx, layout_ctx).move_to_text_end();
        }
    }

    /// Recompute [`Self::scroll_offset`] so that the caret stays visible within the input's
    /// content box.
    ///
    /// `content_box_width` and `content_box_height` are the dimensions of the input's content
    /// box in CSS (unscaled) pixels.
    pub fn clamp_scroll_offset(&mut self, content_box_width: f32, content_box_height: f32) {
        let Some(layout) = self.editor.try_layout() else {
            return;
        };
        // Parley lays out at the editor's scale, so its geometry is in scaled (device) pixels.
        // We convert into CSS (unscaled) pixels to match `scroll_offset` and the content box.
        let scale = layout.scale();

        // The caret geometry relative to the start of the text content.
        let Some(caret) = self.editor.cursor_geometry(1.5) else {
            return;
        };

        // Caret bounds and content/viewport extents along the scrolling axis (CSS pixels).
        let (caret_start, caret_end, content, viewport) = if self.is_multiline {
            (
                caret.y0 as f32 / scale,
                caret.y1 as f32 / scale,
                layout.height() / scale,
                content_box_height,
            )
        } else {
            (
                caret.x0 as f32 / scale,
                caret.x1 as f32 / scale,
                layout.full_width() / scale,
                content_box_width,
            )
        };

        let mut offset = self.scroll_offset;

        // Scroll so that both edges of the caret are within the visible region.
        if caret_end > offset + viewport {
            offset = caret_end - viewport;
        }
        if caret_start < offset {
            offset = caret_start;
        }

        // Never scroll past the content, and never scroll into negative space. The content
        // extent includes the caret so that a caret at the very end remains fully visible
        // (its rendered width extends slightly past the text).
        let max_offset = (content.max(caret_end) - viewport).max(0.0);
        self.scroll_offset = offset.clamp(0.0, max_offset);
    }

    /// The maximum valid value of [`Self::scroll_offset`] (in CSS pixels) given the input's
    /// content box, i.e. the extent by which the text content overflows the content box along
    /// the input's scroll axis.
    ///
    /// `content_box_width` and `content_box_height` are the dimensions of the input's content
    /// box in CSS (unscaled) pixels.
    pub fn max_scroll_offset(&self, content_box_width: f32, content_box_height: f32) -> f32 {
        let Some(layout) = self.editor.try_layout() else {
            return 0.0;
        };
        let scale = layout.scale();
        let (content, viewport) = if self.is_multiline {
            (layout.height() / scale, content_box_height)
        } else {
            (layout.full_width() / scale, content_box_width)
        };
        (content - viewport).max(0.0)
    }

    /// Scroll the input's text content by `delta` CSS pixels along its scroll axis (horizontal
    /// for single-line inputs, vertical for multi-line inputs), clamping to the scrollable
    /// range.
    ///
    /// Returns the portion of `delta` that could not be consumed (because the input was already
    /// scrolled to its limit), so the caller can bubble it up to an ancestor scroller.
    pub fn scroll_by(
        &mut self,
        delta: f32,
        content_box_width: f32,
        content_box_height: f32,
    ) -> f32 {
        let max_offset = self.max_scroll_offset(content_box_width, content_box_height);
        if max_offset <= 0.0 {
            return delta;
        }

        // Match the sign convention used for block scrolling: a positive delta decreases the
        // scroll offset.
        let new_offset = (self.scroll_offset - delta).clamp(0.0, max_offset);
        let consumed = self.scroll_offset - new_offset;
        self.scroll_offset = new_offset;
        delta - consumed
    }

    pub(crate) fn apply_keypress_event(
        &mut self,
        font_ctx: &mut FontContext,
        layout_ctx: &mut LayoutContext<TextBrush>,
        shell_provider: &dyn ShellProvider,
        event: BlitzKeyEvent,
    ) -> Option<GeneratedTextInputEvent> {
        // Do nothing if it is a keyup event
        if !event.state.is_pressed() {
            return None;
        }

        // Undo and redo first: they are the one pair that must not be recorded
        // as edits, and `history_command` is checked before anything mutates.
        if let Some(command) = history_command(&event) {
            return self.apply_history_command(font_ctx, layout_ctx, command);
        }

        // Every path below this point can change the buffer, so the state being
        // left is recorded here rather than at each of them. A keystroke that
        // turns out to only move the caret records a snapshot equal to the last
        // one, which `record` discards.
        self.record_history();

        let mods = event.modifiers;
        let shift = mods.contains(Modifiers::SHIFT);
        let action_mod = mods.contains(ACTION_MOD);
        let word_mod = mods.contains(Modifiers::ALT);
        let is_multiline = self.is_multiline;
        let editor = &mut self.editor;
        let mut driver = editor.driver(font_ctx, layout_ctx);
        if let Some(command) = clipboard_command(&event) {
            match command {
                ClipboardCommand::Copy => {
                    if let Some(text) = driver.editor.selected_text() {
                        let _ = shell_provider.set_clipboard_text(text.to_owned());
                    }
                }
                ClipboardCommand::Cut => {
                    if let Some(text) = driver.editor.selected_text() {
                        let _ = shell_provider.set_clipboard_text(text.to_owned());
                        driver.delete_selection()
                    }
                }
                ClipboardCommand::Paste => {
                    let text = shell_provider.get_clipboard_text().unwrap_or_default();
                    driver.insert_or_replace_selection(&text)
                }
            }

            return Some(GeneratedTextInputEvent::Input);
        }
        match event.key {
            Key::Character(c) if action_mod && matches!(c.to_lowercase().as_str(), "a") => {
                if shift {
                    driver.collapse_selection()
                } else {
                    driver.select_all()
                }
                return Some(GeneratedTextInputEvent::Select);
            }
            Key::ArrowLeft => {
                if action_mod {
                    if shift {
                        driver.select_to_line_start()
                    } else {
                        driver.move_to_line_start()
                    }
                } else if word_mod {
                    if shift {
                        driver.select_word_left()
                    } else {
                        driver.move_word_left()
                    }
                } else if shift {
                    driver.select_left()
                } else {
                    driver.move_left()
                }
                return Some(GeneratedTextInputEvent::Select);
            }
            Key::ArrowRight => {
                if action_mod {
                    if shift {
                        driver.select_to_line_end()
                    } else {
                        driver.move_to_line_end()
                    }
                } else if word_mod {
                    if shift {
                        driver.select_word_right()
                    } else {
                        driver.move_word_right()
                    }
                } else if shift {
                    driver.select_right()
                } else {
                    driver.move_right()
                }
                return Some(GeneratedTextInputEvent::Select);
            }
            Key::ArrowUp => {
                if action_mod && shift {
                    driver.select_to_text_start()
                } else if action_mod {
                    driver.move_to_text_start()
                } else if shift {
                    driver.select_up()
                } else {
                    driver.move_up()
                }
                return Some(GeneratedTextInputEvent::Select);
            }
            Key::ArrowDown => {
                if action_mod && shift {
                    driver.select_to_text_end()
                } else if action_mod {
                    driver.move_to_text_end()
                } else if shift {
                    driver.select_down()
                } else {
                    driver.move_down()
                }
                return Some(GeneratedTextInputEvent::Select);
            }
            Key::Home => {
                if action_mod {
                    if shift {
                        driver.select_to_text_start()
                    } else {
                        driver.move_to_text_start()
                    }
                } else if shift {
                    driver.select_to_line_start()
                } else {
                    driver.move_to_line_start()
                }
                return Some(GeneratedTextInputEvent::Select);
            }
            Key::End => {
                if action_mod {
                    if shift {
                        driver.select_to_text_end()
                    } else {
                        driver.move_to_text_end()
                    }
                } else if shift {
                    driver.select_to_line_end()
                } else {
                    driver.move_to_line_end()
                }
                return Some(GeneratedTextInputEvent::Select);
            }
            Key::Delete => {
                #[cfg(target_os = "macos")]
                if mods.contains(Modifiers::SUPER) {
                    if driver.editor.raw_selection().is_collapsed() {
                        driver.select_to_line_end();
                    }
                    driver.delete_selection();
                } else if mods.contains(Modifiers::ALT) {
                    driver.delete_word();
                } else {
                    driver.delete();
                }
                #[cfg(not(target_os = "macos"))]
                if action_mod {
                    driver.delete_word();
                } else {
                    driver.delete();
                }
                return Some(GeneratedTextInputEvent::Input);
            }
            Key::Backspace => {
                #[cfg(target_os = "macos")]
                if mods.contains(Modifiers::SUPER) {
                    if driver.editor.raw_selection().is_collapsed() {
                        driver.select_to_line_start();
                    }
                    driver.delete_selection();
                } else if mods.contains(Modifiers::ALT) {
                    driver.backdelete_word();
                } else {
                    driver.backdelete();
                }
                #[cfg(not(target_os = "macos"))]
                if action_mod {
                    driver.backdelete_word();
                } else {
                    driver.backdelete();
                }
                return Some(GeneratedTextInputEvent::Input);
            }

            Key::Character(c) if c == "\n" => {
                if is_multiline {
                    driver.insert_or_replace_selection("\n");
                    return Some(GeneratedTextInputEvent::Input);
                } else {
                    return Some(GeneratedTextInputEvent::Submit);
                }
            }
            Key::Enter => {
                if is_multiline {
                    driver.insert_or_replace_selection("\n");
                    return Some(GeneratedTextInputEvent::Input);
                } else {
                    return Some(GeneratedTextInputEvent::Submit);
                }
            }
            Key::Character(s)
                if !mods.contains(Modifiers::CONTROL) && !mods.contains(Modifiers::SUPER) =>
            {
                driver.insert_or_replace_selection(&s);
                return Some(GeneratedTextInputEvent::Input);
            }
            _ => {}
        };

        None
    }

    pub(crate) fn apply_apple_standard_keybinding(
        &mut self,
        font_ctx: &mut FontContext,
        layout_ctx: &mut LayoutContext<TextBrush>,
        shell_provider: &dyn ShellProvider,
        command: &str,
    ) -> Option<GeneratedTextInputEvent> {
        // AppKit routes a large part of macOS text editing here rather than
        // through `apply_keypress_event` — every delete, transpose and kill —
        // so an undo stack fed only by keypresses would miss them.
        self.record_history();

        let editor = &mut self.editor;
        let mut driver = editor.driver(font_ctx, layout_ctx);
        let is_multiline = self.is_multiline;

        match command {
            // Inserting Content

            // Inserts a backtab character.
            "insertBacktab:" => {}
            // Inserts a container break, such as a new page break.
            "insertContainerBreak:" => {}
            // Inserts a double quotation mark without substituting a curly quotation mark.
            "insertDoubleQuoteIgnoringSubstitution:" => {
                driver.insert_or_replace_selection("\"");
                return Some(GeneratedTextInputEvent::Input);
            }
            // Inserts a line break character.
            "insertLineBreak:" => {
                driver.insert_or_replace_selection("\n");
                return Some(GeneratedTextInputEvent::Input);
            }
            // Inserts a newline character.
            "insertNewline:" => {
                if is_multiline {
                    driver.insert_or_replace_selection("\n");
                    return Some(GeneratedTextInputEvent::Input);
                } else {
                    return Some(GeneratedTextInputEvent::Submit);
                }
            }
            // Inserts a newline character without invoking the field editor’s normal handling to end editing.
            "insertNewlineIgnoringFieldEditor:" => {
                driver.insert_or_replace_selection("\n");
                return Some(GeneratedTextInputEvent::Input);
            }
            // Inserts a paragraph separator.
            "insertParagraphSeparator:" => {
                driver.insert_or_replace_selection("\n");
                return Some(GeneratedTextInputEvent::Input);
            }
            "insertSingleQuoteIgnoringSubstitution:" => {
                driver.insert_or_replace_selection("'");
                return Some(GeneratedTextInputEvent::Input);
            }
            // Inserts a tab character.
            "insertTab:" | "insertTabIgnoringFieldEditor:" => {
                // Ignore for now seeing as parley has poor support for laying out tabs
            }
            // Inserts the text you specify.
            "insertText:" => {}

            // Deleting Content

            // Deletes content moving backward from the current insertion point.
            // Physical Backspace/Delete events are handled directly above. AppKit may
            // deliver these selectors as well, but applying both would delete twice.
            "deleteBackward:" | "deleteBackwardByDecomposingPreviousCharacter:" => {}
            "deleteForward:" => {}
            // Deletes content from the insertion point to the beginning of the current line.
            "deleteToBeginningOfLine:" => {
                if driver.editor.raw_selection().is_collapsed() {
                    driver.select_to_line_start();
                }
                driver.delete_selection();
                return Some(GeneratedTextInputEvent::Input);
            }
            // Deletes content from the insertion point to the beginning of the current paragraph.
            "deleteToEndOfLine:" => {
                if driver.editor.raw_selection().is_collapsed() {
                    driver.select_to_line_end();
                }
                driver.delete_selection();
                return Some(GeneratedTextInputEvent::Input);
            }
            "deleteToBeginningOfParagraph:" => {
                if driver.editor.raw_selection().is_collapsed() {
                    driver.select_to_hard_line_start();
                }
                driver.delete_selection();
                return Some(GeneratedTextInputEvent::Input);
            }

            // Deletes content from the insertion point to the end of the current line.
            "deleteToEndOfParagraph:" => {
                if driver.editor.raw_selection().is_collapsed() {
                    driver.select_to_hard_line_end();
                }
                driver.delete_selection();
                return Some(GeneratedTextInputEvent::Input);
            }
            // Deletes content from the insertion point to the end of the current paragraph.
            "deleteWordBackward:" => {}
            // Deletes the word preceding the current insertion point.
            "deleteWordForward:" => {}
            // Deletes the current selection, placing it in a temporary buffer, such as the Clipboard.
            "yank:" => {
                if let Some(text) = driver.editor.selected_text() {
                    let _ = shell_provider.set_clipboard_text(text.to_owned());
                    driver.delete_selection();
                    return Some(GeneratedTextInputEvent::Input);
                }
            }

            // Moving the Insertion Pointer

            // Moves the insertion pointer backward in the current content.
            "moveBackward:" => {
                driver.move_left(); // TODO: Bidi-aware
                return Some(GeneratedTextInputEvent::Select);
            }

            // Moves the insertion pointer down in the current content.
            "moveDown:" => {
                driver.move_down();
                return Some(GeneratedTextInputEvent::Select);
            }
            // Moves the insertion pointer forward in the current content.
            "moveForward:" => {
                driver.move_right();
                return Some(GeneratedTextInputEvent::Select);
            } // TODO: Bidi-aware

            // Moves the insertion pointer left in the current content.
            "moveLeft:" => {
                driver.move_left();
                return Some(GeneratedTextInputEvent::Select);
            }
            // Moves the insertion pointer right in the current content.
            "moveRight:" => {
                driver.move_right();
                return Some(GeneratedTextInputEvent::Select);
            }
            // Moves the insertion pointer up in the current content.
            "moveUp:" => {
                driver.move_up();
                return Some(GeneratedTextInputEvent::Select);
            }

            // Modifying the Selection

            // Extends the selection to include the content before the current selection.
            "moveBackwardAndModifySelection:" => {
                driver.select_left(); // TODO: Bidi-aware
                return Some(GeneratedTextInputEvent::Select);
            }
            // Extends the selection to include the content below the current selection.
            "moveDownAndModifySelection:" => {
                driver.select_down();
                return Some(GeneratedTextInputEvent::Select);
            }
            // Extends the selection to include the content after the current selection.
            "moveForwardAndModifySelection:" => {
                driver.select_right(); // TODO: Bidi-aware
                return Some(GeneratedTextInputEvent::Select);
            }
            // Extends the selection to include the content to the left of the current selection.
            "moveLeftAndModifySelection:" => {
                driver.select_left();
                return Some(GeneratedTextInputEvent::Select);
            }
            // Extends the selection to include the content to the right of the current selection.
            "moveRightAndModifySelection:" => {
                driver.select_right();
                return Some(GeneratedTextInputEvent::Select);
            }
            // Extends the selection to include the content above the current selection.
            "moveUpAndModifySelection:" => {
                driver.select_up();
                return Some(GeneratedTextInputEvent::Select);
            }

            // Changing the Selection
            "selectAll:" => {
                driver.select_all();
                return Some(GeneratedTextInputEvent::Select);
            }
            "selectLine:" => {
                driver.move_to_line_start();
                driver.select_to_line_end();
                return Some(GeneratedTextInputEvent::Select);
            }
            "selectParagraph:" => {
                driver.move_to_hard_line_start();
                driver.select_to_hard_line_end();
                return Some(GeneratedTextInputEvent::Select);
            }
            "selectWord:" => {
                // TODO
            }

            // Moving the Selection in Documents
            "moveToBeginningOfDocument:" => {
                driver.move_to_text_start();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToBeginningOfDocumentAndModifySelection:" => {
                driver.select_to_text_start();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToEndOfDocument:" => {
                driver.move_to_text_end();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToEndOfDocumentAndModifySelection:" => {
                driver.move_to_text_end();
                return Some(GeneratedTextInputEvent::Select);
            }

            // Moving the Selection in Paragraphs
            "moveParagraphBackwardAndModifySelection:" => {}
            "moveParagraphForwardAndModifySelection:" => {}
            "moveToBeginningOfParagraph:" => {
                driver.move_to_hard_line_start();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToBeginningOfParagraphAndModifySelection:" => {
                driver.select_to_hard_line_start();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToEndOfParagraph:" => {
                driver.move_to_hard_line_end();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToEndOfParagraphAndModifySelection:" => {
                driver.select_to_hard_line_end();
                return Some(GeneratedTextInputEvent::Select);
            }

            // Moving the Selection in Lines of Text
            "moveToBeginningOfLine:" => {
                driver.move_to_line_start();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToBeginningOfLineAndModifySelection:" => {
                driver.select_to_line_start();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToEndOfLine:" => {
                driver.move_to_line_end();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToEndOfLineAndModifySelection:" => {
                driver.select_to_line_end();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToLeftEndOfLine:" => {
                driver.move_to_text_start();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToLeftEndOfLineAndModifySelection:" => {
                driver.select_to_line_start();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToRightEndOfLine:" => {
                driver.move_to_line_end();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveToRightEndOfLineAndModifySelection:" => {
                driver.select_to_line_end();
                return Some(GeneratedTextInputEvent::Select);
            }

            // Moving the Selection by Word Boundaries
            "moveWordBackward:" => {
                driver.move_word_left();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveWordBackwardAndModifySelection:" => {
                driver.select_word_left();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveWordForward:" => {
                driver.move_word_right();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveWordForwardAndModifySelection:" => {
                driver.select_word_right();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveWordLeft:" => {
                driver.move_word_left();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveWordLeftAndModifySelection:" => {
                driver.select_word_left();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveWordRight:" => {
                driver.move_word_right();
                return Some(GeneratedTextInputEvent::Select);
            }
            "moveWordRightAndModifySelection:" => {
                driver.select_word_right();
                return Some(GeneratedTextInputEvent::Select);
            }

            // Scrolling Content

            // Scrolls the content down by a page.
            "scrollPageDown:" => {}
            // Scrolls the content up by a page.
            "scrollPageUp:" => {}
            // Scrolls the content down by a line.
            "scrollLineDown:" => {}
            // Scrolls the content up by a line.
            "scrollLineUp:" => {}
            // Scrolls the content to the beginning of the document.
            "scrollToBeginningOfDocument:" => {}
            // Scrolls the content to the end of the document.
            "scrollToEndOfDocument:" => {}
            // Moves the visible content region down by a page.
            "pageDown:" => {}
            // Moves the visible content region up by a page.
            "pageUp:" => {}
            // Moves the visible content region down by a page, and extends the current selection.
            "pageDownAndModifySelection:" => {}
            // Moves the visible content region up by a page, and extends the current selection.
            "pageUpAndModifySelection:" => {}
            // Moves the visible content region so the current selection is visually centered.
            "centerSelectionInVisibleArea:" => {}

            // Transposing Elements

            // Transposes the content around the current selection.
            "transpose:" => {}
            // Transposes the words around the current selection.
            "transposeWords:" => {}

            // Indenting Content
            // Indents the content at the current selection.
            "indent:" => {}

            // Canceling Operations
            // Cancels the current operation.
            "cancelOperation:" => {}

            // Supporting QuickLook
            // Invokes QuickLook to preview the current selection.
            "quickLookPreviewItems:" => {}

            // Supporting Writing Directions
            "makeBaseWritingDirectionLeftToRight:" => {}
            "makeBaseWritingDirectionNatural:" => {}
            "makeBaseWritingDirectionRightToLeft:" => {}
            "makeTextWritingDirectionLeftToRight:" => {}
            "makeTextWritingDirectionNatural:" => {}
            "makeTextWritingDirectionRightToLeft:" => {}

            // Changing Capitalization
            "capitalizeWord:" => {}
            "changeCaseOfLetter:" => {}
            "lowercaseWord:" => {}
            "uppercaseWord:" => {}

            // Supporting Marked Selections
            "setMark:" => {}
            "selectToMark:" => {}
            "deleteToMark:" => {}
            "swapWithMark:" => {}

            // Supporting Autocomplete
            "complete:" => {}

            // Instance Methods
            "showContextMenuForSelection:" => {}

            // Unknown command
            _ => {}
        };

        None
    }

    pub(crate) fn apply_ime_event(
        &mut self,
        font_ctx: &mut FontContext,
        layout_ctx: &mut LayoutContext<TextBrush>,
        event: BlitzImeEvent,
    ) -> Option<GeneratedTextInputEvent> {
        // Only a commit, deliberately.
        //
        // A composition session emits a preedit per keystroke, and recording
        // those would fill the stack with half-composed text: undoing after
        // typing a Japanese word would walk back through its romaji rather than
        // removing the word. The commit is the edit the user made, so it is the
        // only point that becomes undoable.
        if matches!(event, BlitzImeEvent::Commit(_)) {
            self.record_history();
        }

        let editor = &mut self.editor;
        let mut driver = editor.driver(font_ctx, layout_ctx);

        match event {
            BlitzImeEvent::Enabled => {
                // Do nothing
                None
            }
            BlitzImeEvent::Disabled => {
                driver.clear_compose();
                Some(GeneratedTextInputEvent::PreEditChange)
            }
            BlitzImeEvent::Commit(text) => {
                driver.insert_or_replace_selection(&text);
                Some(GeneratedTextInputEvent::Input)
            }
            BlitzImeEvent::Preedit(text, cursor) => {
                if text.is_empty() {
                    driver.clear_compose();
                } else {
                    driver.set_compose(&text, cursor);
                }
                Some(GeneratedTextInputEvent::PreEditChange)
            }
            BlitzImeEvent::DeleteSurrounding {
                before_bytes,
                after_bytes,
            } => {
                let _ = before_bytes;
                let _ = after_bytes;
                // TODO
                None
            }
        }
    }
}

#[cfg(test)]
mod content_widths_cache_tests {
    use super::*;
    use parley::{InlineBox, InlineBoxKind, TextStyle};

    /// Build a [`TextLayout`] containing `text`, optionally followed by an inline box of
    /// `inline_box_width` pixels.
    fn build_layout(text: &str, inline_box_width: Option<f32>) -> TextLayout {
        let mut font_ctx = FontContext::default();
        let mut layout_ctx = LayoutContext::new();
        let style: TextStyle<'_, '_, TextBrush> = TextStyle::default();
        let mut builder = layout_ctx.tree_builder(&mut font_ctx, 1.0, true, &style);
        builder.push_text(text);
        if let Some(width) = inline_box_width {
            builder.push_inline_box(InlineBox {
                id: 0,
                kind: InlineBoxKind::InFlow,
                index: text.len(),
                width,
                height: 10.0,
            });
        }

        let mut text_layout = TextLayout::new();
        text_layout.text = builder.build_into(&mut text_layout.layout);
        text_layout
    }

    #[test]
    fn first_call_matches_an_uncached_computation() {
        let mut text_layout = build_layout("the quick brown fox", None);
        let expected = text_layout.layout.calculate_content_widths();

        let cached = text_layout.content_widths();

        assert_eq!(cached.min, expected.min);
        assert_eq!(cached.max, expected.max);
        assert!(cached.min > 0.0);
        assert!(cached.max > cached.min);
    }

    #[test]
    fn text_only_layout_reuses_the_cached_widths() {
        let mut text_layout = build_layout("the quick brown fox", None);
        text_layout.content_widths();

        // Poison the stored result. A second call that recomputed would overwrite this with
        // the real widths, so seeing the poisoned value back proves the cache was hit.
        let poison = ContentWidths {
            min: -1.0,
            max: -2.0,
        };
        text_layout.content_widths.as_mut().unwrap().widths = poison;

        let second = text_layout.content_widths();
        assert_eq!(second.min, poison.min);
        assert_eq!(second.max, poison.max);
    }

    #[test]
    fn a_changed_inline_box_width_forces_a_recompute() {
        let mut text_layout = build_layout("the quick brown fox", Some(40.0));
        let first = text_layout.content_widths();

        // Same poison as above, so a stale hit would be visible.
        text_layout.content_widths.as_mut().unwrap().widths = ContentWidths {
            min: -1.0,
            max: -2.0,
        };

        // Re-measuring the inline box under a different constraint is exactly what block
        // layout does between a min-content and a max-content pass.
        text_layout.layout.inline_boxes_mut()[0].width = 400.0;

        let second = text_layout.content_widths();
        assert!(second.min > 0.0);
        assert!(second.max > first.max);
        assert_eq!(second.min, 400.0);
    }

    #[test]
    fn an_unchanged_inline_box_width_still_hits_the_cache() {
        let mut text_layout = build_layout("the quick brown fox", Some(40.0));
        text_layout.content_widths();

        let poison = ContentWidths {
            min: -1.0,
            max: -2.0,
        };
        text_layout.content_widths.as_mut().unwrap().widths = poison;
        // Write the identical width back; the key is unchanged so this must not recompute.
        text_layout.layout.inline_boxes_mut()[0].width = 40.0;

        let second = text_layout.content_widths();
        assert_eq!(second.min, poison.min);
        assert_eq!(second.max, poison.max);
    }

    #[test]
    fn rebuilding_the_layout_discards_the_cache() {
        let mut text_layout = build_layout("the quick brown fox", None);
        text_layout.content_widths();
        assert!(text_layout.content_widths.is_some());

        // Stand in for `build_inline_layout_into`, which clears the cache before re-shaping.
        text_layout.content_widths = None;
        let rebuilt = build_layout("a much much much longer run of text", None);
        text_layout.layout = rebuilt.layout;
        text_layout.text = rebuilt.text;

        let widths = text_layout.content_widths();
        let expected = text_layout.layout.calculate_content_widths();
        assert_eq!(widths.max, expected.max);
    }
}

#[cfg(test)]
mod shortcut_tests {
    use super::*;
    use blitz_traits::events::{BlitzKeyEvent, KeyState};
    use blitz_traits::shell::DummyShellProvider;
    use keyboard_types::Location;

    fn control_event(key: Key, code: Code) -> BlitzKeyEvent {
        BlitzKeyEvent {
            key,
            code,
            modifiers: Modifiers::CONTROL,
            location: Location::Standard,
            is_auto_repeating: false,
            is_composing: false,
            state: KeyState::Pressed,
            text: None,
        }
    }

    #[test]
    fn control_character_cut_uses_the_physical_key_code() {
        let event = control_event(Key::Character("\u{18}".into()), Code::KeyX);
        assert_eq!(clipboard_command(&event), Some(ClipboardCommand::Cut));
    }

    #[test]
    fn backspace_does_not_depend_on_an_apple_standard_keybinding() {
        let mut data = TextInputData::new(false);
        let mut font_ctx = FontContext::default();
        let mut layout_ctx = LayoutContext::new();
        data.set_text(&mut font_ctx, &mut layout_ctx, "typo");
        data.editor
            .driver(&mut font_ctx, &mut layout_ctx)
            .move_to_text_end();
        let event = BlitzKeyEvent {
            key: Key::Backspace,
            code: Code::Backspace,
            modifiers: Modifiers::empty(),
            location: Location::Standard,
            is_auto_repeating: false,
            is_composing: false,
            state: KeyState::Pressed,
            text: None,
        };

        assert!(matches!(
            data.apply_keypress_event(&mut font_ctx, &mut layout_ctx, &DummyShellProvider, event,),
            Some(GeneratedTextInputEvent::Input)
        ));
        assert_eq!(data.editor.raw_text(), "typ");
    }
}

/// Undo and redo, driven through the same entry point a keystroke takes.
///
/// Asserted end to end rather than against [`TextEditHistory`] directly: the
/// part that was missing was not a stack, it was a stack wired to the editor,
/// and a unit test of the stack alone would pass with nothing connected.
#[cfg(test)]
mod history_tests {
    use super::*;
    use blitz_traits::events::{BlitzKeyEvent, KeyState};
    use blitz_traits::shell::DummyShellProvider;
    use keyboard_types::Location;

    struct Input {
        data: TextInputData,
        font_ctx: FontContext,
        layout_ctx: LayoutContext<TextBrush>,
    }

    impl Input {
        fn new() -> Self {
            Self {
                data: TextInputData::new(true),
                font_ctx: FontContext::default(),
                layout_ctx: LayoutContext::new(),
            }
        }

        fn press(&mut self, key: Key, code: Code, modifiers: Modifiers) {
            let event = BlitzKeyEvent {
                key,
                code,
                modifiers,
                location: Location::Standard,
                is_auto_repeating: false,
                is_composing: false,
                state: KeyState::Pressed,
                text: None,
            };
            self.data.apply_keypress_event(
                &mut self.font_ctx,
                &mut self.layout_ctx,
                &DummyShellProvider,
                event,
            );
        }

        /// Type `text` one character at a time, as a keyboard would.
        fn type_text(&mut self, text: &str) {
            for ch in text.chars() {
                self.press(
                    Key::Character(ch.to_string()),
                    Code::Unidentified,
                    Modifiers::empty(),
                );
            }
        }

        fn undo(&mut self) {
            self.press(Key::Character("z".into()), Code::KeyZ, Modifiers::CONTROL);
        }

        fn redo(&mut self) {
            self.press(
                Key::Character("z".into()),
                Code::KeyZ,
                Modifiers::CONTROL | Modifiers::SHIFT,
            );
        }

        fn text(&self) -> &str {
            self.data.editor.raw_text()
        }
    }

    /// The bug itself: Cmd+Z reached no handler, so it did nothing.
    #[test]
    fn undo_restores_the_text_from_before_the_edit() {
        let mut input = Input::new();
        input.type_text("first");
        input.type_text(" second");

        input.undo();

        // "first " and not "first": the space closed the run, so the state the
        // next run began from is the one with the separator already typed. That
        // is where Chrome and Firefox land too — the boundary belongs to the
        // text that preceded it, not to the word being started.
        assert_eq!(
            input.text(),
            "first ",
            "undo should remove the most recent word",
        );
    }

    #[test]
    fn redo_reapplies_what_undo_removed() {
        let mut input = Input::new();
        input.type_text("first");
        input.type_text(" second");
        let full = input.text().to_string();

        input.undo();
        input.redo();

        assert_eq!(input.text(), full, "redo should restore the undone text");
    }

    /// One undo removes a word, not a keystroke.
    ///
    /// An undo per character is faithful to what happened and unusable, so a
    /// run of typing coalesces and the whitespace closes it.
    #[test]
    fn a_run_of_typing_undoes_as_one_word_rather_than_per_character() {
        let mut input = Input::new();
        input.type_text("hello world");

        input.undo();

        assert_eq!(
            input.text(),
            "hello ",
            "the burst should end at the space, not at the previous character",
        );
    }

    /// Undo has to be reachable more than once.
    #[test]
    fn repeated_undo_walks_back_through_the_history() {
        let mut input = Input::new();
        input.type_text("one two three");

        input.undo();
        assert_eq!(input.text(), "one two ");
        input.undo();
        assert_eq!(input.text(), "one ");
        input.undo();
        assert_eq!(input.text(), "");
    }

    /// Undo on an untouched input must not panic or invent a state.
    #[test]
    fn undo_with_nothing_to_undo_leaves_the_text_alone() {
        let mut input = Input::new();
        input.type_text("only");

        input.undo();
        input.undo();
        input.undo();

        assert_eq!(input.text(), "");
    }

    /// Typing after an undo drops the redo branch, as every editor does.
    #[test]
    fn a_fresh_edit_after_an_undo_clears_the_redo_stack() {
        let mut input = Input::new();
        input.type_text("first");
        input.type_text(" second");

        input.undo();
        assert_eq!(input.text(), "first ");
        input.type_text("third");
        input.redo();

        assert_eq!(
            input.text(),
            "first third",
            "redo must not resurrect a branch that was typed over",
        );
    }

    /// Ctrl+Y is the Windows redo and is accepted on every platform.
    #[test]
    fn control_y_also_redoes() {
        let mut input = Input::new();
        input.type_text("first");
        input.type_text(" second");
        let full = input.text().to_string();

        input.undo();
        input.press(Key::Character("y".into()), Code::KeyY, Modifiers::CONTROL);

        assert_eq!(input.text(), full);
    }

    /// The chord must not reach the buffer as text.
    ///
    /// `history_command` returns before any mutation, so undo cannot also
    /// insert a `z` — which is what an unhandled chord would have done.
    #[test]
    fn the_undo_chord_does_not_type_its_own_character() {
        let mut input = Input::new();
        input.type_text("text");

        input.undo();
        input.redo();

        assert!(
            !input.text().contains('z'),
            "the undo chord leaked into the buffer: {:?}",
            input.text(),
        );
    }

    /// Undo restores the caret, not just the string.
    #[test]
    fn undo_restores_the_selection_along_with_the_text() {
        let mut input = Input::new();
        input.type_text("alpha");
        input.type_text(" beta");

        input.undo();

        let selection = input.data.editor.raw_selection();
        assert_eq!(
            selection.focus().index(),
            input.text().len(),
            "the caret should return to the end of the restored text",
        );
    }

    /// The stack is bounded, so a long-lived input cannot grow without limit.
    #[test]
    fn the_history_is_capped_at_the_maximum_depth() {
        let mut history = TextEditHistory::default();
        for i in 0..(MAX_UNDO_DEPTH + 50) {
            history.record(TextEditSnapshot {
                text: format!("state {i}"),
                anchor: 0,
                focus: 0,
            });
        }

        assert!(
            history.undo.len() <= MAX_UNDO_DEPTH,
            "history grew to {} entries, past the {MAX_UNDO_DEPTH} cap",
            history.undo.len(),
        );
    }
}

/// Undo and redo under either action modifier.
///
/// macOS users can rebind the standard editing commands system-wide through
/// `NSUserKeyEquivalents`, and a machine that maps Copy to Ctrl+C rather than
/// Cmd+C is not exotic. Both modifiers are accepted for the same reason the
/// clipboard accepts both: dropping one means the chord silently does nothing.
#[cfg(test)]
mod history_chord_tests {
    use super::*;
    use blitz_traits::events::{BlitzKeyEvent, KeyState};
    use keyboard_types::Location;

    fn event(key: Key, code: Code, modifiers: Modifiers) -> BlitzKeyEvent {
        BlitzKeyEvent {
            key,
            code,
            modifiers,
            location: Location::Standard,
            is_auto_repeating: false,
            is_composing: false,
            state: KeyState::Pressed,
            text: None,
        }
    }

    #[test]
    fn undo_is_recognised_under_control_and_under_the_platform_modifier() {
        for modifiers in [Modifiers::CONTROL, ACTION_MOD] {
            assert_eq!(
                history_command(&event(Key::Character("z".into()), Code::KeyZ, modifiers)),
                Some(HistoryCommand::Undo),
            );
        }
    }

    #[test]
    fn shift_z_redoes_under_either_modifier() {
        for modifiers in [Modifiers::CONTROL, ACTION_MOD] {
            assert_eq!(
                history_command(&event(
                    Key::Character("z".into()),
                    Code::KeyZ,
                    modifiers | Modifiers::SHIFT,
                )),
                Some(HistoryCommand::Redo),
            );
        }
    }

    /// A remapped layout still undoes, because the physical key is checked.
    #[test]
    fn a_remapped_character_still_undoes_by_its_physical_key() {
        assert_eq!(
            history_command(&event(
                Key::Character("w".into()),
                Code::KeyZ,
                Modifiers::CONTROL,
            )),
            Some(HistoryCommand::Undo),
        );
    }

    #[test]
    fn the_chord_needs_a_modifier() {
        assert_eq!(
            history_command(&event(
                Key::Character("z".into()),
                Code::KeyZ,
                Modifiers::empty(),
            )),
            None,
        );
    }
}