smudge-text 0.2.0

Font loading and parley-backed text layout for the Smudge GUI library
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
//! Text input editing, through the headless harness and the editor directly.
//!
//! The harness tests cover what a user does: typing, deleting, selecting,
//! composing with an input method, and copying, cutting and pasting, plus
//! the pixels a blink damages. A property test drives random keys and
//! outside writes against an editor that applies the same edits directly.
//! The editor-level tests cover the caret in right-to-left text, which is
//! only meaningful in parley's own geometry.

use std::time::Duration;

use proptest::prelude::*;

use smudge_core::clipboard::{Clipboard, MemoryClipboard};
use smudge_core::geometry::{Color, PixelRect, Point, Rect};
use smudge_core::input::{InputEvent, Key, Modifiers};
use smudge_core::paint::{DisplayItem, PaintOp};
use smudge_core::reactive::RwSignal;
use smudge_core::reactive::prelude::*;
use smudge_core::style::px;
use smudge_core::theme::{ColorToken, Theme};
use smudge_core::widget::panel;
use smudge_test::Harness;
use smudge_text::{Editor, TextInputExt, TextStyle, text_input};

/// How long the caret stays visible or hidden in one blink, the same period
/// the input uses.
const BLINK: Duration = Duration::from_millis(530);

/// The viewport of a plain input harness, in logical pixels.
const VIEWPORT: (f32, f32) = (200.0, 60.0);

/// Mounts an input bound to a fresh signal, and returns the harness and the
/// signal.
fn mounted(initial: &str) -> (Harness, RwSignal<String>) {
    let value = RwSignal::new(String::from(initial));
    let bound = value.clone();
    let mut harness = Harness::new(VIEWPORT.0, VIEWPORT.1, 1.0, move || {
        text_input(bound.clone())
            .width(px(VIEWPORT.0))
            .height(px(VIEWPORT.1))
    });
    harness.frame();
    (harness, value)
}

/// Clicks in the middle of the input, which focuses it, and settles.
fn focus(harness: &mut Harness) {
    harness.click(Point {
        x: 60.0,
        y: VIEWPORT.1 / 2.0,
    });
    harness.settle();
}

#[test]
fn typing_then_backspace_leaves_the_rest_of_the_text() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("héllo");
    assert_eq!(value.get(), "héllo", "the signal carries every typed rune");

    harness.press_key(Key::Backspace);
    assert_eq!(value.get(), "héll", "backspace removes one grapheme");
}

#[test]
fn control_backspace_deletes_the_word_before_the_caret() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("hello world");
    let modifiers = Modifiers {
        control: true,
        ..Modifiers::default()
    };
    harness.press_key_with(Key::Backspace, modifiers);
    assert_eq!(value.get(), "hello ", "the word goes, the space stays");
}

#[test]
fn shift_home_selects_to_the_start_and_typing_replaces_the_selection() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("hello world");
    harness.press_key_with(
        Key::Home,
        Modifiers {
            shift: true,
            ..Modifiers::default()
        },
    );
    harness.type_text("X");
    assert_eq!(value.get(), "X", "the selection is gone, replaced by X");
}

#[test]
fn command_a_selects_all_and_typing_replaces() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("keep one");
    harness.press_key_with(Key::Character(String::from("a")), command());
    harness.type_text("X");
    assert_eq!(value.get(), "X");
}

#[test]
fn undo_removes_typed_text_a_word_at_a_time_and_redo_brings_it_back() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);
    let z = || Key::Character(String::from("z"));
    let redo = Modifiers {
        shift: true,
        ..command()
    };

    harness.type_text("hello world");
    harness.press_key_with(z(), command());
    assert_eq!(value.get(), "hello", "the last word goes first");
    harness.press_key_with(z(), command());
    assert_eq!(value.get(), "");
    harness.press_key_with(z(), command());
    assert_eq!(value.get(), "", "undo past the first step does nothing");

    harness.press_key_with(z(), redo);
    assert_eq!(value.get(), "hello");
    harness.press_key_with(z(), redo);
    assert_eq!(value.get(), "hello world");

    harness.press_key_with(z(), command());
    harness.type_text("!");
    harness.press_key_with(z(), redo);
    assert_eq!(value.get(), "hello!", "an edit after an undo ends redo");
}

#[test]
fn a_word_delete_is_an_undo_step_of_its_own() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);
    let z = || Key::Character(String::from("z"));

    harness.type_text("hello world");
    harness.press_key_with(
        Key::Backspace,
        Modifiers {
            control: true,
            ..Modifiers::default()
        },
    );
    harness.press_key(Key::Backspace);
    assert_eq!(value.get(), "hello");
    harness.press_key_with(z(), command());
    assert_eq!(value.get(), "hello ", "the grapheme delete undoes alone");
    harness.press_key_with(z(), command());
    assert_eq!(value.get(), "hello world", "then the word delete");
}

#[test]
fn committed_text_is_an_undo_step_of_its_own() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.event(InputEvent::ImeCommit {
        text: String::from("世界"),
    });
    harness.type_text("x");
    harness.press_key_with(Key::Character(String::from("z")), command());
    assert_eq!(value.get(), "世界", "the typed character undoes alone");
}

#[test]
fn undo_puts_the_selection_back() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("hello");
    harness.press_key_with(Key::Character(String::from("a")), command());
    harness.type_text("X");
    harness.press_key_with(Key::Character(String::from("z")), command());
    assert_eq!(value.get(), "hello");
    harness.type_text("Y");
    assert_eq!(value.get(), "Y", "the whole text was selected again");
}

#[test]
fn an_outside_write_ends_the_undo_history() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("draft");
    value.set(String::from("saved"));
    harness.settle();
    harness.press_key_with(Key::Character(String::from("z")), command());
    assert_eq!(value.get(), "saved", "undo never brings back replaced text");
}

