iced-cube 0.0.23

Themeable application components for the iced GUI library, with Lucide icons
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
//! A timeline across a sequence of steps, such as the actions of a recorded
//! session or the frames of a run: a tick per step coloured by its tone, a
//! playhead on the current step, and optional lanes below the track that
//! show spans over ranges of steps, such as tasks that ran across several.
//!
//! The app owns the current step. Pressing or dragging along the track, or
//! a shortcut from [`default_keymap`], picks another one, and
//! [`Timeline::on_hover`] reports the step under the pointer so the app can
//! preview it. Shortcuts act only while the timeline has keyboard focus
//! (Tab reaches it) or was the last thing pressed, so several on one screen
//! never fight over keys.
//!
//! Steps sit evenly by default. Give each one a time with
//! [`Timeline::times`] to place them by when they happened, add a labelled
//! [`ruler`](Timeline::ruler), and shorten long idle stretches with
//! [`Timeline::compress_gaps`].

mod timing;

pub use timing::{Break, MARK_SPACING, Mark, Timing, time_label};

use std::borrow::Cow;
use std::time::Duration;

use iced::advanced::layout::{self, Layout};
use iced::advanced::text as core_text;
use iced::advanced::widget::{Tree, Widget, tree};
use iced::advanced::{Clipboard, Shell, renderer};
use iced::alignment::Vertical;
use iced::keyboard::{self, key::Named};
use iced::widget::text::{self, LineHeight, Shaping, Wrapping};
use iced::{
    Border, Color, Element, Event, Length, Pixels, Point, Rectangle, Renderer, Size, Theme, mouse,
    touch,
};

use crate::focus;
use crate::keys::{self, Chord, Keymap};
use crate::theme::{self, Tokens, fade, mix, radius, space, text_size};

/// Height of the track row.
pub const TRACK_HEIGHT: f32 = 28.0;
/// Height of one lane row.
pub const LANE_HEIGHT: f32 = 20.0;
/// Width of the lane labels when the timeline has lanes.
pub const LABEL_WIDTH: f32 = 96.0;
/// Radius of the playhead.
pub const PLAYHEAD_RADIUS: f32 = 6.0;
/// Steps that a page action moves.
pub const PAGE: usize = 10;
/// Height of the time ruler below the track and lanes.
pub const RULER_HEIGHT: f32 = 20.0;

const RAIL_HEIGHT: f32 = 4.0;
const TICK_WIDTH: f32 = 2.0;
const BAR_HEIGHT: f32 = 8.0;
const MARK_HEIGHT: f32 = 4.0;
/// The space left either side of a break in the rail and lane bars.
const BREAK_INSET: f32 = 2.0;
/// Ruler labels closer than this to an edge line up with it instead of
/// centring on their mark.
const EDGE_LABEL: f32 = 24.0;

/// What a step or span signals.
pub use crate::theme::Tone;

/// A run of steps in a lane, from `start` to `end` inclusive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Span {
    pub start: usize,
    pub end: usize,
    pub tone: Tone,
}

impl Span {
    /// A neutral span from `start` to `end`, in either order.
    pub fn new(start: usize, end: usize) -> Self {
        Self {
            start: start.min(end),
            end: start.max(end),
            tone: Tone::Neutral,
        }
    }

    pub fn tone(mut self, tone: Tone) -> Self {
        self.tone = tone;
        self
    }
}

/// A labelled row of spans below the track.
#[derive(Debug, Clone, PartialEq)]
pub struct Lane<'a> {
    label: text::Fragment<'a>,
    spans: Vec<Span>,
}

/// Creates a lane named `label` holding `spans`.
pub fn lane<'a>(
    label: impl text::IntoFragment<'a>,
    spans: impl IntoIterator<Item = Span>,
) -> Lane<'a> {
    Lane {
        label: label.into_fragment(),
        spans: spans.into_iter().collect(),
    }
}

impl Lane<'_> {
    pub fn label(&self) -> &str {
        &self.label
    }

    pub fn spans(&self) -> &[Span] {
        &self.spans
    }
}

/// A timeline builder. Convert it into an [`Element`] to render.
///
/// A timeline without a message is rendered disabled.
pub struct Timeline<'a, Message> {
    steps: Vec<Tone>,
    current: usize,
    lanes: Vec<Lane<'a>>,
    label_width: f32,
    width: Length,
    name: text::Fragment<'a>,
    keymap: Keymap<Action>,
    times: Vec<Duration>,
    end: Option<Duration>,
    compress: Option<Duration>,
    timing: Option<Timing>,
    ruler: bool,
    format: Option<Box<dyn Fn(Duration) -> String + 'a>>,
    on_select: Option<Box<dyn Fn(usize) -> Message + 'a>>,
    on_hover: Option<Box<dyn Fn(Option<usize>) -> Message + 'a>>,
}

impl<Message> std::fmt::Debug for Timeline<'_, Message> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Timeline")
            .field("steps", &self.steps.len())
            .field("current", &self.current)
            .field("lanes", &self.lanes)
            .field("label_width", &self.label_width)
            .field("width", &self.width)
            .field("name", &self.name)
            .field("keymap", &self.keymap)
            .field("timing", &self.timing)
            .field("ruler", &self.ruler)
            .field("enabled", &self.on_select.is_some())
            .field("hover", &self.on_hover.is_some())
            .finish()
    }
}

/// Creates a timeline over `steps`, one tone per step, with `current`
/// selected. The current step is clamped to the steps.
pub fn timeline<'a, Message>(
    steps: impl IntoIterator<Item = Tone>,
    current: usize,
) -> Timeline<'a, Message> {
    let steps: Vec<Tone> = steps.into_iter().collect();
    Timeline {
        current: current.min(steps.len().saturating_sub(1)),
        steps,
        lanes: Vec::new(),
        label_width: LABEL_WIDTH,
        width: Length::Fill,
        name: Cow::Borrowed("Timeline"),
        keymap: default_keymap(),
        times: Vec::new(),
        end: None,
        compress: None,
        timing: None,
        ruler: false,
        format: None,
        on_select: None,
        on_hover: None,
    }
}

