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
//! Sections that expand and collapse under their headers.
//!
//! [`State`] tracks which sections are open. In [`Mode::Single`] opening a
//! section closes the others; in [`Mode::Multiple`] each one is independent.
//!
//! Shortcuts from [`default_keymap`] act only while a section header has
//! keyboard focus (Tab reaches each one) or was the last thing pressed, so
//! the arrow keys stay with scrolling content and other controls the rest
//! of the time. To expand and collapse every section from anywhere, pass
//! the key presses [`keys::subscription`] delivers to [`State::key_events`]
//! with [`app_keymap`].

use std::rc::Rc;

use iced::keyboard::key::Named;
use iced::widget::{self, button::Status, column, container, row, rule, text};
use iced::{Alignment, Element, Length, Theme};

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

/// How many sections may be open at once.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Mode {
    /// At most one section is open.
    #[default]
    Single,
    /// Any number of sections are open.
    Multiple,
}

impl Mode {
    pub const ALL: [Mode; 2] = [Mode::Single, Mode::Multiple];
}

/// Opens or closes a section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event<Id> {
    Toggle(Id),
    Open(Id),
    Close(Id),
}

/// What changed after an [`Event`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Output<Id> {
    Opened(Id),
    Closed(Id),
}

/// Which sections are open.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct State<Id> {
    mode: Mode,
    open: Vec<Id>,
}

impl<Id: Copy + PartialEq> State<Id> {
    /// Starts with every section closed.
    pub fn new(mode: Mode) -> Self {
        Self {
            mode,
            open: Vec::new(),
        }
    }

    /// Starts with `id` open.
    pub fn with_open(mut self, id: Id) -> Self {
        let _ = self.update(Event::Open(id));
        self
    }

    pub fn mode(&self) -> Mode {
        self.mode
    }

    /// Switches mode. Going to single mode keeps only the first open section.
    pub fn set_mode(&mut self, mode: Mode) {
        self.mode = mode;
        if mode == Mode::Single {
            self.open.truncate(1);
        }
    }

    pub fn is_open(&self, id: Id) -> bool {
        self.open.contains(&id)
    }

    /// The open sections, in the order they were opened.
    pub fn open(&self) -> &[Id] {
        &self.open
    }

    pub fn update(&mut self, event: Event<Id>) -> Option<Output<Id>> {
        match event {
            Event::Toggle(id) if self.is_open(id) => self.update(Event::Close(id)),
            Event::Toggle(id) | Event::Open(id) => {
                if self.is_open(id) {
                    return None;
                }
                if self.mode == Mode::Single {
                    self.open.clear();
                }
                self.open.push(id);
                Some(Output::Opened(id))
            }
            Event::Close(id) => {
                let index = self.open.iter().position(|open| *open == id)?;
                let _ = self.open.remove(index);
                Some(Output::Closed(id))
            }
        }
    }

    /// Turns a key press from [`keys::subscription`] into events through
    /// `keymap`, usually [`app_keymap`], given every section id in display
    /// order, for shortcuts that work while no header has focus. Keys a
    /// focused header uses never reach the subscription, so nothing happens
    /// twice.
    pub fn key_events(
        &self,
        keymap: &Keymap<Action>,
        sections: &[Id],
        key: &keys::Event,
    ) -> Vec<Event<Id>> {
        keymap
            .resolve_event(key)
            .map(|action| action.events(self, sections))
            .unwrap_or_default()
    }
}

/// What an accordion keyboard shortcut does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Action {
    /// Moves the most recently opened section to the next one, wrapping.
    Next,
    /// Moves the most recently opened section to the previous one, wrapping.
    Previous,
    ExpandAll,
    CollapseAll,
    /// Opens or closes the section whose header has the keys.
    Toggle,
}

impl Action {
    /// The events this action sends to `state`, given every section id in
    /// display order. `ExpandAll` does nothing in [`Mode::Single`], and
    /// `Toggle` nothing here, since it needs a header; see
    /// [`header_events`](Self::header_events).
    pub fn events<Id: Copy + PartialEq>(
        self,
        state: &State<Id>,
        sections: &[Id],
    ) -> Vec<Event<Id>> {
        match self {
            Action::Toggle => Vec::new(),
            Action::Next => step(state, sections, true),
            Action::Previous => step(state, sections, false),
            Action::ExpandAll if state.mode == Mode::Single => Vec::new(),
            Action::ExpandAll => sections
                .iter()
                .filter(|id| !state.is_open(**id))
                .map(|id| Event::Open(*id))
                .collect(),
            Action::CollapseAll => state.open.iter().map(|id| Event::Close(*id)).collect(),
        }
    }