#[cfg(not(target_os = "macos"))]
#[test]
fn control_y_redoes() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("word");
    harness.press_key_with(Key::Character(String::from("z")), command());
    harness.press_key_with(Key::Character(String::from("y")), command());
    assert_eq!(value.get(), "word");
}

/// Returns the modifiers of the platform's command key.
fn command() -> Modifiers {
    #[cfg(target_os = "macos")]
    {
        Modifiers {
            meta: true,
            ..Modifiers::default()
        }
    }
    #[cfg(not(target_os = "macos"))]
    {
        Modifiers {
            control: true,
            ..Modifiers::default()
        }
    }
}

#[test]
fn enter_and_tab_do_not_edit_and_tab_wraps_to_the_input() {
    let (mut harness, value) = mounted("text");
    focus(&mut harness);

    harness.press_key(Key::Enter);
    assert_eq!(value.get(), "text", "Enter inserts nothing");

    harness.press_key(Key::Tab);
    assert_eq!(value.get(), "text", "Tab inserts nothing");
    assert!(
        harness.app().focused().is_some(),
        "Tab wraps to the input itself when it is the only focusable node"
    );
}

#[test]
fn an_ime_commit_inserts_without_a_key_event() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.event(InputEvent::ImeCommit {
        text: String::from("世界"),
    });
    assert_eq!(value.get(), "世界", "the committed text is in the signal");
}

/// A fill the height of an underline but wider than a caret, which is what
/// a composing preedit paints beneath its text.
fn is_underline(rect: &Rect) -> bool {
    rect.height() <= 2.0 && rect.width() > 4.0
}

/// Commits `text` in the order the platform sends a commit: an empty
/// preedit clears the composition first, then the commit arrives.
fn ime_commit(harness: &mut Harness, text: &str) {
    harness.event(InputEvent::ImePreedit {
        text: String::new(),
        cursor: None,
    });
    harness.event(InputEvent::ImeCommit {
        text: String::from(text),
    });
}

#[test]
fn a_preedit_draws_underlined_text_and_never_touches_the_signal() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.event(InputEvent::ImePreedit {
        text: String::from("こんに"),
        cursor: Some((9, 9)),
    });
    harness.settle();

    let (fills, runs) = painted(&mut harness);
    assert!(
        !runs.is_empty(),
        "the composing text is drawn before it is committed"
    );
    assert!(
        fills.iter().any(is_underline),
        "the composing text is underlined: {fills:?}"
    );
    assert_eq!(
        value.get(),
        "",
        "the preedit is not committed text, so the signal waits"
    );

    ime_commit(&mut harness, "今日は");
    harness.settle();

    assert_eq!(value.get(), "今日は", "the commit writes the signal");
    let (fills, _) = painted(&mut harness);
    assert!(
        !fills.iter().any(is_underline),
        "the underline goes once the text is committed: {fills:?}"
    );
}

#[test]
fn a_commit_while_composing_takes_the_preedit_place() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.event(InputEvent::ImePreedit {
        text: String::from("こんにちは"),
        cursor: Some((15, 15)),
    });
    harness.event(InputEvent::ImeCommit {
        text: String::from("今日は"),
    });
    harness.settle();

    assert_eq!(
        value.get(),
        "今日は",
        "the committed text replaced the preedit, it did not follow it"
    );
    harness.type_text("x");
    harness.settle();
    assert_eq!(
        value.get(),
        "今日はx",
        "the caret sits after the committed text"
    );
}

#[test]
fn a_canceled_preedit_leaves_the_text_as_it_was() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);
    harness.type_text("ab");

    harness.event(InputEvent::ImePreedit {
        text: String::from("かんじ"),
        cursor: Some((9, 9)),
    });
    harness.settle();
    harness.event(InputEvent::ImePreedit {
        text: String::new(),
        cursor: None,
    });
    harness.settle();

    assert_eq!(value.get(), "ab", "the cancel is not an edit of the value");
    harness.type_text("c");
    harness.settle();
    assert_eq!(
        value.get(),
        "abc",
        "the caret sits where the preedit was, and typing goes on"
    );
}

#[test]
fn composing_over_a_selection_replaces_it_like_typing() {
    let (mut harness, value) = mounted("hello world");
    focus(&mut harness);
    harness.press_key(Key::Home);
    let shift = Modifiers {
        shift: true,
        ..Modifiers::default()
    };
    for _ in 0..5 {
        harness.press_key_with(Key::ArrowRight, shift);
    }

    harness.event(InputEvent::ImePreedit {
        text: String::from("こん"),
        cursor: Some((6, 6)),
    });
    harness.settle();
    assert_eq!(
        value.get(),
        " world",
        "the composition takes the selection's place as soon as it starts"
    );

    ime_commit(&mut harness, "今度");
    harness.settle();
    assert_eq!(
        value.get(),
        "今度 world",
        "the committed text stands where the selection was"
    );

    harness.press_key_with(Key::Character(String::from("z")), command());
    assert_eq!(value.get(), " world", "undo removes the commit");
    harness.press_key_with(Key::Character(String::from("z")), command());
    assert_eq!(
        value.get(),
        "hello world",
        "a second undo brings the selection back"
    );
}

#[test]
fn a_paste_while_composing_ends_the_composition() {
    let (mut harness, value, mut clipboard) = mounted_with_clipboard("");
    focus(&mut harness);

    // The input method puts a preedit of two multi-byte characters in and
    // places the caret inside it.
    harness.event(InputEvent::ImePreedit {
        text: String::from("ãé"),
        cursor: Some((4, 1)),
    });
    harness.settle();

    // Pasting over the selected tail of the preedit, with as many bytes as
    // it replaces, would leave a range shifted by bytes ending inside the
    // pasted character if the composition outlived the paste.
    clipboard.set(String::from("xé"));
    harness.press_key_with(Key::Character(String::from("v")), command());
    harness.settle();
    assert_eq!(
        value.get(),
        "xé",
        "the paste drops the preedit and inserts at its start"
    );

    harness.event(InputEvent::ImeCommit {
        text: String::from("あ"),
    });
    harness.settle();
    assert_eq!(
        value.get(),
        "xéあ",
        "the paste cancelled the composition, so the commit lands at the caret"
    );
}