impl<'a, Message> Timeline<'a, Message> {
    /// Adds a lane of spans below the track.
    pub fn lane(mut self, lane: Lane<'a>) -> Self {
        self.lanes.push(lane);
        self
    }

    /// Adds several lanes below the track.
    pub fn lanes(mut self, lanes: impl IntoIterator<Item = Lane<'a>>) -> Self {
        self.lanes.extend(lanes);
        self
    }

    /// Width of the lane labels. Only used when there are lanes.
    pub fn label_width(mut self, width: f32) -> Self {
        self.label_width = width.max(0.0);
        self
    }

    pub fn width(mut self, width: impl Into<Length>) -> Self {
        self.width = width.into();
        self
    }

    /// The name tests and assistive tools know it by. "Timeline" by default.
    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
        self.name = label.into_fragment();
        self
    }

    /// Sets the message sent with the step under the pointer while
    /// pressing or dragging, or the step a shortcut moves to.
    pub fn on_select(mut self, on_select: impl Fn(usize) -> Message + 'a) -> Self {
        self.on_select = Some(Box::new(on_select));
        self
    }

    /// Sets the message sent with the step under the pointer as it moves
    /// over the timeline, and with `None` once it leaves, so the app can
    /// preview a step without selecting it. Nothing is sent during a drag,
    /// which reports its steps through `on_select`. It works on a timeline
    /// without `on_select` too.
    pub fn on_hover(mut self, on_hover: impl Fn(Option<usize>) -> Message + 'a) -> Self {
        self.on_hover = Some(Box::new(on_hover));
        self
    }

    /// Replaces the [`default_keymap`] the timeline resolves keys with
    /// while it has keyboard focus or was the last thing pressed.
    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
        self.keymap = keymap;
        self
    }

    /// Places each step by the moment it began, such as its offset from
    /// the start of a run, instead of evenly. Steps past the last time
    /// given take that time. See [`Timing::new`] for how close and
    /// backward times are handled.
    pub fn times(mut self, times: impl IntoIterator<Item = Duration>) -> Self {
        self.times = times.into_iter().collect();
        self.retime();
        self
    }

    /// When the last step finished, so the track runs on past it. Only
    /// used with [`times`](Self::times).
    pub fn end(mut self, end: Duration) -> Self {
        self.end = Some(end);
        self.retime();
        self
    }

    /// Draws each gap between timed steps longer than `longer_than` as if
    /// it lasted `longer_than`, with a break in the rail, so long idle
    /// stretches do not squeeze the busy parts. Only used with
    /// [`times`](Self::times).
    pub fn compress_gaps(mut self, longer_than: Duration) -> Self {
        self.compress = Some(longer_than);
        self.retime();
        self
    }

    /// Shows a ruler of labelled marks below the track and lanes: round
    /// times for a timed timeline, step numbers for an even one.
    pub fn ruler(mut self, ruler: bool) -> Self {
        self.ruler = ruler;
        self
    }

    /// Replaces the ruler's labels for times, which by default read like
    /// `250 ms`, `1.5 s` or `2:05` depending on the length of the track.
    pub fn ruler_format(mut self, format: impl Fn(Duration) -> String + 'a) -> Self {
        self.format = Some(Box::new(format));
        self
    }

    pub fn current(&self) -> usize {
        self.current
    }

    /// Where the steps sit when they are placed by time.
    pub fn timing(&self) -> Option<&Timing> {
        self.timing.as_ref()
    }

    fn retime(&mut self) {
        if self.times.is_empty() {
            self.timing = None;
            return;
        }
        let mut times = self.times.clone();
        let last = times.last().copied().unwrap_or_default();
        times.resize(self.steps.len().max(1), last);
        self.timing = Some(Timing::new(&times, self.end, self.compress));
    }

    pub fn len(&self) -> usize {
        self.steps.len()
    }

    pub fn is_empty(&self) -> bool {
        self.steps.is_empty()
    }

    pub fn is_enabled(&self) -> bool {
        self.on_select.is_some()
    }

    fn labels(&self) -> f32 {
        if self.lanes.is_empty() {
            0.0
        } else {
            self.label_width
        }
    }

    fn total_height(&self) -> f32 {
        let ruler = if self.ruler { RULER_HEIGHT } else { 0.0 };
        height(self.lanes.len()) + ruler
    }

    /// Where step `index` sits along the track, 0 to 1.
    fn place_of(&self, index: usize) -> f32 {
        match &self.timing {
            Some(timing) => timing.positions().get(index).copied().unwrap_or(0.0),
            None => position_of(index, 1.0, self.steps.len()),
        }
    }

    fn x_of(&self, index: usize, track: Rectangle) -> f32 {
        track.x + track.width * self.place_of(index)
    }

    /// The step nearest `x` on `track`.
    fn index_under(&self, x: f32, track: Rectangle) -> usize {
        let Some(timing) = &self.timing else {
            return index_at(x - track.x, track.width, self.steps.len());
        };
        if track.width <= 0.0 {
            return 0;
        }
        let nearest = timing.nearest((x - track.x) / track.width);
        nearest.min(self.steps.len().saturating_sub(1))
    }

    /// The left and right edges of `span` along `track`, from its left.
    fn extent(&self, span: Span, track: Rectangle) -> (f32, f32) {
        match &self.timing {
            Some(timing) => {
                let (left, right) = timing.extent(span);
                (left * track.width, right * track.width)
            }
            None => span_extent(span, track.width, self.steps.len()),
        }
    }

    /// The compressed gaps along `track`, as left and right x.
    fn breaks(&self, track: Rectangle) -> Vec<(f32, f32)> {
        let Some(timing) = &self.timing else {
            return Vec::new();
        };
        timing
            .breaks()
            .iter()
            .map(|gap| {
                (
                    track.x + gap.start * track.width,
                    track.x + gap.end * track.width,
                )
            })
            .collect()
    }

    /// The ruler's marks along a track `width` wide: a place, 0 to 1, and
    /// a label each.
    fn marks(&self, width: f32) -> Vec<(f32, String)> {
        let Some(timing) = &self.timing else {
            return step_marks(self.steps.len(), width);
        };
        let Some(interval) = timing.interval(width) else {
            return Vec::new();
        };
        timing
            .marks(width)
            .into_iter()
            .map(|mark| {
                let label = match &self.format {
                    Some(format) => format(mark.time),
                    None => time_label(mark.time, interval, timing.end()),
                };
                (mark.place, label)
            })
            .collect()
    }
}