    /// The events this action sends when the header of section `header`
    /// resolved it: `Toggle` opens or closes that section, and the rest act
    /// as [`events`](Self::events).
    pub fn header_events<Id: Copy + PartialEq>(
        self,
        state: &State<Id>,
        sections: &[Id],
        header: Id,
    ) -> Vec<Event<Id>> {
        match self {
            Action::Toggle => vec![Event::Toggle(header)],
            _ => self.events(state, sections),
        }
    }
}

fn step<Id: Copy + PartialEq>(state: &State<Id>, sections: &[Id], forward: bool) -> Vec<Event<Id>> {
    let len = sections.len();
    if len == 0 {
        return Vec::new();
    }
    let current = state.open.last().copied();
    let index = current.and_then(|id| sections.iter().position(|section| *section == id));
    let target = match (index, forward) {
        (Some(index), true) => (index + 1) % len,
        (Some(index), false) => (index + len - 1) % len,
        (None, true) => 0,
        (None, false) => len - 1,
    };
    let target = sections[target];
    if current == Some(target) {
        return Vec::new();
    }
    current
        .map(Event::Close)
        .into_iter()
        .chain([Event::Open(target)])
        .collect()
}

impl keys::Action for Action {
    const ALL: &'static [Self] = &[
        Action::Next,
        Action::Previous,
        Action::ExpandAll,
        Action::CollapseAll,
        Action::Toggle,
    ];

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

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

    fn description(self) -> &'static str {
        match self {
            Action::Next => {
                "Opens the next section in place of the current one, wrapping at the end."
            }
            Action::Previous => {
                "Opens the previous section in place of the current one, wrapping at the start."
            }
            Action::ExpandAll => "Opens every section. Only applies when several may be open.",
            Action::CollapseAll => "Closes every open section.",
            Action::Toggle => "Opens or closes the section whose header has focus.",
        }
    }
}

/// The default accordion shortcuts:
///
/// | Keys | Action |
/// | --- | --- |
/// | `ArrowDown` | [`Action::Next`] |
/// | `ArrowUp` | [`Action::Previous`] |
/// | `Ctrl+Shift+ArrowDown` | [`Action::ExpandAll`] |
/// | `Ctrl+Shift+ArrowUp` | [`Action::CollapseAll`] |
/// | `Enter`, `Space` | [`Action::Toggle`] |
///
/// The accordion resolves them itself while a header has keyboard focus or
/// was the last thing pressed. Pass a changed keymap with
/// [`Accordion::keymap`]. To expand and collapse from anywhere, pass key
/// presses to [`State::key_events`] with [`app_keymap`].
pub fn default_keymap() -> Keymap<Action> {
    app_keymap()
        .bind(Chord::named(Named::ArrowDown), Action::Next)
        .bind(Chord::named(Named::ArrowUp), Action::Previous)
        .bind(Chord::named(Named::Enter), Action::Toggle)
        .bind(Chord::named(Named::Space), Action::Toggle)
}

/// The shortcuts that work from anywhere in the app, for
/// [`State::key_events`]:
///
/// | Keys | Action |
/// | --- | --- |
/// | `Ctrl+Shift+ArrowDown` | [`Action::ExpandAll`] |
/// | `Ctrl+Shift+ArrowUp` | [`Action::CollapseAll`] |
///
/// The plain arrows are left out, since scrolling content and other
/// controls use them.
pub fn app_keymap() -> Keymap<Action> {
    Keymap::new()
        .bind(
            Chord::named(Named::ArrowDown).ctrl().shift(),
            Action::ExpandAll,
        )
        .bind(
            Chord::named(Named::ArrowUp).ctrl().shift(),
            Action::CollapseAll,
        )
}

/// An accordion builder. Convert it into an [`Element`] to render.
pub struct Accordion<'a, Id, Message> {
    state: &'a State<Id>,
    items: Vec<(Id, text::Fragment<'a>, Element<'a, Message>)>,
    keymap: Keymap<Action>,
    on_event: Option<Box<dyn Fn(Event<Id>) -> Message + 'a>>,
}