#[test]
fn losing_the_focus_cancels_the_composition() {
    let value = RwSignal::new(String::new());
    let bound = value.clone();
    let mut harness = Harness::new(VIEWPORT.0, VIEWPORT.1, 1.0, move || {
        panel()
            .column()
            .child(
                text_input(bound.clone())
                    .width(px(VIEWPORT.0))
                    .height(px(30.0)),
            )
            .child(panel().width(px(40.0)).height(px(20.0)).focusable())
    });
    harness.frame();
    let input = Point { x: 60.0, y: 15.0 };
    let other = Point { x: 20.0, y: 45.0 };
    harness.click(input);
    harness.settle();
    harness.type_text("ab");

    harness.event(InputEvent::ImePreedit {
        text: String::from("かんじ"),
        cursor: Some((9, 9)),
    });
    harness.settle();
    let (fills, _) = painted(&mut harness);
    assert!(
        fills.iter().any(is_underline),
        "the composition is showing: {fills:?}"
    );

    harness.click(other);
    harness.settle();
    let (fills, _) = painted(&mut harness);
    assert!(
        !fills.iter().any(is_underline),
        "the preedit goes with the focus: {fills:?}"
    );
    assert_eq!(
        value.get(),
        "ab",
        "a composition that dies with the focus commits nothing"
    );

    // Real clicks take longer than the double click window, which the
    // virtual clock of the harness only crosses when the test advances it.
    harness.advance(Duration::from_secs(1));
    harness.click(input);
    harness.settle();
    harness.type_text("c");
    harness.settle();
    assert_eq!(
        value.get(),
        "abc",
        "typing after the lost composition edits the field, not a stale \
         preedit"
    );
}

/// Mounts an input bound to a fresh signal with a memory clipboard
/// installed, and returns the harness, the signal and a shared handle on
/// the clipboard.
fn mounted_with_clipboard(initial: &str) -> (Harness, RwSignal<String>, MemoryClipboard) {
    let (mut harness, value) = mounted(initial);
    let clipboard = MemoryClipboard::default();
    harness.app().set_clipboard(Box::new(clipboard.clone()));
    (harness, value, clipboard)
}

#[test]
fn copy_then_paste_duplicates_the_selection() {
    let (mut harness, value, mut clipboard) = mounted_with_clipboard("");
    focus(&mut harness);

    harness.type_text("hello world");
    harness.press_key_with(Key::Character(String::from("a")), command());
    harness.press_key_with(Key::Character(String::from("c")), command());
    assert_eq!(
        clipboard.get().as_deref(),
        Some("hello world"),
        "copy puts the selected text on the clipboard"
    );

    harness.press_key(Key::ArrowRight);
    harness.press_key_with(Key::Character(String::from("v")), command());
    assert_eq!(
        value.get(),
        "hello worldhello world",
        "paste inserts the copied text at the caret"
    );
}

#[test]
fn cut_moves_the_selection_to_the_clipboard() {
    let (mut harness, value, mut clipboard) = mounted_with_clipboard("");
    focus(&mut harness);

    harness.type_text("hello world");
    harness.press_key_with(Key::Character(String::from("a")), command());
    harness.press_key_with(Key::Character(String::from("x")), command());
    assert_eq!(value.get(), "", "cut removes the selected text");
    assert_eq!(
        clipboard.get().as_deref(),
        Some("hello world"),
        "cut puts the selected text on the clipboard"
    );

    harness.press_key_with(Key::Character(String::from("v")), command());
    assert_eq!(value.get(), "hello world", "paste brings it back");
}

#[test]
fn a_paste_flattens_line_breaks_into_spaces() {
    let (mut harness, value, mut clipboard) = mounted_with_clipboard("");
    focus(&mut harness);

    clipboard.set(String::from("one\ntwo\r\nthree"));
    harness.press_key_with(Key::Character(String::from("v")), command());
    assert_eq!(
        value.get(),
        "one two three",
        "a single line takes a multi-line paste as spaces, a CRLF pair as one"
    );

    clipboard.set(String::from("\r\nx\ry\nz"));
    harness.press_key_with(Key::Character(String::from("v")), command());
    assert_eq!(
        value.get(),
        "one two three x y z",
        "every kind of line break becomes exactly one space"
    );

    clipboard.set(String::from("\r\n\r"));
    harness.press_key_with(Key::Character(String::from("v")), command());
    assert_eq!(
        value.get(),
        "one two three x y z  ",
        "a paste of nothing but line breaks becomes spaces"
    );
}

#[test]
fn a_paste_flattens_every_mandatory_break_into_one_space() {
    let (mut harness, value, mut clipboard) = mounted_with_clipboard("");
    focus(&mut harness);

    clipboard.set(String::from("a\u{0B}b\u{0C}c\u{85}d\u{2028}e\u{2029}f"));
    harness.press_key_with(Key::Character(String::from("v")), command());
    assert_eq!(
        value.get(),
        "a b c d e f",
        "vertical tab, form feed, next line and the line and paragraph separators become spaces"
    );
}