/// Ruler marks numbering `count` evenly placed steps from 1, skipping
/// enough of them to keep the labels [`MARK_SPACING`] apart on a track
/// `width` wide.
fn step_marks(count: usize, width: f32) -> Vec<(f32, String)> {
    if count == 0 {
        return Vec::new();
    }
    let most = (width / MARK_SPACING).floor().max(1.0) as usize;
    let stride = count.div_ceil(most).max(1);
    (0..count)
        .step_by(stride)
        .map(|index| (position_of(index, 1.0, count), (index + 1).to_string()))
        .collect()
}

/// The stretches from `left` to `right` that stay drawn around `gaps`, each
/// gap given as its left and right x and widened by a small inset.
fn pieces(left: f32, right: f32, gaps: &[(f32, f32)]) -> Vec<(f32, f32)> {
    let mut pieces = Vec::with_capacity(gaps.len() + 1);
    let mut start = left;
    for (gap_left, gap_right) in gaps {
        let end = (gap_left - BREAK_INSET).min(right);
        if end > start {
            pieces.push((start, end));
        }
        start = start.max(gap_right + BREAK_INSET);
    }
    if right > start {
        pieces.push((start, right));
    }
    pieces
}

/// The step under `x`, for a track `width` wide holding `count` steps
/// placed evenly from its left edge to its right edge.
pub fn index_at(x: f32, width: f32, count: usize) -> usize {
    if count < 2 || width <= 0.0 {
        return 0;
    }
    let last = count - 1;
    let fraction = (x / width).clamp(0.0, 1.0);
    let index = (fraction * last as f32).round();
    (index as usize).min(last)
}

/// Where step `index` sits along a track `width` wide.
pub fn position_of(index: usize, width: f32, count: usize) -> f32 {
    if count < 2 {
        return 0.0;
    }
    width * index.min(count - 1) as f32 / (count - 1) as f32
}

/// The left and right edges of a span along a track `width` wide: half a
/// step either side of its first and last steps, kept on the track.
pub fn span_extent(span: Span, width: f32, count: usize) -> (f32, f32) {
    let half = if count < 2 {
        width / 2.0
    } else {
        width / (count - 1) as f32 / 2.0
    };
    let left = (position_of(span.start, width, count) - half).max(0.0);
    let right = (position_of(span.end, width, count) + half).min(width);
    (left, right.max(left))
}

/// The height of a timeline with `lanes` lanes.
pub fn height(lanes: usize) -> f32 {
    TRACK_HEIGHT + lanes as f32 * LANE_HEIGHT
}

/// The part of `bounds` a step maps onto: right of the labels, and inset by
/// the playhead radius so the playhead never leaves the widget.
pub fn track_bounds(bounds: Rectangle, labels: f32) -> Rectangle {
    let left = if labels > 0.0 {
        labels + space::SM
    } else {
        0.0
    };
    let x = bounds.x + left + PLAYHEAD_RADIUS;
    Rectangle {
        x,
        y: bounds.y,
        width: (bounds.width - left - PLAYHEAD_RADIUS * 2.0).max(0.0),
        height: TRACK_HEIGHT,
    }
}

/// What a timeline shortcut does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Action {
    Previous,
    Next,
    PageBack,
    PageForward,
    First,
    Last,
}

impl Action {
    /// The step after this action, from `current` in a timeline of `count`
    /// steps. Send it through the timeline's `on_select` message.
    pub fn apply(self, current: usize, count: usize) -> usize {
        let last = count.saturating_sub(1);
        let current = current.min(last);
        match self {
            Action::Previous => current.saturating_sub(1),
            Action::Next => (current + 1).min(last),
            Action::PageBack => current.saturating_sub(PAGE),
            Action::PageForward => (current + PAGE).min(last),
            Action::First => 0,
            Action::Last => last,
        }
    }
}

impl keys::Action for Action {
    const ALL: &'static [Self] = &[
        Action::Previous,
        Action::Next,
        Action::PageBack,
        Action::PageForward,
        Action::First,
        Action::Last,
    ];

    fn defaults() -> Keymap<Self> {
        default_keymap()
    }

    fn name(self) -> &'static str {
        match self {
            Action::Previous => "Previous",
            Action::Next => "Next",
            Action::PageBack => "Page back",
            Action::PageForward => "Page forward",
            Action::First => "First",
            Action::Last => "Last",
        }
    }

    fn description(self) -> &'static str {
        match self {
            Action::Previous => "Moves to the step before the current one.",
            Action::Next => "Moves to the step after the current one.",
            Action::PageBack => "Moves ten steps back.",
            Action::PageForward => "Moves ten steps forward.",
            Action::First => "Moves to the first step.",
            Action::Last => "Moves to the last step.",
        }
    }
}

/// The default timeline shortcuts:
///
/// | Keys | Action |
/// | --- | --- |
/// | `ArrowLeft` | [`Action::Previous`] |
/// | `ArrowRight` | [`Action::Next`] |
/// | `Shift+ArrowLeft`, `PageUp` | [`Action::PageBack`] |
/// | `Shift+ArrowRight`, `PageDown` | [`Action::PageForward`] |
/// | `Home` | [`Action::First`] |
/// | `End` | [`Action::Last`] |
///
/// The timeline resolves them itself while it has keyboard focus or was the
/// last thing pressed. Pass a changed keymap with [`Timeline::keymap`].
pub fn default_keymap() -> Keymap<Action> {
    Keymap::new()
        .bind(Chord::named(Named::ArrowLeft), Action::Previous)
        .bind(Chord::named(Named::ArrowRight), Action::Next)
        .bind(Chord::named(Named::ArrowLeft).shift(), Action::PageBack)
        .bind(Chord::named(Named::PageUp), Action::PageBack)
        .bind(Chord::named(Named::ArrowRight).shift(), Action::PageForward)
        .bind(Chord::named(Named::PageDown), Action::PageForward)
        .bind(Chord::named(Named::Home), Action::First)
        .bind(Chord::named(Named::End), Action::Last)
}

