iced-cube 0.0.25

Themeable application components for the iced GUI library, with Lucide icons
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
//! Switches between related views that share one place on screen.
//!
//! [`State`] owns the tabs and the selection. Its [`update`](State::update)
//! handles selecting, moving to the next or previous tab with wrap-around,
//! and skips disabled tabs. The app renders the selected view itself.
//!
//! Shortcuts from [`default_keymap`] act only while the tab list has
//! keyboard focus (Tab reaches it) or was the last thing pressed, so several
//! on one screen never fight over keys.
//!
//! To keep `Ctrl+Tab` and `Ctrl+Shift+Tab` working from anywhere in the
//! app, pass the key presses [`keys::subscription`] delivers to
//! [`State::key_event`] with [`app_keymap`]. Keys the focused tab list uses
//! never reach the subscription, so nothing switches twice.
//!
//! ```no_run
//! # #[cfg(feature = "tabs")]
//! # mod example {
//! use iced::Subscription;
//! use iced_cube::keys;
//! use iced_cube::navigation::tabs::{self, app_keymap};
//!
//! #[derive(Debug, Clone)]
//! enum Message {
//!     Key(keys::Event),
//!     Tabs(tabs::Event<u8>),
//! }
//!
//! struct App {
//!     tabs: tabs::State<u8>,
//! }
//!
//! impl App {
//!     fn update(&mut self, message: Message) {
//!         let event = match message {
//!             Message::Key(key) => self.tabs.key_event(&app_keymap(), &key),
//!             Message::Tabs(event) => Some(event),
//!         };
//!         if let Some(event) = event {
//!             let _ = self.tabs.update(event);
//!         }
//!     }
//!
//!     fn subscription(&self) -> Subscription<Message> {
//!         keys::subscription().map(Message::Key)
//!     }
//! }
//! # }
//! ```

use iced::keyboard::key::Named;
use iced::widget::{self, button::Status, column, container, row, rule, scrollable, text};
use iced::{Alignment, Background, Border, Color, Element, Length, Shadow, Theme, Vector};

use crate::focus;
use crate::icon::{Glyph, opacity, themed};
use crate::keys::{self, Chord, Keymap};
use crate::natural::natural;
use crate::theme::{Tokens, fade, mix, radius, space, text_size};

/// How the tab list looks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Variant {
    /// Plain labels over a rule, the selected one underlined.
    #[default]
    Underline,
    /// A segmented control, the selected tab raised.
    Pills,
}

impl Variant {
    pub const ALL: [Variant; 2] = [Variant::Underline, Variant::Pills];
}

/// One tab in a [`State`].
#[derive(Debug, Clone, PartialEq)]
pub struct Tab<Id> {
    pub id: Id,
    pub label: String,
    pub icon: Option<Glyph>,
    pub disabled: bool,
}

/// Creates an enabled tab.
pub fn tab<Id>(id: Id, label: impl Into<String>) -> Tab<Id> {
    Tab {
        id,
        label: label.into(),
        icon: None,
        disabled: false,
    }
}

impl<Id> Tab<Id> {
    pub fn icon(mut self, glyph: Glyph) -> Self {
        self.icon = Some(glyph);
        self
    }

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

/// Changes to the selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event<Id> {
    Select(Id),
    Next,
    Previous,
}

/// The tabs and which one is selected.
#[derive(Debug, Clone, PartialEq)]
pub struct State<Id> {
    tabs: Vec<Tab<Id>>,
    selected: Option<usize>,
}

impl<Id: Copy + PartialEq> State<Id> {
    /// Selects the first enabled tab.
    pub fn new(tabs: impl IntoIterator<Item = Tab<Id>>) -> Self {
        let tabs: Vec<_> = tabs.into_iter().collect();
        let selected = tabs.iter().position(|tab| !tab.disabled);
        Self { tabs, selected }
    }

    /// Starts on `id` when it exists and is enabled.
    pub fn with_selected(mut self, id: Id) -> Self {
        let _ = self.update(Event::Select(id));
        self
    }