#[test]
fn a_paste_is_an_undo_step_of_its_own() {
    let (mut harness, value, mut clipboard) = mounted_with_clipboard("");
    focus(&mut harness);

    harness.type_text("ab");
    clipboard.set(String::from("c"));
    harness.press_key_with(Key::Character(String::from("v")), command());
    assert_eq!(value.get(), "abc");

    harness.press_key_with(Key::Character(String::from("z")), command());
    assert_eq!(
        value.get(),
        "ab",
        "undo takes back the paste and not the word typed before it"
    );
}

#[test]
fn without_a_clipboard_the_clipboard_keys_do_nothing() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("kept");
    harness.press_key_with(Key::Character(String::from("a")), command());
    harness.press_key_with(Key::Character(String::from("x")), command());
    harness.press_key_with(Key::Character(String::from("v")), command());
    assert_eq!(
        value.get(),
        "kept",
        "cut and paste without a clipboard change nothing and do not panic"
    );
}

#[test]
fn a_press_at_the_edges_places_the_caret_at_the_matching_end() {
    let (mut harness, value) = mounted("abcdef");
    harness.settle();

    harness.click(Point {
        x: 2.0,
        y: VIEWPORT.1 / 2.0,
    });
    harness.settle();
    harness.type_text("X");
    assert_eq!(
        value.get(),
        "Xabcdef",
        "a press near the left edge puts the caret at the start"
    );

    value.set(String::from("abcdef"));
    harness.settle();

    harness.click(Point {
        x: VIEWPORT.0 - 2.0,
        y: VIEWPORT.1 / 2.0,
    });
    harness.settle();
    harness.type_text("X");
    assert_eq!(
        value.get(),
        "abcdefX",
        "a press near the right edge puts the caret at the end"
    );
}

#[test]
fn a_drag_selects_and_typing_replaces_the_selection() {
    let (mut harness, value) = mounted("abcdef");
    focus(&mut harness);

    harness.button_down(Point {
        x: 2.0,
        y: VIEWPORT.1 / 2.0,
    });
    harness.move_to(Point {
        x: VIEWPORT.0 - 2.0,
        y: VIEWPORT.1 / 2.0,
    });
    harness.button_up(Point {
        x: VIEWPORT.0 - 2.0,
        y: VIEWPORT.1 / 2.0,
    });
    harness.type_text("X");
    assert_eq!(value.get(), "X", "the drag selected everything");
}

#[test]
fn a_double_click_selects_a_word() {
    let (mut harness, value) = mounted("foo bar");
    focus(&mut harness);

    // Both clicks land inside "bar", which ends the text and so owns the
    // right side of the field.
    let point = Point {
        x: VIEWPORT.0 - 10.0,
        y: VIEWPORT.1 / 2.0,
    };
    harness.click(point);
    harness.click(point);
    harness.type_text("X");
    assert_eq!(
        value.get(),
        "foo X",
        "the double click selected the word under the pointer"
    );
}

#[test]
fn clicks_too_far_apart_in_time_or_space_are_not_a_double_click() {
    let (mut harness, value) = mounted("foo bar");
    focus(&mut harness);
    let end = Point {
        x: VIEWPORT.0 - 10.0,
        y: VIEWPORT.1 / 2.0,
    };

    harness.click(end);
    harness.advance(Duration::from_millis(401));
    harness.click(end);
    harness.type_text("X");
    assert_eq!(value.get(), "foo barX", "401 ms apart is two single clicks");

    harness.advance(Duration::from_secs(1));
    harness.click(end);
    harness.click(Point {
        x: end.x - 5.0,
        ..end
    });
    harness.type_text("Y");
    assert_eq!(value.get(), "foo barXY", "5 px apart is two single clicks");
}

#[test]
fn a_click_right_after_a_drag_places_the_caret() {
    let (mut harness, value) = mounted("foo bar");
    focus(&mut harness);
    let start = Point {
        x: 2.0,
        y: VIEWPORT.1 / 2.0,
    };

    harness.advance(Duration::from_secs(1));
    harness.button_down(start);
    harness.move_to(Point {
        x: VIEWPORT.0 - 2.0,
        ..start
    });
    harness.button_up(Point {
        x: VIEWPORT.0 - 2.0,
        ..start
    });
    harness.click(start);
    harness.type_text("X");
    assert_eq!(
        value.get(),
        "Xfoo bar",
        "the click after a drag is a single click, not a double click on \
         the drag's start"
    );
}

#[test]
fn a_blink_frame_damages_only_the_caret() {
    let (mut harness, _value) = mounted("");
    focus(&mut harness);
    harness.type_text("hi");
    harness.settle();

    // Everything has settled: a frame with a steady caret repaints nothing.
    let steady = harness.frame();
    assert!(
        steady.damage.is_empty() && steady.nodes_painted == 0,
        "the caret does not move on its own: {steady:?}"
    );

    // One blink later, only the caret node repaints.
    let blink = harness.advance(BLINK);
    assert_eq!(blink.nodes_painted, 1, "only the caret node repaints");
    assert_eq!(blink.damage.len(), 1, "the blink damages one rectangle");
    let caret = blink.damage[0];
    assert!(
        caret.width <= 4,
        "the caret is a pixel wide, not the whole input: {caret:?}"
    );
    assert!(caret.height <= 34, "the caret is one line tall: {caret:?}");
    harness.assert_matches_full_repaint();

    // And the next blink damages the same small area bringing it back.
    let back = harness.advance(BLINK);
    assert_eq!(back.nodes_painted, 1);
    assert_eq!(back.damage.len(), 1);
    assert!(back.damage[0].width <= 4 && back.damage[0].height <= 34);
}