/// How the pointer is interacting with a timeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Status {
    #[default]
    Active,
    Hovered,
    Dragged,
    Disabled,
}

impl Status {
    pub const ALL: [Status; 4] = [
        Status::Active,
        Status::Hovered,
        Status::Dragged,
        Status::Disabled,
    ];
}

/// Colours of a timeline in one status.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Style {
    pub rail: Color,
    pub lane: Color,
    pub label: Color,
    pub playhead: Color,
    pub playhead_border: Color,
    pub playhead_border_width: f32,
    /// The line from the playhead down through the lanes.
    pub cursor: Color,
    /// The outline round the step under the pointer.
    pub hover: Color,
    /// The ruler's tick marks.
    pub mark: Color,
    /// Multiplies the alpha of tone colours.
    pub tone_alpha: f32,
}

/// Resolves the colours of a timeline for a status.
pub fn style(tokens: &Tokens, status: Status) -> Style {
    let border = match status {
        Status::Active | Status::Disabled => tokens.primary,
        Status::Hovered => mix(tokens.primary, tokens.background, 0.15),
        Status::Dragged => mix(tokens.primary, tokens.background, 0.3),
    };
    let style = Style {
        rail: mix(tokens.muted, tokens.border, 0.5),
        lane: tokens.muted,
        label: tokens.muted_foreground,
        playhead: tokens.background,
        playhead_border: border,
        playhead_border_width: match status {
            Status::Hovered | Status::Dragged => 2.5,
            Status::Active | Status::Disabled => 2.0,
        },
        cursor: fade(tokens.primary, 0.4),
        hover: fade(tokens.primary, 0.5),
        mark: fade(tokens.muted_foreground, 0.6),
        tone_alpha: 1.0,
    };
    if status != Status::Disabled {
        return style;
    }
    Style {
        rail: fade(style.rail, 0.5),
        lane: fade(style.lane, 0.5),
        label: fade(style.label, 0.5),
        playhead_border: fade(style.playhead_border, 0.5),
        cursor: fade(style.cursor, 0.5),
        hover: fade(style.hover, 0.5),
        mark: fade(style.mark, 0.5),
        tone_alpha: 0.5,
        ..style
    }
}

#[derive(Debug, Default)]
struct State {
    dragging: bool,
    hovered: bool,
    finger: Option<touch::Finger>,
    last: Option<usize>,
    /// The step under the pointer.
    hover: Option<usize>,
    keys: focus::Scope,
}

impl<Message> Timeline<'_, Message> {
    /// Whether it takes keyboard focus and keys, and reacts to the pointer.
    fn is_focusable(&self) -> bool {
        self.on_select.is_some() && !self.steps.is_empty()
    }

    /// Whether it follows the step under the pointer.
    fn is_hoverable(&self) -> bool {
        (self.on_select.is_some() || self.on_hover.is_some()) && !self.steps.is_empty()
    }

    /// Sends the step under `x` when it differs from the last one sent. A
    /// press starts from the current step, so a drag that comes back to it
    /// within one batch of events still sends it.
    fn select(&self, state: &mut State, x: f32, track: Rectangle, shell: &mut Shell<'_, Message>) {
        let Some(on_select) = &self.on_select else {
            return;
        };
        let index = self.index_under(x, track);
        if state.last != Some(index) {
            shell.publish(on_select(index));
        }
        state.last = Some(index);
    }

    /// Records the step under the pointer and reports it when it changes.
    /// Returns whether it changed.
    fn hover(
        &self,
        state: &mut State,
        hover: Option<usize>,
        shell: &mut Shell<'_, Message>,
    ) -> bool {
        if state.hover == hover {
            return false;
        }
        state.hover = hover;
        if let Some(on_hover) = &self.on_hover {
            shell.publish(on_hover(hover));
        }
        true
    }

    fn status(&self, state: &State, layout: Layout<'_>, cursor: mouse::Cursor) -> Status {
        if self.on_select.is_none() {
            return Status::Disabled;
        }
        if state.dragging {
            return Status::Dragged;
        }
        if cursor.is_over(layout.bounds()) {
            return Status::Hovered;
        }
        Status::Active
    }
}

/// The track row with room for the playhead, which focus reports and the
/// ring surrounds.
fn focus_target(track: Rectangle) -> Rectangle {
    let middle = track.center_y();
    Rectangle {
        x: track.x - PLAYHEAD_RADIUS,
        y: middle - PLAYHEAD_RADIUS,
        width: track.width + PLAYHEAD_RADIUS * 2.0,
        height: PLAYHEAD_RADIUS * 2.0,
    }
}

/// How tall a step's tick is. Toned steps stand taller, as tall as the
/// playhead, so they stand out in a long run.
fn tick_height(tone: Tone) -> f32 {
    if tone == Tone::Neutral {
        8.0
    } else {
        PLAYHEAD_RADIUS * 2.0
    }
}

/// How tall the current step's tick is inside a playhead whose border is
/// `border` wide, leaving a pixel clear of the border at either end.
fn playhead_tick(border: f32) -> f32 {
    ((PLAYHEAD_RADIUS - border) * 2.0 - 2.0).max(0.0)
}

fn fill(renderer: &mut Renderer, bounds: Rectangle, colour: Color, corner: f32) {
    <Renderer as renderer::Renderer>::fill_quad(
        renderer,
        renderer::Quad {
            bounds,
            border: Border {
                radius: corner.into(),
                ..Border::default()
            },
            ..renderer::Quad::default()
        },
        colour,
    );
}

/// Small text aligned by `align_x` on `at`, centred vertically on it and
/// clipped to `clip`.
fn caption(
    renderer: &mut Renderer,
    content: &str,
    at: Point,
    align_x: text::Alignment,
    colour: Color,
    clip: Rectangle,
) {
    <Renderer as core_text::Renderer>::fill_text(
        renderer,
        core_text::Text {
            content: content.to_owned(),
            bounds: Size::new(f32::INFINITY, LANE_HEIGHT),
            size: Pixels(text_size::XS),
            line_height: LineHeight::Absolute(Pixels(LANE_HEIGHT)),
            font: theme::font(),
            align_x,
            align_y: Vertical::Center,
            shaping: Shaping::Advanced,
            wrapping: Wrapping::None,
        },
        at,
        colour,
        clip,
    );
}