    pub fn tabs(&self) -> &[Tab<Id>] {
        &self.tabs
    }

    pub fn selected(&self) -> Option<Id> {
        self.selected.map(|index| self.tabs[index].id)
    }

    pub fn is_selected(&self, id: Id) -> bool {
        self.selected() == Some(id)
    }

    /// Enables or disables a tab. The selection stays where it is.
    pub fn set_disabled(&mut self, id: Id, disabled: bool) {
        if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) {
            tab.disabled = disabled;
        }
    }

    /// Applies an event and returns the newly selected id, if it changed.
    pub fn update(&mut self, event: Event<Id>) -> Option<Id> {
        let target = match event {
            Event::Select(id) => self
                .tabs
                .iter()
                .position(|tab| tab.id == id && !tab.disabled),
            Event::Next => self.step(true),
            Event::Previous => self.step(false),
        }?;

        if self.selected == Some(target) {
            return None;
        }
        self.selected = Some(target);
        Some(self.tabs[target].id)
    }

    /// Turns a key press from [`keys::subscription`] into an event through
    /// `keymap`, usually [`app_keymap`], for shortcuts that work while the
    /// tab list does not have focus.
    pub fn key_event(&self, keymap: &Keymap<Action>, key: &keys::Event) -> Option<Event<Id>> {
        keymap
            .resolve_event(key)
            .and_then(|action| action.event(self))
    }

    /// The nearest enabled index in one direction, wrapping round.
    fn step(&self, forward: bool) -> Option<usize> {
        let len = self.tabs.len();
        if len == 0 {
            return None;
        }
        let start = self.selected.unwrap_or(if forward { len - 1 } else { 0 });
        let offset = if forward { 1 } else { len - 1 };
        (1..=len)
            .map(|n| (start + offset * n) % len)
            .find(|&index| !self.tabs[index].disabled)
    }
}

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

impl Action {
    /// The [`Event`] this action sends to `state`, or `None` when no tab
    /// is enabled.
    pub fn event<Id: Copy + PartialEq>(self, state: &State<Id>) -> Option<Event<Id>> {
        let mut enabled = state.tabs.iter().filter(|tab| !tab.disabled);
        match self {
            Action::Next => Some(Event::Next),
            Action::Previous => Some(Event::Previous),
            Action::First => enabled.next().map(|tab| Event::Select(tab.id)),
            Action::Last => enabled.next_back().map(|tab| Event::Select(tab.id)),
        }
    }
}

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

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

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

    fn description(self) -> &'static str {
        match self {
            Action::Next => "Selects the next enabled tab, wrapping at the end.",
            Action::Previous => "Selects the previous enabled tab, wrapping at the start.",
            Action::First => "Selects the first enabled tab.",
            Action::Last => "Selects the last enabled tab.",
        }
    }
}

/// The default tabs shortcuts:
///
/// | Keys | Action |
/// | --- | --- |
/// | `Ctrl+Tab`, `ArrowRight` | [`Action::Next`] |
/// | `Ctrl+Shift+Tab`, `ArrowLeft` | [`Action::Previous`] |
/// | `Home` | [`Action::First`] |
/// | `End` | [`Action::Last`] |
///
/// The tab list resolves them itself while it has keyboard focus or was the
/// last thing pressed. Pass a changed keymap with [`Tabs::keymap`]. To
/// switch tabs with `Ctrl+Tab` from anywhere, pass key presses to
/// [`State::key_event`] with [`app_keymap`]. Document tabs bind `Ctrl+Tab`
/// and `Ctrl+Shift+Tab` too, so while both are on screen an app should route
/// only one of them from [`keys::subscription`].
pub fn default_keymap() -> Keymap<Action> {
    app_keymap()
        .bind(Chord::named(Named::ArrowRight), Action::Next)
        .bind(Chord::named(Named::ArrowLeft), Action::Previous)
        .bind(Chord::named(Named::Home), Action::First)
        .bind(Chord::named(Named::End), Action::Last)
}