#[test]
fn an_editing_frame_repaints_the_text_and_the_blink_stays_small() {
    let (mut harness, _value) = mounted("");
    focus(&mut harness);

    harness.type_text("a");
    let report = harness.frame();
    assert!(
        !report.damage.is_empty(),
        "typing repaints the text the frame the key arrives"
    );
    harness.assert_matches_full_repaint();

    harness.settle();
    let steady = harness.frame();
    assert!(steady.damage.is_empty() && steady.nodes_painted == 0);
    let blink = harness.advance(BLINK);
    assert_eq!(blink.nodes_painted, 1, "the blink repaints the caret alone");
    assert!(blink.damage.iter().all(is_small_caret));
}

#[test]
fn scrolling_keeps_the_caret_inside_the_input() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    let long = "0123456789".repeat(6);
    harness.type_text(&long);
    harness.settle();
    assert_eq!(value.get(), long);

    // The caret sits past the right edge of the text, which is wider than
    // the input, so the input has to scroll for the blink to stay visible.
    let blink = harness.advance(BLINK);
    assert_eq!(
        blink.damage.len(),
        1,
        "the blink still damages one rectangle"
    );
    let caret = blink.damage[0];
    assert!(is_small_caret(&caret));
    assert!(
        caret.x + caret.width <= VIEWPORT.0 as u32,
        "the caret stays inside the input while the text scrolls: {caret:?}"
    );
}

#[test]
fn trailing_spaces_keep_the_caret_inside_the_input() {
    let (mut harness, _value) = mounted("");
    focus(&mut harness);
    harness.type_text(&"0123456789".repeat(4));
    harness.type_text(&" ".repeat(12));
    harness.settle();

    let (fills, _) = painted(&mut harness);
    let caret = fills.last().expect("the focused input paints its caret");
    assert!(
        caret.x1 <= VIEWPORT.0 && caret.x0 > VIEWPORT.0 - 4.0,
        "spaces past the text's ink still scroll the caret to the right \
         edge: {caret:?}"
    );
}

/// A rectangle small enough to be a caret and nothing else.
fn is_small_caret(rect: &PixelRect) -> bool {
    rect.width <= 4 && rect.height <= 34
}

#[test]
fn the_placeholder_shows_while_the_text_is_empty() {
    let value = RwSignal::new(String::new());
    let mut harness = Harness::new(VIEWPORT.0, VIEWPORT.1, 1.0, move || {
        text_input(value.clone())
            .width(px(VIEWPORT.0))
            .height(px(VIEWPORT.1))
            .placeholder("Type here")
    });
    harness.frame();
    harness.settle();
    harness.assert_matches_full_repaint();

    harness.type_text("hi");
    harness.settle();
    assert!(
        !harness.png().is_empty(),
        "the input renders with and without its placeholder"
    );
}

#[test]
fn editing_right_to_left_text_edits_the_signal() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.type_text("سلام");
    assert_eq!(value.get(), "سلام");
    harness.press_key(Key::Backspace);
    let remaining = value.get();
    assert_eq!(
        remaining.chars().count(),
        3,
        "backspace removes one grapheme"
    );
    assert!(remaining.chars().eq("سلام".chars().take(3)));
}

#[test]
fn the_caret_moves_visually_in_right_to_left_text_as_parley_reports() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());
    editor.set_text("سلام");
    let caret_width = 1.0;

    // The caret starts at the end of the text, which in a right-to-left run
    // is its visual left edge.
    let end = editor
        .cursor_geometry(caret_width)
        .expect("the editor has a caret");

    editor.move_right();
    let after_right = editor
        .cursor_geometry(caret_width)
        .expect("the caret is still there");
    assert!(
        after_right.x0 > end.x0,
        "moving right moves the caret visually right, even though it is \
         moving towards the logical start: {} -> {}",
        end.x0,
        after_right.x0
    );

    editor.move_left();
    editor.move_left();
    let after_left = editor
        .cursor_geometry(caret_width)
        .expect("the caret is still there");
    assert!(
        after_left.x0 < after_right.x0,
        "moving left moves the caret visually left: {} -> {}",
        after_right.x0,
        after_left.x0
    );
    assert!(
        (after_left.x0 - end.x0).abs() < 1.0,
        "the caret lands on the boundaries parley reported before: {} vs {}",
        after_left.x0,
        end.x0
    );
}

#[test]
fn an_empty_commit_removes_the_preedit_and_keeps_the_selection() {
    let value = RwSignal::new(String::from("abc"));
    let editor = Editor::new(value.clone());
    editor.set_style(&TextStyle::default());
    editor.set_text("abc");
    editor.select_all();

    editor.commit("");
    assert_eq!(value.get(), "abc", "committing nothing deletes nothing");
    assert_eq!(editor.selection(), 0..3, "the selection stays");

    editor.compose("か", None);
    editor.commit("");
    assert!(!editor.is_composing(), "the preedit is gone");
    assert_eq!(
        value.get(),
        "",
        "the composition took the selection's place"
    );
}

#[test]
fn an_outside_write_replaces_the_text_and_moves_the_caret_to_the_end() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value.clone());
    editor.set_style(&TextStyle::default());

    value.set(String::from("héllo"));
    editor.set_text(&value.get());
    editor.insert("!");
    assert_eq!(
        editor.text(),
        "héllo!",
        "the caret sits at the end after an outside write"
    );

    editor.set_text("short");
    assert_eq!(editor.selection(), 5..5, "the caret is at the new end");
}

#[test]
fn deleting_a_line_break_cuts_its_paragraphs_into_one() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());
    editor.set_text("ab\n");

    editor.move_to_start();
    editor.move_right();
    editor.move_right();
    editor.delete();
    assert_eq!(editor.text(), "ab", "the delete took the line break");

    // The paragraph the break ended is one with the empty one that
    // followed, so another delete finds no break past the caret.
    editor.delete();
    assert_eq!(editor.text(), "ab", "nothing is left after the caret");

    editor.move_down();
    editor.insert("X");
    assert_eq!(
        editor.text(),
        "abX",
        "the caret stays at the end of the one paragraph"
    );
}