fn label(renderer: &mut Renderer, content: &str, bounds: Rectangle, colour: Color) {
    caption(
        renderer,
        content,
        Point::new(bounds.x, bounds.center_y()),
        text::Alignment::Left,
        colour,
        bounds,
    );
}

/// How a ruler label at `x` lines up: with the nearer edge of `bounds`
/// when it is close to one, so it is never cut off, and centred otherwise.
fn mark_alignment(x: f32, bounds: Rectangle) -> text::Alignment {
    if x - bounds.x < EDGE_LABEL {
        text::Alignment::Left
    } else if bounds.x + bounds.width - x < EDGE_LABEL {
        text::Alignment::Right
    } else {
        text::Alignment::Center
    }
}

impl<Message> Widget<Message, Theme, Renderer> for Timeline<'_, Message> {
    fn size(&self) -> Size<Length> {
        Size::new(self.width, Length::Fixed(self.total_height()))
    }

    fn tag(&self) -> tree::Tag {
        tree::Tag::of::<State>()
    }

    fn state(&self) -> tree::State {
        tree::State::new(State::default())
    }

    fn layout(
        &mut self,
        _tree: &mut Tree,
        _renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        let height = self.total_height();
        layout::Node::new(limits.resolve(self.width, Length::Fixed(height), Size::new(0.0, height)))
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        _style: &renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _viewport: &Rectangle,
    ) {
        let tokens = Tokens::of(theme);
        let state = tree.state.downcast_ref::<State>();
        let style = style(&tokens, self.status(state, layout, cursor));
        let bounds = layout.bounds();
        let labels = self.labels();
        let track = track_bounds(bounds, labels);
        let count = self.steps.len();
        let middle = track.center_y();
        let breaks = self.breaks(track);
        let pieces = pieces(
            track.x - PLAYHEAD_RADIUS,
            track.x + track.width + PLAYHEAD_RADIUS,
            &breaks,
        );
        // Each break leaves a gap in the bars with a slash pair over it.
        let bars = |renderer: &mut Renderer, y: f32, height: f32, colour: Color| {
            for (left, right) in &pieces {
                fill(
                    renderer,
                    Rectangle {
                        x: *left,
                        y: y - height / 2.0,
                        width: right - left,
                        height,
                    },
                    colour,
                    radius::FULL,
                );
            }
        };

        bars(renderer, middle, RAIL_HEIGHT, style.rail);
        for (left, right) in &breaks {
            caption(
                renderer,
                "//",
                Point::new((left + right) / 2.0, middle),
                text::Alignment::Center,
                style.label,
                bounds,
            );
        }
        if state.keys.is_focused() && self.is_focusable() {
            focus::draw_ring(renderer, theme, focus_target(track), radius::FULL);
        }

        for (index, lane) in self.lanes.iter().enumerate() {
            let row = Rectangle {
                x: bounds.x,
                y: bounds.y + TRACK_HEIGHT + index as f32 * LANE_HEIGHT,
                width: bounds.width,
                height: LANE_HEIGHT,
            };
            label(
                renderer,
                &lane.label,
                Rectangle {
                    width: labels,
                    ..row
                },
                style.label,
            );
            let bar_y = row.center_y() - BAR_HEIGHT / 2.0;
            bars(renderer, row.center_y(), BAR_HEIGHT, style.lane);
            for span in &lane.spans {
                if span.start >= count {
                    continue;
                }
                let (left, right) = self.extent(*span, track);
                let (left, right) = (
                    track.x + left,
                    track.x + (right - left).max(BAR_HEIGHT) + left,
                );
                for (left, right) in self::pieces(left, right, &breaks) {
                    fill(
                        renderer,
                        Rectangle {
                            x: left,
                            y: bar_y,
                            width: right - left,
                            height: BAR_HEIGHT,
                        },
                        fade(span.tone.colour(&tokens), style.tone_alpha),
                        radius::FULL,
                    );
                }
            }
        }

        if self.ruler {
            let top = bounds.y + height(self.lanes.len());
            // Labels line up with the ends of the track, not the widget, so
            // the first never runs under the lane labels.
            let span = Rectangle {
                x: track.x - PLAYHEAD_RADIUS,
                width: track.width + PLAYHEAD_RADIUS * 2.0,
                ..bounds
            };
            for (place, mark) in self.marks(track.width) {
                let x = track.x + place * track.width;
                fill(
                    renderer,
                    Rectangle {
                        x: x - 0.5,
                        y: top,
                        width: 1.0,
                        height: MARK_HEIGHT,
                    },
                    style.mark,
                    0.0,
                );
                caption(
                    renderer,
                    &mark,
                    Point::new(x, top + (RULER_HEIGHT + MARK_HEIGHT) / 2.0),
                    mark_alignment(x, span),
                    style.label,
                    bounds,
                );
            }
        }

        for (index, tone) in self.steps.iter().enumerate() {
            let tall = tick_height(*tone);
            fill(
                renderer,
                Rectangle {
                    x: self.x_of(index, track) - TICK_WIDTH / 2.0,
                    y: middle - tall / 2.0,
                    width: TICK_WIDTH,
                    height: tall,
                },
                fade(tone.colour(&tokens), style.tone_alpha),
                0.0,
            );
        }

        if count == 0 {
            return;
        }
        let x = self.x_of(self.current, track);
        if !self.lanes.is_empty() {
            fill(
                renderer,
                Rectangle {
                    x: x - 0.5,
                    y: middle,
                    width: 1.0,
                    height: bounds.y + height(self.lanes.len()) - middle,
                },
                style.cursor,
                0.0,
            );
        }
        if let Some(hover) = state.hover
            && hover != self.current
            && hover < count
            && !state.dragging
            && self.is_hoverable()
        {
            let x = self.x_of(hover, track);
            <Renderer as renderer::Renderer>::fill_quad(
                renderer,
                renderer::Quad {
                    bounds: Rectangle {
                        x: x - PLAYHEAD_RADIUS,
                        y: middle - PLAYHEAD_RADIUS,
                        width: PLAYHEAD_RADIUS * 2.0,
                        height: PLAYHEAD_RADIUS * 2.0,
                    },
                    border: Border {
                        color: style.hover,
                        width: 1.5,
                        radius: PLAYHEAD_RADIUS.into(),
                    },
                    ..renderer::Quad::default()
                },
                Color::TRANSPARENT,
            );
        }
        <Renderer as renderer::Renderer>::fill_quad(
            renderer,
            renderer::Quad {
                bounds: Rectangle {
                    x: x - PLAYHEAD_RADIUS,
                    y: middle - PLAYHEAD_RADIUS,
                    width: PLAYHEAD_RADIUS * 2.0,
                    height: PLAYHEAD_RADIUS * 2.0,
                },
                border: Border {
                    color: style.playhead_border,
                    width: style.playhead_border_width,
                    radius: PLAYHEAD_RADIUS.into(),
                },
                ..renderer::Quad::default()
            },
            style.playhead,
        );
        // The current step's tick shows through the playhead, so its tone
        // is never hidden.
        if let Some(tone) = self.steps.get(self.current) {
            let tall = playhead_tick(style.playhead_border_width);
            fill(
                renderer,
                Rectangle {
                    x: x - TICK_WIDTH / 2.0,
                    y: middle - tall / 2.0,
                    width: TICK_WIDTH,
                    height: tall,
                },
                fade(tone.colour(&tokens), style.tone_alpha),
                0.0,
            );
        }
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _renderer: &Renderer,
        _clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        _viewport: &Rectangle,
    ) {
        let state = tree.state.downcast_mut::<State>();
        let bounds = layout.bounds();
        let track = track_bounds(bounds, self.labels());
        // Presses on the lane labels pick nothing.
        let pressable = Rectangle {
            x: track.x - PLAYHEAD_RADIUS,
            width: track.width + PLAYHEAD_RADIUS * 2.0,
            ..bounds
        };
        // A drag reports its steps through `on_select`, so hovering waits
        // for the next move after it ends.
        let hover = if !self.is_hoverable() {
            Some(None)
        } else if state.dragging {
            None
        } else {
            match event {
                Event::Mouse(mouse::Event::CursorMoved { position }) => {
                    // An overlay over the timeline hides the pointer from it.
                    let covered = matches!(cursor, mouse::Cursor::Levitating(_));
                    let over = !covered && pressable.contains(*position);
                    Some(over.then(|| self.index_under(position.x, track)))
                }
                Event::Mouse(mouse::Event::CursorLeft) => Some(None),
                _ => None,
            }
        };
        let hovered = hover.is_some_and(|hover| self.hover(state, hover, shell));
        if !self.is_focusable() {
            if state.keys.release() || hovered {
                shell.request_redraw();
            }
            return;
        }
        let before = (state.dragging, state.hovered);
        state.hovered = cursor.is_over(bounds);
        let keyed = state.keys.update(event, cursor, pressable);
        match event {
            Event::Mouse(mouse::Event::ButtonPressed(button)) => {
                let position = cursor.position_over(pressable);
                if let (mouse::Button::Left, Some(position)) = (button, position) {
                    state.dragging = true;
                    state.last = Some(self.current);
                    self.select(state, position.x, track, shell);
                    shell.capture_event();
                }
            }
            Event::Touch(touch::Event::FingerPressed { id, position }) => {
                if pressable.contains(*position) && !state.dragging {
                    state.dragging = true;
                    state.finger = Some(*id);
                    state.last = Some(self.current);
                    self.select(state, position.x, track, shell);
                    shell.capture_event();
                }
            }
            Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. })
                if state.keys.has_keys() && !shell.is_event_captured() =>
            {
                if let Some(action) = self.keymap.resolve(key, *modifiers) {
                    let next = action.apply(self.current, self.steps.len());
                    if let Some(on_select) = &self.on_select
                        && next != self.current
                    {
                        shell.publish(on_select(next));
                    }
                    shell.capture_event();
                }
            }
            Event::Mouse(mouse::Event::CursorMoved { position })
                if state.dragging && state.finger.is_none() =>
            {
                self.select(state, position.x, track, shell);
            }
            Event::Touch(touch::Event::FingerMoved { id, position })
                if state.finger == Some(*id) =>
            {
                self.select(state, position.x, track, shell);
                shell.capture_event();
            }
            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
                if state.dragging && state.finger.is_none() =>
            {
                state.dragging = false;
                state.last = None;
                shell.capture_event();
            }
            Event::Touch(
                touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. },
            ) if state.finger == Some(*id) => {
                state.dragging = false;
                state.finger = None;
                state.last = None;
                shell.capture_event();
            }
            _ => {}
        }
        if keyed || hovered || (state.dragging, state.hovered) != before {
            shell.request_redraw();
        }
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _viewport: &Rectangle,
        _renderer: &Renderer,
    ) -> mouse::Interaction {
        if self.on_select.is_none() {
            return mouse::Interaction::None;
        }
        if tree.state.downcast_ref::<State>().dragging {
            return mouse::Interaction::Grabbing;
        }
        if cursor.is_over(layout.bounds()) {
            return mouse::Interaction::Pointer;
        }
        mouse::Interaction::None
    }

    fn operate(
        &mut self,
        tree: &mut Tree,
        layout: Layout<'_>,
        _renderer: &Renderer,
        operation: &mut dyn iced::advanced::widget::Operation,
    ) {
        let target = focus_target(track_bounds(layout.bounds(), self.labels()));
        #[cfg(feature = "icedwright")]
        {
            use icedwright_probe::{Annotation, report, role};

            let enabled = self.on_select.is_some();
            let last = self.steps.len().saturating_sub(1) as f64;
            // A timed timeline also reports when the current step began.
            let time = self.timing.as_ref().and_then(|_| {
                let until = (self.current + 1).min(self.times.len());
                let time = self.times.get(..until)?.iter().max()?;
                Some(time.as_millis().to_string())
            });
            report(operation, target, || {
                let annotation = Annotation::new()
                    .role(role::Slider)
                    .name(self.name.to_string())
                    .range(self.current as f64, 0.0..=last)
                    .component("iced_cube::timeline");
                let annotation = match time.clone() {
                    Some(time) => annotation.prop("time_ms", time),
                    None => annotation,
                };
                if enabled {
                    annotation
                } else {
                    annotation.disabled(true)
                }
            });
        }
        // Reported after the annotation, at the same bounds, so a recorder
        // merges the two into one node.
        let state = tree.state.downcast_mut::<State>();
        if self.is_focusable() {
            focus::report(operation, None, target, &mut state.keys);
        } else {
            let _ = state.keys.release();
        }
    }
}