/// The shortcuts that switch tabs from anywhere in the app, for
/// [`State::key_event`]:
///
/// | Keys | Action |
/// | --- | --- |
/// | `Ctrl+Tab` | [`Action::Next`] |
/// | `Ctrl+Shift+Tab` | [`Action::Previous`] |
///
/// The arrow keys, Home and End are left out, since text fields and other
/// controls use them.
pub fn app_keymap() -> Keymap<Action> {
    Keymap::new()
        .bind(Chord::named(Named::Tab).ctrl(), Action::Next)
        .bind(Chord::named(Named::Tab).ctrl().shift(), Action::Previous)
}

/// A tab list builder. Convert it into an [`Element`] to render.
pub struct Tabs<'a, Id, Message> {
    state: &'a State<Id>,
    variant: Variant,
    width: Option<Length>,
    keymap: Keymap<Action>,
    on_event: Option<Box<dyn Fn(Event<Id>) -> Message + 'a>>,
}

/// Renders the tab list of `state`. Without
/// [`on_event`](Tabs::on_event) every tab renders disabled.
pub fn tabs<Id, Message>(state: &State<Id>) -> Tabs<'_, Id, Message> {
    Tabs {
        state,
        variant: Variant::default(),
        width: None,
        keymap: default_keymap(),
        on_event: None,
    }
}

impl<Id: std::fmt::Debug, Message> std::fmt::Debug for Tabs<'_, Id, Message> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Tabs")
            .field("state", self.state)
            .field("variant", &self.variant)
            .field("keymap", &self.keymap)
            .finish_non_exhaustive()
    }
}

impl<'a, Id, Message> Tabs<'a, Id, Message> {
    pub fn variant(mut self, variant: Variant) -> Self {
        self.variant = variant;
        self
    }

    /// Underline lists fill their row by default, pills shrink to fit.
    pub fn width(mut self, width: impl Into<Length>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
        self.on_event = Some(Box::new(on_event));
        self
    }

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

impl<'a, Id, Message> From<Tabs<'a, Id, Message>> for Element<'a, Message>
where
    Id: Copy + PartialEq + 'a,
    Message: Clone + 'a,
{
    fn from(tabs: Tabs<'a, Id, Message>) -> Self {
        let Tabs {
            state,
            variant,
            width,
            keymap,
            on_event,
        } = tabs;

        let items = state.tabs.iter().map(|tab| {
            let selected = state.is_selected(tab.id);
            let message = on_event
                .as_ref()
                .filter(|_| !tab.disabled)
                .map(|on_event| on_event(Event::Select(tab.id)));
            item(tab, variant, selected, message)
        });

        let list: Element<'a, Message> = match variant {
            Variant::Underline => column![
                sideways(row(items).spacing(space::XS)),
                rule::horizontal(1).style(|theme: &Theme| rule::Style {
                    color: Tokens::of(theme).border,
                    radius: 0.0.into(),
                    fill_mode: rule::FillMode::Full,
                    snap: true,
                }),
            ]
            .width(width.unwrap_or(Length::Fill))
            .into(),
            Variant::Pills => container(sideways(row(items).spacing(space::XS)))
                .padding(space::XS)
                .width(width.unwrap_or(Length::Shrink))
                .style(move |theme| list_style(&Tokens::of(theme), variant))
                .into(),
        };
        let list = match on_event {
            Some(on_event) => focus::keyed(list, keymap, move |action: Action| {
                action.event(state).map(&on_event).into_iter().collect()
            })
            .radius(radius::MD)
            .into(),
            None => list,
        };
        #[cfg(feature = "icedwright")]
        let list = icedwright_probe::semantic(list)
            .role(icedwright_probe::role::TabList)
            .component("iced_cube::tabs")
            .into();
        list
    }
}