#[test]
fn a_word_delete_at_a_paragraph_end_takes_the_break_and_the_next_word() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());
    editor.set_text("\nab cd");

    editor.move_to_start();
    editor.delete_word();
    assert_eq!(
        editor.text(),
        "cd",
        "the delete reached from the empty first paragraph across \
         the break and through the word and its trailing space"
    );
}

#[test]
fn a_word_backspace_at_a_paragraph_start_reaches_the_previous_word() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());
    editor.set_text("ab\ncd");

    editor.move_to_start();
    editor.move_right();
    editor.move_right();
    editor.move_right();
    editor.backspace_word();
    assert_eq!(
        editor.text(),
        "cd",
        "the backspace reached from the start of the second line \
         back through the word on the first"
    );
}

#[test]
fn a_preedit_update_that_shrinks_keeps_the_paragraphs_in_bounds() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());

    editor.compose("あいう", None);
    editor.compose("あ", None);
    editor.move_down();
    assert_eq!(
        editor.raw_text(),
        "あ",
        "the paragraphs the smaller preedit left still reach the text"
    );
}

#[test]
fn a_backspace_after_an_emoji_takes_the_emoji_and_not_the_line_break() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());
    editor.set_text("ab\u{1F600}\ncd");

    editor.move_to_start();
    editor.move_right();
    editor.move_right();
    editor.move_right();
    editor.backspace();
    assert_eq!(
        editor.text(),
        "ab\ncd",
        "the emoji goes whole, the break after it stays"
    );
}

#[test]
fn a_backspace_over_a_carriage_return_takes_the_whole_break() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());
    editor.set_text("ab\r\ncd");

    editor.move_to_start();
    editor.move_right();
    editor.move_right();
    editor.move_right();
    editor.backspace();
    assert_eq!(
        editor.text(),
        "abcd",
        "the carriage return and the line break it starts go together"
    );
}

#[test]
fn a_preedit_of_only_a_line_break_anchors_the_ime_area() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());

    editor.compose("\n", None);
    let area = editor.ime_area();
    assert!(
        area.y1 > area.y0 && area.x1 >= area.x0,
        "the area falls back to the caret when the preedit holds no glyphs"
    );
}

#[test]
fn a_preedit_cursor_inside_a_character_snaps_to_a_boundary() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());

    editor.compose("あいう", Some((5, 2)));
    let raw = editor.raw_text();
    assert_eq!(
        editor.selection(),
        0..3,
        "the preedit cursor snapped back to the boundaries of the \
         characters it was inside, of {raw:?}"
    );
}

#[test]
fn an_insert_of_several_lines_leaves_the_caret_on_the_last_line() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());
    editor.insert("one\ntwo");

    let line = TextStyle::default().size * TextStyle::default().line_height;
    let caret = editor.cursor_geometry(1.0).expect("the editor has a caret");
    assert!(
        caret.y0 >= line - 1.0,
        "the caret sits on the second line, not the first: {caret:?}"
    );
}

/// Returns the rectangles and glyph runs of the current display list.
///
/// The frame that builds the list changes nothing when the harness has
/// settled, so the list is the one the last real frame painted.
fn painted(harness: &mut Harness) -> (Vec<Rect>, Vec<Color>) {
    let output = harness.app().frame();
    let mut fills = Vec::new();
    let mut glyph_colors = Vec::new();
    for item in output.list.items() {
        match item {
            DisplayItem::Op(PaintOp::FillRect { rect, .. }) => fills.push(*rect),
            DisplayItem::Op(PaintOp::Glyphs(run)) => glyph_colors.push(run.color),
            _ => {}
        }
    }
    (fills, glyph_colors)
}

#[test]
fn an_edit_moves_the_caret_in_the_frame_that_shows_the_text() {
    let (mut harness, _value) = mounted("");
    focus(&mut harness);

    harness.type_text("ab");
    harness.frame();
    assert!(
        !harness.woken(),
        "placing the caret in the apply step asks for no second frame"
    );
    let next = harness.frame();
    assert!(
        next.nodes_painted == 0 && next.damage.is_empty(),
        "the frame that painted the text also placed the caret: {next:?}"
    );
}

#[test]
fn a_selection_in_scrolled_text_paints_over_its_glyphs() {
    let (mut harness, _value) = mounted("");
    focus(&mut harness);
    harness.type_text(&"0123456789".repeat(6));
    harness.settle();
    let shift = Modifiers {
        shift: true,
        ..Modifiers::default()
    };
    for _ in 0..3 {
        harness.press_key_with(Key::ArrowLeft, shift);
    }
    harness.settle();

    let (fills, _) = painted(&mut harness);
    let selection = fills
        .iter()
        .find(|rect| rect.width() > 4.0)
        .expect("three selected digits paint a selection");
    assert!(
        selection.x0 >= 0.0 && selection.x1 <= VIEWPORT.0,
        "the selection scrolls with the text it covers: {selection:?}"
    );
}

#[test]
fn an_outside_write_repaints_without_running_layout() {
    let (mut harness, value) = mounted("one");
    harness.settle();

    value.set(String::from("two"));
    let report = harness.frame();
    assert!(
        !report.layout_ran,
        "the input's size does not hang on its text"
    );
    assert!(report.nodes_painted > 0, "the new text is painted");
}

#[test]
fn the_placeholder_paints_in_the_muted_text_color() {
    let value = RwSignal::new(String::new());
    let mut harness = Harness::new(VIEWPORT.0, VIEWPORT.1, 1.0, move || {
        text_input(value.clone())
            .width(px(VIEWPORT.0))
            .height(px(VIEWPORT.1))
            .placeholder("Type here")
    });
    harness.settle();

    let (_, colors) = painted(&mut harness);
    let muted = Theme::light().color(ColorToken::TEXT_MUTED);
    assert!(!colors.is_empty(), "the placeholder paints");
    assert!(colors.iter().all(|color| *color == muted));
}