impl<'a, Message: 'a> From<Timeline<'a, Message>> for Element<'a, Message> {
    fn from(timeline: Timeline<'a, Message>) -> Self {
        Element::new(timeline)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keys::Action as _;
    use crate::theme::{dark, light};

    fn bounds() -> Rectangle {
        Rectangle {
            x: 10.0,
            y: 20.0,
            width: 400.0,
            height: 100.0,
        }
    }

    #[test]
    fn default_builder_fills_the_width_and_is_disabled() {
        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 1);
        assert_eq!(t.width, Length::Fill);
        assert_eq!(t.name, "Timeline");
        assert_eq!(t.label_width, LABEL_WIDTH);
        assert!(t.lanes.is_empty());
        assert!(!t.is_enabled());
        assert!(t.on_select(|_| ()).is_enabled());
    }

    #[test]
    fn the_current_step_is_clamped_to_the_steps() {
        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 9);
        assert_eq!(t.current(), 2);
        let t: Timeline<'_, ()> = timeline([], 4);
        assert_eq!(t.current(), 0);
        assert!(t.is_empty());
    }

    #[test]
    fn spans_are_ordered_and_take_a_tone() {
        let span = Span::new(5, 2).tone(Tone::Warning);
        assert_eq!((span.start, span.end, span.tone), (2, 5, Tone::Warning));
        assert_eq!(Span::new(1, 1).tone, Tone::Neutral);
    }

    #[test]
    fn positions_and_indices_agree_at_every_step() {
        for count in [1, 2, 3, 10, 57] {
            for index in 0..count {
                let x = position_of(index, 600.0, count);
                assert_eq!(index_at(x, 600.0, count), index, "{index} of {count}");
            }
        }
    }

    #[test]
    fn points_outside_the_track_clamp_to_the_ends() {
        assert_eq!(index_at(-50.0, 100.0, 5), 0);
        assert_eq!(index_at(150.0, 100.0, 5), 4);
        assert_eq!(index_at(10.0, 0.0, 5), 0);
        assert_eq!(index_at(10.0, 100.0, 0), 0);
    }

    #[test]
    fn points_go_to_the_nearest_step() {
        assert_eq!(index_at(24.0, 100.0, 5), 1);
        assert_eq!(index_at(26.0, 100.0, 5), 1);
        assert_eq!(index_at(38.0, 100.0, 5), 2);
    }

    #[test]
    fn a_span_reaches_half_a_step_either_side_and_stays_on_the_track() {
        assert_eq!(span_extent(Span::new(1, 2), 100.0, 5), (12.5, 62.5));
        assert_eq!(span_extent(Span::new(0, 4), 100.0, 5), (0.0, 100.0));
        assert_eq!(span_extent(Span::new(3, 3), 100.0, 1), (0.0, 50.0));
    }

    #[test]
    fn the_track_sits_right_of_the_labels_and_inside_the_playhead() {
        let track = track_bounds(bounds(), 0.0);
        assert_eq!(track.x, 10.0 + PLAYHEAD_RADIUS);
        assert_eq!(track.width, 400.0 - PLAYHEAD_RADIUS * 2.0);
        assert_eq!(track.height, TRACK_HEIGHT);
        let track = track_bounds(bounds(), 96.0);
        assert_eq!(track.x, 10.0 + 96.0 + space::SM + PLAYHEAD_RADIUS);
        let narrow = Rectangle {
            width: 20.0,
            ..bounds()
        };
        assert_eq!(track_bounds(narrow, 96.0).width, 0.0);
    }

    #[test]
    fn height_grows_by_a_row_per_lane() {
        assert_eq!(height(0), TRACK_HEIGHT);
        assert_eq!(height(2), TRACK_HEIGHT + 2.0 * LANE_HEIGHT);
    }

    #[test]
    fn actions_move_within_the_steps() {
        assert_eq!(Action::Previous.apply(3, 10), 2);
        assert_eq!(Action::Previous.apply(0, 10), 0);
        assert_eq!(Action::Next.apply(3, 10), 4);
        assert_eq!(Action::Next.apply(9, 10), 9);
        assert_eq!(Action::PageBack.apply(4, 30), 0);
        assert_eq!(Action::PageBack.apply(14, 30), 4);
        assert_eq!(Action::PageForward.apply(25, 30), 29);
        assert_eq!(Action::PageForward.apply(5, 30), 15);
        assert_eq!(Action::First.apply(7, 10), 0);
        assert_eq!(Action::Last.apply(2, 10), 9);
        assert_eq!(Action::Last.apply(0, 0), 0);
        assert_eq!(Action::Next.apply(50, 10), 9);
    }

    fn resolve(keymap: &Keymap<Action>, chord: Chord) -> Option<Action> {
        keymap.resolve(chord.key(), chord.modifiers())
    }

    #[test]
    fn default_keymap_binds_arrows_pages_and_ends() {
        let keymap = default_keymap();
        assert_eq!(
            resolve(&keymap, Chord::named(Named::ArrowLeft)),
            Some(Action::Previous)
        );
        assert_eq!(
            resolve(&keymap, Chord::named(Named::ArrowRight).shift()),
            Some(Action::PageForward)
        );
        assert_eq!(
            resolve(&keymap, Chord::named(Named::PageUp)),
            Some(Action::PageBack)
        );
        assert_eq!(
            resolve(&keymap, Chord::named(Named::End)),
            Some(Action::Last)
        );
        assert_eq!(Keymap::<Action>::defaults(), keymap);
        for action in Action::ALL {
            assert!(!action.name().is_empty());
            assert!(action.description().ends_with('.'));
        }
    }

    #[test]
    fn keymap_overrides_and_unbinding() {
        let keymap = default_keymap()
            .bind(Chord::character('j'), Action::Next)
            .unbind(&Chord::named(Named::Home));
        assert_eq!(resolve(&keymap, Chord::character('j')), Some(Action::Next));
        assert_eq!(resolve(&keymap, Chord::named(Named::Home)), None);
        assert_eq!(
            resolve(&keymap, Chord::named(Named::End)),
            Some(Action::Last)
        );
    }

    #[test]
    fn style_follows_the_status_in_light_and_dark() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let active = style(&tokens, Status::Active);
            assert_eq!(active.playhead_border, tokens.primary);
            assert_eq!(active.playhead, tokens.background);
            assert_eq!(active.tone_alpha, 1.0);
            let hovered = style(&tokens, Status::Hovered);
            assert_ne!(hovered.playhead_border, active.playhead_border);
            assert!(hovered.playhead_border_width > active.playhead_border_width);
            let dragged = style(&tokens, Status::Dragged);
            assert_ne!(dragged.playhead_border, hovered.playhead_border);
            let disabled = style(&tokens, Status::Disabled);
            assert!(disabled.rail.a < active.rail.a);
            assert!(disabled.playhead_border.a < active.playhead_border.a);
            assert_eq!(disabled.tone_alpha, 0.5);
            assert!(disabled.hover.a < active.hover.a);
            assert_eq!(Status::ALL.len(), 4);
        }
    }

    #[test]
    fn the_current_tick_fits_inside_the_playhead_in_every_status() {
        let tokens = Tokens::of(&light());
        for status in Status::ALL {
            let border = style(&tokens, status).playhead_border_width;
            let tall = playhead_tick(border);
            assert!(tall >= 4.0, "{status:?} leaves the tick visible");
            assert!(tall < (PLAYHEAD_RADIUS - border) * 2.0, "{status:?}");
        }
        assert!(tick_height(Tone::Warning) > tick_height(Tone::Neutral));
    }

    #[test]
    fn times_place_the_steps_and_fill_in_missing_ones() {
        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 4], 0).times([
            Duration::from_secs(0),
            Duration::from_secs(1),
            Duration::from_secs(4),
        ]);
        let Some(timing) = t.timing() else {
            panic!("timed");
        };
        assert_eq!(timing.positions().len(), 4);
        assert!(timing.positions()[3] > timing.positions()[2]);
        let track = Rectangle {
            x: 0.0,
            y: 0.0,
            width: 400.0,
            height: TRACK_HEIGHT,
        };
        assert_eq!(t.index_under(0.0, track), 0);
        assert_eq!(t.index_under(400.0, track), 3);

        let even: Timeline<'_, ()> = timeline([Tone::Neutral; 4], 0);
        assert!(even.timing().is_none());
        assert_eq!(even.place_of(1), 1.0 / 3.0);
    }

    #[test]
    fn end_and_compression_apply_in_any_order() {
        let times = [Duration::from_secs(0), Duration::from_secs(100)];
        let a: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
            .compress_gaps(Duration::from_secs(1))
            .end(Duration::from_secs(101))
            .times(times);
        let b: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
            .times(times)
            .end(Duration::from_secs(101))
            .compress_gaps(Duration::from_secs(1));
        assert_eq!(a.timing(), b.timing());
        assert_eq!(a.timing().map(|t| t.breaks().len()), Some(1));
    }

    #[test]
    fn the_ruler_adds_a_row_below_the_lanes() {
        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 0);
        assert_eq!(t.total_height(), TRACK_HEIGHT);
        let t = t.ruler(true).lane(lane("A", []));
        assert_eq!(t.total_height(), TRACK_HEIGHT + LANE_HEIGHT + RULER_HEIGHT);
    }

    #[test]
    fn even_rulers_number_the_steps_and_thin_out_when_narrow() {
        let marks = step_marks(5, 640.0);
        let labels: Vec<&str> = marks.iter().map(|(_, label)| label.as_str()).collect();
        assert_eq!(labels, ["1", "2", "3", "4", "5"]);
        assert_eq!(marks[4].0, 1.0);
        let narrow = step_marks(100, 320.0);
        assert_eq!(narrow.len(), 5);
        assert_eq!(narrow[1].1, "21");
        assert!(step_marks(0, 320.0).is_empty());
    }

    #[test]
    fn timed_rulers_use_the_format() {
        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
            .times([Duration::from_secs(0), Duration::from_secs(2)])
            .ruler(true);
        let labels: Vec<String> = t.marks(128.0).into_iter().map(|(_, l)| l).collect();
        assert_eq!(labels, ["0 s", "1 s", "2 s"]);
        let t = t.ruler_format(|time| format!("t+{}", time.as_secs()));
        let labels: Vec<String> = t.marks(128.0).into_iter().map(|(_, l)| l).collect();
        assert_eq!(labels, ["t+0", "t+1", "t+2"]);
    }

    #[test]
    fn breaks_cut_gaps_in_the_bars() {
        assert_eq!(pieces(0.0, 100.0, &[]), [(0.0, 100.0)]);
        assert_eq!(
            pieces(0.0, 100.0, &[(40.0, 60.0)]),
            [(0.0, 40.0 - BREAK_INSET), (60.0 + BREAK_INSET, 100.0)]
        );
        assert_eq!(pieces(0.0, 100.0, &[(0.0, 100.0)]), []);
    }

    #[test]
    fn labels_near_an_edge_line_up_with_it() {
        let bounds = Rectangle {
            x: 0.0,
            y: 0.0,
            width: 300.0,
            height: 40.0,
        };
        assert_eq!(mark_alignment(6.0, bounds), text::Alignment::Left);
        assert_eq!(mark_alignment(150.0, bounds), text::Alignment::Center);
        assert_eq!(mark_alignment(294.0, bounds), text::Alignment::Right);
    }
}