/// Lets a tab list wider than its space scroll sideways rather than run off
/// the edge or squeeze its triggers.
fn sideways<'a, Message: 'a>(list: widget::Row<'a, Message>) -> widget::Scrollable<'a, Message> {
    widget::scrollable(list).direction(scrollable::Direction::Horizontal(
        scrollable::Scrollbar::hidden(),
    ))
}

fn item<'a, Id, Message: Clone + 'a>(
    tab: &'a Tab<Id>,
    variant: Variant,
    selected: bool,
    message: Option<Message>,
) -> Element<'a, Message> {
    let enabled = message.is_some();
    let mut label = row![].spacing(space::SM).align_y(Alignment::Center);
    if let Some(glyph) = tab.icon {
        let status = if enabled {
            Status::Active
        } else {
            Status::Disabled
        };
        label = label.push(themed(glyph, 16.0, opacity(enabled), move |theme| {
            foreground(&Tokens::of(theme), selected, status)
        }));
    }
    label = label.push(
        text(tab.label.as_str())
            .size(text_size::SM)
            .wrapping(text::Wrapping::None),
    );

    let button = widget::button(label)
        .padding([6.0, space::MD])
        .on_press_maybe(message)
        .style(move |theme, status| style(&Tokens::of(theme), variant, selected, status));

    let element = if variant == Variant::Pills {
        natural(button)
    } else {
        natural(
            column![
                button,
                container(iced::widget::space())
                    .width(Length::Fill)
                    .height(2)
                    .style(move |theme| indicator_style(&Tokens::of(theme), selected)),
            ]
            .width(Length::Shrink),
        )
    };
    #[cfg(feature = "icedwright")]
    let element = {
        icedwright_probe::semantic(element)
            .role(icedwright_probe::role::Tab)
            .name(tab.label.as_str())
            .selected(selected)
            .disabled(!enabled)
            .component("iced_cube::tabs")
            .into()
    };
    element
}

fn foreground(tokens: &Tokens, selected: bool, status: Status) -> Color {
    let colour = match status {
        _ if selected => tokens.foreground,
        Status::Hovered | Status::Pressed => tokens.foreground,
        _ => tokens.muted_foreground,
    };
    if status == Status::Disabled {
        fade(colour, 0.5)
    } else {
        colour
    }
}

/// The style of one tab.
pub fn style(
    tokens: &Tokens,
    variant: Variant,
    selected: bool,
    status: Status,
) -> widget::button::Style {
    let raised = variant == Variant::Pills && selected;
    let background = raised.then(|| {
        if tokens.is_dark {
            mix(tokens.muted, tokens.foreground, 0.12)
        } else {
            tokens.background
        }
    });

    widget::button::Style {
        background: background.map(Background::Color),
        text_color: foreground(tokens, selected, status),
        border: Border {
            radius: radius::MD.into(),
            ..Border::default()
        },
        shadow: if raised {
            Shadow {
                color: fade(Color::BLACK, 0.1),
                offset: Vector::new(0.0, 1.0),
                blur_radius: 3.0,
            }
        } else {
            Shadow::default()
        },
        snap: true,
    }
}

/// The underline below a tab.
pub fn indicator_style(tokens: &Tokens, selected: bool) -> container::Style {
    container::Style {
        background: selected.then_some(Background::Color(tokens.foreground)),
        ..container::Style::default()
    }
}