#[cfg(not(target_os = "macos"))]
#[test]
fn alt_gr_types_its_character_and_control_does_not() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    let alt_gr = Modifiers {
        control: true,
        alt: true,
        ..Modifiers::default()
    };
    harness.press_key_with(Key::Character(String::from("@")), alt_gr);
    let control = Modifiers {
        control: true,
        ..Modifiers::default()
    };
    harness.press_key_with(Key::Character(String::from("x")), control);
    harness.press_key_with(Key::Character(String::from("a")), alt_gr);
    assert_eq!(
        value.get(),
        "@a",
        "AltGr types even the letter Control selects everything with, and a \
         Control shortcut types nothing"
    );
}

#[test]
fn an_input_is_one_line_tall_without_a_height() {
    let value = RwSignal::new(String::new());
    let bound = value.clone();
    let mut harness = Harness::new(VIEWPORT.0, VIEWPORT.1, 1.0, move || {
        panel()
            .column()
            .child(text_input(bound.clone()).width(px(VIEWPORT.0)))
    });
    harness.frame();
    harness.settle();

    let line = TextStyle::default().size * TextStyle::default().line_height;
    let mut height = None;
    harness.app().visit_nodes(|_depth, type_name, rect| {
        if type_name.rsplit("::").next() == Some("TextInput") {
            height = Some(rect.height());
        }
    });
    let height = height.expect("the input lays out");
    assert!(
        (height - line).abs() < 0.5,
        "the input measures one line tall: {height} against {line}"
    );
}

#[test]
fn a_word_drag_to_the_left_leaves_the_caret_at_the_dragged_end() {
    let value = RwSignal::new(String::new());
    let editor = Editor::new(value);
    editor.set_style(&TextStyle::default());
    editor.set_text("alpha beta gamma");
    let width = editor.layout_size().width;

    editor.select_word_at_point(width - 4.0, 5.0);
    editor.extend_to_point(4.0, 5.0);
    assert_eq!(editor.selection(), 0..16, "the drag takes in every word");
    let caret = editor.cursor_geometry(1.0).expect("a caret");
    assert!(
        caret.x0 < 1.0,
        "the caret follows the pointer to the left end: {caret:?}"
    );

    editor.extend_right();
    assert_eq!(
        editor.selection(),
        1..16,
        "Shift and Right move the dragged end, not the double click's"
    );
}

#[test]
fn an_input_composing_a_line_break_keeps_its_first_line_in_view() {
    let value = RwSignal::new(String::new());
    let bound = value.clone();
    let mut harness = Harness::new(VIEWPORT.0, VIEWPORT.1, 1.0, move || {
        panel()
            .column()
            .child(text_input(bound.clone()).width(px(VIEWPORT.0)))
    });
    harness.frame();
    harness.click(Point { x: 60.0, y: 5.0 });
    harness.settle();

    harness.event(InputEvent::ImePreedit {
        text: String::from("one\ntwo"),
        cursor: Some((7, 7)),
    });
    harness.settle();

    let output = harness.app().frame();
    let mut top = f32::INFINITY;
    for item in output.list.items() {
        if let DisplayItem::Op(PaintOp::Glyphs(run)) = item {
            for glyph in &run.glyphs {
                top = top.min(glyph.y);
            }
        }
    }
    assert!(
        top > 0.0 && top < VIEWPORT.1,
        "the one-line input never scrolls up or down, so the first line's \
         baseline stays inside it: {top}"
    );
}

#[test]
fn an_input_method_commit_with_line_breaks_types_one_line() {
    let (mut harness, value) = mounted("");
    focus(&mut harness);

    harness.event(InputEvent::ImeCommit {
        text: String::from("one\ntwo\r\nthree"),
    });
    assert_eq!(value.get(), "one two three", "each break becomes a space");
}

#[test]
fn an_outside_write_with_line_breaks_shows_one_line() {
    let (mut harness, value) = mounted("");
    harness.settle();

    value.set(String::from("one\ntwo\u{2028}three"));
    harness.settle();
    assert_eq!(
        value.get(),
        "one two three",
        "the input writes the one line it kept back to the signal"
    );
}

/// One thing the property test does to an input.
#[derive(Clone, Debug)]
enum Op {
    /// Types a short string.
    Type(String),
    /// Presses a key, with Shift held when the flag is set.
    Key(Key, bool),
    /// Presses a key with Control held, and Shift when the flag is set.
    WordKey(Key, bool),
    /// Presses Alt and Backspace.
    AltBackspace,
    /// Selects everything with the command modifier.
    SelectAll,
    /// Writes the bound signal from outside.
    Write(String),
    /// Undoes with the command key.
    Undo,
    /// Redoes with the command key and Shift.
    Redo,
}

/// A short piece of text, mixed scripts and whitespace included.
fn any_text() -> impl Strategy<Value = String> {
    proptest::collection::vec(
        proptest::char::any().prop_filter("printable only", |c| !c.is_control()),
        0..4,
    )
    .prop_map(String::from_iter)
}

fn any_key() -> impl Strategy<Value = Key> {
    prop_oneof![
        Just(Key::Backspace),
        Just(Key::Delete),
        Just(Key::ArrowLeft),
        Just(Key::ArrowRight),
        Just(Key::Home),
        Just(Key::End),
    ]
}

fn any_op() -> impl Strategy<Value = Op> {
    prop_oneof![
        3 => any_text().prop_map(Op::Type),
        4 => (any_key(), any::<bool>()).prop_map(|(key, shift)| Op::Key(key, shift)),
        2 => (any_key(), any::<bool>()).prop_map(|(key, shift)| Op::WordKey(key, shift)),
        1 => Just(Op::AltBackspace),
        1 => Just(Op::SelectAll),
        1 => any_text().prop_map(Op::Write),
        1 => Just(Op::Undo),
        1 => Just(Op::Redo),
    ]
}