/// Renders sections whose open state comes from `state`. Without
/// [`on_event`](Accordion::on_event) the headers render disabled.
pub fn accordion<Id, Message>(state: &State<Id>) -> Accordion<'_, Id, Message> {
    Accordion {
        state,
        items: Vec::new(),
        keymap: default_keymap(),
        on_event: None,
    }
}

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

impl<'a, Id, Message> Accordion<'a, Id, Message> {
    /// Adds a section with a header and the content shown while open.
    /// Content inherits muted text unless it supplies its own colour.
    pub fn item(
        mut self,
        id: Id,
        title: impl text::IntoFragment<'a>,
        content: impl Into<Element<'a, Message>>,
    ) -> Self {
        self.items.push((id, title.into_fragment(), content.into()));
        self
    }

    /// Replaces the [`default_keymap`] the headers resolve keys with while
    /// one has keyboard focus or was the last thing pressed.
    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
        self.keymap = keymap;
        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
    }
}

/// What a header does with a resolved shortcut: the messages to send.
type OnAction<'a, Message> = Box<dyn Fn(Action) -> Vec<Message> + 'a>;

impl<'a, Id, Message> From<Accordion<'a, Id, Message>> for Element<'a, Message>
where
    Id: Copy + PartialEq + 'a,
    Message: Clone + 'a,
{
    fn from(accordion: Accordion<'a, Id, Message>) -> Self {
        let Accordion {
            state,
            items,
            keymap,
            on_event,
        } = accordion;
        let sections: Rc<[Id]> = items.iter().map(|(id, _, _)| *id).collect();
        let on_event: Option<Rc<dyn Fn(Event<Id>) -> Message + 'a>> = on_event.map(Rc::from);

        column(items.into_iter().map(|(id, title, content)| {
            let open = state.is_open(id);
            let keys = on_event.as_ref().map(|on_event| {
                let (on_event, sections) = (Rc::clone(on_event), Rc::clone(&sections));
                let on_action: OnAction<'a, Message> = Box::new(move |action: Action| {
                    action
                        .header_events(state, &sections, id)
                        .into_iter()
                        .map(|event| on_event(event))
                        .collect()
                });
                (keymap.clone(), on_action)
            });
            let message = on_event
                .as_ref()
                .map(|on_event| on_event(Event::Toggle(id)));
            section(title, content, open, message, keys)
        }))
        .width(Length::Fill)
        .into()
    }
}

fn section<'a, Message: Clone + 'a>(
    title: text::Fragment<'a>,
    content: Element<'a, Message>,
    open: bool,
    message: Option<Message>,
    keys: Option<(Keymap<Action>, OnAction<'a, Message>)>,
) -> Element<'a, Message> {
    let enabled = message.is_some();
    #[cfg(feature = "icedwright")]
    let (name, key) = (
        title.clone(),
        icedwright_probe::Key::from(format!("iced_cube::accordion/{title}")),
    );
    let chevron = if open {
        crate::lucide!(ChevronUp)
    } else {
        crate::lucide!(ChevronDown)
    };

    let header = widget::button(
        row![
            text(title)
                .font(crate::theme::semibold())
                .size(text_size::SM)
                .width(Length::Fill),
            themed(chevron, 16.0, opacity(enabled), |theme| {
                Tokens::of(theme).muted_foreground
            }),
        ]
        .spacing(space::MD)
        .align_y(Alignment::Center),
    )
    .width(Length::Fill)
    .padding([space::MD, 0.0])
    .on_press_maybe(message)
    .style(|theme, status| style(&Tokens::of(theme), status));
    // Each header takes focus and keys, rather than the whole accordion,
    // so arrow keys pressed in a section's content stay with it.
    let header: Element<'a, Message> = match keys {
        Some((keymap, on_action)) => focus::keyed(header, keymap, on_action)
            .radius(radius::SM)
            .into(),
        None => header.into(),
    };
    #[cfg(feature = "icedwright")]
    let header = {
        icedwright_probe::semantic(header)
            .role(icedwright_probe::role::Button)
            .name(name.clone())
            .expanded(open)
            .controls(key.clone())
            .disabled(!enabled)
            .component("iced_cube::accordion")
    };

    let mut body = column![header].width(Length::Fill);
    if open {
        let panel = container(content)
            .padding(iced::Padding::ZERO.bottom(space::LG).right(space::XL))
            .width(Length::Fill)
            .style(|theme: &Theme| container::Style {
                text_color: Some(Tokens::of(theme).muted_foreground),
                ..container::Style::default()
            });
        #[cfg(feature = "icedwright")]
        let panel = icedwright_probe::semantic(panel)
            .role(icedwright_probe::role::Region)
            .name(name)
            .key(key)
            .component("iced_cube::accordion");
        body = body.push(panel);
    }
    body.push(rule::horizontal(1).style(|theme: &Theme| {
        let tokens = Tokens::of(theme);
        rule::Style {
            color: mix(tokens.background, tokens.border, 0.7),
            radius: 0.0.into(),
            fill_mode: rule::FillMode::Full,
            snap: true,
        }
    }))
    .into()
}

