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. Shortcuts act
8//! only while the timeline has keyboard focus (Tab reaches it) or was the
9//! last thing pressed, so several on one screen never fight over keys.
10
11use std::borrow::Cow;
12
13use iced::advanced::layout::{self, Layout};
14use iced::advanced::text as core_text;
15use iced::advanced::widget::{Tree, Widget, tree};
16use iced::advanced::{Clipboard, Shell, renderer};
17use iced::alignment::Vertical;
18use iced::keyboard::{self, key::Named};
19use iced::widget::text::{self, LineHeight, Shaping, Wrapping};
20use iced::{
21    Border, Color, Element, Event, Length, Pixels, Point, Rectangle, Renderer, Size, Theme, mouse,
22    touch,
23};
24
25use crate::focus;
26use crate::keys::{self, Chord, Keymap};
27use crate::theme::{self, Tokens, fade, mix, radius, space, text_size};
28
29/// Height of the track row.
30pub const TRACK_HEIGHT: f32 = 28.0;
31/// Height of one lane row.
32pub const LANE_HEIGHT: f32 = 20.0;
33/// Width of the lane labels when the timeline has lanes.
34pub const LABEL_WIDTH: f32 = 96.0;
35/// Radius of the playhead.
36pub const PLAYHEAD_RADIUS: f32 = 6.0;
37/// Steps that a page action moves.
38pub const PAGE: usize = 10;
39
40const RAIL_HEIGHT: f32 = 4.0;
41const TICK_WIDTH: f32 = 2.0;
42const BAR_HEIGHT: f32 = 8.0;
43
44/// What a step or span signals.
45pub use crate::theme::Tone;
46
47/// A run of steps in a lane, from `start` to `end` inclusive.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub struct Span {
50    pub start: usize,
51    pub end: usize,
52    pub tone: Tone,
53}
54
55impl Span {
56    /// A neutral span from `start` to `end`, in either order.
57    pub fn new(start: usize, end: usize) -> Self {
58        Self {
59            start: start.min(end),
60            end: start.max(end),
61            tone: Tone::Neutral,
62        }
63    }
64
65    pub fn tone(mut self, tone: Tone) -> Self {
66        self.tone = tone;
67        self
68    }
69}
70
71/// A labelled row of spans below the track.
72#[derive(Debug, Clone, PartialEq)]
73pub struct Lane<'a> {
74    label: text::Fragment<'a>,
75    spans: Vec<Span>,
76}
77
78/// Creates a lane named `label` holding `spans`.
79pub fn lane<'a>(
80    label: impl text::IntoFragment<'a>,
81    spans: impl IntoIterator<Item = Span>,
82) -> Lane<'a> {
83    Lane {
84        label: label.into_fragment(),
85        spans: spans.into_iter().collect(),
86    }
87}
88
89impl Lane<'_> {
90    pub fn label(&self) -> &str {
91        &self.label
92    }
93
94    pub fn spans(&self) -> &[Span] {
95        &self.spans
96    }
97}
98
99/// A timeline builder. Convert it into an [`Element`] to render.
100///
101/// A timeline without a message is rendered disabled.
102pub struct Timeline<'a, Message> {
103    steps: Vec<Tone>,
104    current: usize,
105    lanes: Vec<Lane<'a>>,
106    label_width: f32,
107    width: Length,
108    name: text::Fragment<'a>,
109    keymap: Keymap<Action>,
110    on_select: Option<Box<dyn Fn(usize) -> Message + 'a>>,
111}
112
113impl<Message> std::fmt::Debug for Timeline<'_, Message> {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.debug_struct("Timeline")
116            .field("steps", &self.steps.len())
117            .field("current", &self.current)
118            .field("lanes", &self.lanes)
119            .field("label_width", &self.label_width)
120            .field("width", &self.width)
121            .field("name", &self.name)
122            .field("keymap", &self.keymap)
123            .field("enabled", &self.on_select.is_some())
124            .finish()
125    }
126}
127
128/// Creates a timeline over `steps`, one tone per step, with `current`
129/// selected. The current step is clamped to the steps.
130pub fn timeline<'a, Message>(
131    steps: impl IntoIterator<Item = Tone>,
132    current: usize,
133) -> Timeline<'a, Message> {
134    let steps: Vec<Tone> = steps.into_iter().collect();
135    Timeline {
136        current: current.min(steps.len().saturating_sub(1)),
137        steps,
138        lanes: Vec::new(),
139        label_width: LABEL_WIDTH,
140        width: Length::Fill,
141        name: Cow::Borrowed("Timeline"),
142        keymap: default_keymap(),
143        on_select: None,
144    }
145}
146
147impl<'a, Message> Timeline<'a, Message> {
148    /// Adds a lane of spans below the track.
149    pub fn lane(mut self, lane: Lane<'a>) -> Self {
150        self.lanes.push(lane);
151        self
152    }
153
154    /// Adds several lanes below the track.
155    pub fn lanes(mut self, lanes: impl IntoIterator<Item = Lane<'a>>) -> Self {
156        self.lanes.extend(lanes);
157        self
158    }
159
160    /// Width of the lane labels. Only used when there are lanes.
161    pub fn label_width(mut self, width: f32) -> Self {
162        self.label_width = width.max(0.0);
163        self
164    }
165
166    pub fn width(mut self, width: impl Into<Length>) -> Self {
167        self.width = width.into();
168        self
169    }
170
171    /// The name tests and assistive tools know it by. "Timeline" by default.
172    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
173        self.name = label.into_fragment();
174        self
175    }
176
177    /// Sets the message sent with the step under the pointer while
178    /// pressing or dragging, or the step a shortcut moves to.
179    pub fn on_select(mut self, on_select: impl Fn(usize) -> Message + 'a) -> Self {
180        self.on_select = Some(Box::new(on_select));
181        self
182    }
183
184    /// Replaces the [`default_keymap`] the timeline resolves keys with
185    /// while it has keyboard focus or was the last thing pressed.
186    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
187        self.keymap = keymap;
188        self
189    }
190
191    pub fn current(&self) -> usize {
192        self.current
193    }
194
195    pub fn len(&self) -> usize {
196        self.steps.len()
197    }
198
199    pub fn is_empty(&self) -> bool {
200        self.steps.is_empty()
201    }
202
203    pub fn is_enabled(&self) -> bool {
204        self.on_select.is_some()
205    }
206
207    fn labels(&self) -> f32 {
208        if self.lanes.is_empty() {
209            0.0
210        } else {
211            self.label_width
212        }
213    }
214}
215
216/// The step under `x`, for a track `width` wide holding `count` steps
217/// placed evenly from its left edge to its right edge.
218pub fn index_at(x: f32, width: f32, count: usize) -> usize {
219    if count < 2 || width <= 0.0 {
220        return 0;
221    }
222    let last = count - 1;
223    let fraction = (x / width).clamp(0.0, 1.0);
224    let index = (fraction * last as f32).round();
225    (index as usize).min(last)
226}
227
228/// Where step `index` sits along a track `width` wide.
229pub fn position_of(index: usize, width: f32, count: usize) -> f32 {
230    if count < 2 {
231        return 0.0;
232    }
233    width * index.min(count - 1) as f32 / (count - 1) as f32
234}
235
236/// The left and right edges of a span along a track `width` wide: half a
237/// step either side of its first and last steps, kept on the track.
238pub fn span_extent(span: Span, width: f32, count: usize) -> (f32, f32) {
239    let half = if count < 2 {
240        width / 2.0
241    } else {
242        width / (count - 1) as f32 / 2.0
243    };
244    let left = (position_of(span.start, width, count) - half).max(0.0);
245    let right = (position_of(span.end, width, count) + half).min(width);
246    (left, right.max(left))
247}
248
249/// The height of a timeline with `lanes` lanes.
250pub fn height(lanes: usize) -> f32 {
251    TRACK_HEIGHT + lanes as f32 * LANE_HEIGHT
252}
253
254/// The part of `bounds` a step maps onto: right of the labels, and inset by
255/// the playhead radius so the playhead never leaves the widget.
256pub fn track_bounds(bounds: Rectangle, labels: f32) -> Rectangle {
257    let left = if labels > 0.0 {
258        labels + space::SM
259    } else {
260        0.0
261    };
262    let x = bounds.x + left + PLAYHEAD_RADIUS;
263    Rectangle {
264        x,
265        y: bounds.y,
266        width: (bounds.width - left - PLAYHEAD_RADIUS * 2.0).max(0.0),
267        height: TRACK_HEIGHT,
268    }
269}
270
271/// What a timeline shortcut does.
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
273pub enum Action {
274    Previous,
275    Next,
276    PageBack,
277    PageForward,
278    First,
279    Last,
280}
281
282impl Action {
283    /// The step after this action, from `current` in a timeline of `count`
284    /// steps. Send it through the timeline's `on_select` message.
285    pub fn apply(self, current: usize, count: usize) -> usize {
286        let last = count.saturating_sub(1);
287        let current = current.min(last);
288        match self {
289            Action::Previous => current.saturating_sub(1),
290            Action::Next => (current + 1).min(last),
291            Action::PageBack => current.saturating_sub(PAGE),
292            Action::PageForward => (current + PAGE).min(last),
293            Action::First => 0,
294            Action::Last => last,
295        }
296    }
297}
298
299impl keys::Action for Action {
300    const ALL: &'static [Self] = &[
301        Action::Previous,
302        Action::Next,
303        Action::PageBack,
304        Action::PageForward,
305        Action::First,
306        Action::Last,
307    ];
308
309    fn defaults() -> Keymap<Self> {
310        default_keymap()
311    }
312
313    fn name(self) -> &'static str {
314        match self {
315            Action::Previous => "Previous",
316            Action::Next => "Next",
317            Action::PageBack => "Page back",
318            Action::PageForward => "Page forward",
319            Action::First => "First",
320            Action::Last => "Last",
321        }
322    }
323
324    fn description(self) -> &'static str {
325        match self {
326            Action::Previous => "Moves to the step before the current one.",
327            Action::Next => "Moves to the step after the current one.",
328            Action::PageBack => "Moves ten steps back.",
329            Action::PageForward => "Moves ten steps forward.",
330            Action::First => "Moves to the first step.",
331            Action::Last => "Moves to the last step.",
332        }
333    }
334}
335
336/// The default timeline shortcuts:
337///
338/// | Keys | Action |
339/// | --- | --- |
340/// | `ArrowLeft` | [`Action::Previous`] |
341/// | `ArrowRight` | [`Action::Next`] |
342/// | `Shift+ArrowLeft`, `PageUp` | [`Action::PageBack`] |
343/// | `Shift+ArrowRight`, `PageDown` | [`Action::PageForward`] |
344/// | `Home` | [`Action::First`] |
345/// | `End` | [`Action::Last`] |
346///
347/// The timeline resolves them itself while it has keyboard focus or was the
348/// last thing pressed. Pass a changed keymap with [`Timeline::keymap`].
349pub fn default_keymap() -> Keymap<Action> {
350    Keymap::new()
351        .bind(Chord::named(Named::ArrowLeft), Action::Previous)
352        .bind(Chord::named(Named::ArrowRight), Action::Next)
353        .bind(Chord::named(Named::ArrowLeft).shift(), Action::PageBack)
354        .bind(Chord::named(Named::PageUp), Action::PageBack)
355        .bind(Chord::named(Named::ArrowRight).shift(), Action::PageForward)
356        .bind(Chord::named(Named::PageDown), Action::PageForward)
357        .bind(Chord::named(Named::Home), Action::First)
358        .bind(Chord::named(Named::End), Action::Last)
359}
360
361/// How the pointer is interacting with a timeline.
362#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
363pub enum Status {
364    #[default]
365    Active,
366    Hovered,
367    Dragged,
368    Disabled,
369}
370
371impl Status {
372    pub const ALL: [Status; 4] = [
373        Status::Active,
374        Status::Hovered,
375        Status::Dragged,
376        Status::Disabled,
377    ];
378}
379
380/// Colours of a timeline in one status.
381#[derive(Debug, Clone, Copy, PartialEq)]
382pub struct Style {
383    pub rail: Color,
384    pub lane: Color,
385    pub label: Color,
386    pub playhead: Color,
387    pub playhead_border: Color,
388    pub playhead_border_width: f32,
389    /// The line from the playhead down through the lanes.
390    pub cursor: Color,
391    /// Multiplies the alpha of tone colours.
392    pub tone_alpha: f32,
393}
394
395/// Resolves the colours of a timeline for a status.
396pub fn style(tokens: &Tokens, status: Status) -> Style {
397    let border = match status {
398        Status::Active | Status::Disabled => tokens.primary,
399        Status::Hovered => mix(tokens.primary, tokens.background, 0.15),
400        Status::Dragged => mix(tokens.primary, tokens.background, 0.3),
401    };
402    let style = Style {
403        rail: mix(tokens.muted, tokens.border, 0.5),
404        lane: tokens.muted,
405        label: tokens.muted_foreground,
406        playhead: tokens.background,
407        playhead_border: border,
408        playhead_border_width: match status {
409            Status::Hovered | Status::Dragged => 2.5,
410            Status::Active | Status::Disabled => 2.0,
411        },
412        cursor: fade(tokens.primary, 0.4),
413        tone_alpha: 1.0,
414    };
415    if status != Status::Disabled {
416        return style;
417    }
418    Style {
419        rail: fade(style.rail, 0.5),
420        lane: fade(style.lane, 0.5),
421        label: fade(style.label, 0.5),
422        playhead_border: fade(style.playhead_border, 0.5),
423        cursor: fade(style.cursor, 0.5),
424        tone_alpha: 0.5,
425        ..style
426    }
427}
428
429#[derive(Debug, Default)]
430struct State {
431    dragging: bool,
432    hovered: bool,
433    finger: Option<touch::Finger>,
434    last: Option<usize>,
435    keys: focus::Scope,
436}
437
438impl<Message> Timeline<'_, Message> {
439    /// Whether it takes keyboard focus and keys, and reacts to the pointer.
440    fn is_focusable(&self) -> bool {
441        self.on_select.is_some() && !self.steps.is_empty()
442    }
443
444    /// Sends the step under `x` when it differs from the last one sent. A
445    /// press starts from the current step, so a drag that comes back to it
446    /// within one batch of events still sends it.
447    fn select(&self, state: &mut State, x: f32, track: Rectangle, shell: &mut Shell<'_, Message>) {
448        let Some(on_select) = &self.on_select else {
449            return;
450        };
451        let index = index_at(x - track.x, track.width, self.steps.len());
452        if state.last != Some(index) {
453            shell.publish(on_select(index));
454        }
455        state.last = Some(index);
456    }
457
458    fn status(&self, state: &State, layout: Layout<'_>, cursor: mouse::Cursor) -> Status {
459        if self.on_select.is_none() {
460            return Status::Disabled;
461        }
462        if state.dragging {
463            return Status::Dragged;
464        }
465        if cursor.is_over(layout.bounds()) {
466            return Status::Hovered;
467        }
468        Status::Active
469    }
470}
471
472/// The track row with room for the playhead, which focus reports and the
473/// ring surrounds.
474fn focus_target(track: Rectangle) -> Rectangle {
475    let middle = track.center_y();
476    Rectangle {
477        x: track.x - PLAYHEAD_RADIUS,
478        y: middle - PLAYHEAD_RADIUS,
479        width: track.width + PLAYHEAD_RADIUS * 2.0,
480        height: PLAYHEAD_RADIUS * 2.0,
481    }
482}
483
484fn fill(renderer: &mut Renderer, bounds: Rectangle, colour: Color, corner: f32) {
485    <Renderer as renderer::Renderer>::fill_quad(
486        renderer,
487        renderer::Quad {
488            bounds,
489            border: Border {
490                radius: corner.into(),
491                ..Border::default()
492            },
493            ..renderer::Quad::default()
494        },
495        colour,
496    );
497}
498
499fn label(renderer: &mut Renderer, content: &str, bounds: Rectangle, colour: Color) {
500    <Renderer as core_text::Renderer>::fill_text(
501        renderer,
502        core_text::Text {
503            content: content.to_owned(),
504            bounds: Size::new(f32::INFINITY, bounds.height),
505            size: Pixels(text_size::XS),
506            line_height: LineHeight::Absolute(Pixels(LANE_HEIGHT)),
507            font: theme::font(),
508            align_x: text::Alignment::Left,
509            align_y: Vertical::Center,
510            shaping: Shaping::Advanced,
511            wrapping: Wrapping::None,
512        },
513        Point::new(bounds.x, bounds.center_y()),
514        colour,
515        bounds,
516    );
517}
518
519impl<Message> Widget<Message, Theme, Renderer> for Timeline<'_, Message> {
520    fn size(&self) -> Size<Length> {
521        Size::new(self.width, Length::Fixed(height(self.lanes.len())))
522    }
523
524    fn tag(&self) -> tree::Tag {
525        tree::Tag::of::<State>()
526    }
527
528    fn state(&self) -> tree::State {
529        tree::State::new(State::default())
530    }
531
532    fn layout(
533        &mut self,
534        _tree: &mut Tree,
535        _renderer: &Renderer,
536        limits: &layout::Limits,
537    ) -> layout::Node {
538        let height = height(self.lanes.len());
539        layout::Node::new(limits.resolve(self.width, Length::Fixed(height), Size::new(0.0, height)))
540    }
541
542    fn draw(
543        &self,
544        tree: &Tree,
545        renderer: &mut Renderer,
546        theme: &Theme,
547        _style: &renderer::Style,
548        layout: Layout<'_>,
549        cursor: mouse::Cursor,
550        _viewport: &Rectangle,
551    ) {
552        let tokens = Tokens::of(theme);
553        let state = tree.state.downcast_ref::<State>();
554        let style = style(&tokens, self.status(state, layout, cursor));
555        let bounds = layout.bounds();
556        let labels = self.labels();
557        let track = track_bounds(bounds, labels);
558        let count = self.steps.len();
559        let middle = track.center_y();
560
561        fill(
562            renderer,
563            Rectangle {
564                x: track.x - PLAYHEAD_RADIUS,
565                y: middle - RAIL_HEIGHT / 2.0,
566                width: track.width + PLAYHEAD_RADIUS * 2.0,
567                height: RAIL_HEIGHT,
568            },
569            style.rail,
570            radius::FULL,
571        );
572        if state.keys.is_focused() && self.is_focusable() {
573            focus::draw_ring(renderer, theme, focus_target(track), radius::FULL);
574        }
575
576        for (index, lane) in self.lanes.iter().enumerate() {
577            let row = Rectangle {
578                x: bounds.x,
579                y: bounds.y + TRACK_HEIGHT + index as f32 * LANE_HEIGHT,
580                width: bounds.width,
581                height: LANE_HEIGHT,
582            };
583            label(
584                renderer,
585                &lane.label,
586                Rectangle {
587                    width: labels,
588                    ..row
589                },
590                style.label,
591            );
592            let bar_y = row.center_y() - BAR_HEIGHT / 2.0;
593            fill(
594                renderer,
595                Rectangle {
596                    x: track.x - PLAYHEAD_RADIUS,
597                    y: bar_y,
598                    width: track.width + PLAYHEAD_RADIUS * 2.0,
599                    height: BAR_HEIGHT,
600                },
601                style.lane,
602                radius::FULL,
603            );
604            for span in &lane.spans {
605                if span.start >= count {
606                    continue;
607                }
608                let (left, right) = span_extent(*span, track.width, count);
609                fill(
610                    renderer,
611                    Rectangle {
612                        x: track.x + left,
613                        y: bar_y,
614                        width: (right - left).max(BAR_HEIGHT),
615                        height: BAR_HEIGHT,
616                    },
617                    fade(span.tone.colour(&tokens), style.tone_alpha),
618                    radius::FULL,
619                );
620            }
621        }
622
623        for (index, tone) in self.steps.iter().enumerate() {
624            let x = track.x + position_of(index, track.width, count);
625            // No taller than the playhead, which covers the current tick.
626            let tall = if *tone == Tone::Neutral {
627                8.0
628            } else {
629                PLAYHEAD_RADIUS * 2.0
630            };
631            fill(
632                renderer,
633                Rectangle {
634                    x: x - TICK_WIDTH / 2.0,
635                    y: middle - tall / 2.0,
636                    width: TICK_WIDTH,
637                    height: tall,
638                },
639                fade(tone.colour(&tokens), style.tone_alpha),
640                0.0,
641            );
642        }
643
644        if count == 0 {
645            return;
646        }
647        let x = track.x + position_of(self.current, track.width, count);
648        if !self.lanes.is_empty() {
649            fill(
650                renderer,
651                Rectangle {
652                    x: x - 0.5,
653                    y: middle,
654                    width: 1.0,
655                    height: bounds.y + bounds.height - middle,
656                },
657                style.cursor,
658                0.0,
659            );
660        }
661        <Renderer as renderer::Renderer>::fill_quad(
662            renderer,
663            renderer::Quad {
664                bounds: Rectangle {
665                    x: x - PLAYHEAD_RADIUS,
666                    y: middle - PLAYHEAD_RADIUS,
667                    width: PLAYHEAD_RADIUS * 2.0,
668                    height: PLAYHEAD_RADIUS * 2.0,
669                },
670                border: Border {
671                    color: style.playhead_border,
672                    width: style.playhead_border_width,
673                    radius: PLAYHEAD_RADIUS.into(),
674                },
675                ..renderer::Quad::default()
676            },
677            style.playhead,
678        );
679    }
680
681    fn update(
682        &mut self,
683        tree: &mut Tree,
684        event: &Event,
685        layout: Layout<'_>,
686        cursor: mouse::Cursor,
687        _renderer: &Renderer,
688        _clipboard: &mut dyn Clipboard,
689        shell: &mut Shell<'_, Message>,
690        _viewport: &Rectangle,
691    ) {
692        let state = tree.state.downcast_mut::<State>();
693        if !self.is_focusable() {
694            if state.keys.release() {
695                shell.request_redraw();
696            }
697            return;
698        }
699        let bounds = layout.bounds();
700        let track = track_bounds(bounds, self.labels());
701        // Presses on the lane labels pick nothing.
702        let pressable = Rectangle {
703            x: track.x - PLAYHEAD_RADIUS,
704            width: track.width + PLAYHEAD_RADIUS * 2.0,
705            ..bounds
706        };
707        let before = (state.dragging, state.hovered);
708        state.hovered = cursor.is_over(bounds);
709        let keyed = state.keys.update(event, cursor, pressable);
710        match event {
711            Event::Mouse(mouse::Event::ButtonPressed(button)) => {
712                let position = cursor.position_over(pressable);
713                if let (mouse::Button::Left, Some(position)) = (button, position) {
714                    state.dragging = true;
715                    state.last = Some(self.current);
716                    self.select(state, position.x, track, shell);
717                    shell.capture_event();
718                }
719            }
720            Event::Touch(touch::Event::FingerPressed { id, position }) => {
721                if pressable.contains(*position) && !state.dragging {
722                    state.dragging = true;
723                    state.finger = Some(*id);
724                    state.last = Some(self.current);
725                    self.select(state, position.x, track, shell);
726                    shell.capture_event();
727                }
728            }
729            Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. })
730                if state.keys.has_keys() && !shell.is_event_captured() =>
731            {
732                if let Some(action) = self.keymap.resolve(key, *modifiers) {
733                    let next = action.apply(self.current, self.steps.len());
734                    if let Some(on_select) = &self.on_select
735                        && next != self.current
736                    {
737                        shell.publish(on_select(next));
738                    }
739                    shell.capture_event();
740                }
741            }
742            Event::Mouse(mouse::Event::CursorMoved { position })
743                if state.dragging && state.finger.is_none() =>
744            {
745                self.select(state, position.x, track, shell);
746            }
747            Event::Touch(touch::Event::FingerMoved { id, position })
748                if state.finger == Some(*id) =>
749            {
750                self.select(state, position.x, track, shell);
751                shell.capture_event();
752            }
753            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
754                if state.dragging && state.finger.is_none() =>
755            {
756                state.dragging = false;
757                state.last = None;
758                shell.capture_event();
759            }
760            Event::Touch(
761                touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. },
762            ) if state.finger == Some(*id) => {
763                state.dragging = false;
764                state.finger = None;
765                state.last = None;
766                shell.capture_event();
767            }
768            _ => {}
769        }
770        if keyed || (state.dragging, state.hovered) != before {
771            shell.request_redraw();
772        }
773    }
774
775    fn mouse_interaction(
776        &self,
777        tree: &Tree,
778        layout: Layout<'_>,
779        cursor: mouse::Cursor,
780        _viewport: &Rectangle,
781        _renderer: &Renderer,
782    ) -> mouse::Interaction {
783        if self.on_select.is_none() {
784            return mouse::Interaction::None;
785        }
786        if tree.state.downcast_ref::<State>().dragging {
787            return mouse::Interaction::Grabbing;
788        }
789        if cursor.is_over(layout.bounds()) {
790            return mouse::Interaction::Pointer;
791        }
792        mouse::Interaction::None
793    }
794
795    fn operate(
796        &mut self,
797        tree: &mut Tree,
798        layout: Layout<'_>,
799        _renderer: &Renderer,
800        operation: &mut dyn iced::advanced::widget::Operation,
801    ) {
802        let target = focus_target(track_bounds(layout.bounds(), self.labels()));
803        #[cfg(feature = "icedwright")]
804        {
805            use icedwright_probe::{Annotation, report, role};
806
807            let enabled = self.on_select.is_some();
808            let last = self.steps.len().saturating_sub(1) as f64;
809            report(operation, target, || {
810                let annotation = Annotation::new()
811                    .role(role::Slider)
812                    .name(self.name.to_string())
813                    .range(self.current as f64, 0.0..=last)
814                    .component("iced_cube::timeline");
815                if enabled {
816                    annotation
817                } else {
818                    annotation.disabled(true)
819                }
820            });
821        }
822        // Reported after the annotation, at the same bounds, so a recorder
823        // merges the two into one node.
824        let state = tree.state.downcast_mut::<State>();
825        if self.is_focusable() {
826            focus::report(operation, None, target, &mut state.keys);
827        } else {
828            let _ = state.keys.release();
829        }
830    }
831}
832
833impl<'a, Message: 'a> From<Timeline<'a, Message>> for Element<'a, Message> {
834    fn from(timeline: Timeline<'a, Message>) -> Self {
835        Element::new(timeline)
836    }
837}
838
839#[cfg(test)]
840mod tests {
841    use super::*;
842    use crate::keys::Action as _;
843    use crate::theme::{dark, light};
844
845    fn bounds() -> Rectangle {
846        Rectangle {
847            x: 10.0,
848            y: 20.0,
849            width: 400.0,
850            height: 100.0,
851        }
852    }
853
854    #[test]
855    fn default_builder_fills_the_width_and_is_disabled() {
856        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 1);
857        assert_eq!(t.width, Length::Fill);
858        assert_eq!(t.name, "Timeline");
859        assert_eq!(t.label_width, LABEL_WIDTH);
860        assert!(t.lanes.is_empty());
861        assert!(!t.is_enabled());
862        assert!(t.on_select(|_| ()).is_enabled());
863    }
864
865    #[test]
866    fn the_current_step_is_clamped_to_the_steps() {
867        let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 9);
868        assert_eq!(t.current(), 2);
869        let t: Timeline<'_, ()> = timeline([], 4);
870        assert_eq!(t.current(), 0);
871        assert!(t.is_empty());
872    }
873
874    #[test]
875    fn spans_are_ordered_and_take_a_tone() {
876        let span = Span::new(5, 2).tone(Tone::Warning);
877        assert_eq!((span.start, span.end, span.tone), (2, 5, Tone::Warning));
878        assert_eq!(Span::new(1, 1).tone, Tone::Neutral);
879    }
880
881    #[test]
882    fn positions_and_indices_agree_at_every_step() {
883        for count in [1, 2, 3, 10, 57] {
884            for index in 0..count {
885                let x = position_of(index, 600.0, count);
886                assert_eq!(index_at(x, 600.0, count), index, "{index} of {count}");
887            }
888        }
889    }
890
891    #[test]
892    fn points_outside_the_track_clamp_to_the_ends() {
893        assert_eq!(index_at(-50.0, 100.0, 5), 0);
894        assert_eq!(index_at(150.0, 100.0, 5), 4);
895        assert_eq!(index_at(10.0, 0.0, 5), 0);
896        assert_eq!(index_at(10.0, 100.0, 0), 0);
897    }
898
899    #[test]
900    fn points_go_to_the_nearest_step() {
901        assert_eq!(index_at(24.0, 100.0, 5), 1);
902        assert_eq!(index_at(26.0, 100.0, 5), 1);
903        assert_eq!(index_at(38.0, 100.0, 5), 2);
904    }
905
906    #[test]
907    fn a_span_reaches_half_a_step_either_side_and_stays_on_the_track() {
908        assert_eq!(span_extent(Span::new(1, 2), 100.0, 5), (12.5, 62.5));
909        assert_eq!(span_extent(Span::new(0, 4), 100.0, 5), (0.0, 100.0));
910        assert_eq!(span_extent(Span::new(3, 3), 100.0, 1), (0.0, 50.0));
911    }
912
913    #[test]
914    fn the_track_sits_right_of_the_labels_and_inside_the_playhead() {
915        let track = track_bounds(bounds(), 0.0);
916        assert_eq!(track.x, 10.0 + PLAYHEAD_RADIUS);
917        assert_eq!(track.width, 400.0 - PLAYHEAD_RADIUS * 2.0);
918        assert_eq!(track.height, TRACK_HEIGHT);
919        let track = track_bounds(bounds(), 96.0);
920        assert_eq!(track.x, 10.0 + 96.0 + space::SM + PLAYHEAD_RADIUS);
921        let narrow = Rectangle {
922            width: 20.0,
923            ..bounds()
924        };
925        assert_eq!(track_bounds(narrow, 96.0).width, 0.0);
926    }
927
928    #[test]
929    fn height_grows_by_a_row_per_lane() {
930        assert_eq!(height(0), TRACK_HEIGHT);
931        assert_eq!(height(2), TRACK_HEIGHT + 2.0 * LANE_HEIGHT);
932    }
933
934    #[test]
935    fn actions_move_within_the_steps() {
936        assert_eq!(Action::Previous.apply(3, 10), 2);
937        assert_eq!(Action::Previous.apply(0, 10), 0);
938        assert_eq!(Action::Next.apply(3, 10), 4);
939        assert_eq!(Action::Next.apply(9, 10), 9);
940        assert_eq!(Action::PageBack.apply(4, 30), 0);
941        assert_eq!(Action::PageBack.apply(14, 30), 4);
942        assert_eq!(Action::PageForward.apply(25, 30), 29);
943        assert_eq!(Action::PageForward.apply(5, 30), 15);
944        assert_eq!(Action::First.apply(7, 10), 0);
945        assert_eq!(Action::Last.apply(2, 10), 9);
946        assert_eq!(Action::Last.apply(0, 0), 0);
947        assert_eq!(Action::Next.apply(50, 10), 9);
948    }
949
950    fn resolve(keymap: &Keymap<Action>, chord: Chord) -> Option<Action> {
951        keymap.resolve(chord.key(), chord.modifiers())
952    }
953
954    #[test]
955    fn default_keymap_binds_arrows_pages_and_ends() {
956        let keymap = default_keymap();
957        assert_eq!(
958            resolve(&keymap, Chord::named(Named::ArrowLeft)),
959            Some(Action::Previous)
960        );
961        assert_eq!(
962            resolve(&keymap, Chord::named(Named::ArrowRight).shift()),
963            Some(Action::PageForward)
964        );
965        assert_eq!(
966            resolve(&keymap, Chord::named(Named::PageUp)),
967            Some(Action::PageBack)
968        );
969        assert_eq!(
970            resolve(&keymap, Chord::named(Named::End)),
971            Some(Action::Last)
972        );
973        assert_eq!(Keymap::<Action>::defaults(), keymap);
974        for action in Action::ALL {
975            assert!(!action.name().is_empty());
976            assert!(action.description().ends_with('.'));
977        }
978    }
979
980    #[test]
981    fn keymap_overrides_and_unbinding() {
982        let keymap = default_keymap()
983            .bind(Chord::character('j'), Action::Next)
984            .unbind(&Chord::named(Named::Home));
985        assert_eq!(resolve(&keymap, Chord::character('j')), Some(Action::Next));
986        assert_eq!(resolve(&keymap, Chord::named(Named::Home)), None);
987        assert_eq!(
988            resolve(&keymap, Chord::named(Named::End)),
989            Some(Action::Last)
990        );
991    }
992
993    #[test]
994    fn style_follows_the_status_in_light_and_dark() {
995        for theme in [light(), dark()] {
996            let tokens = Tokens::of(&theme);
997            let active = style(&tokens, Status::Active);
998            assert_eq!(active.playhead_border, tokens.primary);
999            assert_eq!(active.playhead, tokens.background);
1000            assert_eq!(active.tone_alpha, 1.0);
1001            let hovered = style(&tokens, Status::Hovered);
1002            assert_ne!(hovered.playhead_border, active.playhead_border);
1003            assert!(hovered.playhead_border_width > active.playhead_border_width);
1004            let dragged = style(&tokens, Status::Dragged);
1005            assert_ne!(dragged.playhead_border, hovered.playhead_border);
1006            let disabled = style(&tokens, Status::Disabled);
1007            assert!(disabled.rail.a < active.rail.a);
1008            assert!(disabled.playhead_border.a < active.playhead_border.a);
1009            assert_eq!(disabled.tone_alpha, 0.5);
1010            assert_eq!(Status::ALL.len(), 4);
1011        }
1012    }
1013}