/// The container around the tab list.
pub fn list_style(tokens: &Tokens, variant: Variant) -> container::Style {
    match variant {
        Variant::Underline => container::Style::default(),
        Variant::Pills => container::Style {
            background: Some(Background::Color(tokens.muted)),
            border: Border {
                radius: radius::LG.into(),
                ..Border::default()
            },
            ..container::Style::default()
        },
    }
}

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

    fn state() -> State<u8> {
        State::new([
            tab(0, "A"),
            tab(1, "B").disabled(true),
            tab(2, "C"),
            tab(3, "D"),
        ])
    }

    #[test]
    fn new_selects_first_enabled_tab() {
        assert_eq!(state().selected(), Some(0));
        let skipped = State::new([tab(0, "A").disabled(true), tab(1, "B")]);
        assert_eq!(skipped.selected(), Some(1));
    }

    #[test]
    fn empty_and_all_disabled_have_no_selection() {
        let mut empty: State<u8> = State::new([]);
        assert_eq!(empty.selected(), None);
        assert_eq!(empty.update(Event::Next), None);
        assert_eq!(empty.update(Event::Previous), None);

        let mut disabled = State::new([tab(0, "A").disabled(true)]);
        assert_eq!(disabled.selected(), None);
        assert_eq!(disabled.update(Event::Next), None);
    }

    #[test]
    fn select_ignores_disabled_unknown_and_current() {
        let mut state = state();
        assert_eq!(state.update(Event::Select(1)), None);
        assert_eq!(state.update(Event::Select(9)), None);
        assert_eq!(state.update(Event::Select(0)), None);
        assert_eq!(state.update(Event::Select(3)), Some(3));
        assert_eq!(state.selected(), Some(3));
    }

    #[test]
    fn next_skips_disabled_and_wraps() {
        let mut state = state();
        assert_eq!(state.update(Event::Next), Some(2));
        assert_eq!(state.update(Event::Next), Some(3));
        assert_eq!(state.update(Event::Next), Some(0));
    }

    #[test]
    fn previous_skips_disabled_and_wraps() {
        let mut state = state();
        assert_eq!(state.update(Event::Previous), Some(3));
        assert_eq!(state.update(Event::Previous), Some(2));
        assert_eq!(state.update(Event::Previous), Some(0));
    }

    #[test]
    fn single_enabled_tab_never_moves() {
        let mut state = State::new([tab(0, "A"), tab(1, "B").disabled(true)]);
        assert_eq!(state.update(Event::Next), None);
        assert_eq!(state.update(Event::Previous), None);
        assert_eq!(state.selected(), Some(0));
    }

    #[test]
    fn with_selected_and_set_disabled() {
        let mut state = state().with_selected(2);
        assert_eq!(state.selected(), Some(2));
        state.set_disabled(1, false);
        assert_eq!(state.update(Event::Previous), Some(1));
    }

    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
        let chord: Chord = chord.parse().unwrap();
        keymap.resolve(chord.key(), chord.modifiers())
    }

    #[test]
    fn default_keymap_covers_every_action() {
        let keymap = default_keymap();
        assert_eq!(press(&keymap, "Ctrl+Tab"), Some(Action::Next));
        assert_eq!(press(&keymap, "ArrowRight"), Some(Action::Next));
        assert_eq!(press(&keymap, "Ctrl+Shift+Tab"), Some(Action::Previous));
        assert_eq!(press(&keymap, "ArrowLeft"), Some(Action::Previous));
        assert_eq!(press(&keymap, "Home"), Some(Action::First));
        assert_eq!(press(&keymap, "End"), Some(Action::Last));
        assert_eq!(press(&keymap, "Tab"), None);
        for action in <Action as keys::Action>::ALL {
            assert!(!keymap.chords(action).is_empty(), "{action:?}");
        }
        assert_eq!(Keymap::<Action>::defaults(), keymap);
    }

    #[test]
    fn app_keymap_holds_only_the_ctrl_tab_chords() {
        let keymap = app_keymap();
        assert_eq!(press(&keymap, "Ctrl+Tab"), Some(Action::Next));
        assert_eq!(press(&keymap, "Ctrl+Shift+Tab"), Some(Action::Previous));
        for chord in ["ArrowRight", "ArrowLeft", "Home", "End", "Tab"] {
            assert_eq!(press(&keymap, chord), None, "{chord}");
        }
        assert_eq!(keymap.len(), 2);
    }

    fn key(chord: &str) -> keys::Event {
        let chord: Chord = chord.parse().unwrap();
        keys::Event {
            key: chord.key().clone(),
            modifiers: chord.modifiers(),
        }
    }

    #[test]
    fn key_events_switch_tabs_from_anywhere() {
        let mut state = state();
        let keymap = app_keymap();

        let next = state.key_event(&keymap, &key("Ctrl+Tab")).unwrap();
        assert_eq!(next, Event::Next);
        assert_eq!(state.update(next), Some(2), "skips the disabled tab");

        let previous = state.key_event(&keymap, &key("Ctrl+Shift+Tab")).unwrap();
        assert_eq!(state.update(previous), Some(0));

        assert_eq!(state.key_event(&keymap, &key("ArrowRight")), None);
        assert_eq!(state.key_event(&keymap, &key("Ctrl+K")), None);
    }

    #[test]
    fn key_events_follow_a_changed_keymap() {
        let state = state();
        let keymap = app_keymap()
            .unbind(&"Ctrl+Tab".parse().unwrap())
            .bind("Ctrl+PageDown".parse().unwrap(), Action::Next)
            .bind("Ctrl+End".parse().unwrap(), Action::Last);
        assert_eq!(state.key_event(&keymap, &key("Ctrl+Tab")), None);
        assert_eq!(
            state.key_event(&keymap, &key("Ctrl+PageDown")),
            Some(Event::Next)
        );
        assert_eq!(
            state.key_event(&keymap, &key("Ctrl+End")),
            Some(Event::Select(3))
        );
    }

    #[test]
    fn keymap_overrides_and_unbinding() {
        let keymap = default_keymap()
            .unbind(&"ArrowRight".parse().unwrap())
            .unbind(&"ArrowLeft".parse().unwrap())
            .bind("Ctrl+PageDown".parse().unwrap(), Action::Next);
        assert_eq!(press(&keymap, "ArrowRight"), None);
        assert_eq!(press(&keymap, "Ctrl+PageDown"), Some(Action::Next));
        assert_eq!(press(&keymap, "Ctrl+Tab"), Some(Action::Next));
    }

    #[test]
    fn actions_map_to_events() {
        let mut state = state().with_selected(2);
        assert_eq!(Action::Next.event(&state), Some(Event::Next));
        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
        assert_eq!(Action::First.event(&state), Some(Event::Select(0)));
        assert_eq!(Action::Last.event(&state), Some(Event::Select(3)));

        let event = Action::First.event(&state).unwrap();
        assert_eq!(state.update(event), Some(0));

        let disabled = State::new([tab(0, "A").disabled(true)]);
        assert_eq!(Action::First.event(&disabled), None);
        assert_eq!(Action::Last.event(&disabled), None);
    }

    #[test]
    fn first_and_last_skip_disabled_tabs() {
        let state = State::new([
            tab(0, "A").disabled(true),
            tab(1, "B"),
            tab(2, "C"),
            tab(3, "D").disabled(true),
        ]);
        assert_eq!(Action::First.event(&state), Some(Event::Select(1)));
        assert_eq!(Action::Last.event(&state), Some(Event::Select(2)));
    }

    #[test]
    fn selected_tab_is_emphasised_in_both_themes() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for variant in Variant::ALL {
                let on = style(&tokens, variant, true, Status::Active);
                let off = style(&tokens, variant, false, Status::Active);
                assert_eq!(on.text_color, tokens.foreground);
                assert_eq!(off.text_color, tokens.muted_foreground);
            }
        }
    }

    #[test]
    fn only_selected_pill_is_raised() {
        let tokens = Tokens::of(&light());
        assert!(
            style(&tokens, Variant::Pills, true, Status::Active)
                .background
                .is_some()
        );
        assert!(
            style(&tokens, Variant::Pills, false, Status::Active)
                .background
                .is_none()
        );
        assert!(
            style(&tokens, Variant::Underline, true, Status::Active)
                .background
                .is_none()
        );
    }

    #[test]
    fn hover_and_disabled_change_the_label_colour() {
        let tokens = Tokens::of(&dark());
        let hovered = style(&tokens, Variant::Underline, false, Status::Hovered);
        let disabled = style(&tokens, Variant::Underline, false, Status::Disabled);
        assert_eq!(hovered.text_color, tokens.foreground);
        assert!(disabled.text_color.a < tokens.muted_foreground.a);
    }

    #[test]
    fn indicator_and_list_styles() {
        let tokens = Tokens::of(&light());
        assert!(indicator_style(&tokens, true).background.is_some());
        assert!(indicator_style(&tokens, false).background.is_none());
        assert!(list_style(&tokens, Variant::Pills).background.is_some());
        assert!(list_style(&tokens, Variant::Underline).background.is_none());
    }
}