/// The style of a section header.
pub fn style(tokens: &Tokens, status: Status) -> widget::button::Style {
    let text_color = match status {
        Status::Active => tokens.foreground,
        Status::Hovered | Status::Pressed => tokens.muted_foreground,
        Status::Disabled => fade(tokens.foreground, 0.5),
    };
    widget::button::Style {
        background: None,
        text_color,
        ..widget::button::Style::default()
    }
}

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

    #[test]
    fn starts_closed_in_single_mode_by_default() {
        let state: State<u8> = State::default();
        assert_eq!(state.mode(), Mode::Single);
        assert!(state.open().is_empty());
    }

    fn apply(state: &mut State<u8>, action: Action, sections: &[u8]) {
        for event in action.events(state, sections) {
            let _ = state.update(event);
        }
    }

    #[test]
    fn next_and_previous_move_the_open_section_and_wrap() {
        let sections = [1, 2, 3];
        let mut state = State::new(Mode::Single);
        apply(&mut state, Action::Next, &sections);
        assert_eq!(state.open(), [1]);
        apply(&mut state, Action::Next, &sections);
        assert_eq!(state.open(), [2]);
        apply(&mut state, Action::Previous, &sections);
        apply(&mut state, Action::Previous, &sections);
        assert_eq!(state.open(), [3]);

        let mut closed = State::new(Mode::Single);
        apply(&mut closed, Action::Previous, &sections);
        assert_eq!(closed.open(), [3]);
    }

    #[test]
    fn next_in_multiple_mode_moves_only_the_latest_section() {
        let mut state = State::new(Mode::Multiple).with_open(1).with_open(2);
        apply(&mut state, Action::Next, &[1, 2, 3]);
        assert_eq!(state.open(), [1, 3]);
    }

    #[test]
    fn next_with_one_or_no_sections() {
        let state = State::new(Mode::Single).with_open(1);
        assert!(Action::Next.events(&state, &[1]).is_empty());
        assert!(Action::Next.events(&state, &[]).is_empty());
    }

    #[test]
    fn expand_and_collapse_all() {
        let sections = [1, 2, 3];
        let mut state = State::new(Mode::Multiple).with_open(2);
        assert_eq!(
            Action::ExpandAll.events(&state, &sections),
            [Event::Open(1), Event::Open(3)]
        );
        apply(&mut state, Action::ExpandAll, &sections);
        assert_eq!(state.open(), [2, 1, 3]);
        apply(&mut state, Action::CollapseAll, &sections);
        assert!(state.open().is_empty());

        let single = State::new(Mode::Single).with_open(1);
        assert!(Action::ExpandAll.events(&single, &sections).is_empty());
        assert_eq!(
            Action::CollapseAll.events(&single, &sections),
            [Event::Close(1)]
        );
    }

    #[test]
    fn default_keymap_and_overrides() {
        let keymap = default_keymap();
        let resolve = |keymap: &Keymap<Action>, chord: &str| {
            let chord: Chord = chord.parse().unwrap();
            keymap.resolve(chord.key(), chord.modifiers())
        };
        assert_eq!(resolve(&keymap, "ArrowDown"), Some(Action::Next));
        assert_eq!(resolve(&keymap, "ArrowUp"), Some(Action::Previous));
        assert_eq!(
            resolve(&keymap, "Ctrl+Shift+ArrowDown"),
            Some(Action::ExpandAll)
        );
        assert_eq!(
            resolve(&keymap, "Ctrl+Shift+ArrowUp"),
            Some(Action::CollapseAll)
        );
        let custom = keymap
            .unbind_action(&Action::Next)
            .bind("N".parse().unwrap(), Action::Next);
        assert_eq!(resolve(&custom, "ArrowDown"), None);
        assert_eq!(resolve(&custom, "n"), Some(Action::Next));
    }

    #[test]
    fn toggle_acts_on_the_header_that_resolved_it() {
        let sections = [1, 2];
        let state = State::new(Mode::Single).with_open(1);
        assert!(Action::Toggle.events(&state, &sections).is_empty());
        assert_eq!(
            Action::Toggle.header_events(&state, &sections, 2),
            [Event::Toggle(2)]
        );
        assert_eq!(
            Action::Next.header_events(&state, &sections, 1),
            Action::Next.events(&state, &sections)
        );
        let keymap = default_keymap();
        for chord in ["Enter", "Space"] {
            let chord: Chord = chord.parse().unwrap();
            assert_eq!(
                keymap.resolve(chord.key(), chord.modifiers()),
                Some(Action::Toggle)
            );
        }
    }

    #[test]
    fn app_keymap_holds_only_the_expand_and_collapse_chords() {
        let keymap = app_keymap();
        assert_eq!(keymap.len(), 2);
        let key = |chord: &str| {
            let chord: Chord = chord.parse().unwrap();
            keys::Event {
                key: chord.key().clone(),
                modifiers: chord.modifiers(),
            }
        };
        let sections = [1, 2];
        let state = State::new(Mode::Multiple).with_open(2);
        assert_eq!(
            state.key_events(&keymap, &sections, &key("Ctrl+Shift+ArrowDown")),
            [Event::Open(1)]
        );
        assert_eq!(
            state.key_events(&keymap, &sections, &key("Ctrl+Shift+ArrowUp")),
            [Event::Close(2)]
        );
        assert!(
            state
                .key_events(&keymap, &sections, &key("ArrowDown"))
                .is_empty()
        );
    }

    #[test]
    fn single_mode_keeps_one_section_open() {
        let mut state = State::new(Mode::Single);
        assert_eq!(state.update(Event::Toggle(1)), Some(Output::Opened(1)));
        assert_eq!(state.update(Event::Toggle(2)), Some(Output::Opened(2)));
        assert_eq!(state.open(), [2]);
        assert_eq!(state.update(Event::Toggle(2)), Some(Output::Closed(2)));
        assert!(state.open().is_empty());
    }

    #[test]
    fn multiple_mode_opens_sections_independently() {
        let mut state = State::new(Mode::Multiple);
        let _ = state.update(Event::Toggle(1));
        let _ = state.update(Event::Toggle(2));
        assert!(state.is_open(1) && state.is_open(2));
        let _ = state.update(Event::Toggle(1));
        assert_eq!(state.open(), [2]);
    }

    #[test]
    fn open_and_close_are_idempotent() {
        let mut state = State::new(Mode::Multiple).with_open(1);
        assert_eq!(state.update(Event::Open(1)), None);
        assert_eq!(state.update(Event::Close(3)), None);
        assert_eq!(state.update(Event::Close(1)), Some(Output::Closed(1)));
        assert_eq!(state.update(Event::Close(1)), None);
    }

    #[test]
    fn switching_to_single_keeps_the_first_open_section() {
        let mut state = State::new(Mode::Multiple).with_open(3).with_open(1);
        state.set_mode(Mode::Single);
        assert_eq!(state.open(), [3]);
        let _ = state.update(Event::Open(1));
        assert_eq!(state.open(), [1]);
    }

    #[test]
    fn header_style_in_every_status_and_theme() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            assert_eq!(style(&tokens, Status::Active).text_color, tokens.foreground);
            assert_eq!(
                style(&tokens, Status::Hovered).text_color,
                tokens.muted_foreground
            );
            assert_eq!(
                style(&tokens, Status::Pressed).text_color,
                tokens.muted_foreground
            );
            assert!(style(&tokens, Status::Disabled).text_color.a < 1.0);
            assert!(style(&tokens, Status::Active).background.is_none());
        }
    }
}