Skip to main content

iced_cube/data/
timeline.rs

1//! A timeline across a sequence of steps, such as the actions of a recorded
2//! session or the frames of a run: a tick per step coloured by its tone, a
3//! playhead on the current step, and optional lanes below the track that
4//! show spans over ranges of steps, such as tasks that ran across several.
5//!
6//! The app owns the current step. Pressing or dragging along the track, or
7//! a shortcut from [`default_keymap`], picks another one, and
8//! [`Timeline::on_hover`] reports the step under the pointer so the app can
9//! preview it. Shortcuts act only while the timeline has keyboard focus
10//! (Tab reaches it) or was the last thing pressed, so several on one screen
11//! never fight over keys.
12//!
13//! Steps sit evenly by default. Give each one a time with
14//! [`Timeline::times`] to place them by when they happened, add a labelled
15//! [`ruler`](Timeline::ruler), and shorten long idle stretches with
16//! [`Timeline::compress_gaps`].
17//!
18//! Under the `icedwright` feature it reports itself as a slider named by
19//! its [`label`](Timeline::label). The value is always the current step's
20//! index, from 0 to one less than the number of steps, however the steps
21//! are placed, with a step of 1. The slider runs from the first tick to the
22//! last. icedwright 0.0.7 and later reach a value with the arrow keys, one
23//! step per press, so it lands on the right step even when steps are placed
24//! by time; a test can also press a tick at its place in
25//! [`Timing::positions`].
26
27mod timing;
28
29pub use timing::{Break, MARK_SPACING, Mark, Timing, time_label};
30
31use std::borrow::Cow;
32use std::time::Duration;
33
34use iced::advanced::layout::{self, Layout};
35use iced::advanced::text as core_text;
36use iced::advanced::widget::{Tree, Widget, tree};
37use iced::advanced::{Clipboard, Shell, renderer};
38use iced::alignment::Vertical;
39use iced::keyboard::{self, key::Named};
40use iced::widget::text::{self, LineHeight, Shaping, Wrapping};
41use iced::{
42    Border, Color, Element, Event, Length, Pixels, Point, Rectangle, Renderer, Size, Theme, mouse,
43    touch,
44};
45
46use crate::focus;
47use crate::keys::{self, Chord, Keymap};
48use crate::theme::{self, Tokens, fade, mix, radius, space, text_size};
49
50/// Height of the track row.
51pub const TRACK_HEIGHT: f32 = 28.0;
52/// Height of one lane row.
53pub const LANE_HEIGHT: f32 = 20.0;
54/// Width of the lane labels when the timeline has lanes.
55pub const LABEL_WIDTH: f32 = 96.0;
56/// Radius of the playhead.
57pub const PLAYHEAD_RADIUS: f32 = 6.0;
58/// Steps that a page action moves.
59pub const PAGE: usize = 10;
60/// Height of the time ruler below the track and lanes.
61pub const RULER_HEIGHT: f32 = 20.0;
62
63const RAIL_HEIGHT: f32 = 4.0;
64const TICK_WIDTH: f32 = 2.0;
65const BAR_HEIGHT: f32 = 8.0;
66const MARK_HEIGHT: f32 = 4.0;
67/// The space left either side of a break in the rail and lane bars.
68const BREAK_INSET: f32 = 2.0;
69/// Ruler labels closer than this to an edge line up with it instead of
70/// centring on their mark.
71const EDGE_LABEL: f32 = 24.0;
72
73/// What a step or span signals.
74pub use crate::theme::Tone;
75
76/// A run of steps in a lane, from `start` to `end` inclusive.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78pub struct Span {
79    pub start: usize,
80    pub end: usize,
81    pub tone: Tone,
82}
83
84impl Span {
85    /// A neutral span from `start` to `end`, in either order.
86    pub fn new(start: usize, end: usize) -> Self {
87        Self {
88            start: start.min(end),
89            end: start.max(end),
90            tone: Tone::Neutral,
91        }
92    }
93
94    pub fn tone(mut self, tone: Tone) -> Self {
95        self.tone = tone;
96        self
97    }
98}
99
100/// A labelled row of spans below the track.
101#[derive(Debug, Clone, PartialEq)]
102pub struct Lane<'a> {
103    label: text::Fragment<'a>,
104    spans: Vec<Span>,
105}
106
107/// Creates a lane named `label` holding `spans`.
108pub fn lane<'a>(
109    label: impl text::IntoFragment<'a>,
110    spans: impl IntoIterator<Item = Span>,
111) -> Lane<'a> {
112    Lane {
113        label: label.into_fragment(),
114        spans: spans.into_iter().collect(),
115    }
116}
117
118impl Lane<'_> {
119    pub fn label(&self) -> &str {
120        &self.label
121    }
122
123    pub fn spans(&self) -> &[Span] {
124        &self.spans
125    }
126}
127
128/// A timeline builder. Convert it into an [`Element`] to render.
129///
130/// A timeline without a message is rendered disabled.
131pub struct Timeline<'a, Message> {
132    steps: Vec<Tone>,
133    current: usize,
134    lanes: Vec<Lane<'a>>,
135    label_width: f32,
136    width: Length,
137    name: text::Fragment<'a>,
138    keymap: Keymap<Action>,
139    times: Vec<Duration>,
140    end: Option<Duration>,
141    compress: Option<Duration>,
142    timing: Option<Timing>,
143    ruler: bool,
144    format: Option<Box<dyn Fn(Duration) -> String + 'a>>,
145    on_select: Option<Box<dyn Fn(usize) -> Message + 'a>>,
146    on_hover: Option<Box<dyn Fn(Option<usize>) -> Message + 'a>>,
147}
148
149impl<Message> std::fmt::Debug for Timeline<'_, Message> {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        f.debug_struct("Timeline")
152            .field("steps", &self.steps.len())
153            .field("current", &self.current)
154            .field("lanes", &self.lanes)
155            .field("label_width", &self.label_width)
156            .field("width", &self.width)
157            .field("name", &self.name)
158            .field("keymap", &self.keymap)
159            .field("timing", &self.timing)
160            .field("ruler", &self.ruler)
161            .field("enabled", &self.on_select.is_some())
162            .field("hover", &self.on_hover.is_some())
163            .finish()
164    }
165}
166
167/// Creates a timeline over `steps`, one tone per step, with `current`
168/// selected. The current step is clamped to the steps.
169pub fn timeline<'a, Message>(
170    steps: impl IntoIterator<Item = Tone>,
171    current: usize,
172) -> Timeline<'a, Message> {
173    let steps: Vec<Tone> = steps.into_iter().collect();
174    Timeline {
175        current: current.min(steps.len().saturating_sub(1)),
176        steps,
177        lanes: Vec::new(),
178        label_width: LABEL_WIDTH,
179        width: Length::Fill,
180        name: Cow::Borrowed("Timeline"),
181        keymap: default_keymap(),
182        times: Vec::new(),
183        end: None,
184        compress: None,
185        timing: None,
186        ruler: false,
187        format: None,
188        on_select: None,
189        on_hover: None,
190    }
191}
192
193impl<'a, Message> Timeline<'a, Message> {
194    /// Adds a lane of spans below the track.
195    pub fn lane(mut self, lane: Lane<'a>) -> Self {
196        self.lanes.push(lane);
197        self
198    }
199
200    /// Adds several lanes below the track.
201    pub fn lanes(mut self, lanes: impl IntoIterator<Item = Lane<'a>>) -> Self {
202        self.lanes.extend(lanes);
203        self
204    }
205
206    /// Width of the lane labels. Only used when there are lanes.
207    pub fn label_width(mut self, width: f32) -> Self {
208        self.label_width = width.max(0.0);
209        self
210    }
211
212    pub fn width(mut self, width: impl Into<Length>) -> Self {
213        self.width = width.into();
214        self
215    }
216
217    /// The name tests and assistive tools know it by. "Timeline" by default.
218    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
219        self.name = label.into_fragment();
220        self
221    }
222
223    /// Sets the message sent with the step under the pointer while
224    /// pressing or dragging, or the step a shortcut moves to.
225    pub fn on_select(mut self, on_select: impl Fn(usize) -> Message + 'a) -> Self {
226        self.on_select = Some(Box::new(on_select));
227        self
228    }
229
230    /// Sets the message sent with the step under the pointer as it moves
231    /// over the timeline, and with `None` once it leaves, so the app can
232    /// preview a step without selecting it. Nothing is sent during a drag,
233    /// which reports its steps through `on_select`. It works on a timeline
234    /// without `on_select` too.
235    pub fn on_hover(mut self, on_hover: impl Fn(Option<usize>) -> Message + 'a) -> Self {
236        self.on_hover = Some(Box::new(on_hover));
237        self
238    }
239
240    /// Replaces the [`default_keymap`] the timeline resolves keys with
241    /// while it has keyboard focus or was the last thing pressed.
242    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
243        self.keymap = keymap;
244        self
245    }
246
247    /// Places each step by the moment it began, such as its offset from
248    /// the start of a run, instead of evenly. Steps past the last time
249    /// given take that time. See [`Timing::new`] for how close and
250    /// backward times are handled.
251    pub fn times(mut self, times: impl IntoIterator<Item = Duration>) -> Self {
252        self.times = times.into_iter().collect();
253        self.retime();
254        self
255    }
256
257    /// When the last step finished, so the track runs on past it. Only
258    /// used with [`times`](Self::times).
259    pub fn end(mut self, end: Duration) -> Self {
260        self.end = Some(end);
261        self.retime();
262        self
263    }
264
265    /// Draws each gap between timed steps longer than `longer_than` as if
266    /// it lasted `longer_than`, with a break in the rail, so long idle
267    /// stretches do not squeeze the busy parts. Only used with
268    /// [`times`](Self::times).
269    pub fn compress_gaps(mut self, longer_than: Duration) -> Self {
270        self.compress = Some(longer_than);
271        self.retime();
272        self
273    }
274
275    /// Shows a ruler of labelled marks below the track and lanes: round
276    /// times for a timed timeline, step numbers for an even one.
277    pub fn ruler(mut self, ruler: bool) -> Self {
278        self.ruler = ruler;
279        self
280    }
281
282    /// Replaces the ruler's labels for times, which by default read like
283    /// `250 ms`, `1.5 s` or `2:05` depending on the length of the track.
284    pub fn ruler_format(mut self, format: impl Fn(Duration) -> String + 'a) -> Self {
285        self.format = Some(Box::new(format));
286        self
287    }
288
289    pub fn current(&self) -> usize {
290        self.current
291    }
292
293    /// Where the steps sit when they are placed by time.
294    pub fn timing(&self) -> Option<&Timing> {
295        self.timing.as_ref()
296    }
297
298    fn retime(&mut self) {
299        if self.times.is_empty() {
300            self.timing = None;
301            return;
302        }
303        let mut times = self.times.clone();
304        let last = times.last().copied().unwrap_or_default();
305        times.resize(self.steps.len().max(1), last);
306        self.timing = Some(Timing::new(&times, self.end, self.compress));
307    }
308
309    pub fn len(&self) -> usize {
310        self.steps.len()
311    }
312
313    pub fn is_empty(&self) -> bool {
314        self.steps.is_empty()
315    }
316
317    pub fn is_enabled(&self) -> bool {
318        self.on_select.is_some()
319    }
320
321    fn labels(&self) -> f32 {
322        if self.lanes.is_empty() {
323            0.0
324        } else {
325            self.label_width
326        }
327    }
328
329    fn total_height(&self) -> f32 {
330        let ruler = if self.ruler { RULER_HEIGHT } else { 0.0 };
331        height(self.lanes.len()) + ruler
332    }
333
334    /// Where step `index` sits along the track, 0 to 1.
335    fn place_of(&self, index: usize) -> f32 {
336        match &self.timing {
337            Some(timing) => timing.positions().get(index).copied().unwrap_or(0.0),
338            None => position_of(index, 1.0, self.steps.len()),
339        }
340    }
341
342    fn x_of(&self, index: usize, track: Rectangle) -> f32 {
343        track.x + track.width * self.place_of(index)
344    }
345
346    /// The step nearest `x` on `track`.
347    fn index_under(&self, x: f32, track: Rectangle) -> usize {
348        let Some(timing) = &self.timing else {
349            return index_at(x - track.x, track.width, self.steps.len());
350        };
351        if track.width <= 0.0 {
352            return 0;
353        }
354        let nearest = timing.nearest((x - track.x) / track.width);
355        nearest.min(self.steps.len().saturating_sub(1))
356    }
357
358    /// The left and right edges of `span` along `track`, from its left.
359    fn extent(&self, span: Span, track: Rectangle) -> (f32, f32) {
360        match &self.timing {
361            Some(timing) => {
362                let (left, right) = timing.extent(span);
363                (left * track.width, right * track.width)
364            }
365            None => span_extent(span, track.width, self.steps.len()),
366        }
367    }
368
369    /// The compressed gaps along `track`, as left and right x.
370    fn breaks(&self, track: Rectangle) -> Vec<(f32, f32)> {
371        let Some(timing) = &self.timing else {
372            return Vec::new();
373        };
374        timing
375            .breaks()
376            .iter()
377            .map(|gap| {
378                (
379                    track.x + gap.start * track.width,
380                    track.x + gap.end * track.width,
381                )
382            })
383            .collect()
384    }
385
386    /// The ruler's marks along a track `width` wide: a place, 0 to 1, and
387    /// a label each.
388    fn marks(&self, width: f32) -> Vec<(f32, String)> {
389        let Some(timing) = &self.timing else {
390            return step_marks(self.steps.len(), width);
391        };
392        let Some(interval) = timing.interval(width) else {
393            return Vec::new();
394        };
395        timing
396            .marks(width)
397            .into_iter()
398            .map(|mark| {
399                let label = match &self.format {
400                    Some(format) => format(mark.time),
401                    None => time_label(mark.time, interval, timing.end()),
402                };
403                (mark.place, label)
404            })
405            .collect()
406    }
407}
408
409/// Ruler marks numbering `count` evenly placed steps from 1, skipping
410/// enough of them to keep the labels [`MARK_SPACING`] apart on a track
411/// `width` wide.
412fn step_marks(count: usize, width: f32) -> Vec<(f32, String)> {
413    if count == 0 {
414        return Vec::new();
415    }
416    let most = (width / MARK_SPACING).floor().max(1.0) as usize;
417    let stride = count.div_ceil(most).max(1);
418    (0..count)
419        .step_by(stride)
420        .map(|index| (position_of(index, 1.0, count), (index + 1).to_string()))
421        .collect()
422}
423
424/// The stretches from `left` to `right` that stay drawn around `gaps`, each
425/// gap given as its left and right x and widened by a small inset.
426fn pieces(left: f32, right: f32, gaps: &[(f32, f32)]) -> Vec<(f32, f32)> {
427    let mut pieces = Vec::with_capacity(gaps.len() + 1);
428    let mut start = left;
429    for (gap_left, gap_right) in gaps {
430        let end = (gap_left - BREAK_INSET).min(right);
431        if end > start {
432            pieces.push((start, end));
433        }
434        start = start.max(gap_right + BREAK_INSET);
435    }
436    if right > start {
437        pieces.push((start, right));
438    }
439    pieces
440}
441
442/// The step under `x`, for a track `width` wide holding `count` steps
443/// placed evenly from its left edge to its right edge.
444pub fn index_at(x: f32, width: f32, count: usize) -> usize {
445    if count < 2 || width <= 0.0 {
446        return 0;
447    }
448    let last = count - 1;
449    let fraction = (x / width).clamp(0.0, 1.0);
450    let index = (fraction * last as f32).round();
451    (index as usize).min(last)
452}
453
454/// Where step `index` sits along a track `width` wide.
455pub fn position_of(index: usize, width: f32, count: usize) -> f32 {
456    if count < 2 {
457        return 0.0;
458    }
459    width * index.min(count - 1) as f32 / (count - 1) as f32
460}
461
462/// The left and right edges of a span along a track `width` wide: half a
463/// step either side of its first and last steps, kept on the track.
464pub fn span_extent(span: Span, width: f32, count: usize) -> (f32, f32) {
465    let half = if count < 2 {
466        width / 2.0
467    } else {
468        width / (count - 1) as f32 / 2.0
469    };
470    let left = (position_of(span.start, width, count) - half).max(0.0);
471    let right = (position_of(span.end, width, count) + half).min(width);
472    (left, right.max(left))
473}
474
475/// The height of a timeline with `lanes` lanes.
476pub fn height(lanes: usize) -> f32 {
477    TRACK_HEIGHT + lanes as f32 * LANE_HEIGHT
478}
479
480/// The part of `bounds` a step maps onto: right of the labels, and inset by
481/// the playhead radius so the playhead never leaves the widget.
482pub fn track_bounds(bounds: Rectangle, labels: f32) -> Rectangle {
483    let left = if labels > 0.0 {
484        labels + space::SM
485    } else {
486        0.0
487    };
488    let x = bounds.x + left + PLAYHEAD_RADIUS;
489    Rectangle {
490        x,
491        y: bounds.y,
492        width: (bounds.width - left - PLAYHEAD_RADIUS * 2.0).max(0.0),
493        height: TRACK_HEIGHT,
494    }
495}
496
497/// What a timeline shortcut does.
498#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
499pub enum Action {
500    Previous,
501    Next,
502    PageBack,
503    PageForward,
504    First,
505    Last,
506}
507
508impl Action {
509    /// The step after this action, from `current` in a timeline of `count`
510    /// steps. Send it through the timeline's `on_select` message.
511    pub fn apply(self, current: usize, count: usize) -> usize {
512        let last = count.saturating_sub(1);
513        let current = current.min(last);
514        match self {
515            Action::Previous => current.saturating_sub(1),
516            Action::Next => (current + 1).min(last),
517            Action::PageBack => current.saturating_sub(PAGE),
518            Action::PageForward => (current + PAGE).min(last),
519            Action::First => 0,
520            Action::Last => last,
521        }
522    }
523}
524
525impl keys::Action for Action {
526    const ALL: &'static [Self] = &[
527        Action::Previous,
528        Action::Next,
529        Action::PageBack,
530        Action::PageForward,
531        Action::First,
532        Action::Last,
533    ];
534
535    fn defaults() -> Keymap<Self> {
536        default_keymap()
537    }
538
539    fn name(self) -> &'static str {
540        match self {
541            Action::Previous => "Previous",
542            Action::Next => "Next",
543            Action::PageBack => "Page back",
544            Action::PageForward => "Page forward",
545            Action::First => "First",
546            Action::Last => "Last",
547        }
548    }
549
550    fn description(self) -> &'static str {
551        match self {
552            Action::Previous => "Moves to the step before the current one.",
553            Action::Next => "Moves to the step after the current one.",
554            Action::PageBack => "Moves ten steps back.",
555            Action::PageForward => "Moves ten steps forward.",
556            Action::First => "Moves to the first step.",
557            Action::Last => "Moves to the last step.",
558        }
559    }
560}
561
562/// The default timeline shortcuts:
563///
564/// | Keys | Action |
565/// | --- | --- |
566/// | `ArrowLeft` | [`Action::Previous`] |
567/// | `ArrowRight` | [`Action::Next`] |
568/// | `Shift+ArrowLeft`, `PageUp` | [`Action::PageBack`] |
569/// | `Shift+ArrowRight`, `PageDown` | [`Action::PageForward`] |
570/// | `Home` | [`Action::First`] |
571/// | `End` | [`Action::Last`] |
572///
573/// The timeline resolves them itself while it has keyboard focus or was the
574/// last thing pressed. Pass a changed keymap with [`Timeline::keymap`].
575pub fn default_keymap() -> Keymap<Action> {
576    Keymap::new()
577        .bind(Chord::named(Named::ArrowLeft), Action::Previous)
578        .bind(Chord::named(Named::ArrowRight), Action::Next)
579        .bind(Chord::named(Named::ArrowLeft).shift(), Action::PageBack)
580        .bind(Chord::named(Named::PageUp), Action::PageBack)
581        .bind(Chord::named(Named::ArrowRight).shift(), Action::PageForward)
582        .bind(Chord::named(Named::PageDown), Action::PageForward)
583        .bind(Chord::named(Named::Home), Action::First)
584        .bind(Chord::named(Named::End), Action::Last)
585}
586
587/// How the pointer is interacting with a timeline.
588#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
589pub enum Status {
590    #[default]
591    Active,
592    Hovered,
593    Dragged,
594    Disabled,
595}
596
597impl Status {
598    pub const ALL: [Status; 4] = [
599        Status::Active,
600        Status::Hovered,
601        Status::Dragged,
602        Status::Disabled,
603    ];
604}
605
606/// Colours of a timeline in one status.
607#[derive(Debug, Clone, Copy, PartialEq)]
608pub struct Style {
609    pub rail: Color,
610    pub lane: Color,
611    pub label: Color,
612    pub playhead: Color,
613    pub playhead_border: Color,
614    pub playhead_border_width: f32,
615    /// The line from the playhead down through the lanes.
616    pub cursor: Color,
617    /// The outline round the step under the pointer.
618    pub hover: Color,
619    /// The ruler's tick marks.
620    pub mark: Color,
621    /// Multiplies the alpha of tone colours.
622    pub tone_alpha: f32,
623}
624
625/// Resolves the colours of a timeline for a status.
626pub fn style(tokens: &Tokens, status: Status) -> Style {
627    let border = match status {
628        Status::Active | Status::Disabled => tokens.primary,
629        Status::Hovered => mix(tokens.primary, tokens.background, 0.15),
630        Status::Dragged => mix(tokens.primary, tokens.background, 0.3),
631    };
632    let style = Style {
633        rail: mix(tokens.muted, tokens.border, 0.5),
634        lane: tokens.muted,
635        label: tokens.muted_foreground,
636        playhead: tokens.background,
637        playhead_border: border,
638        playhead_border_width: match status {
639            Status::Hovered | Status::Dragged => 2.5,
640            Status::Active | Status::Disabled => 2.0,
641        },
642        cursor: fade(tokens.primary, 0.4),
643        hover: fade(tokens.primary, 0.5),
644        mark: fade(tokens.muted_foreground, 0.6),
645        tone_alpha: 1.0,
646    };
647    if status != Status::Disabled {
648        return style;
649    }
650    Style {
651        rail: fade(style.rail, 0.5),
652        lane: fade(style.lane, 0.5),
653        label: fade(style.label, 0.5),
654        playhead_border: fade(style.playhead_border, 0.5),
655        cursor: fade(style.cursor, 0.5),
656        hover: fade(style.hover, 0.5),
657        mark: fade(style.mark, 0.5),
658        tone_alpha: 0.5,
659        ..style
660    }
661}
662
663#[derive(Debug, Default)]
664struct State {
665    dragging: bool,
666    hovered: bool,
667    finger: Option<touch::Finger>,
668    last: Option<usize>,
669    /// The step under the pointer.
670    hover: Option<usize>,
671    keys: focus::Scope,
672}
673
674impl<Message> Timeline<'_, Message> {
675    /// Whether it takes keyboard focus and keys, and reacts to the pointer.
676    fn is_focusable(&self) -> bool {
677        self.on_select.is_some() && !self.steps.is_empty()
678    }
679
680    /// Whether it follows the step under the pointer.
681    fn is_hoverable(&self) -> bool {
682        (self.on_select.is_some() || self.on_hover.is_some()) && !self.steps.is_empty()
683    }
684
685    /// Sends the step under `x` when it differs from the last one sent. A
686    /// press starts from the current step, so a drag that comes back to it
687    /// within one batch of events still sends it.
688    fn select(&self, state: &mut State, x: f32, track: Rectangle, shell: &mut Shell<'_, Message>) {
689        let Some(on_select) = &self.on_select else {
690            return;
691        };
692        let index = self.index_under(x, track);
693        if state.last != Some(index) {
694            shell.publish(on_select(index));
695        }
696        state.last = Some(index);
697    }
698
699    /// Records the step under the pointer and reports it when it changes.
700    /// Returns whether it changed.
701    fn hover(
702        &self,
703        state: &mut State,
704        hover: Option<usize>,
705        shell: &mut Shell<'_, Message>,
706    ) -> bool {
707        if state.hover == hover {
708            return false;
709        }
710        state.hover = hover;
711        if let Some(on_hover) = &self.on_hover {
712            shell.publish(on_hover(hover));
713        }
714        true
715    }
716
717    /// The bounds it reports as a slider and for focus: from the first
718    /// tick to the last, as tall as the playhead, so a value maps evenly
719    /// onto the ticks of evenly placed steps. When every tick sits in one
720    /// place, the playhead's room on the track.
721    fn reported(&self, track: Rectangle) -> Rectangle {
722        let room = focus_target(track);
723        let last = self.steps.len().saturating_sub(1);
724        let left = self.x_of(0, track);
725        let width = self.x_of(last, track) - left;
726        if width <= 0.0 {
727            return room;
728        }
729        Rectangle {
730            x: left,
731            width,
732            ..room
733        }
734    }
735
736    fn status(&self, state: &State, layout: Layout<'_>, cursor: mouse::Cursor) -> Status {
737        if self.on_select.is_none() {
738            return Status::Disabled;
739        }
740        if state.dragging {
741            return Status::Dragged;
742        }
743        if cursor.is_over(layout.bounds()) {
744            return Status::Hovered;
745        }
746        Status::Active
747    }
748}
749
750/// The track row with room for the playhead, which focus reports and the
751/// ring surrounds.
752fn focus_target(track: Rectangle) -> Rectangle {
753    let middle = track.center_y();
754    Rectangle {
755        x: track.x - PLAYHEAD_RADIUS,
756        y: middle - PLAYHEAD_RADIUS,
757        width: track.width + PLAYHEAD_RADIUS * 2.0,
758        height: PLAYHEAD_RADIUS * 2.0,
759    }
760}
761
762/// How tall a step's tick is. Toned steps stand taller, as tall as the
763/// playhead, so they stand out in a long run.
764fn tick_height(tone: Tone) -> f32 {
765    if tone == Tone::Neutral {
766        8.0
767    } else {
768        PLAYHEAD_RADIUS * 2.0
769    }
770}
771
772/// How tall the current step's tick is inside a playhead whose border is
773/// `border` wide, leaving a pixel clear of the border at either end.
774fn playhead_tick(border: f32) -> f32 {
775    ((PLAYHEAD_RADIUS - border) * 2.0 - 2.0).max(0.0)
776}
777
778fn fill(renderer: &mut Renderer, bounds: Rectangle, colour: Color, corner: f32) {
779    <Renderer as renderer::Renderer>::fill_quad(
780        renderer,
781        renderer::Quad {
782            bounds,
783            border: Border {
784                radius: corner.into(),
785                ..Border::default()
786            },
787            ..renderer::Quad::default()
788        },
789        colour,
790    );
791}
792
793/// Small text aligned by `align_x` on `at`, centred vertically on it and
794/// clipped to `clip`.
795fn caption(
796    renderer: &mut Renderer,
797    content: &str,
798    at: Point,
799    align_x: text::Alignment,
800    colour: Color,
801    clip: Rectangle,
802) {
803    <Renderer as core_text::Renderer>::fill_text(
804        renderer,
805        core_text::Text {
806            content: content.to_owned(),
807            bounds: Size::new(f32::INFINITY, LANE_HEIGHT),
808            size: Pixels(text_size::XS),
809            line_height: LineHeight::Absolute(Pixels(LANE_HEIGHT)),
810            font: theme::font(),
811            align_x,
812            align_y: Vertical::Center,
813            shaping: Shaping::Advanced,
814            wrapping: Wrapping::None,
815        },
816        at,
817        colour,
818        clip,
819    );
820}
821
822fn label(renderer: &mut Renderer, content: &str, bounds: Rectangle, colour: Color) {
823    caption(
824        renderer,
825        content,
826        Point::new(bounds.x, bounds.center_y()),
827        text::Alignment::Left,
828        colour,
829        bounds,
830    );
831}
832
833/// How a ruler label at `x` lines up: with the nearer edge of `bounds`
834/// when it is close to one, so it is never cut off, and centred otherwise.
835fn mark_alignment(x: f32, bounds: Rectangle) -> text::Alignment {
836    if x - bounds.x < EDGE_LABEL {
837        text::Alignment::Left
838    } else if bounds.x + bounds.width - x < EDGE_LABEL {
839        text::Alignment::Right
840    } else {
841        text::Alignment::Center
842    }
843}
844
845impl<Message> Widget<Message, Theme, Renderer> for Timeline<'_, Message> {
846    fn size(&self) -> Size<Length> {
847        Size::new(self.width, Length::Fixed(self.total_height()))
848    }
849
850    fn tag(&self) -> tree::Tag {
851        tree::Tag::of::<State>()
852    }
853
854    fn state(&self) -> tree::State {
855        tree::State::new(State::default())
856    }
857
858    fn layout(
859        &mut self,
860        _tree: &mut Tree,
861        _renderer: &Renderer,
862        limits: &layout::Limits,
863    ) -> layout::Node {
864        let height = self.total_height();
865        layout::Node::new(limits.resolve(self.width, Length::Fixed(height), Size::new(0.0, height)))
866    }
867
868    fn draw(
869        &self,
870        tree: &Tree,
871        renderer: &mut Renderer,
872        theme: &Theme,
873        _style: &renderer::Style,
874        layout: Layout<'_>,
875        cursor: mouse::Cursor,
876        _viewport: &Rectangle,
877    ) {
878        let tokens = Tokens::of(theme);
879        let state = tree.state.downcast_ref::<State>();
880        let style = style(&tokens, self.status(state, layout, cursor));
881        let bounds = layout.bounds();
882        let labels = self.labels();
883        let track = track_bounds(bounds, labels);
884        let count = self.steps.len();
885        let middle = track.center_y();
886        let breaks = self.breaks(track);
887        let pieces = pieces(
888            track.x - PLAYHEAD_RADIUS,
889            track.x + track.width + PLAYHEAD_RADIUS,
890            &breaks,
891        );
892        // Each break leaves a gap in the bars with a slash pair over it.
893        let bars = |renderer: &mut Renderer, y: f32, height: f32, colour: Color| {
894            for (left, right) in &pieces {
895                fill(
896                    renderer,
897                    Rectangle {
898                        x: *left,
899                        y: y - height / 2.0,
900                        width: right - left,
901                        height,
902                    },
903                    colour,
904                    radius::FULL,
905                );
906            }
907        };
908
909        bars(renderer, middle, RAIL_HEIGHT, style.rail);
910        for (left, right) in &breaks {
911            caption(
912                renderer,
913                "//",
914                Point::new((left + right) / 2.0, middle),
915                text::Alignment::Center,
916                style.label,
917                bounds,
918            );
919        }
920        if state.keys.is_focused() && self.is_focusable() {
921            focus::draw_ring(renderer, theme, focus_target(track), radius::FULL);
922        }
923
924        for (index, lane) in self.lanes.iter().enumerate() {
925            let row = Rectangle {
926                x: bounds.x,
927                y: bounds.y + TRACK_HEIGHT + index as f32 * LANE_HEIGHT,
928                width: bounds.width,
929                height: LANE_HEIGHT,
930            };
931            label(
932                renderer,
933                &lane.label,
934                Rectangle {
935                    width: labels,
936                    ..row
937                },
938                style.label,
939            );
940            let bar_y = row.center_y() - BAR_HEIGHT / 2.0;
941            bars(renderer, row.center_y(), BAR_HEIGHT, style.lane);
942            for span in &lane.spans {
943                if span.start >= count {
944                    continue;
945                }
946                let (left, right) = self.extent(*span, track);
947                let (left, right) = (
948                    track.x + left,
949                    track.x + (right - left).max(BAR_HEIGHT) + left,
950                );
951                for (left, right) in self::pieces(left, right, &breaks) {
952                    fill(
953                        renderer,
954                        Rectangle {
955                            x: left,
956                            y: bar_y,
957                            width: right - left,
958                            height: BAR_HEIGHT,
959                        },
960                        fade(span.tone.colour(&tokens), style.tone_alpha),
961                        radius::FULL,
962                    );
963                }
964            }
965        }
966
967        if self.ruler {
968            let top = bounds.y + height(self.lanes.len());
969            // Labels line up with the ends of the track, not the widget, so
970            // the first never runs under the lane labels.
971            let span = Rectangle {
972                x: track.x - PLAYHEAD_RADIUS,
973                width: track.width + PLAYHEAD_RADIUS * 2.0,
974                ..bounds
975            };
976            for (place, mark) in self.marks(track.width) {
977                let x = track.x + place * track.width;
978                fill(
979                    renderer,
980                    Rectangle {
981                        x: x - 0.5,
982                        y: top,
983                        width: 1.0,
984                        height: MARK_HEIGHT,
985                    },
986                    style.mark,
987                    0.0,
988                );
989                caption(
990                    renderer,
991                    &mark,
992                    Point::new(x, top + (RULER_HEIGHT + MARK_HEIGHT) / 2.0),
993                    mark_alignment(x, span),
994                    style.label,
995                    bounds,
996                );
997            }
998        }
999
1000        for (index, tone) in self.steps.iter().enumerate() {
1001            let tall = tick_height(*tone);
1002            fill(
1003                renderer,
1004                Rectangle {
1005                    x: self.x_of(index, track) - TICK_WIDTH / 2.0,
1006                    y: middle - tall / 2.0,
1007                    width: TICK_WIDTH,
1008                    height: tall,
1009                },
1010                fade(tone.colour(&tokens), style.tone_alpha),
1011                0.0,
1012            );
1013        }
1014
1015        if count == 0 {
1016            return;
1017        }
1018        let x = self.x_of(self.current, track);
1019        if !self.lanes.is_empty() {
1020            fill(
1021                renderer,
1022                Rectangle {
1023                    x: x - 0.5,
1024                    y: middle,
1025                    width: 1.0,
1026                    height: bounds.y + height(self.lanes.len()) - middle,
1027                },
1028                style.cursor,
1029                0.0,
1030            );
1031        }
1032        if let Some(hover) = state.hover
1033            && hover != self.current
1034            && hover < count
1035            && !state.dragging
1036            && self.is_hoverable()
1037        {
1038            let x = self.x_of(hover, track);
1039            <Renderer as renderer::Renderer>::fill_quad(
1040                renderer,
1041                renderer::Quad {
1042                    bounds: Rectangle {
1043                        x: x - PLAYHEAD_RADIUS,
1044                        y: middle - PLAYHEAD_RADIUS,
1045                        width: PLAYHEAD_RADIUS * 2.0,
1046                        height: PLAYHEAD_RADIUS * 2.0,
1047                    },
1048                    border: Border {
1049                        color: style.hover,
1050                        width: 1.5,
1051                        radius: PLAYHEAD_RADIUS.into(),
1052                    },
1053                    ..renderer::Quad::default()
1054                },
1055                Color::TRANSPARENT,
1056            );
1057        }
1058        <Renderer as renderer::Renderer>::fill_quad(
1059            renderer,
1060            renderer::Quad {
1061                bounds: Rectangle {
1062                    x: x - PLAYHEAD_RADIUS,
1063                    y: middle - PLAYHEAD_RADIUS,
1064                    width: PLAYHEAD_RADIUS * 2.0,
1065                    height: PLAYHEAD_RADIUS * 2.0,
1066                },
1067                border: Border {
1068                    color: style.playhead_border,
1069                    width: style.playhead_border_width,
1070                    radius: PLAYHEAD_RADIUS.into(),
1071                },
1072                ..renderer::Quad::default()
1073            },
1074            style.playhead,
1075        );
1076        // The current step's tick shows through the playhead, so its tone
1077        // is never hidden.
1078        if let Some(tone) = self.steps.get(self.current) {
1079            let tall = playhead_tick(style.playhead_border_width);
1080            fill(
1081                renderer,
1082                Rectangle {
1083                    x: x - TICK_WIDTH / 2.0,
1084                    y: middle - tall / 2.0,
1085                    width: TICK_WIDTH,
1086                    height: tall,
1087                },
1088                fade(tone.colour(&tokens), style.tone_alpha),
1089                0.0,
1090            );
1091        }
1092    }
1093
1094    fn update(
1095        &mut self,
1096        tree: &mut Tree,
1097        event: &Event,
1098        layout: Layout<'_>,
1099        cursor: mouse::Cursor,
1100        _renderer: &Renderer,
1101        _clipboard: &mut dyn Clipboard,
1102        shell: &mut Shell<'_, Message>,
1103        _viewport: &Rectangle,
1104    ) {
1105        let state = tree.state.downcast_mut::<State>();
1106        let bounds = layout.bounds();
1107        let track = track_bounds(bounds, self.labels());
1108        // Presses on the lane labels pick nothing.
1109        let pressable = Rectangle {
1110            x: track.x - PLAYHEAD_RADIUS,
1111            width: track.width + PLAYHEAD_RADIUS * 2.0,
1112            ..bounds
1113        };
1114        // A drag reports its steps through `on_select`, so hovering waits
1115        // for the next move after it ends.
1116        let hover = if !self.is_hoverable() {
1117            Some(None)
1118        } else if state.dragging {
1119            None
1120        } else {
1121            match event {
1122                Event::Mouse(mouse::Event::CursorMoved { position }) => {
1123                    // An overlay over the timeline hides the pointer from it.
1124                    let covered = matches!(cursor, mouse::Cursor::Levitating(_));
1125                    let over = !covered && pressable.contains(*position);
1126                    Some(over.then(|| self.index_under(position.x, track)))
1127                }
1128                Event::Mouse(mouse::Event::CursorLeft) => Some(None),
1129                _ => None,
1130            }
1131        };
1132        let hovered = hover.is_some_and(|hover| self.hover(state, hover, shell));
1133        if !self.is_focusable() {
1134            if state.keys.release() || hovered {
1135                shell.request_redraw();
1136            }
1137            return;
1138        }
1139        let before = (state.dragging, state.hovered);
1140        state.hovered = cursor.is_over(bounds);
1141        let keyed = state.keys.update(event, cursor, pressable);
1142        match event {
1143            Event::Mouse(mouse::Event::ButtonPressed(button)) => {
1144                let position = cursor.position_over(pressable);
1145                if let (mouse::Button::Left, Some(position)) = (button, position) {
1146                    state.dragging = true;
1147                    state.last = Some(self.current);
1148                    self.select(state, position.x, track, shell);
1149                    shell.capture_event();
1150                }
1151            }
1152            Event::Touch(touch::Event::FingerPressed { id, position }) => {
1153                if pressable.contains(*position) && !state.dragging {
1154                    state.dragging = true;
1155                    state.finger = Some(*id);
1156                    state.last = Some(self.current);
1157                    self.select(state, position.x, track, shell);
1158                    shell.capture_event();
1159                }
1160            }
1161            Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. })
1162                if state.keys.has_keys() && !shell.is_event_captured() =>
1163            {
1164                if let Some(action) = self.keymap.resolve(key, *modifiers) {
1165                    let next = action.apply(self.current, self.steps.len());
1166                    if let Some(on_select) = &self.on_select
1167                        && next != self.current
1168                    {
1169                        shell.publish(on_select(next));
1170                    }
1171                    shell.capture_event();
1172                }
1173            }
1174            Event::Mouse(mouse::Event::CursorMoved { position })
1175                if state.dragging && state.finger.is_none() =>
1176            {
1177                self.select(state, position.x, track, shell);
1178            }
1179            Event::Touch(touch::Event::FingerMoved { id, position })
1180                if state.finger == Some(*id) =>
1181            {
1182                self.select(state, position.x, track, shell);
1183                shell.capture_event();
1184            }
1185            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
1186                if state.dragging && state.finger.is_none() =>
1187            {
1188                state.dragging = false;
1189                state.last = None;
1190                shell.capture_event();
1191            }
1192            Event::Touch(
1193                touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. },
1194            ) if state.finger == Some(*id) => {
1195                state.dragging = false;
1196                state.finger = None;
1197                state.last = None;
1198                shell.capture_event();
1199            }
1200            _ => {}
1201        }
1202        if keyed || hovered || (state.dragging, state.hovered) != before {
1203            shell.request_redraw();
1204        }
1205    }
1206
1207    fn mouse_interaction(
1208        &self,
1209        tree: &Tree,
1210        layout: Layout<'_>,
1211        cursor: mouse::Cursor,
1212        _viewport: &Rectangle,
1213        _renderer: &Renderer,
1214    ) -> mouse::Interaction {
1215        if self.on_select.is_none() {
1216            return mouse::Interaction::None;
1217        }
1218        if tree.state.downcast_ref::<State>().dragging {
1219            return mouse::Interaction::Grabbing;
1220        }
1221        if cursor.is_over(layout.bounds()) {
1222            return mouse::Interaction::Pointer;
1223        }
1224        mouse::Interaction::None
1225    }
1226
1227    fn operate(
1228        &mut self,
1229        tree: &mut Tree,
1230        layout: Layout<'_>,
1231        _renderer: &Renderer,
1232        operation: &mut dyn iced::advanced::widget::Operation,
1233    ) {
1234        let target = self.reported(track_bounds(layout.bounds(), self.labels()));
1235        #[cfg(feature = "icedwright")]
1236        {
1237            use icedwright_probe::{Annotation, report, role};
1238
1239            let enabled = self.on_select.is_some();
1240            let last = self.steps.len().saturating_sub(1) as f64;
1241            // A timed timeline also reports when the current step began.
1242            let time = self.timing.as_ref().and_then(|_| {
1243                let until = (self.current + 1).min(self.times.len());
1244                let time = self.times.get(..until)?.iter().max()?;
1245                Some(time.as_millis().to_string())
1246            });
1247            report(operation, target, || {
1248                let annotation = Annotation::new()
1249                    .role(role::Slider)
1250                    .name(self.name.to_string())
1251                    .range(self.current as f64, 0.0..=last)
1252                    .step(1.0)
1253                    .disabled(!enabled)
1254                    .component("iced_cube::timeline");
1255                match time.clone() {
1256                    Some(time) => annotation.prop("time_ms", time),
1257                    None => annotation,
1258                }
1259            });
1260        }
1261        // Reported after the annotation, at the same bounds, so a recorder
1262        // merges the two into one node.
1263        let state = tree.state.downcast_mut::<State>();
1264        if self.is_focusable() {
1265            focus::report(operation, None, target, &mut state.keys);
1266        } else {
1267            let _ = state.keys.release();
1268        }
1269    }
1270}
1271
1272impl<'a, Message: 'a> From<Timeline<'a, Message>> for Element<'a, Message> {
1273    fn from(timeline: Timeline<'a, Message>) -> Self {
1274        Element::new(timeline)
1275    }
1276}
1277
1278#[cfg(test)]
1279mod tests {
1280    use super::*;
1281    use crate::keys::Action as _;
1282    use crate::theme::{dark, light};
1283
1284    fn bounds() -> Rectangle {
1285        Rectangle {
1286            x: 10.0,
1287            y: 20.0,
1288            width: 400.0,
1289            height: 100.0,
1290        }
1291    }
1292
1293    #[test]
1294    fn default_builder_fills_the_width_and_is_disabled() {
1295        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 1);
1296        assert_eq!(t.width, Length::Fill);
1297        assert_eq!(t.name, "Timeline");
1298        assert_eq!(t.label_width, LABEL_WIDTH);
1299        assert!(t.lanes.is_empty());
1300        assert!(!t.is_enabled());
1301        assert!(t.on_select(|_| ()).is_enabled());
1302    }
1303
1304    #[test]
1305    fn the_current_step_is_clamped_to_the_steps() {
1306        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 9);
1307        assert_eq!(t.current(), 2);
1308        let t: Timeline<'_, ()> = timeline([], 4);
1309        assert_eq!(t.current(), 0);
1310        assert!(t.is_empty());
1311    }
1312
1313    #[test]
1314    fn spans_are_ordered_and_take_a_tone() {
1315        let span = Span::new(5, 2).tone(Tone::Warning);
1316        assert_eq!((span.start, span.end, span.tone), (2, 5, Tone::Warning));
1317        assert_eq!(Span::new(1, 1).tone, Tone::Neutral);
1318    }
1319
1320    #[test]
1321    fn positions_and_indices_agree_at_every_step() {
1322        for count in [1, 2, 3, 10, 57] {
1323            for index in 0..count {
1324                let x = position_of(index, 600.0, count);
1325                assert_eq!(index_at(x, 600.0, count), index, "{index} of {count}");
1326            }
1327        }
1328    }
1329
1330    #[test]
1331    fn points_outside_the_track_clamp_to_the_ends() {
1332        assert_eq!(index_at(-50.0, 100.0, 5), 0);
1333        assert_eq!(index_at(150.0, 100.0, 5), 4);
1334        assert_eq!(index_at(10.0, 0.0, 5), 0);
1335        assert_eq!(index_at(10.0, 100.0, 0), 0);
1336    }
1337
1338    #[test]
1339    fn points_go_to_the_nearest_step() {
1340        assert_eq!(index_at(24.0, 100.0, 5), 1);
1341        assert_eq!(index_at(26.0, 100.0, 5), 1);
1342        assert_eq!(index_at(38.0, 100.0, 5), 2);
1343    }
1344
1345    #[test]
1346    fn a_span_reaches_half_a_step_either_side_and_stays_on_the_track() {
1347        assert_eq!(span_extent(Span::new(1, 2), 100.0, 5), (12.5, 62.5));
1348        assert_eq!(span_extent(Span::new(0, 4), 100.0, 5), (0.0, 100.0));
1349        assert_eq!(span_extent(Span::new(3, 3), 100.0, 1), (0.0, 50.0));
1350    }
1351
1352    #[test]
1353    fn the_track_sits_right_of_the_labels_and_inside_the_playhead() {
1354        let track = track_bounds(bounds(), 0.0);
1355        assert_eq!(track.x, 10.0 + PLAYHEAD_RADIUS);
1356        assert_eq!(track.width, 400.0 - PLAYHEAD_RADIUS * 2.0);
1357        assert_eq!(track.height, TRACK_HEIGHT);
1358        let track = track_bounds(bounds(), 96.0);
1359        assert_eq!(track.x, 10.0 + 96.0 + space::SM + PLAYHEAD_RADIUS);
1360        let narrow = Rectangle {
1361            width: 20.0,
1362            ..bounds()
1363        };
1364        assert_eq!(track_bounds(narrow, 96.0).width, 0.0);
1365    }
1366
1367    #[test]
1368    fn height_grows_by_a_row_per_lane() {
1369        assert_eq!(height(0), TRACK_HEIGHT);
1370        assert_eq!(height(2), TRACK_HEIGHT + 2.0 * LANE_HEIGHT);
1371    }
1372
1373    #[test]
1374    fn actions_move_within_the_steps() {
1375        assert_eq!(Action::Previous.apply(3, 10), 2);
1376        assert_eq!(Action::Previous.apply(0, 10), 0);
1377        assert_eq!(Action::Next.apply(3, 10), 4);
1378        assert_eq!(Action::Next.apply(9, 10), 9);
1379        assert_eq!(Action::PageBack.apply(4, 30), 0);
1380        assert_eq!(Action::PageBack.apply(14, 30), 4);
1381        assert_eq!(Action::PageForward.apply(25, 30), 29);
1382        assert_eq!(Action::PageForward.apply(5, 30), 15);
1383        assert_eq!(Action::First.apply(7, 10), 0);
1384        assert_eq!(Action::Last.apply(2, 10), 9);
1385        assert_eq!(Action::Last.apply(0, 0), 0);
1386        assert_eq!(Action::Next.apply(50, 10), 9);
1387    }
1388
1389    fn resolve(keymap: &Keymap<Action>, chord: Chord) -> Option<Action> {
1390        keymap.resolve(chord.key(), chord.modifiers())
1391    }
1392
1393    #[test]
1394    fn default_keymap_binds_arrows_pages_and_ends() {
1395        let keymap = default_keymap();
1396        assert_eq!(
1397            resolve(&keymap, Chord::named(Named::ArrowLeft)),
1398            Some(Action::Previous)
1399        );
1400        assert_eq!(
1401            resolve(&keymap, Chord::named(Named::ArrowRight).shift()),
1402            Some(Action::PageForward)
1403        );
1404        assert_eq!(
1405            resolve(&keymap, Chord::named(Named::PageUp)),
1406            Some(Action::PageBack)
1407        );
1408        assert_eq!(
1409            resolve(&keymap, Chord::named(Named::End)),
1410            Some(Action::Last)
1411        );
1412        assert_eq!(Keymap::<Action>::defaults(), keymap);
1413        for action in Action::ALL {
1414            assert!(!action.name().is_empty());
1415            assert!(action.description().ends_with('.'));
1416        }
1417    }
1418
1419    #[test]
1420    fn keymap_overrides_and_unbinding() {
1421        let keymap = default_keymap()
1422            .bind(Chord::character('j'), Action::Next)
1423            .unbind(&Chord::named(Named::Home));
1424        assert_eq!(resolve(&keymap, Chord::character('j')), Some(Action::Next));
1425        assert_eq!(resolve(&keymap, Chord::named(Named::Home)), None);
1426        assert_eq!(
1427            resolve(&keymap, Chord::named(Named::End)),
1428            Some(Action::Last)
1429        );
1430    }
1431
1432    #[test]
1433    fn style_follows_the_status_in_light_and_dark() {
1434        for theme in [light(), dark()] {
1435            let tokens = Tokens::of(&theme);
1436            let active = style(&tokens, Status::Active);
1437            assert_eq!(active.playhead_border, tokens.primary);
1438            assert_eq!(active.playhead, tokens.background);
1439            assert_eq!(active.tone_alpha, 1.0);
1440            let hovered = style(&tokens, Status::Hovered);
1441            assert_ne!(hovered.playhead_border, active.playhead_border);
1442            assert!(hovered.playhead_border_width > active.playhead_border_width);
1443            let dragged = style(&tokens, Status::Dragged);
1444            assert_ne!(dragged.playhead_border, hovered.playhead_border);
1445            let disabled = style(&tokens, Status::Disabled);
1446            assert!(disabled.rail.a < active.rail.a);
1447            assert!(disabled.playhead_border.a < active.playhead_border.a);
1448            assert_eq!(disabled.tone_alpha, 0.5);
1449            assert!(disabled.hover.a < active.hover.a);
1450            assert_eq!(Status::ALL.len(), 4);
1451        }
1452    }
1453
1454    #[test]
1455    fn the_current_tick_fits_inside_the_playhead_in_every_status() {
1456        let tokens = Tokens::of(&light());
1457        for status in Status::ALL {
1458            let border = style(&tokens, status).playhead_border_width;
1459            let tall = playhead_tick(border);
1460            assert!(tall >= 4.0, "{status:?} leaves the tick visible");
1461            assert!(tall < (PLAYHEAD_RADIUS - border) * 2.0, "{status:?}");
1462        }
1463        assert!(tick_height(Tone::Warning) > tick_height(Tone::Neutral));
1464    }
1465
1466    #[test]
1467    fn times_place_the_steps_and_fill_in_missing_ones() {
1468        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 4], 0).times([
1469            Duration::from_secs(0),
1470            Duration::from_secs(1),
1471            Duration::from_secs(4),
1472        ]);
1473        let Some(timing) = t.timing() else {
1474            panic!("timed");
1475        };
1476        assert_eq!(timing.positions().len(), 4);
1477        assert!(timing.positions()[3] > timing.positions()[2]);
1478        let track = Rectangle {
1479            x: 0.0,
1480            y: 0.0,
1481            width: 400.0,
1482            height: TRACK_HEIGHT,
1483        };
1484        assert_eq!(t.index_under(0.0, track), 0);
1485        assert_eq!(t.index_under(400.0, track), 3);
1486
1487        let even: Timeline<'_, ()> = timeline([Tone::Neutral; 4], 0);
1488        assert!(even.timing().is_none());
1489        assert_eq!(even.place_of(1), 1.0 / 3.0);
1490    }
1491
1492    #[test]
1493    fn end_and_compression_apply_in_any_order() {
1494        let times = [Duration::from_secs(0), Duration::from_secs(100)];
1495        let a: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
1496            .compress_gaps(Duration::from_secs(1))
1497            .end(Duration::from_secs(101))
1498            .times(times);
1499        let b: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
1500            .times(times)
1501            .end(Duration::from_secs(101))
1502            .compress_gaps(Duration::from_secs(1));
1503        assert_eq!(a.timing(), b.timing());
1504        assert_eq!(a.timing().map(|t| t.breaks().len()), Some(1));
1505    }
1506
1507    #[test]
1508    fn the_ruler_adds_a_row_below_the_lanes() {
1509        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 0);
1510        assert_eq!(t.total_height(), TRACK_HEIGHT);
1511        let t = t.ruler(true).lane(lane("A", []));
1512        assert_eq!(t.total_height(), TRACK_HEIGHT + LANE_HEIGHT + RULER_HEIGHT);
1513    }
1514
1515    #[test]
1516    fn even_rulers_number_the_steps_and_thin_out_when_narrow() {
1517        let marks = step_marks(5, 640.0);
1518        let labels: Vec<&str> = marks.iter().map(|(_, label)| label.as_str()).collect();
1519        assert_eq!(labels, ["1", "2", "3", "4", "5"]);
1520        assert_eq!(marks[4].0, 1.0);
1521        let narrow = step_marks(100, 320.0);
1522        assert_eq!(narrow.len(), 5);
1523        assert_eq!(narrow[1].1, "21");
1524        assert!(step_marks(0, 320.0).is_empty());
1525    }
1526
1527    #[test]
1528    fn timed_rulers_use_the_format() {
1529        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
1530            .times([Duration::from_secs(0), Duration::from_secs(2)])
1531            .ruler(true);
1532        let labels: Vec<String> = t.marks(128.0).into_iter().map(|(_, l)| l).collect();
1533        assert_eq!(labels, ["0 s", "1 s", "2 s"]);
1534        let t = t.ruler_format(|time| format!("t+{}", time.as_secs()));
1535        let labels: Vec<String> = t.marks(128.0).into_iter().map(|(_, l)| l).collect();
1536        assert_eq!(labels, ["t+0", "t+1", "t+2"]);
1537    }
1538
1539    #[test]
1540    fn breaks_cut_gaps_in_the_bars() {
1541        assert_eq!(pieces(0.0, 100.0, &[]), [(0.0, 100.0)]);
1542        assert_eq!(
1543            pieces(0.0, 100.0, &[(40.0, 60.0)]),
1544            [(0.0, 40.0 - BREAK_INSET), (60.0 + BREAK_INSET, 100.0)]
1545        );
1546        assert_eq!(pieces(0.0, 100.0, &[(0.0, 100.0)]), []);
1547    }
1548
1549    #[test]
1550    fn labels_near_an_edge_line_up_with_it() {
1551        let bounds = Rectangle {
1552            x: 0.0,
1553            y: 0.0,
1554            width: 300.0,
1555            height: 40.0,
1556        };
1557        assert_eq!(mark_alignment(6.0, bounds), text::Alignment::Left);
1558        assert_eq!(mark_alignment(150.0, bounds), text::Alignment::Center);
1559        assert_eq!(mark_alignment(294.0, bounds), text::Alignment::Right);
1560    }
1561}