/// Applies `op` to the reference editor, the way the input's handlers and
/// its binding do.
fn apply_to_reference(editor: &Editor, op: &Op) {
    match op {
        Op::Type(text) => text.chars().for_each(|c| editor.insert(&c.to_string())),
        Op::Key(key, shift) => match (key, shift) {
            (Key::Backspace, _) => editor.backspace(),
            (Key::Delete, _) => editor.delete(),
            (Key::ArrowLeft, false) => editor.move_left(),
            (Key::ArrowLeft, true) => editor.extend_left(),
            (Key::ArrowRight, false) => editor.move_right(),
            (Key::ArrowRight, true) => editor.extend_right(),
            (Key::Home, false) => editor.move_to_start(),
            (Key::Home, true) => editor.extend_to_start(),
            (Key::End, false) => editor.move_to_end(),
            (Key::End, true) => editor.extend_to_end(),
            _ => unreachable!("the strategy makes no other keys"),
        },
        Op::WordKey(key, shift) => match (key, shift) {
            (Key::Backspace, _) => editor.backspace_word(),
            (Key::Delete, _) => editor.delete_word(),
            (Key::ArrowLeft, false) => editor.move_word_left(),
            (Key::ArrowLeft, true) => editor.extend_word_left(),
            (Key::ArrowRight, false) => editor.move_word_right(),
            (Key::ArrowRight, true) => editor.extend_word_right(),
            (Key::Home, false) => editor.move_to_start(),
            (Key::Home, true) => editor.extend_to_start(),
            (Key::End, false) => editor.move_to_end(),
            (Key::End, true) => editor.extend_to_end(),
            _ => unreachable!("the strategy makes no other keys"),
        },
        Op::AltBackspace => editor.backspace_word(),
        Op::SelectAll => editor.select_all(),
        // The input applies an outside write only when it changes the text.
        Op::Write(text) if !editor.has_text(text) => editor.set_text(text),
        Op::Write(_) => {}
        Op::Undo => editor.undo(),
        Op::Redo => editor.redo(),
    }
}

/// Applies `op` to the input through the harness.
fn apply_to_input(harness: &mut Harness, value: &RwSignal<String>, op: &Op) {
    let control = Modifiers {
        control: true,
        ..Modifiers::default()
    };
    match op {
        Op::Type(text) => harness.type_text(text),
        Op::Key(key, shift) => harness.press_key_with(
            key.clone(),
            Modifiers {
                shift: *shift,
                ..Modifiers::default()
            },
        ),
        Op::WordKey(key, shift) => harness.press_key_with(
            key.clone(),
            Modifiers {
                shift: *shift,
                ..control
            },
        ),
        Op::AltBackspace => harness.press_key_with(
            Key::Backspace,
            Modifiers {
                alt: true,
                ..Modifiers::default()
            },
        ),
        Op::SelectAll => harness.press_key_with(Key::Character(String::from("a")), command()),
        Op::Write(text) => value.set(text.clone()),
        Op::Undo => harness.press_key_with(Key::Character(String::from("z")), command()),
        Op::Redo => harness.press_key_with(
            Key::Character(String::from("z")),
            Modifiers {
                shift: true,
                ..command()
            },
        ),
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(64))]

    #[test]
    fn random_edits_keep_the_signal_in_step(ops in proptest::collection::vec(any_op(), 0..30)) {
        let (mut harness, value) = mounted("");
        focus(&mut harness);
        let reference = Editor::single_line(RwSignal::new(String::new()));
        reference.set_style(&TextStyle::default());

        for op in &ops {
            apply_to_input(&mut harness, &value, op);
            harness.settle();
            apply_to_reference(&reference, op);
            prop_assert_eq!(
                value.get(),
                reference.text(),
                "the signal holds the text the edits made, after {:?}",
                op
            );
            let raw = reference.raw_text();
            let selection = reference.selection();
            prop_assert!(raw.is_char_boundary(selection.start));
            prop_assert!(raw.is_char_boundary(selection.end));
        }
    }
}

/// An upper bound on the undo steps one operation can make: a typed string
/// has fewer than four characters, and each may start a step.
const STEPS_PER_OP: usize = 4;

/// The most operations the undo property applies, so that even when every
/// one makes [`STEPS_PER_OP`] steps they fit the editor's history of 100.
const MAX_UNDO_OPS: usize = 100 / STEPS_PER_OP;

proptest! {
    #![proptest_config(ProptestConfig::with_cases(256))]

    #[test]
    fn undoing_every_step_returns_to_the_last_outside_write_and_redo_returns(
        ops in proptest::collection::vec(any_op(), 0..=MAX_UNDO_OPS)
    ) {
        let reference = Editor::new(RwSignal::new(String::new()));
        reference.set_style(&TextStyle::default());
        let ops: Vec<Op> = ops
            .into_iter()
            .filter(|op| !matches!(op, Op::Undo | Op::Redo))
            .collect();
        let mut baseline = String::new();
        for op in &ops {
            if let Op::Write(text) = op
                && !reference.has_text(text)
            {
                baseline = text.clone();
            }
            apply_to_reference(&reference, op);
        }
        let end = reference.text();

        for _ in 0..=STEPS_PER_OP * ops.len() {
            reference.undo();
        }
        prop_assert_eq!(reference.text(), baseline, "undo walks back to the last outside write");
        for _ in 0..=STEPS_PER_OP * ops.len() {
            reference.redo();
        }
        prop_assert_eq!(reference.text(), end, "redo walks forward to where the edits ended");
    }
}