Skip to main content

iced_cube/navigation/
document_tabs.rs

1//! A strip of open documents above an editor, one tab per document.
2//!
3//! [`State`] owns the documents in order, the active one and the order they
4//! were last used in. Its [`update`](State::update) activates, reorders and
5//! pins tabs, and turns close gestures into [`Output::CloseRequested`] so
6//! the app decides what closing means, such as asking to save a modified
7//! document first, before it calls [`State::close`].
8//!
9//! Each tab shows an optional icon, a label that ends in an ellipsis past
10//! its maximum width, and a slot that holds the close button on the active
11//! and hovered tab, or a dot while the document has unsaved changes. The
12//! slot is always reserved, so labels do not move when it changes. Pinned
13//! tabs sit first, compact and without a close button.
14//!
15//! With the pointer, a press activates a tab, dragging moves it (a line
16//! marks where it will land), a middle click asks to close it and a right
17//! click opens its context menu. When the tabs do not fit, pinned tabs stay
18//! at the start and the wheel scrolls the others, and a button at the end
19//! of the strip lists every tab. The strip keeps the active tab in view.
20//!
21//! [`Document::closable`] and [`Document::locked`] keep a document open
22//! and pinned, such as a list the other tabs are opened from.
23//!
24//! Keyboard shortcuts resolve through a [`Keymap`] of [`Action`]s; see
25//! [`default_keymap`] and [`crate::keys`].
26
27use std::rc::Rc;
28
29use iced::advanced::layout::{self, Layout};
30use iced::advanced::mouse;
31
32use crate::click::{self, Click};
33use iced::advanced::overlay;
34use iced::advanced::renderer;
35use iced::advanced::widget::operation::scrollable::{AbsoluteOffset, RelativeOffset, Scrollable};
36use iced::advanced::widget::{Operation, Tree, Widget, tree};
37use iced::advanced::{Clipboard, Renderer as _, Shell};
38use iced::alignment::Vertical;
39use iced::border::Radius;
40use iced::keyboard::{self, key::Named};
41use iced::touch::{self, Finger};
42use iced::widget::{self, button::Status, container, row};
43use iced::{
44    Alignment, Background, Border, Color, Element, Event as Input, Length, Padding, Point,
45    Rectangle, Renderer, Size, Subscription, Theme, Vector,
46};
47
48use crate::data::ellipsis::ellipsis;
49use crate::icon::{Glyph, opacity, themed};
50use crate::keys::{self, Chord, Keymap};
51use crate::overlay::anchored::{Align, Placement, Side, anchored};
52use crate::overlay::context_menu::{self, KEYBOARD_GAP};
53use crate::overlay::dropdown_menu::{self, Entry, item, radio_item, separator};
54use crate::overlay::menu::{self, RowStatus};
55use crate::overlay::scrolling::{fitted, scrolling};
56use crate::overlay::tooltip;
57use crate::primitives::button::Size as ButtonSize;
58use crate::primitives::icon_button::icon_button;
59use crate::theme::{Tokens, fade, mix, radius, space, text_size};
60
61/// Height of the strip and its tabs.
62pub const HEIGHT: f32 = 36.0;
63
64/// Default widest a label grows before it ends in an ellipsis.
65pub const MAX_LABEL_WIDTH: f32 = 200.0;
66
67/// Widest label of a pinned tab without an icon.
68pub const PINNED_LABEL_WIDTH: f32 = 80.0;
69
70/// Widest the list of every tab grows before its labels end in an ellipsis.
71pub const OVERFLOW_WIDTH: f32 = 320.0;
72
73/// How far, in logical pixels, a pressed tab moves before it drags.
74pub const DRAG_THRESHOLD: f32 = 4.0;
75
76/// Side of the square slot for the close button or the modified dot.
77const SLOT: f32 = 16.0;
78const CLOSE_ICON: f32 = 12.0;
79const ICON: f32 = 16.0;
80const DOT: f32 = 8.0;
81const PADDING_X: f32 = 12.0;
82const DIVIDER_HEIGHT: f32 = 16.0;
83const INDICATOR_WIDTH: f32 = 2.0;
84/// Pixels one wheel line scrolls the strip.
85const WHEEL_LINE: f32 = 40.0;
86
87/// One open document.
88#[derive(Debug, Clone, PartialEq)]
89pub struct Document<Id> {
90    pub id: Id,
91    pub label: String,
92    pub icon: Option<Glyph>,
93    /// Unsaved changes, shown as a dot in the tab's slot.
94    pub modified: bool,
95    pub pinned: bool,
96    /// Whether the user can ask to close it. See [`Document::closable`].
97    pub closable: bool,
98    /// Whether it keeps its pinned state. See [`Document::locked`].
99    pub locked: bool,
100}
101
102/// Creates a saved, unpinned document that can be closed and pinned.
103pub fn document<Id>(id: Id, label: impl Into<String>) -> Document<Id> {
104    Document {
105        id,
106        label: label.into(),
107        icon: None,
108        modified: false,
109        pinned: false,
110        closable: true,
111        locked: false,
112    }
113}
114
115impl<Id> Document<Id> {
116    pub fn icon(mut self, glyph: Glyph) -> Self {
117        self.icon = Some(glyph);
118        self
119    }
120
121    pub fn modified(mut self, modified: bool) -> Self {
122        self.modified = modified;
123        self
124    }
125
126    pub fn pinned(mut self, pinned: bool) -> Self {
127        self.pinned = pinned;
128        self
129    }
130
131    /// With `false`, the tab has no close button or Close item, and no
132    /// close event or shortcut asks to close it. Defaults to `true`.
133    pub fn closable(mut self, closable: bool) -> Self {
134        self.closable = closable;
135        self
136    }
137
138    /// With `true`, the document stays pinned or unpinned as it is: its
139    /// menu has no Pin or Unpin item and [`Event::Pin`] leaves it alone. It
140    /// still moves within its group. Defaults to `false`.
141    pub fn locked(mut self, locked: bool) -> Self {
142        self.locked = locked;
143        self
144    }
145}
146
147/// An item in a tab's context menu.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
149pub enum MenuItem {
150    Close,
151    CloseOthers,
152    CloseToTheRight,
153    CloseSaved,
154    CloseAll,
155    Pin,
156    Unpin,
157    /// An item the app added with [`State::with_menu_items`]. Choosing it
158    /// returns [`Output::Custom`] with the tab it was chosen on.
159    Custom(&'static str),
160}
161
162/// Changes to the documents.
163#[derive(Debug, Clone, Copy, PartialEq)]
164pub enum Event<Id> {
165    /// Makes a document the active one.
166    Activate(Id),
167    /// Activates the next document, wrapping at the end.
168    Next,
169    /// Activates the previous document, wrapping at the start.
170    Previous,
171    /// Activates the next document in most-recently-used order. Repeated
172    /// presses walk further down the list until [`Event::EndCycle`].
173    RecentNext,
174    /// Walks the most-recently-used list the other way.
175    RecentPrevious,
176    /// Ends a walk through the most-recently-used list, making the document
177    /// it stopped on the most recent. Any other event ends it too.
178    EndCycle,
179    /// Asks to close one document, unless it is not closable.
180    Close(Id),
181    /// Asks to close every other unpinned, closable document.
182    CloseOthers(Id),
183    /// Asks to close the unpinned, closable documents after this one.
184    CloseToTheRight(Id),
185    /// Asks to close every unpinned, closable document without unsaved
186    /// changes.
187    CloseSaved,
188    /// Asks to close every unpinned, closable document.
189    CloseAll,
190    /// Moves a document to an index. Pinned documents stay before the
191    /// others, so the index is clamped to the document's group.
192    Move(Id, usize),
193    /// Pins or unpins a document, unless it is locked. It moves to the end
194    /// of the pinned tabs or the start of the others.
195    Pin(Id, bool),
196    /// Asks for a new document, from the new tab button, a double click on
197    /// the empty strip or a shortcut.
198    New,
199    /// The context menu of a tab.
200    Menu(context_menu::Event<MenuItem, Id>),
201    /// The menu listing every document.
202    Overflow(dropdown_menu::Event<Id>),
203}
204
205/// Sent by [`cycle_end`] when every modifier key is released.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207pub struct CycleEnd;
208
209impl<Id> From<CycleEnd> for Event<Id> {
210    fn from(_: CycleEnd) -> Self {
211        Event::EndCycle
212    }
213}
214
215/// Reports when the last modifier key is released, which ends a walk
216/// through recent documents as editors do when Ctrl is let go.
217pub fn cycle_end() -> Subscription<CycleEnd> {
218    keyboard::listen().filter_map(|event| match event {
219        keyboard::Event::ModifiersChanged(modifiers) if modifiers.is_empty() => Some(CycleEnd),
220        _ => None,
221    })
222}
223
224/// What an [`Event`] changed or asks the app to do.
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub enum Output<Id> {
227    /// A different document became active.
228    Activated(Id),
229    /// The user asked to close these documents, in strip order. Nothing is
230    /// closed yet: the app saves or confirms as it needs to, then calls
231    /// [`State::close`].
232    CloseRequested(Vec<Id>),
233    /// A document moved from one index to another.
234    Moved { id: Id, from: usize, to: usize },
235    /// A document was pinned or unpinned.
236    Pinned(Id, bool),
237    /// The user asked for a new document.
238    NewTab,
239    /// An app menu item was chosen on a tab.
240    Custom(&'static str, Id),
241}
242
243/// The open documents, the active one and the order they were used in.
244#[derive(Debug, Clone, PartialEq)]
245pub struct State<Id> {
246    documents: Vec<Document<Id>>,
247    active: Option<Id>,
248    /// Every document id, most recently used first.
249    recent: Vec<Id>,
250    /// Where a walk through `recent` has got to.
251    cycle: Option<usize>,
252    menu: context_menu::State<MenuItem, Id>,
253    extra: Vec<Entry<MenuItem>>,
254    overflow: dropdown_menu::State<Id>,
255}
256
257impl<Id: Copy + PartialEq> State<Id> {
258    /// Opens `documents`, pinned ones first, with the first one active.
259    /// Ids must be unique.
260    pub fn new(documents: impl IntoIterator<Item = Document<Id>>) -> Self {
261        let (mut documents, others): (Vec<_>, Vec<_>) =
262            documents.into_iter().partition(|document| document.pinned);
263        documents.extend(others);
264        let recent = documents.iter().map(|document| document.id).collect();
265        Self {
266            active: documents.first().map(|document| document.id),
267            documents,
268            recent,
269            cycle: None,
270            menu: context_menu::State::new([]),
271            extra: Vec::new(),
272            overflow: dropdown_menu::State::new([]),
273        }
274    }
275
276    /// Starts on `id`, when it exists.
277    pub fn with_active(mut self, id: Id) -> Self {
278        let _ = self.activate(id);
279        self
280    }
281
282    /// Adds items to the end of every tab's context menu, such as "Copy
283    /// path". Give them [`MenuItem::Custom`] ids.
284    pub fn with_menu_items(mut self, entries: impl IntoIterator<Item = Entry<MenuItem>>) -> Self {
285        self.extra = entries.into_iter().collect();
286        self
287    }
288
289    /// The documents in strip order.
290    pub fn documents(&self) -> &[Document<Id>] {
291        &self.documents
292    }
293
294    pub fn document(&self, id: Id) -> Option<&Document<Id>> {
295        self.documents.iter().find(|document| document.id == id)
296    }
297
298    pub fn active(&self) -> Option<Id> {
299        self.active
300    }
301
302    pub fn is_active(&self, id: Id) -> bool {
303        self.active == Some(id)
304    }
305
306    /// Document ids, most recently used first.
307    pub fn recent(&self) -> &[Id] {
308        &self.recent
309    }
310
311    /// The tab context menu.
312    pub fn menu(&self) -> &context_menu::State<MenuItem, Id> {
313        &self.menu
314    }
315
316    /// The menu listing every document.
317    pub fn overflow(&self) -> &dropdown_menu::State<Id> {
318        &self.overflow
319    }
320
321    /// How many documents are pinned. They are always the first ones.
322    pub fn pinned_count(&self) -> usize {
323        self.documents
324            .iter()
325            .take_while(|document| document.pinned)
326            .count()
327    }
328
329    fn index_of(&self, id: Id) -> Option<usize> {
330        self.documents.iter().position(|document| document.id == id)
331    }
332
333    fn active_index(&self) -> Option<usize> {
334        self.active.and_then(|id| self.index_of(id))
335    }
336
337    /// Activates `document`, adding it at the end of its group (pinned or
338    /// not) when it is not open yet.
339    pub fn open(&mut self, document: Document<Id>) {
340        self.end_cycle();
341        let id = document.id;
342        if self.index_of(id).is_none() {
343            let index = if document.pinned {
344                self.pinned_count()
345            } else {
346                self.documents.len()
347            };
348            self.documents.insert(index, document);
349            self.recent.push(id);
350        }
351        let _ = self.activate(id);
352    }
353
354    /// Closes documents. When the active one closes, the most recently used
355    /// one left becomes active, and is returned.
356    pub fn close(&mut self, ids: &[Id]) -> Option<Id> {
357        self.end_cycle();
358        self.documents
359            .retain(|document| !ids.contains(&document.id));
360        self.recent.retain(|id| !ids.contains(id));
361        let closed = self.active.is_some_and(|id| ids.contains(&id));
362        if !closed {
363            return None;
364        }
365        self.active = self.recent.first().copied();
366        self.active
367    }
368
369    /// Marks a document as having unsaved changes, or as saved.
370    pub fn set_modified(&mut self, id: Id, modified: bool) {
371        if let Some(document) = self.document_mut(id) {
372            document.modified = modified;
373        }
374    }
375
376    pub fn set_label(&mut self, id: Id, label: impl Into<String>) {
377        if let Some(document) = self.document_mut(id) {
378            document.label = label.into();
379        }
380    }
381
382    fn document_mut(&mut self, id: Id) -> Option<&mut Document<Id>> {
383        self.documents.iter_mut().find(|document| document.id == id)
384    }
385
386    /// Applies an event and returns what changed, if anything.
387    pub fn update(&mut self, event: Event<Id>) -> Option<Output<Id>> {
388        if !matches!(event, Event::RecentNext | Event::RecentPrevious) {
389            self.end_cycle();
390        }
391        match event {
392            Event::Activate(id) => self.activate(id),
393            Event::Next => self.step(true),
394            Event::Previous => self.step(false),
395            Event::RecentNext => self.walk(true),
396            Event::RecentPrevious => self.walk(false),
397            Event::EndCycle => None,
398            Event::Close(id) => self.request(|document| document.id == id && document.closable),
399            Event::CloseOthers(id) => {
400                self.request(|document| document.id != id && in_bulk_close(document))
401            }
402            Event::CloseToTheRight(id) => {
403                let index = self.index_of(id)?;
404                let right: Vec<Id> = self.documents[index + 1..]
405                    .iter()
406                    .filter(|document| in_bulk_close(document))
407                    .map(|document| document.id)
408                    .collect();
409                (!right.is_empty()).then_some(Output::CloseRequested(right))
410            }
411            Event::CloseSaved => {
412                self.request(|document| !document.modified && in_bulk_close(document))
413            }
414            Event::CloseAll => self.request(in_bulk_close),
415            Event::Move(id, to) => self.move_to(id, to),
416            Event::Pin(id, pinned) => self.pin(id, pinned),
417            Event::New => Some(Output::NewTab),
418            Event::Menu(event) => self.menu_event(event),
419            Event::Overflow(event) => self.overflow_event(event),
420        }
421    }
422
423    fn activate(&mut self, id: Id) -> Option<Output<Id>> {
424        self.index_of(id)?;
425        if self.active == Some(id) {
426            return None;
427        }
428        self.active = Some(id);
429        self.touch(id);
430        Some(Output::Activated(id))
431    }
432
433    /// Moves `id` to the front of the recent list.
434    fn touch(&mut self, id: Id) {
435        self.recent.retain(|recent| *recent != id);
436        self.recent.insert(0, id);
437    }
438
439    fn step(&mut self, forward: bool) -> Option<Output<Id>> {
440        let len = self.documents.len();
441        let current = self.active_index()?;
442        let next = if forward {
443            (current + 1) % len
444        } else {
445            (current + len - 1) % len
446        };
447        let id = self.documents[next].id;
448        self.activate(id)
449    }
450
451    fn walk(&mut self, forward: bool) -> Option<Output<Id>> {
452        let len = self.recent.len();
453        if len < 2 {
454            return None;
455        }
456        let current = self.cycle.unwrap_or(0);
457        let next = if forward {
458            (current + 1) % len
459        } else {
460            (current + len - 1) % len
461        };
462        self.cycle = Some(next);
463        let id = self.recent[next];
464        self.active = Some(id);
465        Some(Output::Activated(id))
466    }
467
468    fn end_cycle(&mut self) {
469        if self.cycle.take().is_none() {
470            return;
471        }
472        if let Some(id) = self.active {
473            self.touch(id);
474        }
475    }
476
477    fn request(&self, close: impl Fn(&Document<Id>) -> bool) -> Option<Output<Id>> {
478        let ids: Vec<Id> = self
479            .documents
480            .iter()
481            .filter(|document| close(document))
482            .map(|document| document.id)
483            .collect();
484        (!ids.is_empty()).then_some(Output::CloseRequested(ids))
485    }
486
487    fn move_to(&mut self, id: Id, to: usize) -> Option<Output<Id>> {
488        let from = self.index_of(id)?;
489        let pinned = self.pinned_count();
490        let (start, end) = if from < pinned {
491            (0, pinned - 1)
492        } else {
493            (pinned, self.documents.len() - 1)
494        };
495        let to = to.clamp(start, end);
496        if to == from {
497            return None;
498        }
499        let document = self.documents.remove(from);
500        self.documents.insert(to, document);
501        Some(Output::Moved { id, from, to })
502    }
503
504    fn pin(&mut self, id: Id, pinned: bool) -> Option<Output<Id>> {
505        let from = self.index_of(id)?;
506        let document = &self.documents[from];
507        if document.locked || document.pinned == pinned {
508            return None;
509        }
510        let mut document = self.documents.remove(from);
511        document.pinned = pinned;
512        let to = self.pinned_count();
513        self.documents.insert(to, document);
514        Some(Output::Pinned(id, pinned))
515    }
516
517    fn menu_event(&mut self, event: context_menu::Event<MenuItem, Id>) -> Option<Output<Id>> {
518        let event = match event {
519            // The menu opens below the tab, not at the pointer, so it never
520            // covers the tab's label.
521            context_menu::Event::Open(target, _) => {
522                context_menu::Event::Open(target, Point::new(0.0, HEIGHT + KEYBOARD_GAP))
523            }
524            event => event,
525        };
526        if let context_menu::Event::Open(target, _)
527        | context_menu::Event::OpenFromKeyboard(target) = event
528        {
529            self.menu = context_menu::State::new(self.menu_entries(target)?);
530        }
531        let dropdown_menu::Output::Activated(item) = self.menu.update(event)? else {
532            return None;
533        };
534        let target = *self.menu.target()?;
535        let event = match item {
536            MenuItem::Close => Event::Close(target),
537            MenuItem::CloseOthers => Event::CloseOthers(target),
538            MenuItem::CloseToTheRight => Event::CloseToTheRight(target),
539            MenuItem::CloseSaved => Event::CloseSaved,
540            MenuItem::CloseAll => Event::CloseAll,
541            MenuItem::Pin => Event::Pin(target, true),
542            MenuItem::Unpin => Event::Pin(target, false),
543            MenuItem::Custom(name) => return Some(Output::Custom(name, target)),
544        };
545        self.update(event)
546    }
547
548    /// The context menu of the tab `target`, leaving out the choices that
549    /// would do nothing. `None` when no choice is left.
550    fn menu_entries(&self, target: Id) -> Option<Vec<Entry<MenuItem>>> {
551        let index = self.index_of(target)?;
552        let document = &self.documents[index];
553        let ids = |range: &[Document<Id>], keep: &dyn Fn(&Document<Id>) -> bool| -> Vec<usize> {
554            range
555                .iter()
556                .enumerate()
557                .filter(|(_, d)| in_bulk_close(d) && keep(d))
558                .map(|(i, _)| i)
559                .collect()
560        };
561        let all = ids(&self.documents, &|_| true);
562        let right: Vec<usize> = ids(&self.documents[index + 1..], &|_| true)
563            .into_iter()
564            .map(|i| i + index + 1)
565            .collect();
566        // What each choice would close, by position, in the menu's order.
567        let choices = [
568            (
569                MenuItem::Close,
570                "Close",
571                if document.closable {
572                    vec![index]
573                } else {
574                    Vec::new()
575                },
576            ),
577            (
578                MenuItem::CloseOthers,
579                "Close others",
580                all.iter().copied().filter(|i| *i != index).collect(),
581            ),
582            (MenuItem::CloseToTheRight, "Close to the right", right),
583            (
584                MenuItem::CloseSaved,
585                "Close saved",
586                ids(&self.documents, &|d| !d.modified),
587            ),
588            (MenuItem::CloseAll, "Close all", all),
589        ];
590        let close = offered_closes(&choices);
591        let pin = match (document.locked, document.pinned) {
592            (true, _) => Vec::new(),
593            (false, true) => vec![item(MenuItem::Unpin, "Unpin")],
594            (false, false) => vec![item(MenuItem::Pin, "Pin")],
595        };
596
597        let groups: Vec<Vec<Entry<MenuItem>>> = [close, pin, self.extra.clone()]
598            .into_iter()
599            .filter(|group| !group.is_empty())
600            .collect();
601        let entries = groups.join(&separator());
602        (!entries.is_empty()).then_some(entries)
603    }
604
605    fn overflow_event(&mut self, event: dropdown_menu::Event<Id>) -> Option<Output<Id>> {
606        if !self.overflow.is_open() {
607            self.overflow = dropdown_menu::State::new(self.documents.iter().map(|document| {
608                let entry = radio_item(
609                    document.id,
610                    document.label.clone(),
611                    self.active == Some(document.id),
612                );
613                if document.modified {
614                    entry.shortcut("Modified")
615                } else {
616                    entry
617                }
618            }));
619        }
620        match self.overflow.update(event)? {
621            dropdown_menu::Output::Activated(id) | dropdown_menu::Output::Selected(id) => {
622                self.activate(id)
623            }
624            dropdown_menu::Output::Toggled(..) => None,
625        }
626    }
627}
628
629/// The close choices worth offering, in the menu's order: each one closes
630/// some tabs, and never exactly the tabs another offered choice closes.
631/// Close and Close all win a tie, then the order of the menu.
632fn offered_closes(choices: &[(MenuItem, &str, Vec<usize>)]) -> Vec<Entry<MenuItem>> {
633    let priority = [
634        MenuItem::Close,
635        MenuItem::CloseAll,
636        MenuItem::CloseOthers,
637        MenuItem::CloseToTheRight,
638        MenuItem::CloseSaved,
639    ];
640    let mut kept: Vec<&(MenuItem, &str, Vec<usize>)> = Vec::new();
641    for wanted in priority {
642        let Some(choice) = choices.iter().find(|(id, ..)| *id == wanted) else {
643            continue;
644        };
645        let (_, _, closes) = choice;
646        if closes.is_empty() || kept.iter().any(|(_, _, other)| other == closes) {
647            continue;
648        }
649        kept.push(choice);
650    }
651    choices
652        .iter()
653        .filter(|choice| kept.iter().any(|kept| kept.0 == choice.0))
654        .map(|(id, label, _)| item(*id, *label))
655        .collect()
656}
657
658/// Whether Close others, Close to the right, Close saved and Close all
659/// include `document`.
660fn in_bulk_close<Id>(document: &Document<Id>) -> bool {
661    document.closable && !document.pinned
662}
663
664/// What a document tabs keyboard shortcut does.
665#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
666pub enum Action {
667    RecentNext,
668    RecentPrevious,
669    Next,
670    Previous,
671    MoveLeft,
672    MoveRight,
673    Close,
674    New,
675    /// Activates the document at this position, counting from 1.
676    Tab(u8),
677    /// Activates the last document.
678    LastTab,
679    /// Opens the active tab's context menu.
680    OpenMenu,
681}
682
683impl Action {
684    /// The [`Event`] this action sends to `state`, or `None` when it would
685    /// do nothing, such as moving the first tab left.
686    pub fn event<Id: Copy + PartialEq>(self, state: &State<Id>) -> Option<Event<Id>> {
687        let active = state.active;
688        let index = state.active_index();
689        match self {
690            Action::RecentNext => Some(Event::RecentNext),
691            Action::RecentPrevious => Some(Event::RecentPrevious),
692            Action::Next => Some(Event::Next),
693            Action::Previous => Some(Event::Previous),
694            Action::MoveLeft => {
695                let index = index?.checked_sub(1)?;
696                Some(Event::Move(active?, index))
697            }
698            Action::MoveRight => Some(Event::Move(active?, index? + 1)),
699            Action::Close => active
700                .filter(|id| state.document(*id).is_some_and(|d| d.closable))
701                .map(Event::Close),
702            Action::New => Some(Event::New),
703            Action::Tab(position) => {
704                let index = usize::from(position).checked_sub(1)?;
705                state
706                    .documents
707                    .get(index)
708                    .map(|document| Event::Activate(document.id))
709            }
710            Action::LastTab => state
711                .documents
712                .last()
713                .map(|document| Event::Activate(document.id)),
714            Action::OpenMenu => {
715                active.map(|id| Event::Menu(context_menu::Event::OpenFromKeyboard(id)))
716            }
717        }
718    }
719}
720
721impl keys::Action for Action {
722    const ALL: &'static [Self] = &[
723        Action::RecentNext,
724        Action::RecentPrevious,
725        Action::Next,
726        Action::Previous,
727        Action::MoveLeft,
728        Action::MoveRight,
729        Action::Close,
730        Action::New,
731        Action::Tab(1),
732        Action::Tab(2),
733        Action::Tab(3),
734        Action::Tab(4),
735        Action::Tab(5),
736        Action::Tab(6),
737        Action::Tab(7),
738        Action::Tab(8),
739        Action::LastTab,
740        Action::OpenMenu,
741    ];
742
743    fn defaults() -> Keymap<Self> {
744        default_keymap()
745    }
746
747    fn name(self) -> &'static str {
748        match self {
749            Action::RecentNext => "RecentNext",
750            Action::RecentPrevious => "RecentPrevious",
751            Action::Next => "Next",
752            Action::Previous => "Previous",
753            Action::MoveLeft => "MoveLeft",
754            Action::MoveRight => "MoveRight",
755            Action::Close => "Close",
756            Action::New => "New",
757            Action::Tab(1) => "Tab1",
758            Action::Tab(2) => "Tab2",
759            Action::Tab(3) => "Tab3",
760            Action::Tab(4) => "Tab4",
761            Action::Tab(5) => "Tab5",
762            Action::Tab(6) => "Tab6",
763            Action::Tab(7) => "Tab7",
764            Action::Tab(8) => "Tab8",
765            Action::Tab(_) => "Tab",
766            Action::LastTab => "LastTab",
767            Action::OpenMenu => "OpenMenu",
768        }
769    }
770
771    fn description(self) -> &'static str {
772        match self {
773            Action::RecentNext => {
774                "Activates the previously used document. Pressed again while the modifier is held, goes further back."
775            }
776            Action::RecentPrevious => "Walks the recently used documents the other way.",
777            Action::Next => "Activates the tab to the right, wrapping at the end.",
778            Action::Previous => "Activates the tab to the left, wrapping at the start.",
779            Action::MoveLeft => "Moves the active tab one place left, within its group.",
780            Action::MoveRight => "Moves the active tab one place right, within its group.",
781            Action::Close => "Asks to close the active document.",
782            Action::New => "Asks for a new document.",
783            Action::Tab(1) => "Activates the first tab.",
784            Action::Tab(2) => "Activates the second tab.",
785            Action::Tab(3) => "Activates the third tab.",
786            Action::Tab(4) => "Activates the fourth tab.",
787            Action::Tab(5) => "Activates the fifth tab.",
788            Action::Tab(6) => "Activates the sixth tab.",
789            Action::Tab(7) => "Activates the seventh tab.",
790            Action::Tab(8) => "Activates the eighth tab.",
791            Action::Tab(_) => "Activates the tab at that position.",
792            Action::LastTab => "Activates the last tab.",
793            Action::OpenMenu => "Opens the active tab's context menu.",
794        }
795    }
796}
797
798/// The default document tabs shortcuts:
799///
800/// | Keys | Action |
801/// | --- | --- |
802/// | `Ctrl+Tab` | [`Action::RecentNext`] |
803/// | `Ctrl+Shift+Tab` | [`Action::RecentPrevious`] |
804/// | `Ctrl+PageDown` | [`Action::Next`] |
805/// | `Ctrl+PageUp` | [`Action::Previous`] |
806/// | `Ctrl+Shift+PageUp` | [`Action::MoveLeft`] |
807/// | `Ctrl+Shift+PageDown` | [`Action::MoveRight`] |
808/// | `Ctrl+W` | [`Action::Close`] |
809/// | `Ctrl+N` | [`Action::New`] |
810/// | `Ctrl+1` to `Ctrl+8` | [`Action::Tab`] |
811/// | `Ctrl+9` | [`Action::LastTab`] |
812///
813/// `Ctrl+Tab` walks the documents in most-recently-used order, and
814/// `Ctrl+PageDown` and `Ctrl+PageUp` in strip order. Ctrl+W, Ctrl+N and the
815/// digits use Cmd on macOS. Subscribe to [`cycle_end`] so a walk ends when
816/// Ctrl is released.
817///
818/// [`Action::OpenMenu`] has no default chord. The strip has no keyboard
819/// focus, so `Shift+F10` or `Menu` bound app-wide would also open any
820/// other context menu on screen. Bind it when the tab strip is the only
821/// one, or only while the editor has focus:
822///
823/// ```
824/// use iced::keyboard::key::Named;
825/// use iced_cube::keys::Chord;
826/// use iced_cube::navigation::document_tabs::{Action, default_keymap};
827///
828/// let keymap = default_keymap()
829///     .bind(Chord::named(Named::F10).shift(), Action::OpenMenu)
830///     .bind(Chord::named(Named::ContextMenu), Action::OpenMenu);
831/// ```
832///
833/// The segmented tabs also bind `Ctrl+Tab` and `Ctrl+Shift+Tab`. An app
834/// showing both should unbind them from one of them.
835pub fn default_keymap() -> Keymap<Action> {
836    let keymap = Keymap::new()
837        .bind(Chord::named(Named::Tab).ctrl(), Action::RecentNext)
838        .bind(
839            Chord::named(Named::Tab).ctrl().shift(),
840            Action::RecentPrevious,
841        )
842        .bind(Chord::named(Named::PageDown).ctrl(), Action::Next)
843        .bind(Chord::named(Named::PageUp).ctrl(), Action::Previous)
844        .bind(Chord::named(Named::PageUp).ctrl().shift(), Action::MoveLeft)
845        .bind(
846            Chord::named(Named::PageDown).ctrl().shift(),
847            Action::MoveRight,
848        )
849        .bind(Chord::character('w').command(), Action::Close)
850        .bind(Chord::character('n').command(), Action::New);
851    let keymap = ('1'..='8')
852        .zip(1..)
853        .fold(keymap, |keymap, (digit, position)| {
854            keymap.bind(Chord::character(digit).command(), Action::Tab(position))
855        });
856    keymap.bind(Chord::character('9').command(), Action::LastTab)
857}
858
859type OnEvent<'a, Id, Message> = dyn Fn(Event<Id>) -> Message + 'a;
860
861/// A document tab strip builder. Convert it into an [`Element`] to render.
862pub struct DocumentTabs<'a, Id, Message> {
863    state: &'a State<Id>,
864    new_tab: bool,
865    max_label_width: f32,
866    context_menu_keymap: Keymap<context_menu::Action>,
867    overflow_keymap: Keymap<dropdown_menu::Action>,
868    on_event: Option<Box<OnEvent<'a, Id, Message>>>,
869}
870
871/// Renders the tab strip of `state`. Without
872/// [`on_event`](DocumentTabs::on_event) every tab renders disabled.
873pub fn document_tabs<Id, Message>(state: &State<Id>) -> DocumentTabs<'_, Id, Message> {
874    DocumentTabs {
875        state,
876        new_tab: false,
877        max_label_width: MAX_LABEL_WIDTH,
878        context_menu_keymap: context_menu::default_keymap(),
879        overflow_keymap: dropdown_menu::default_keymap(),
880        on_event: None,
881    }
882}
883
884impl<Id: std::fmt::Debug, Message> std::fmt::Debug for DocumentTabs<'_, Id, Message> {
885    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
886        f.debug_struct("DocumentTabs")
887            .field("state", self.state)
888            .field("new_tab", &self.new_tab)
889            .field("max_label_width", &self.max_label_width)
890            .finish_non_exhaustive()
891    }
892}
893
894impl<'a, Id, Message> DocumentTabs<'a, Id, Message> {
895    /// Shows a button after the last tab, and lets a double click on the
896    /// empty strip ask for a new document. Both send [`Event::New`].
897    pub fn new_tab(mut self, new_tab: bool) -> Self {
898        self.new_tab = new_tab;
899        self
900    }
901
902    /// The widest a label grows before it ends in an ellipsis. Defaults to
903    /// [`MAX_LABEL_WIDTH`].
904    pub fn max_label_width(mut self, width: f32) -> Self {
905        self.max_label_width = width;
906        self
907    }
908
909    /// Replaces the default keymap of the open tab context menu.
910    pub fn context_menu_keymap(mut self, keymap: Keymap<context_menu::Action>) -> Self {
911        self.context_menu_keymap = keymap;
912        self
913    }
914
915    /// Replaces the default keymap of the open menu listing every tab.
916    pub fn overflow_keymap(mut self, keymap: Keymap<dropdown_menu::Action>) -> Self {
917        self.overflow_keymap = keymap;
918        self
919    }
920
921    pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
922        self.on_event = Some(Box::new(on_event));
923        self
924    }
925
926    pub fn is_enabled(&self) -> bool {
927        self.on_event.is_some()
928    }
929}
930
931/// How one tab is drawn.
932#[derive(Debug, Clone, Copy, PartialEq, Eq)]
933struct Look {
934    active: bool,
935    hovered: bool,
936    enabled: bool,
937}
938
939impl<'a, Id, Message> From<DocumentTabs<'a, Id, Message>> for Element<'a, Message>
940where
941    Id: Copy + PartialEq + 'a,
942    Message: Clone + 'a,
943{
944    fn from(tabs: DocumentTabs<'a, Id, Message>) -> Self {
945        let DocumentTabs {
946            state,
947            new_tab,
948            max_label_width,
949            context_menu_keymap,
950            overflow_keymap,
951            on_event,
952        } = tabs;
953        let on_event: Option<Rc<OnEvent<'a, Id, Message>>> = on_event.map(Rc::from);
954        let enabled = on_event.is_some();
955
956        let tab = |document: &'a Document<Id>| -> Element<'a, Message> {
957            let active = state.is_active(document.id);
958            let on_close = on_event
959                .as_ref()
960                .map(|on_event| on_event(Event::Close(document.id)));
961            let look = Look {
962                active,
963                hovered: false,
964                enabled,
965            };
966            let base = tab_view(document, look, max_label_width, on_close.clone(), false);
967            let Some(on_event) = on_event.clone() else {
968                return annotate_tab(base, document, active);
969            };
970            let hovered = Look {
971                hovered: true,
972                ..look
973            };
974            let top = tab_view(document, hovered, max_label_width, on_close, true);
975            // The hovered copy holds a close button on every closable tab,
976            // so it alone is reported.
977            #[cfg(feature = "icedwright")]
978            let base: Element<'a, Message> = icedwright_probe::semantic(base).hidden(true).into();
979            let tab: Element<'a, Message> =
980                context_menu::keyed(state.menu(), document.id, widget::hover(base, top))
981                    .keymap(context_menu_keymap.clone())
982                    .on_event(move |event| on_event(Event::Menu(event)))
983                    .into();
984            annotate_tab(tab, document, active)
985        };
986        let (pinned, unpinned) = state.documents.split_at(state.pinned_count());
987        let pinned_row = row(pinned.iter().map(&tab)).into();
988        let content = row(unpinned.iter().map(&tab)).into();
989
990        let trailing: Element<'a, Message> = if new_tab {
991            icon_button(crate::lucide!(Plus))
992                .label("New tab")
993                .tooltip(Some(tooltip::Position::Bottom))
994                .size(ButtonSize::Sm)
995                .on_press_maybe(on_event.as_ref().map(|on_event| on_event(Event::New)))
996                .into()
997        } else {
998            widget::space().into()
999        };
1000
1001        let open = state.overflow().is_open();
1002        let toggle = on_event
1003            .as_ref()
1004            .map(|on_event| on_event(Event::Overflow(dropdown_menu::Event::Toggle)));
1005        let trigger = icon_button(crate::lucide!(ChevronDown))
1006            .label("All tabs")
1007            .tooltip(None)
1008            .size(ButtonSize::Sm)
1009            .pressed(open)
1010            .on_press_maybe(toggle);
1011        let mut overflow = anchored(trigger)
1012            .kind("iced_cube::document_tabs")
1013            .content(open.then(|| overflow_panel(state, on_event.as_deref())))
1014            .placement(Placement::new(Side::Bottom, Align::End))
1015            .fit_height(true)
1016            .dismiss_keys([]);
1017        if let Some(on_event) = on_event.clone().filter(|_| open) {
1018            overflow = overflow
1019                .on_dismiss(on_event(Event::Overflow(dropdown_menu::Event::Close)))
1020                .on_key(move |key| {
1021                    state
1022                        .overflow()
1023                        .key_event(&overflow_keymap, key)
1024                        .map(|event| on_event(Event::Overflow(event)))
1025                });
1026        }
1027
1028        let ids: Vec<Id> = state.documents.iter().map(|document| document.id).collect();
1029        let on_gesture = on_event.map(|on_event| {
1030            Box::new(move |gesture: Gesture| {
1031                let event = match gesture {
1032                    Gesture::Press(index) => Event::Activate(*ids.get(index)?),
1033                    Gesture::Middle(index) => Event::Close(*ids.get(index)?),
1034                    Gesture::Drop { from, to } => Event::Move(*ids.get(from)?, to),
1035                    Gesture::DoubleClick if new_tab => Event::New,
1036                    Gesture::DoubleClick => return None,
1037                };
1038                Some(on_event(event))
1039            }) as Box<dyn Fn(Gesture) -> Option<Message> + 'a>
1040        });
1041
1042        let strip = Element::new(Strip {
1043            pinned_row,
1044            content,
1045            trailing,
1046            overflow: overflow.into(),
1047            active: state.active_index(),
1048            count: state.documents.len(),
1049            pinned: state.pinned_count(),
1050            on_gesture,
1051        });
1052        #[cfg(feature = "icedwright")]
1053        let strip = icedwright_probe::semantic(strip)
1054            .role(icedwright_probe::role::TabList)
1055            .click_clock(icedwright_probe::ClickClock::Probe)
1056            .component("iced_cube::document_tabs")
1057            .into();
1058        strip
1059    }
1060}
1061
1062/// Reports one document as a tab.
1063#[cfg(feature = "icedwright")]
1064fn annotate_tab<'a, Id, Message: 'a>(
1065    tab: Element<'a, Message>,
1066    document: &'a Document<Id>,
1067    active: bool,
1068) -> Element<'a, Message> {
1069    icedwright_probe::semantic(tab)
1070        .role(icedwright_probe::role::Tab)
1071        .name(document.label.as_str())
1072        .selected(active)
1073        .prop("unsaved", if document.modified { "true" } else { "false" })
1074        .click_clock(icedwright_probe::ClickClock::Probe)
1075        .component("iced_cube::document_tabs")
1076        .into()
1077}
1078
1079#[cfg(not(feature = "icedwright"))]
1080fn annotate_tab<'a, Id, Message>(
1081    tab: Element<'a, Message>,
1082    _document: &'a Document<Id>,
1083    _active: bool,
1084) -> Element<'a, Message> {
1085    tab
1086}
1087
1088fn tab_view<'a, Id, Message>(
1089    document: &'a Document<Id>,
1090    look: Look,
1091    max_label_width: f32,
1092    on_close: Option<Message>,
1093    fill: bool,
1094) -> Element<'a, Message>
1095where
1096    Id: 'a,
1097    Message: Clone + 'a,
1098{
1099    let Look {
1100        active,
1101        hovered,
1102        enabled,
1103    } = look;
1104    let colour = move |theme: &Theme| label_colour(&Tokens::of(theme), active, hovered, enabled);
1105
1106    let mut content = row![].spacing(space::SM).align_y(Alignment::Center);
1107    if let Some(glyph) = document.icon {
1108        content = content.push(themed(glyph, ICON, opacity(enabled), colour));
1109    }
1110    if !document.pinned || document.icon.is_none() {
1111        let width = if document.pinned {
1112            PINNED_LABEL_WIDTH
1113        } else {
1114            max_label_width
1115        };
1116        let label = ellipsis(document.label.as_str())
1117            .width(Length::Shrink)
1118            .colour(colour);
1119        content = content.push(container(label).max_width(width));
1120    }
1121    if let Some(slot) = slot(document, look, on_close) {
1122        content = content.push(slot);
1123    }
1124
1125    container(content)
1126        .width(if fill { Length::Fill } else { Length::Shrink })
1127        .height(HEIGHT)
1128        .padding(Padding::from([0.0, PADDING_X]))
1129        .align_y(Vertical::Center)
1130        .style(move |theme| tab_style(&Tokens::of(theme), active, hovered))
1131        .into()
1132}
1133
1134/// The open list of every tab, one row per document with the active one
1135/// checked, scrolled to show the highlighted row or else the active one.
1136fn overflow_panel<'a, Id, Message>(
1137    state: &'a State<Id>,
1138    on_event: Option<&OnEvent<'a, Id, Message>>,
1139) -> Element<'a, Message>
1140where
1141    Id: Copy + PartialEq + 'a,
1142    Message: Clone + 'a,
1143{
1144    let highlighted = state.overflow().highlighted();
1145    let rows = state.documents.iter().map(|document| {
1146        let status = match (on_event.is_some(), highlighted == Some(document.id)) {
1147            (false, _) => RowStatus::Disabled,
1148            (true, true) => RowStatus::Highlighted,
1149            (true, false) => RowStatus::Idle,
1150        };
1151        overflow_row(document, state.is_active(document.id), status, on_event)
1152    });
1153    let reveal = highlighted
1154        .and_then(|id| state.index_of(id))
1155        .or_else(|| state.active_index());
1156    menu::surface(scrolling(fitted(rows, OVERFLOW_WIDTH), reveal)).into()
1157}
1158
1159/// One row of the list of every tab. The label ends in an ellipsis rather
1160/// than wrapping.
1161fn overflow_row<'a, Id, Message>(
1162    document: &'a Document<Id>,
1163    active: bool,
1164    status: RowStatus,
1165    on_event: Option<&OnEvent<'a, Id, Message>>,
1166) -> Element<'a, Message>
1167where
1168    Id: Copy + 'a,
1169    Message: Clone + 'a,
1170{
1171    let colours = move |theme: &Theme| menu::row_style(&Tokens::of(theme), status, false);
1172    let opacity = opacity(status != RowStatus::Disabled);
1173
1174    let mark: Element<'a, Message> = if active {
1175        themed(
1176            crate::lucide!(Check),
1177            menu::ICON_SIZE,
1178            opacity,
1179            move |theme| colours(theme).text,
1180        )
1181        .into()
1182    } else {
1183        widget::space().into()
1184    };
1185    let mut content = row![
1186        container(mark)
1187            .center_x(menu::ICON_SIZE)
1188            .center_y(menu::ICON_SIZE)
1189    ]
1190    .spacing(space::SM)
1191    .align_y(Alignment::Center);
1192    if let Some(glyph) = document.icon {
1193        content = content.push(themed(glyph, menu::ICON_SIZE, opacity, move |theme| {
1194            colours(theme).icon
1195        }));
1196    }
1197    content = content.push(
1198        ellipsis(document.label.as_str())
1199            .width(Length::Fill)
1200            .colour(move |theme| colours(theme).text),
1201    );
1202    if document.modified {
1203        content = content.push(
1204            widget::text("Modified")
1205                .size(text_size::XS)
1206                .wrapping(widget::text::Wrapping::None)
1207                .style(move |theme| widget::text::Style {
1208                    color: Some(colours(theme).hint),
1209                }),
1210        );
1211    }
1212
1213    let body = container(content)
1214        .padding(menu::ROW_PADDING)
1215        .width(Length::Fill)
1216        .style(move |theme| menu::row_container_style(colours(theme)));
1217    let Some(on_event) = on_event.filter(|_| status != RowStatus::Disabled) else {
1218        return menu::inset(body);
1219    };
1220    let id = document.id;
1221    menu::inset(
1222        widget::mouse_area(body)
1223            .on_enter(on_event(Event::Overflow(dropdown_menu::Event::Highlight(
1224                id,
1225            ))))
1226            .on_press(on_event(Event::Overflow(dropdown_menu::Event::Activate(
1227                id,
1228            ))))
1229            .interaction(mouse::Interaction::Pointer),
1230    )
1231}
1232
1233/// The trailing slot of a tab: the close button on the active or hovered
1234/// tab, otherwise a dot while modified, otherwise empty space so the label
1235/// does not move. Pinned and unclosable tabs only show the dot.
1236fn slot<'a, Id, Message>(
1237    document: &Document<Id>,
1238    look: Look,
1239    on_close: Option<Message>,
1240) -> Option<Element<'a, Message>>
1241where
1242    Message: Clone + 'a,
1243{
1244    let active = look.active;
1245    let closable = in_bulk_close(document);
1246    if closable && (look.hovered || (active && !document.modified)) {
1247        return Some(close_button(&document.label, on_close));
1248    }
1249    if document.modified {
1250        let dot = container(widget::space())
1251            .width(DOT)
1252            .height(DOT)
1253            .style(move |theme| dot_style(&Tokens::of(theme), active));
1254        return Some(container(dot).center(SLOT).into());
1255    }
1256    closable.then(|| widget::space().width(SLOT).height(SLOT).into())
1257}
1258
1259fn close_button<'a, Message: Clone + 'a>(
1260    label: &str,
1261    on_close: Option<Message>,
1262) -> Element<'a, Message> {
1263    let enabled = on_close.is_some();
1264    let button: Element<'a, Message> = widget::button(themed(
1265        crate::lucide!(X),
1266        CLOSE_ICON,
1267        opacity(enabled),
1268        |theme| Tokens::of(theme).foreground,
1269    ))
1270    .width(SLOT)
1271    .height(SLOT)
1272    .padding((SLOT - CLOSE_ICON) / 2.0)
1273    .on_press_maybe(on_close)
1274    .style(|theme, status| close_style(&Tokens::of(theme), status))
1275    .into();
1276    #[cfg(feature = "icedwright")]
1277    let button = {
1278        let mut annotated = icedwright_probe::semantic(button)
1279            .role(icedwright_probe::role::Button)
1280            .name(format!("Close {label}"))
1281            .component("iced_cube::document_tabs");
1282        if !enabled {
1283            annotated = annotated.disabled(true);
1284        }
1285        annotated.into()
1286    };
1287    #[cfg(not(feature = "icedwright"))]
1288    let _ = label;
1289    button
1290}
1291
1292/// The colour of a tab's label and icon.
1293pub fn label_colour(tokens: &Tokens, active: bool, hovered: bool, enabled: bool) -> Color {
1294    let colour = if active || hovered {
1295        tokens.foreground
1296    } else {
1297        tokens.muted_foreground
1298    };
1299    if enabled { colour } else { fade(colour, 0.5) }
1300}
1301
1302/// The surface of one tab. The active tab takes the page background, so it
1303/// joins the content below; the others sit flat on the strip.
1304pub fn tab_style(tokens: &Tokens, active: bool, hovered: bool) -> container::Style {
1305    let background = if active {
1306        Some(tokens.background)
1307    } else if hovered {
1308        Some(mix(tokens.muted, tokens.foreground, 0.06))
1309    } else {
1310        None
1311    };
1312    container::Style {
1313        background: background.map(Background::Color),
1314        text_color: Some(label_colour(tokens, active, hovered, true)),
1315        border: Border {
1316            radius: Radius {
1317                top_left: radius::MD,
1318                top_right: radius::MD,
1319                bottom_right: 0.0,
1320                bottom_left: 0.0,
1321            },
1322            ..Border::default()
1323        },
1324        ..container::Style::default()
1325    }
1326}
1327
1328/// The close button inside a tab.
1329pub fn close_style(tokens: &Tokens, status: Status) -> widget::button::Style {
1330    let background = match status {
1331        Status::Hovered | Status::Pressed => Some(fade(tokens.foreground, 0.1)),
1332        Status::Active | Status::Disabled => None,
1333    };
1334    widget::button::Style {
1335        background: background.map(Background::Color),
1336        text_color: tokens.foreground,
1337        border: Border {
1338            radius: radius::SM.into(),
1339            ..Border::default()
1340        },
1341        ..widget::button::Style::default()
1342    }
1343}
1344
1345/// The dot that marks unsaved changes.
1346pub fn dot_style(tokens: &Tokens, active: bool) -> container::Style {
1347    let colour = if active {
1348        tokens.foreground
1349    } else {
1350        tokens.muted_foreground
1351    };
1352    container::Style {
1353        background: Some(Background::Color(colour)),
1354        border: Border {
1355            radius: radius::FULL.into(),
1356            ..Border::default()
1357        },
1358        ..container::Style::default()
1359    }
1360}
1361
1362/// Colours the strip draws itself.
1363#[derive(Debug, Clone, Copy, PartialEq)]
1364pub struct StripStyle {
1365    pub background: Color,
1366    /// The line along the bottom, broken under the active tab.
1367    pub line: Color,
1368    /// Short lines between inactive tabs.
1369    pub divider: Color,
1370    /// Where a dragged tab will land.
1371    pub indicator: Color,
1372}
1373
1374pub fn strip_style(tokens: &Tokens) -> StripStyle {
1375    StripStyle {
1376        background: tokens.muted,
1377        line: tokens.border,
1378        divider: tokens.border,
1379        indicator: tokens.primary,
1380    }
1381}
1382
1383/// The gap a pointer at `x` points to: the number of tabs whose centre lies
1384/// before it. `tabs` holds each tab's left edge and width, in order.
1385fn gap_at(tabs: &[(f32, f32)], x: f32) -> usize {
1386    tabs.iter()
1387        .take_while(|(left, width)| left + width / 2.0 < x)
1388        .count()
1389}
1390
1391/// The gap a tab dragged from `from` may drop into, kept within its group:
1392/// the first `pinned` tabs, or the rest of the `count`.
1393fn clamp_gap(from: usize, gap: usize, pinned: usize, count: usize) -> usize {
1394    if from < pinned {
1395        gap.min(pinned)
1396    } else {
1397        gap.clamp(pinned, count)
1398    }
1399}
1400
1401/// The index a tab dragged from `from` ends up at when dropped into `gap`,
1402/// or `None` when it would not move.
1403fn drop_index(from: usize, gap: usize) -> Option<usize> {
1404    let to = if gap > from { gap - 1 } else { gap };
1405    (to != from).then_some(to)
1406}
1407
1408/// Pointer gestures on the strip, by tab index.
1409#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1410enum Gesture {
1411    Press(usize),
1412    Middle(usize),
1413    Drop { from: usize, to: usize },
1414    DoubleClick,
1415}
1416
1417/// A press on a tab that may become a drag.
1418#[derive(Debug, Clone, Copy, PartialEq)]
1419struct Press {
1420    index: usize,
1421    origin: Point,
1422    dragging: bool,
1423    gap: Option<usize>,
1424}
1425
1426/// Most of the room for tabs the pinned tabs may take and still stay in
1427/// place. Wider pinned tabs scroll with the others, so the unpinned tabs
1428/// always keep at least this share of a narrow strip.
1429const MAX_PINNED_SHARE: f32 = 0.5;
1430
1431/// Space between the pinned tabs' divider and scrolled tabs cut off by it.
1432const PINNED_GAP: f32 = 6.0;
1433
1434/// Whether pinned tabs `pinned` pixels wide stay in place, given `room`
1435/// pixels for every tab.
1436fn pinned_stay(pinned: f32, room: f32, overflowing: bool) -> bool {
1437    !overflowing || pinned <= room * MAX_PINNED_SHARE
1438}
1439
1440/// What the strip remembers between frames.
1441///
1442/// Tab positions are measured from the strip's left edge as laid out. The
1443/// first `fixed_tabs` tabs (the pinned ones, `fixed` pixels wide) never
1444/// scroll. The rest scroll by `offset` in the `viewport_width` pixels after
1445/// them, and `content_width` is how wide they are together.
1446#[derive(Debug, Clone, Default)]
1447struct Memory {
1448    offset: f32,
1449    content_width: f32,
1450    viewport_width: f32,
1451    fixed: f32,
1452    fixed_tabs: usize,
1453    overflowing: bool,
1454    /// The active index and tab count the strip last scrolled into view.
1455    revealed: Option<(Option<usize>, usize)>,
1456    /// The content and viewport widths the strip last scrolled for.
1457    measured: Option<(f32, f32)>,
1458    press: Option<Press>,
1459    last_click: Option<Click>,
1460    touch: Option<Touch>,
1461}
1462
1463/// A finger on the strip. It pans the strip as it moves, and taps the tab
1464/// it started on if it lifts without having moved.
1465#[derive(Debug, Clone, Copy, PartialEq)]
1466struct Touch {
1467    finger: Finger,
1468    /// Where the finger was last, along the strip.
1469    last: f32,
1470    origin: Point,
1471    tab: Option<usize>,
1472}
1473
1474/// How far a finger may drift and still tap a tab rather than pan.
1475const TAP_SLOP: f32 = 10.0;
1476
1477impl Touch {
1478    /// The tab a finger lifted at `position` taps, if it is a tap.
1479    fn tapped(&self, position: Point) -> Option<usize> {
1480        self.tab
1481            .filter(|_| self.origin.distance(position) <= TAP_SLOP)
1482    }
1483}
1484
1485impl Scrollable for Memory {
1486    fn snap_to(&mut self, offset: RelativeOffset<Option<f32>>) {
1487        if let Some(x) = offset.x {
1488            self.offset = (x.clamp(0.0, 1.0) * self.max_offset()).round();
1489        }
1490    }
1491
1492    fn scroll_to(&mut self, offset: AbsoluteOffset<Option<f32>>) {
1493        if let Some(x) = offset.x {
1494            self.offset = x.clamp(0.0, self.max_offset());
1495        }
1496    }
1497
1498    fn scroll_by(&mut self, offset: AbsoluteOffset, _bounds: Rectangle, _content: Rectangle) {
1499        let _ = Memory::scroll_by(self, offset.x);
1500    }
1501}
1502
1503impl Memory {
1504    fn max_offset(&self) -> f32 {
1505        (self.content_width - self.viewport_width).max(0.0)
1506    }
1507
1508    fn scroll_by(&mut self, delta: f32) -> bool {
1509        let offset = (self.offset + delta).clamp(0.0, self.max_offset());
1510        let changed = offset != self.offset;
1511        self.offset = offset;
1512        changed
1513    }
1514
1515    /// Scrolls the least distance that shows a tab spanning `left` to
1516    /// `right` in full.
1517    fn reveal(&mut self, left: f32, right: f32) {
1518        if right > self.offset + self.viewport_width {
1519            self.offset = right - self.viewport_width;
1520        }
1521        if left < self.offset {
1522            self.offset = left;
1523        }
1524        self.offset = self.offset.clamp(0.0, self.max_offset());
1525    }
1526
1527    /// Keeps the active tab, spanning `active`, in view after a layout.
1528    ///
1529    /// When the active tab or the tab count changes, the strip scrolls the
1530    /// least distance. When only the sizes change, such as on the first
1531    /// layout, a resize or once fonts load, the offset is worked out afresh
1532    /// from the start of the strip, so it never depends on earlier sizes.
1533    fn follow(
1534        &mut self,
1535        key: (Option<usize>, usize),
1536        widths: (f32, f32),
1537        active: Option<(f32, f32)>,
1538    ) {
1539        (self.content_width, self.viewport_width) = widths;
1540        let moved = self.revealed != Some(key);
1541        let resized = self.measured != Some(widths);
1542        self.revealed = Some(key);
1543        self.measured = Some(widths);
1544        if !moved && resized {
1545            self.offset = 0.0;
1546        }
1547        if let Some((left, width)) = active.filter(|_| moved || resized) {
1548            self.reveal(left, left + width);
1549        }
1550        self.offset = self.offset.clamp(0.0, self.max_offset());
1551    }
1552
1553    /// Where the scrolling tabs show.
1554    fn viewport(&self, bounds: Rectangle) -> Rectangle {
1555        Rectangle {
1556            x: bounds.x + self.fixed,
1557            width: self.viewport_width,
1558            ..bounds
1559        }
1560    }
1561
1562    fn shift(&self) -> Vector {
1563        Vector::new(self.offset, 0.0)
1564    }
1565
1566    fn scrolls(&self, index: usize) -> bool {
1567        index >= self.fixed_tabs
1568    }
1569
1570    /// The left edge and width of the tab at `index` among the scrolling
1571    /// tabs, for [`Memory::follow`]. `None` for a tab that stays in place,
1572    /// which is always in view.
1573    fn scroll_span(&self, spans: &[(f32, f32)], index: usize) -> Option<(f32, f32)> {
1574        let (left, width) = spans.get(index).filter(|_| self.scrolls(index))?;
1575        Some((left - self.fixed, *width))
1576    }
1577
1578    /// Where the pinned tabs show, and how far they are scrolled: in place
1579    /// while they stay, otherwise with the rest.
1580    fn pinned_frame(&self, bounds: Rectangle) -> (Rectangle, Vector) {
1581        if self.fixed_tabs == 0 {
1582            return (self.viewport(bounds), self.shift());
1583        }
1584        let clip = Rectangle {
1585            width: self.fixed,
1586            ..bounds
1587        };
1588        (clip, Vector::ZERO)
1589    }
1590
1591    /// The tab position under a pointer `x` pixels from the strip's left
1592    /// edge, or `None` outside the tabs' regions.
1593    fn locate(&self, x: f32) -> Option<f32> {
1594        if x < 0.0 {
1595            return None;
1596        }
1597        if x < self.fixed {
1598            return Some(x);
1599        }
1600        (x < self.fixed + self.viewport_width).then_some(x + self.offset)
1601    }
1602
1603    /// Like [`Memory::locate`], but past the regions too, for dragging.
1604    fn unscroll(&self, x: f32) -> f32 {
1605        if x < self.fixed { x } else { x + self.offset }
1606    }
1607
1608    /// The shown part of the tab at `index`, as its left and right edges
1609    /// from the strip's left edge.
1610    fn visible_span(&self, spans: &[(f32, f32)], index: usize) -> Option<(f32, f32)> {
1611        let (left, width) = *spans.get(index)?;
1612        let (start, end, shift) = if self.scrolls(index) {
1613            (self.fixed, self.fixed + self.viewport_width, self.offset)
1614        } else {
1615            (0.0, self.fixed, 0.0)
1616        };
1617        let shown_left = (left - shift).max(start);
1618        let shown_right = (left - shift + width).min(end);
1619        (shown_right > shown_left).then_some((shown_left, shown_right))
1620    }
1621
1622    /// Where scrolled tabs start to show, from the strip's left edge: a few
1623    /// pixels clear of the pinned tabs' divider once tabs are scrolled under
1624    /// it, so a cut-off label never touches the line.
1625    fn scroll_start(&self) -> f32 {
1626        if self.fixed_tabs == 0 || self.offset <= 0.0 {
1627            return self.fixed;
1628        }
1629        self.fixed + PINNED_GAP.min(self.viewport_width)
1630    }
1631
1632    /// The scrolling region as drawn, starting at [`Memory::scroll_start`].
1633    fn scroll_clip(&self, bounds: Rectangle) -> Rectangle {
1634        let clip = self.viewport(bounds);
1635        let inset = self.scroll_start() - self.fixed;
1636        Rectangle {
1637            x: clip.x + inset,
1638            width: (clip.width - inset).max(0.0),
1639            ..clip
1640        }
1641    }
1642
1643    /// Where the short lines between tabs go, from the strip's left edge.
1644    /// None touches the active tab, and one marks where the pinned tabs end
1645    /// while they stay in place.
1646    fn dividers(&self, spans: &[(f32, f32)], active: Option<usize>) -> Vec<f32> {
1647        let end = self.fixed + self.viewport_width;
1648        (1..spans.len())
1649            .filter_map(|index| {
1650                let boundary = index == self.fixed_tabs;
1651                let next_to_active = active == Some(index) && !(boundary && self.offset > 0.0);
1652                if active == Some(index - 1) || next_to_active {
1653                    return None;
1654                }
1655                if boundary {
1656                    return Some(self.fixed);
1657                }
1658                let left = spans[index].0;
1659                if !self.scrolls(index) {
1660                    return Some(left);
1661                }
1662                let x = left - self.offset;
1663                (x > self.scroll_start() && x < end).then_some(x)
1664            })
1665            .collect()
1666    }
1667
1668    /// Where the drop indicator for a tab dragged from `from` into `gap`
1669    /// starts, from the strip's left edge, kept inside the dragged tab's
1670    /// region.
1671    fn indicator_x(&self, spans: &[(f32, f32)], from: usize, gap: usize) -> Option<f32> {
1672        let scrolls = self.scrolls(from);
1673        let end = if scrolls {
1674            spans.len()
1675        } else {
1676            self.fixed_tabs
1677        };
1678        let edge = match spans.get(gap).filter(|_| gap < end) {
1679            Some((left, _)) => *left,
1680            None => {
1681                let (left, width) = spans.get(end.checked_sub(1)?)?;
1682                left + width
1683            }
1684        };
1685        let x = edge - INDICATOR_WIDTH / 2.0;
1686        if !scrolls {
1687            return Some(x.clamp(0.0, (self.fixed - INDICATOR_WIDTH).max(0.0)));
1688        }
1689        let start = self.fixed;
1690        let stop = (start + self.viewport_width - INDICATOR_WIDTH).max(start);
1691        Some((x - self.offset).clamp(start, stop))
1692    }
1693}
1694
1695/// The cursor in the coordinates of tabs shown through `clip` and scrolled
1696/// by `shift`. Outside `clip` it is levitated, so no tab reacts to it.
1697fn inner_cursor(cursor: mouse::Cursor, clip: Rectangle, shift: Vector) -> mouse::Cursor {
1698    match cursor.position_over(clip) {
1699        Some(position) => mouse::Cursor::Available(position + shift),
1700        None => cursor.levitate() + shift,
1701    }
1702}
1703
1704/// The tab strip: pinned tabs that stay in place, the other tabs scrolling
1705/// sideways after them, a new tab button after those and, while they
1706/// overflow, a menu button listing them at the end.
1707struct Strip<'a, Message> {
1708    pinned_row: Element<'a, Message>,
1709    content: Element<'a, Message>,
1710    trailing: Element<'a, Message>,
1711    overflow: Element<'a, Message>,
1712    active: Option<usize>,
1713    count: usize,
1714    pinned: usize,
1715    on_gesture: Option<Box<dyn Fn(Gesture) -> Option<Message> + 'a>>,
1716}
1717
1718impl<Message> Strip<'_, Message> {
1719    fn publish(&self, shell: &mut Shell<'_, Message>, gesture: Gesture) {
1720        if let Some(message) = self.on_gesture.as_ref().and_then(|on| on(gesture)) {
1721            shell.publish(message);
1722        }
1723    }
1724}
1725
1726/// Each tab's left edge and width, measured from `origin`, pinned first.
1727fn spans(origin: f32, pinned: Layout<'_>, content: Layout<'_>) -> Vec<(f32, f32)> {
1728    pinned
1729        .children()
1730        .chain(content.children())
1731        .map(|tab| {
1732            let bounds = tab.bounds();
1733            (bounds.x - origin, bounds.width)
1734        })
1735        .collect()
1736}
1737
1738/// The strip's laid out children.
1739struct Parts<'a> {
1740    pinned: Layout<'a>,
1741    content: Layout<'a>,
1742    trailing: Layout<'a>,
1743    overflow: Layout<'a>,
1744}
1745
1746fn parts(layout: Layout<'_>) -> Option<Parts<'_>> {
1747    let mut children = layout.children();
1748    Some(Parts {
1749        pinned: children.next()?,
1750        content: children.next()?,
1751        trailing: children.next()?,
1752        overflow: children.next()?,
1753    })
1754}
1755
1756impl<Message> Widget<Message, Theme, Renderer> for Strip<'_, Message> {
1757    fn size(&self) -> Size<Length> {
1758        Size::new(Length::Fill, Length::Shrink)
1759    }
1760
1761    fn tag(&self) -> tree::Tag {
1762        tree::Tag::of::<Memory>()
1763    }
1764
1765    fn state(&self) -> tree::State {
1766        tree::State::new(Memory::default())
1767    }
1768
1769    fn children(&self) -> Vec<Tree> {
1770        vec![
1771            Tree::new(&self.pinned_row),
1772            Tree::new(&self.content),
1773            Tree::new(&self.trailing),
1774            Tree::new(&self.overflow),
1775        ]
1776    }
1777
1778    fn diff(&self, tree: &mut Tree) {
1779        tree.diff_children(&[
1780            &self.pinned_row,
1781            &self.content,
1782            &self.trailing,
1783            &self.overflow,
1784        ]);
1785    }
1786
1787    fn layout(
1788        &mut self,
1789        tree: &mut Tree,
1790        renderer: &Renderer,
1791        limits: &layout::Limits,
1792    ) -> layout::Node {
1793        let max = limits.max();
1794        let [pinned_tree, content_tree, trailing_tree, overflow_tree] =
1795            tree.children.as_mut_slice()
1796        else {
1797            return layout::Node::new(Size::ZERO);
1798        };
1799        let unbounded = layout::Limits::new(Size::ZERO, Size::new(f32::INFINITY, max.height));
1800        let pinned = self
1801            .pinned_row
1802            .as_widget_mut()
1803            .layout(pinned_tree, renderer, &unbounded);
1804        let content = self
1805            .content
1806            .as_widget_mut()
1807            .layout(content_tree, renderer, &unbounded);
1808        let loose = layout::Limits::new(Size::ZERO, max);
1809        let trailing = self
1810            .trailing
1811            .as_widget_mut()
1812            .layout(trailing_tree, renderer, &loose);
1813        let overflow = self
1814            .overflow
1815            .as_widget_mut()
1816            .layout(overflow_tree, renderer, &loose);
1817
1818        let pinned_size = pinned.size();
1819        let content_size = content.size();
1820        let trailing_size = trailing.size();
1821        let overflow_size = overflow.size();
1822        let tabs_width = pinned_size.width + content_size.width;
1823        let natural = tabs_width + trailing_size.width;
1824        let width = if max.width.is_finite() {
1825            max.width
1826        } else {
1827            natural
1828        };
1829        let height = pinned_size
1830            .height
1831            .max(content_size.height)
1832            .max(trailing_size.height)
1833            .max(overflow_size.height)
1834            .max(limits.min().height);
1835        let overflowing = natural > width + 0.5;
1836        let room = if overflowing {
1837            (width - trailing_size.width - overflow_size.width).max(0.0)
1838        } else {
1839            tabs_width
1840        };
1841        let (fixed, fixed_tabs) = if pinned_stay(pinned_size.width, room, overflowing) {
1842            (pinned_size.width, self.pinned)
1843        } else {
1844            (0.0, 0)
1845        };
1846        let viewport_width = (room - fixed).max(0.0);
1847        let centre = |size: Size| (height - size.height) / 2.0;
1848
1849        let spans: Vec<(f32, f32)> = pinned
1850            .children()
1851            .iter()
1852            .map(|tab| (tab.bounds().x, tab.bounds().width))
1853            .chain(
1854                content
1855                    .children()
1856                    .iter()
1857                    .map(|tab| (pinned_size.width + tab.bounds().x, tab.bounds().width)),
1858            )
1859            .collect();
1860        let memory = tree.state.downcast_mut::<Memory>();
1861        memory.overflowing = overflowing;
1862        memory.fixed = fixed;
1863        memory.fixed_tabs = fixed_tabs;
1864        let active = self
1865            .active
1866            .and_then(|index| memory.scroll_span(&spans, index));
1867        memory.follow(
1868            (self.active, self.count),
1869            (tabs_width - fixed, viewport_width),
1870            active,
1871        );
1872
1873        let overflow_x = width - overflow_size.width;
1874        layout::Node::with_children(
1875            Size::new(width, height),
1876            vec![
1877                pinned.move_to(Point::new(0.0, centre(pinned_size))),
1878                content.move_to(Point::new(pinned_size.width, centre(content_size))),
1879                trailing.move_to(Point::new(fixed + viewport_width, centre(trailing_size))),
1880                overflow.move_to(Point::new(overflow_x, centre(overflow_size))),
1881            ],
1882        )
1883    }
1884
1885    fn draw(
1886        &self,
1887        tree: &Tree,
1888        renderer: &mut Renderer,
1889        theme: &Theme,
1890        style: &renderer::Style,
1891        layout: Layout<'_>,
1892        cursor: mouse::Cursor,
1893        viewport: &Rectangle,
1894    ) {
1895        let memory = tree.state.downcast_ref::<Memory>();
1896        let colours = strip_style(&Tokens::of(theme));
1897        let bounds = layout.bounds();
1898        let Some(Parts {
1899            pinned,
1900            content,
1901            trailing,
1902            overflow,
1903        }) = parts(layout)
1904        else {
1905            return;
1906        };
1907
1908        fill(renderer, bounds, colours.background);
1909
1910        let clip = memory.scroll_clip(bounds);
1911        let rows = [
1912            (
1913                &self.pinned_row,
1914                &tree.children[0],
1915                pinned,
1916                memory.pinned_frame(bounds),
1917            ),
1918            (
1919                &self.content,
1920                &tree.children[1],
1921                content,
1922                (clip, memory.shift()),
1923            ),
1924        ];
1925        for (row, row_tree, row_layout, (row_clip, shift)) in rows {
1926            renderer.with_layer(row_clip, |renderer| {
1927                renderer.with_translation(Vector::new(-shift.x, 0.0), |renderer| {
1928                    row.as_widget().draw(
1929                        row_tree,
1930                        renderer,
1931                        theme,
1932                        style,
1933                        row_layout,
1934                        inner_cursor(cursor, row_clip, shift),
1935                        &(row_clip + shift),
1936                    );
1937                });
1938            });
1939        }
1940
1941        let spans = spans(bounds.x, pinned, content);
1942        let top = bounds.y + (bounds.height - DIVIDER_HEIGHT) / 2.0;
1943        let divider = |renderer: &mut Renderer, x: f32| {
1944            fill(
1945                renderer,
1946                Rectangle::new(
1947                    Point::new((bounds.x + x).round(), top),
1948                    Size::new(1.0, DIVIDER_HEIGHT),
1949                ),
1950                colours.divider,
1951            );
1952        };
1953        for x in memory.dividers(&spans, self.active) {
1954            divider(renderer, x);
1955        }
1956        // Marks where tabs are cut off before the buttons.
1957        if memory.overflowing {
1958            divider(renderer, memory.fixed + memory.viewport_width);
1959        }
1960        self.draw_indicator(renderer, memory, &spans, colours, bounds);
1961
1962        // The bottom line, broken under the active tab where it is visible.
1963        let line = Rectangle {
1964            y: bounds.y + bounds.height - 1.0,
1965            height: 1.0,
1966            ..bounds
1967        };
1968        let gap = self
1969            .active
1970            .and_then(|index| memory.visible_span(&spans, index));
1971        match gap {
1972            Some((left, right)) => {
1973                fill(
1974                    renderer,
1975                    Rectangle {
1976                        width: left,
1977                        ..line
1978                    },
1979                    colours.line,
1980                );
1981                fill(
1982                    renderer,
1983                    Rectangle {
1984                        x: line.x + right,
1985                        width: line.width - right,
1986                        ..line
1987                    },
1988                    colours.line,
1989                );
1990            }
1991            None => fill(renderer, line, colours.line),
1992        }
1993
1994        self.trailing.as_widget().draw(
1995            &tree.children[2],
1996            renderer,
1997            theme,
1998            style,
1999            trailing,
2000            cursor,
2001            viewport,
2002        );
2003        if memory.overflowing {
2004            self.overflow.as_widget().draw(
2005                &tree.children[3],
2006                renderer,
2007                theme,
2008                style,
2009                overflow,
2010                cursor,
2011                viewport,
2012            );
2013        }
2014    }
2015
2016    fn operate(
2017        &mut self,
2018        tree: &mut Tree,
2019        layout: Layout<'_>,
2020        renderer: &Renderer,
2021        operation: &mut dyn Operation,
2022    ) {
2023        let bounds = layout.bounds();
2024        let Some(Parts {
2025            pinned,
2026            content,
2027            trailing,
2028            overflow,
2029        }) = parts(layout)
2030        else {
2031            return;
2032        };
2033        let [pinned_tree, content_tree, trailing_tree, overflow_tree] =
2034            tree.children.as_mut_slice()
2035        else {
2036            return;
2037        };
2038        let memory = tree.state.downcast_mut::<Memory>();
2039        let clip = memory.viewport(bounds);
2040        let shift = memory.shift();
2041        let pinned_scroll = memory.fixed_tabs == 0;
2042        let scrolled = Rectangle {
2043            x: clip.x,
2044            width: memory.content_width,
2045            ..content.bounds()
2046        };
2047        if !pinned_scroll {
2048            operation.traverse(&mut |operation| {
2049                self.pinned_row
2050                    .as_widget_mut()
2051                    .operate(pinned_tree, pinned, renderer, operation);
2052            });
2053        }
2054        operation.traverse(&mut |operation| {
2055            operation.scrollable(None, clip, scrolled, shift, memory);
2056            operation.traverse(&mut |operation| {
2057                if pinned_scroll {
2058                    self.pinned_row.as_widget_mut().operate(
2059                        pinned_tree,
2060                        pinned,
2061                        renderer,
2062                        operation,
2063                    );
2064                }
2065                self.content
2066                    .as_widget_mut()
2067                    .operate(content_tree, content, renderer, operation);
2068            });
2069        });
2070        self.trailing
2071            .as_widget_mut()
2072            .operate(trailing_tree, trailing, renderer, operation);
2073        self.overflow
2074            .as_widget_mut()
2075            .operate(overflow_tree, overflow, renderer, operation);
2076    }
2077
2078    fn update(
2079        &mut self,
2080        tree: &mut Tree,
2081        event: &Input,
2082        layout: Layout<'_>,
2083        cursor: mouse::Cursor,
2084        renderer: &Renderer,
2085        clipboard: &mut dyn Clipboard,
2086        shell: &mut Shell<'_, Message>,
2087        viewport: &Rectangle,
2088    ) {
2089        let bounds = layout.bounds();
2090        let Some(Parts {
2091            pinned,
2092            content,
2093            trailing,
2094            overflow,
2095        }) = parts(layout)
2096        else {
2097            return;
2098        };
2099        let spans = spans(bounds.x, pinned, content);
2100
2101        if self.drag(tree, event, cursor, bounds.x, &spans, shell) {
2102            return;
2103        }
2104
2105        let memory = tree.state.downcast_ref::<Memory>();
2106        let clip = memory.viewport(bounds);
2107        let frames = [memory.pinned_frame(bounds), (clip, memory.shift())];
2108        let overflowing = memory.overflowing;
2109        let [pinned_tree, content_tree, trailing_tree, overflow_tree] =
2110            tree.children.as_mut_slice()
2111        else {
2112            return;
2113        };
2114        let rows = [
2115            (&mut self.pinned_row, pinned_tree, pinned),
2116            (&mut self.content, content_tree, content),
2117        ];
2118        for ((row, row_tree, row_layout), (row_clip, shift)) in rows.into_iter().zip(frames) {
2119            row.as_widget_mut().update(
2120                row_tree,
2121                event,
2122                row_layout,
2123                inner_cursor(cursor, row_clip, shift),
2124                renderer,
2125                clipboard,
2126                shell,
2127                &(row_clip + shift),
2128            );
2129        }
2130        self.trailing.as_widget_mut().update(
2131            trailing_tree,
2132            event,
2133            trailing,
2134            cursor,
2135            renderer,
2136            clipboard,
2137            shell,
2138            viewport,
2139        );
2140        if overflowing {
2141            self.overflow.as_widget_mut().update(
2142                overflow_tree,
2143                event,
2144                overflow,
2145                cursor,
2146                renderer,
2147                clipboard,
2148                shell,
2149                viewport,
2150            );
2151        }
2152        if shell.is_event_captured() {
2153            return;
2154        }
2155
2156        let memory = tree.state.downcast_mut::<Memory>();
2157        self.pointer(memory, event, cursor, bounds, &spans, shell);
2158    }
2159
2160    fn mouse_interaction(
2161        &self,
2162        tree: &Tree,
2163        layout: Layout<'_>,
2164        cursor: mouse::Cursor,
2165        viewport: &Rectangle,
2166        renderer: &Renderer,
2167    ) -> mouse::Interaction {
2168        let memory = tree.state.downcast_ref::<Memory>();
2169        if memory.press.is_some_and(|press| press.dragging) {
2170            return mouse::Interaction::Grabbing;
2171        }
2172        let bounds = layout.bounds();
2173        let Some(Parts {
2174            pinned,
2175            content,
2176            trailing,
2177            overflow,
2178        }) = parts(layout)
2179        else {
2180            return mouse::Interaction::None;
2181        };
2182        let clip = memory.viewport(bounds);
2183        let rows = [
2184            (
2185                &self.pinned_row,
2186                &tree.children[0],
2187                pinned,
2188                memory.pinned_frame(bounds),
2189            ),
2190            (
2191                &self.content,
2192                &tree.children[1],
2193                content,
2194                (clip, memory.shift()),
2195            ),
2196        ];
2197        let interaction = rows
2198            .into_iter()
2199            .map(|(row, row_tree, row_layout, (row_clip, shift))| {
2200                row.as_widget().mouse_interaction(
2201                    row_tree,
2202                    row_layout,
2203                    inner_cursor(cursor, row_clip, shift),
2204                    &(row_clip + shift),
2205                    renderer,
2206                )
2207            })
2208            .fold(mouse::Interaction::None, mouse::Interaction::max)
2209            .max(self.trailing.as_widget().mouse_interaction(
2210                &tree.children[2],
2211                trailing,
2212                cursor,
2213                viewport,
2214                renderer,
2215            ));
2216        if !memory.overflowing {
2217            return interaction;
2218        }
2219        interaction.max(self.overflow.as_widget().mouse_interaction(
2220            &tree.children[3],
2221            overflow,
2222            cursor,
2223            viewport,
2224            renderer,
2225        ))
2226    }
2227
2228    fn overlay<'b>(
2229        &'b mut self,
2230        tree: &'b mut Tree,
2231        layout: Layout<'b>,
2232        renderer: &Renderer,
2233        viewport: &Rectangle,
2234        translation: Vector,
2235    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
2236        let memory = tree.state.downcast_ref::<Memory>();
2237        let bounds = layout.bounds();
2238        let frames = [
2239            memory.pinned_frame(bounds),
2240            (memory.viewport(bounds), memory.shift()),
2241        ];
2242        let overflowing = memory.overflowing;
2243        let Parts {
2244            pinned,
2245            content,
2246            trailing,
2247            overflow,
2248        } = parts(layout)?;
2249        let [pinned_tree, content_tree, trailing_tree, overflow_tree] =
2250            tree.children.as_mut_slice()
2251        else {
2252            return None;
2253        };
2254
2255        let mut overlays = Vec::new();
2256        let rows = [
2257            (&mut self.pinned_row, pinned_tree, pinned),
2258            (&mut self.content, content_tree, content),
2259        ];
2260        for ((row, row_tree, row_layout), (row_clip, shift)) in rows.into_iter().zip(frames) {
2261            overlays.extend(row.as_widget_mut().overlay(
2262                row_tree,
2263                row_layout,
2264                renderer,
2265                &(row_clip + shift),
2266                translation - shift,
2267            ));
2268        }
2269        overlays.extend(self.trailing.as_widget_mut().overlay(
2270            trailing_tree,
2271            trailing,
2272            renderer,
2273            viewport,
2274            translation,
2275        ));
2276        if overflowing {
2277            overlays.extend(self.overflow.as_widget_mut().overlay(
2278                overflow_tree,
2279                overflow,
2280                renderer,
2281                viewport,
2282                translation,
2283            ));
2284        }
2285        match overlays.len() {
2286            0 => None,
2287            1 => overlays.pop(),
2288            _ => Some(overlay::Group::with_children(overlays).overlay()),
2289        }
2290    }
2291}
2292
2293fn fill(renderer: &mut Renderer, bounds: Rectangle, colour: Color) {
2294    if bounds.width <= 0.0 || bounds.height <= 0.0 {
2295        return;
2296    }
2297    renderer.fill_quad(
2298        renderer::Quad {
2299            bounds,
2300            snap: true,
2301            ..renderer::Quad::default()
2302        },
2303        Background::Color(colour),
2304    );
2305}
2306
2307impl<Message> Strip<'_, Message> {
2308    /// The line marking where a dragged tab will land.
2309    fn draw_indicator(
2310        &self,
2311        renderer: &mut Renderer,
2312        memory: &Memory,
2313        spans: &[(f32, f32)],
2314        colours: StripStyle,
2315        bounds: Rectangle,
2316    ) {
2317        let Some(x) = memory
2318            .press
2319            .filter(|press| press.dragging)
2320            .and_then(|press| {
2321                let gap = press.gap?;
2322                drop_index(press.index, gap)?;
2323                memory.indicator_x(spans, press.index, gap)
2324            })
2325        else {
2326            return;
2327        };
2328        fill(
2329            renderer,
2330            Rectangle::new(
2331                Point::new(bounds.x + x, bounds.y),
2332                Size::new(INDICATOR_WIDTH, bounds.height),
2333            ),
2334            colours.indicator,
2335        );
2336    }
2337
2338    /// Follows a tab being dragged. Returns whether it used the event.
2339    fn drag(
2340        &self,
2341        tree: &mut Tree,
2342        event: &Input,
2343        cursor: mouse::Cursor,
2344        strip_x: f32,
2345        spans: &[(f32, f32)],
2346        shell: &mut Shell<'_, Message>,
2347    ) -> bool {
2348        let memory = tree.state.downcast_mut::<Memory>();
2349        let Some(mut press) = memory.press else {
2350            return false;
2351        };
2352        match event {
2353            Input::Mouse(mouse::Event::CursorMoved { .. }) => {
2354                let Some(position) = cursor.position() else {
2355                    return false;
2356                };
2357                if !press.dragging {
2358                    let far = press.origin.distance(position) > DRAG_THRESHOLD;
2359                    if !far || self.on_gesture.is_none() {
2360                        return false;
2361                    }
2362                    press.dragging = true;
2363                }
2364                let gap = gap_at(spans, memory.unscroll(position.x - strip_x));
2365                press.gap = Some(clamp_gap(press.index, gap, self.pinned, self.count));
2366                memory.press = Some(press);
2367                shell.request_redraw();
2368                shell.capture_event();
2369                true
2370            }
2371            Input::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
2372                memory.press = None;
2373                if !press.dragging {
2374                    return false;
2375                }
2376                shell.request_redraw();
2377                shell.capture_event();
2378                let Some(to) = press.gap.and_then(|gap| drop_index(press.index, gap)) else {
2379                    return true;
2380                };
2381                self.publish(
2382                    shell,
2383                    Gesture::Drop {
2384                        from: press.index,
2385                        to,
2386                    },
2387                );
2388                true
2389            }
2390            _ => false,
2391        }
2392    }
2393
2394    /// Presses, double clicks, the wheel and touch panning, once no child
2395    /// has used the event.
2396    fn pointer(
2397        &self,
2398        memory: &mut Memory,
2399        event: &Input,
2400        cursor: mouse::Cursor,
2401        bounds: Rectangle,
2402        spans: &[(f32, f32)],
2403        shell: &mut Shell<'_, Message>,
2404    ) {
2405        let tab_at = |memory: &Memory, cursor: mouse::Cursor| {
2406            let position = cursor.position_over(bounds)?;
2407            let x = memory.locate(position.x - bounds.x)?;
2408            spans
2409                .iter()
2410                .position(|(left, width)| x >= *left && x < left + width)
2411        };
2412        match event {
2413            Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
2414                let Some(position) = cursor.position_over(bounds) else {
2415                    return;
2416                };
2417                if let Some(index) = tab_at(memory, cursor) {
2418                    memory.press = Some(Press {
2419                        index,
2420                        origin: position,
2421                        dragging: false,
2422                        gap: None,
2423                    });
2424                    self.publish(shell, Gesture::Press(index));
2425                    shell.capture_event();
2426                    return;
2427                }
2428                let click = Click::new(
2429                    position,
2430                    mouse::Button::Left,
2431                    memory.last_click,
2432                    crate::time::now(),
2433                );
2434                memory.last_click = Some(click);
2435                if click.kind() == click::Kind::Double {
2436                    self.publish(shell, Gesture::DoubleClick);
2437                    shell.capture_event();
2438                }
2439            }
2440            Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)) => {
2441                if let Some(index) = tab_at(memory, cursor) {
2442                    self.publish(shell, Gesture::Middle(index));
2443                    shell.capture_event();
2444                }
2445            }
2446            Input::Mouse(mouse::Event::WheelScrolled { delta }) => {
2447                if !cursor.is_over(bounds) {
2448                    return;
2449                }
2450                let step = match *delta {
2451                    mouse::ScrollDelta::Lines { x, y } => {
2452                        (if x != 0.0 { x } else { y }) * WHEEL_LINE
2453                    }
2454                    mouse::ScrollDelta::Pixels { x, y } => {
2455                        if x.abs() > y.abs() {
2456                            x
2457                        } else {
2458                            y
2459                        }
2460                    }
2461                };
2462                if memory.scroll_by(-step) {
2463                    shell.request_redraw();
2464                    shell.capture_event();
2465                }
2466            }
2467            Input::Touch(touch::Event::FingerPressed { id, position }) => {
2468                if !bounds.contains(*position) {
2469                    return;
2470                }
2471                let tab = tab_at(memory, cursor);
2472                memory.touch = Some(Touch {
2473                    finger: *id,
2474                    last: position.x,
2475                    origin: *position,
2476                    tab,
2477                });
2478                if tab.is_some() {
2479                    shell.capture_event();
2480                }
2481            }
2482            Input::Touch(touch::Event::FingerMoved { id, position }) => {
2483                let Some(touch) = memory.touch.filter(|touch| touch.finger == *id) else {
2484                    return;
2485                };
2486                memory.touch = Some(Touch {
2487                    last: position.x,
2488                    ..touch
2489                });
2490                if memory.scroll_by(touch.last - position.x) {
2491                    shell.request_redraw();
2492                    shell.capture_event();
2493                }
2494            }
2495            Input::Touch(touch::Event::FingerLifted { id, position }) => {
2496                let Some(touch) = memory.touch.filter(|touch| touch.finger == *id) else {
2497                    return;
2498                };
2499                memory.touch = None;
2500                if let Some(index) = touch.tapped(*position) {
2501                    self.publish(shell, Gesture::Press(index));
2502                    shell.capture_event();
2503                }
2504            }
2505            Input::Touch(touch::Event::FingerLost { id, .. })
2506                if memory.touch.is_some_and(|touch| touch.finger == *id) =>
2507            {
2508                memory.touch = None;
2509            }
2510            _ => {}
2511        }
2512    }
2513}
2514
2515#[cfg(test)]
2516mod tests {
2517    use super::*;
2518    use crate::theme::{dark, light};
2519    use iced::keyboard::{Key, Modifiers};
2520
2521    fn state() -> State<u8> {
2522        State::new([
2523            document(1, "main.rs"),
2524            document(2, "lib.rs").modified(true),
2525            document(3, "README.md").pinned(true),
2526            document(4, "Cargo.toml"),
2527        ])
2528    }
2529
2530    fn ids(state: &State<u8>) -> Vec<u8> {
2531        state
2532            .documents()
2533            .iter()
2534            .map(|document| document.id)
2535            .collect()
2536    }
2537
2538    #[test]
2539    fn new_puts_pinned_documents_first_and_activates_the_first() {
2540        let state = state();
2541        assert_eq!(ids(&state), [3, 1, 2, 4]);
2542        assert_eq!(state.active(), Some(3));
2543        assert_eq!(state.recent(), [3, 1, 2, 4]);
2544        assert_eq!(state.pinned_count(), 1);
2545        assert!(state.is_active(3));
2546        assert!(!state.menu().is_open());
2547        assert!(!state.overflow().is_open());
2548    }
2549
2550    #[test]
2551    fn empty_state_has_nothing_to_do() {
2552        let mut state: State<u8> = State::new([]);
2553        assert_eq!(state.active(), None);
2554        assert_eq!(state.update(Event::Next), None);
2555        assert_eq!(state.update(Event::RecentNext), None);
2556        assert_eq!(state.update(Event::CloseAll), None);
2557        assert_eq!(Action::Close.event(&state), None);
2558        assert_eq!(Action::LastTab.event(&state), None);
2559    }
2560
2561    #[test]
2562    fn activate_reports_changes_only() {
2563        let mut state = state();
2564        assert_eq!(state.update(Event::Activate(2)), Some(Output::Activated(2)));
2565        assert_eq!(state.update(Event::Activate(2)), None);
2566        assert_eq!(state.update(Event::Activate(9)), None);
2567        assert_eq!(state.recent()[0], 2);
2568        assert_eq!(state.clone().with_active(4).active(), Some(4));
2569    }
2570
2571    #[test]
2572    fn next_and_previous_wrap_in_strip_order() {
2573        let mut state = state().with_active(4);
2574        assert_eq!(state.update(Event::Next), Some(Output::Activated(3)));
2575        assert_eq!(state.update(Event::Previous), Some(Output::Activated(4)));
2576        assert_eq!(state.update(Event::Previous), Some(Output::Activated(2)));
2577    }
2578
2579    #[test]
2580    fn recent_walks_until_the_cycle_ends() {
2581        let mut state = state();
2582        for id in [1, 2, 4] {
2583            let _ = state.update(Event::Activate(id));
2584        }
2585        assert_eq!(state.recent(), [4, 2, 1, 3]);
2586        assert_eq!(state.update(Event::RecentNext), Some(Output::Activated(2)));
2587        assert_eq!(state.update(Event::RecentNext), Some(Output::Activated(1)));
2588        assert_eq!(state.recent(), [4, 2, 1, 3], "the order holds mid-walk");
2589        assert_eq!(state.update(Event::EndCycle), None);
2590        assert_eq!(state.recent(), [1, 4, 2, 3]);
2591        assert_eq!(state.update(Event::RecentNext), Some(Output::Activated(4)));
2592        assert_eq!(state.update(Event::from(CycleEnd)), None);
2593        assert_eq!(state.recent(), [4, 1, 2, 3]);
2594    }
2595
2596    #[test]
2597    fn recent_previous_starts_from_the_oldest_and_other_events_end_the_walk() {
2598        let mut state = state();
2599        assert_eq!(
2600            state.update(Event::RecentPrevious),
2601            Some(Output::Activated(4))
2602        );
2603        assert_eq!(state.update(Event::Activate(2)), Some(Output::Activated(2)));
2604        assert_eq!(state.recent(), [2, 4, 3, 1]);
2605        let mut single = State::new([document(1, "a")]);
2606        assert_eq!(single.update(Event::RecentNext), None);
2607    }
2608
2609    #[test]
2610    fn close_events_request_without_closing() {
2611        let mut state = state();
2612        assert_eq!(
2613            state.update(Event::Close(3)),
2614            Some(Output::CloseRequested(vec![3]))
2615        );
2616        assert_eq!(state.update(Event::Close(9)), None);
2617        assert_eq!(
2618            state.update(Event::CloseOthers(1)),
2619            Some(Output::CloseRequested(vec![2, 4]))
2620        );
2621        assert_eq!(
2622            state.update(Event::CloseToTheRight(1)),
2623            Some(Output::CloseRequested(vec![2, 4]))
2624        );
2625        assert_eq!(state.update(Event::CloseToTheRight(4)), None);
2626        assert_eq!(
2627            state.update(Event::CloseSaved),
2628            Some(Output::CloseRequested(vec![1, 4]))
2629        );
2630        assert_eq!(
2631            state.update(Event::CloseAll),
2632            Some(Output::CloseRequested(vec![1, 2, 4]))
2633        );
2634        assert_eq!(state.documents().len(), 4);
2635    }
2636
2637    #[test]
2638    fn closing_the_active_document_activates_the_most_recent() {
2639        let mut state = state();
2640        let _ = state.update(Event::Activate(4));
2641        let _ = state.update(Event::Activate(1));
2642        assert_eq!(state.close(&[1]), Some(4));
2643        assert_eq!(ids(&state), [3, 2, 4]);
2644        assert_eq!(state.close(&[2]), None, "the active one stays");
2645        assert_eq!(state.active(), Some(4));
2646        assert_eq!(state.close(&[3, 4]), None);
2647        assert_eq!(state.active(), None);
2648        assert!(state.recent().is_empty());
2649    }
2650
2651    #[test]
2652    fn open_adds_to_the_end_of_its_group_or_activates() {
2653        let mut state = state();
2654        state.open(document(5, "new.rs"));
2655        assert_eq!(ids(&state), [3, 1, 2, 4, 5]);
2656        assert_eq!(state.active(), Some(5));
2657        state.open(document(6, "notes.md").pinned(true));
2658        assert_eq!(ids(&state), [3, 6, 1, 2, 4, 5]);
2659        state.open(document(1, "ignored"));
2660        assert_eq!(state.active(), Some(1));
2661        assert_eq!(state.document(1).map(|d| d.label.as_str()), Some("main.rs"));
2662        assert_eq!(state.recent()[..3], [1, 6, 5]);
2663    }
2664
2665    #[test]
2666    fn modified_and_label_change_in_place() {
2667        let mut state = state();
2668        state.set_modified(1, true);
2669        state.set_label(1, "main2.rs");
2670        let main = state.document(1).cloned();
2671        assert_eq!(
2672            main,
2673            Some(document(1, "main2.rs").modified(true)),
2674            "{main:?}"
2675        );
2676        state.set_modified(9, true);
2677    }
2678
2679    #[test]
2680    fn moves_stay_within_the_group() {
2681        let mut state = state();
2682        assert_eq!(
2683            state.update(Event::Move(1, 3)),
2684            Some(Output::Moved {
2685                id: 1,
2686                from: 1,
2687                to: 3
2688            })
2689        );
2690        assert_eq!(ids(&state), [3, 2, 4, 1]);
2691        assert_eq!(
2692            state.update(Event::Move(1, 0)),
2693            Some(Output::Moved {
2694                id: 1,
2695                from: 3,
2696                to: 1
2697            })
2698        );
2699        assert_eq!(state.update(Event::Move(1, 1)), None);
2700        assert_eq!(state.update(Event::Move(3, 5)), None, "pinned stays first");
2701        assert_eq!(state.update(Event::Move(4, 99)), None, "already last");
2702    }
2703
2704    #[test]
2705    fn pinning_moves_to_the_group_boundary() {
2706        let mut state = state();
2707        assert_eq!(
2708            state.update(Event::Pin(4, true)),
2709            Some(Output::Pinned(4, true))
2710        );
2711        assert_eq!(ids(&state), [3, 4, 1, 2]);
2712        assert_eq!(state.update(Event::Pin(4, true)), None);
2713        assert_eq!(
2714            state.update(Event::Pin(3, false)),
2715            Some(Output::Pinned(3, false))
2716        );
2717        assert_eq!(ids(&state), [4, 3, 1, 2]);
2718        assert_eq!(state.pinned_count(), 1);
2719    }
2720
2721    fn items(state: &State<u8>) -> Vec<(MenuItem, bool)> {
2722        state
2723            .menu()
2724            .menu()
2725            .entries()
2726            .iter()
2727            .filter_map(|entry| entry.as_item())
2728            .map(|item| (item.id, item.disabled))
2729            .collect()
2730    }
2731
2732    #[test]
2733    fn the_context_menu_is_built_for_the_tab_it_opens_on() {
2734        let mut state = state().with_menu_items([item(MenuItem::Custom("copy-path"), "Copy path")]);
2735        let _ = state.update(Event::Menu(context_menu::Event::Open(4, Point::ORIGIN)));
2736        assert!(state.menu().is_open_on(&4));
2737        assert_eq!(
2738            items(&state),
2739            [
2740                (MenuItem::Close, false),
2741                (MenuItem::CloseOthers, false),
2742                (MenuItem::CloseSaved, false),
2743                (MenuItem::CloseAll, false),
2744                (MenuItem::Pin, false),
2745                (MenuItem::Custom("copy-path"), false),
2746            ],
2747            "the last tab has nothing to its right"
2748        );
2749        let _ = state.update(Event::Menu(context_menu::Event::OpenFromKeyboard(3)));
2750        assert!(items(&state).contains(&(MenuItem::Unpin, false)));
2751        assert_eq!(
2752            state.update(Event::Menu(context_menu::Event::Open(9, Point::ORIGIN))),
2753            None
2754        );
2755    }
2756
2757    #[test]
2758    fn menu_items_map_to_outputs() {
2759        let choose = |target: u8, item: MenuItem| {
2760            let mut state =
2761                state().with_menu_items([dropdown_menu::item(MenuItem::Custom("copy"), "Copy")]);
2762            let _ = state.update(Event::Menu(context_menu::Event::OpenFromKeyboard(target)));
2763            let output = state.update(Event::Menu(context_menu::Event::Menu(
2764                dropdown_menu::Event::Activate(item),
2765            )));
2766            assert!(!state.menu().is_open());
2767            (output, ids(&state))
2768        };
2769        assert_eq!(
2770            choose(1, MenuItem::Close).0,
2771            Some(Output::CloseRequested(vec![1]))
2772        );
2773        assert_eq!(
2774            choose(2, MenuItem::CloseOthers).0,
2775            Some(Output::CloseRequested(vec![1, 4]))
2776        );
2777        assert_eq!(
2778            choose(2, MenuItem::CloseToTheRight).0,
2779            Some(Output::CloseRequested(vec![4]))
2780        );
2781        assert_eq!(
2782            choose(1, MenuItem::CloseSaved).0,
2783            Some(Output::CloseRequested(vec![1, 4]))
2784        );
2785        assert_eq!(
2786            choose(1, MenuItem::CloseAll).0,
2787            Some(Output::CloseRequested(vec![1, 2, 4]))
2788        );
2789        assert_eq!(
2790            choose(4, MenuItem::Pin),
2791            (Some(Output::Pinned(4, true)), vec![3, 4, 1, 2])
2792        );
2793        assert_eq!(choose(3, MenuItem::Unpin).0, Some(Output::Pinned(3, false)));
2794        assert_eq!(
2795            choose(2, MenuItem::Custom("copy")).0,
2796            Some(Output::Custom("copy", 2))
2797        );
2798    }
2799
2800    #[test]
2801    fn the_overflow_menu_lists_every_document_and_activates_one() {
2802        let mut state = state();
2803        let _ = state.update(Event::Overflow(dropdown_menu::Event::Toggle));
2804        assert!(state.overflow().is_open());
2805        assert_eq!(state.overflow().entries().len(), 4);
2806        assert!(state.overflow().is_checked(3));
2807        let lib = state.overflow().item(2).cloned();
2808        assert_eq!(lib.and_then(|item| item.shortcut), Some("Modified".into()));
2809        assert_eq!(
2810            state.update(Event::Overflow(dropdown_menu::Event::Activate(4))),
2811            Some(Output::Activated(4))
2812        );
2813        assert!(!state.overflow().is_open());
2814        assert_eq!(state.update(Event::New), Some(Output::NewTab));
2815    }
2816
2817    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
2818        let chord: Chord = chord.parse().unwrap();
2819        keymap.resolve(chord.key(), chord.modifiers())
2820    }
2821
2822    #[test]
2823    fn default_keymap_covers_every_action() {
2824        let keymap = default_keymap();
2825        assert_eq!(press(&keymap, "Ctrl+Tab"), Some(Action::RecentNext));
2826        assert_eq!(
2827            press(&keymap, "Ctrl+Shift+Tab"),
2828            Some(Action::RecentPrevious)
2829        );
2830        assert_eq!(press(&keymap, "Ctrl+PageDown"), Some(Action::Next));
2831        assert_eq!(press(&keymap, "Ctrl+PageUp"), Some(Action::Previous));
2832        assert_eq!(press(&keymap, "Ctrl+Shift+PageUp"), Some(Action::MoveLeft));
2833        assert_eq!(
2834            press(&keymap, "Ctrl+Shift+PageDown"),
2835            Some(Action::MoveRight)
2836        );
2837        assert_eq!(press(&keymap, "Mod+W"), Some(Action::Close));
2838        assert_eq!(press(&keymap, "Mod+N"), Some(Action::New));
2839        assert_eq!(press(&keymap, "Mod+1"), Some(Action::Tab(1)));
2840        assert_eq!(press(&keymap, "Mod+8"), Some(Action::Tab(8)));
2841        assert_eq!(press(&keymap, "Mod+9"), Some(Action::LastTab));
2842        assert_eq!(press(&keymap, "Tab"), None);
2843        assert_eq!(press(&keymap, "PageDown"), None);
2844        for action in <Action as keys::Action>::ALL {
2845            let unbound = *action == Action::OpenMenu;
2846            assert_eq!(keymap.chords(action).is_empty(), unbound, "{action:?}");
2847            assert!(keys::Action::description(*action).ends_with('.'));
2848        }
2849        assert_eq!(Keymap::<Action>::defaults(), keymap);
2850    }
2851
2852    #[test]
2853    fn opening_the_tab_menu_is_left_to_context_menus_by_default() {
2854        let keymap = default_keymap();
2855        for chord in ["Shift+F10", "Menu"] {
2856            assert_eq!(press(&keymap, chord), None, "{chord}");
2857            let context = context_menu::default_keymap();
2858            assert_eq!(
2859                press_menu(&context, chord),
2860                Some(context_menu::Action::Open)
2861            );
2862        }
2863        let bound = keymap.bind("Shift+F10".parse().unwrap(), Action::OpenMenu);
2864        assert_eq!(press(&bound, "Shift+F10"), Some(Action::OpenMenu));
2865    }
2866
2867    fn press_menu(
2868        keymap: &Keymap<context_menu::Action>,
2869        chord: &str,
2870    ) -> Option<context_menu::Action> {
2871        let chord: Chord = chord.parse().unwrap();
2872        keymap.resolve(chord.key(), chord.modifiers())
2873    }
2874
2875    #[test]
2876    fn default_keymap_leaves_plain_and_alt_keys_to_other_components() {
2877        let keymap = default_keymap();
2878        for chord in ["ArrowLeft", "ArrowRight", "Home", "End", "Alt+1", "Escape"] {
2879            assert_eq!(press(&keymap, chord), None, "{chord}");
2880        }
2881    }
2882
2883    #[test]
2884    fn keymap_overrides_and_unbinding() {
2885        let keymap = default_keymap()
2886            .unbind(&"Ctrl+Tab".parse().unwrap())
2887            .bind("Alt+PageDown".parse().unwrap(), Action::Next);
2888        assert_eq!(press(&keymap, "Ctrl+Tab"), None);
2889        assert_eq!(press(&keymap, "Alt+PageDown"), Some(Action::Next));
2890        assert_eq!(press(&keymap, "Ctrl+PageDown"), Some(Action::Next));
2891        let event = keys::Event {
2892            key: Key::Character("w".into()),
2893            modifiers: Modifiers::COMMAND,
2894        };
2895        assert_eq!(keymap.resolve_event(&event), Some(Action::Close));
2896    }
2897
2898    #[test]
2899    fn actions_map_to_events() {
2900        let state = state().with_active(1);
2901        assert_eq!(Action::RecentNext.event(&state), Some(Event::RecentNext));
2902        assert_eq!(
2903            Action::RecentPrevious.event(&state),
2904            Some(Event::RecentPrevious)
2905        );
2906        assert_eq!(Action::Next.event(&state), Some(Event::Next));
2907        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
2908        assert_eq!(Action::MoveLeft.event(&state), Some(Event::Move(1, 0)));
2909        assert_eq!(Action::MoveRight.event(&state), Some(Event::Move(1, 2)));
2910        assert_eq!(Action::Close.event(&state), Some(Event::Close(1)));
2911        assert_eq!(Action::New.event(&state), Some(Event::New));
2912        assert_eq!(Action::Tab(1).event(&state), Some(Event::Activate(3)));
2913        assert_eq!(Action::Tab(4).event(&state), Some(Event::Activate(4)));
2914        assert_eq!(Action::Tab(5).event(&state), None);
2915        assert_eq!(Action::Tab(0).event(&state), None);
2916        assert_eq!(Action::LastTab.event(&state), Some(Event::Activate(4)));
2917        assert_eq!(
2918            Action::OpenMenu.event(&state),
2919            Some(Event::Menu(context_menu::Event::OpenFromKeyboard(1)))
2920        );
2921        let first = state.clone().with_active(3);
2922        assert_eq!(Action::MoveLeft.event(&first), None);
2923
2924        let mut state = state;
2925        let event = Action::MoveRight.event(&state).unwrap();
2926        assert!(state.update(event).is_some());
2927        assert_eq!(ids(&state), [3, 2, 1, 4]);
2928    }
2929
2930    #[test]
2931    fn gaps_follow_tab_centres() {
2932        let tabs = [(0.0, 100.0), (100.0, 60.0), (160.0, 80.0)];
2933        assert_eq!(gap_at(&tabs, -5.0), 0);
2934        assert_eq!(gap_at(&tabs, 49.0), 0);
2935        assert_eq!(gap_at(&tabs, 51.0), 1);
2936        assert_eq!(gap_at(&tabs, 131.0), 2);
2937        assert_eq!(gap_at(&tabs, 500.0), 3);
2938    }
2939
2940    #[test]
2941    fn gaps_are_kept_within_the_group() {
2942        assert_eq!(clamp_gap(0, 4, 2, 5), 2);
2943        assert_eq!(clamp_gap(3, 0, 2, 5), 2);
2944        assert_eq!(clamp_gap(3, 5, 2, 5), 5);
2945        assert_eq!(clamp_gap(1, 0, 0, 3), 0);
2946    }
2947
2948    #[test]
2949    fn dropping_next_to_itself_does_not_move() {
2950        assert_eq!(drop_index(2, 2), None);
2951        assert_eq!(drop_index(2, 3), None);
2952        assert_eq!(drop_index(2, 0), Some(0));
2953        assert_eq!(drop_index(0, 3), Some(2));
2954    }
2955
2956    #[test]
2957    fn memory_reveals_and_clamps() {
2958        let mut memory = Memory {
2959            content_width: 600.0,
2960            viewport_width: 200.0,
2961            ..Memory::default()
2962        };
2963        memory.reveal(450.0, 550.0);
2964        assert_eq!(memory.offset, 350.0);
2965        memory.reveal(100.0, 180.0);
2966        assert_eq!(memory.offset, 100.0);
2967        assert!(memory.scroll_by(1000.0));
2968        assert_eq!(memory.offset, 400.0);
2969        assert!(!memory.scroll_by(10.0));
2970        assert!(memory.scroll_by(-1000.0));
2971        assert_eq!(memory.offset, 0.0);
2972    }
2973
2974    /// The offset after laying the strip out at each viewport width in
2975    /// turn, with the active tab at 450 to 550 of 600 pixels of tabs.
2976    fn offset_after(widths: &[f32]) -> f32 {
2977        let mut memory = Memory::default();
2978        for width in widths {
2979            memory.follow((Some(4), 6), (600.0, *width), Some((450.0, 100.0)));
2980        }
2981        memory.offset
2982    }
2983
2984    #[test]
2985    fn the_first_offset_does_not_depend_on_earlier_sizes() {
2986        assert_eq!(offset_after(&[300.0]), 250.0, "active tab ends at the edge");
2987        assert_eq!(offset_after(&[1000.0, 300.0]), 250.0);
2988        assert_eq!(offset_after(&[0.0, 300.0]), 250.0);
2989        assert_eq!(offset_after(&[200.0, 300.0]), 250.0);
2990        assert_eq!(offset_after(&[200.0, 300.0, 300.0]), 250.0);
2991    }
2992
2993    #[test]
2994    fn a_new_active_tab_scrolls_the_least_distance_and_keeps_wheel_scrolling() {
2995        let mut memory = Memory::default();
2996        memory.follow((Some(4), 6), (600.0, 300.0), Some((450.0, 100.0)));
2997        memory.follow((Some(3), 6), (600.0, 300.0), Some((350.0, 100.0)));
2998        assert_eq!(memory.offset, 250.0, "already in view");
2999        memory.follow((Some(0), 6), (600.0, 300.0), Some((0.0, 100.0)));
3000        assert_eq!(memory.offset, 0.0);
3001        let _ = memory.scroll_by(120.0);
3002        memory.follow((Some(0), 6), (600.0, 300.0), Some((0.0, 100.0)));
3003        assert_eq!(memory.offset, 120.0, "a relayout leaves the wheel offset");
3004    }
3005
3006    #[test]
3007    fn pointer_opens_place_the_menu_below_the_tab() {
3008        let mut state = state();
3009        let _ = state.update(Event::Menu(context_menu::Event::Open(
3010            1,
3011            Point::new(40.0, 12.0),
3012        )));
3013        assert!(state.menu().is_open_on(&1));
3014        assert_eq!(
3015            state.menu().position(),
3016            Some(Point::new(0.0, HEIGHT + KEYBOARD_GAP))
3017        );
3018        assert_eq!(state.menu().menu().highlighted(), None);
3019    }
3020
3021    #[test]
3022    fn active_tab_joins_the_page_and_others_sit_on_the_strip() {
3023        for theme in [light(), dark()] {
3024            let tokens = Tokens::of(&theme);
3025            let active = tab_style(&tokens, true, false);
3026            let idle = tab_style(&tokens, false, false);
3027            let hovered = tab_style(&tokens, false, true);
3028            assert_eq!(
3029                active.background,
3030                Some(Background::Color(tokens.background))
3031            );
3032            assert_eq!(idle.background, None);
3033            assert!(hovered.background.is_some());
3034            assert_ne!(hovered.background, active.background);
3035            assert_eq!(active.text_color, Some(tokens.foreground));
3036            assert_eq!(idle.text_color, Some(tokens.muted_foreground));
3037            assert_eq!(hovered.text_color, Some(tokens.foreground));
3038            assert_eq!(active.border.radius.bottom_left, 0.0);
3039            assert_eq!(active.border.radius.top_left, radius::MD);
3040            assert_eq!(strip_style(&tokens).background, tokens.muted);
3041            assert_ne!(strip_style(&tokens).background, tokens.background);
3042        }
3043    }
3044
3045    #[test]
3046    fn disabled_labels_fade() {
3047        let tokens = Tokens::of(&light());
3048        let on = label_colour(&tokens, true, false, true);
3049        let off = label_colour(&tokens, true, false, false);
3050        assert!(off.a < on.a);
3051    }
3052
3053    #[test]
3054    fn close_button_shows_a_surface_on_hover_only() {
3055        for theme in [light(), dark()] {
3056            let tokens = Tokens::of(&theme);
3057            assert!(close_style(&tokens, Status::Active).background.is_none());
3058            assert!(close_style(&tokens, Status::Disabled).background.is_none());
3059            assert!(close_style(&tokens, Status::Hovered).background.is_some());
3060            assert!(close_style(&tokens, Status::Pressed).background.is_some());
3061        }
3062    }
3063
3064    #[test]
3065    fn modified_dot_is_stronger_on_the_active_tab() {
3066        let tokens = Tokens::of(&dark());
3067        assert_eq!(
3068            dot_style(&tokens, true).background,
3069            Some(Background::Color(tokens.foreground))
3070        );
3071        assert_eq!(
3072            dot_style(&tokens, false).background,
3073            Some(Background::Color(tokens.muted_foreground))
3074        );
3075    }
3076
3077    #[test]
3078    fn slots_show_close_dot_or_space() {
3079        let look = |active, hovered| Look {
3080            active,
3081            hovered,
3082            enabled: true,
3083        };
3084        let saved = document(1, "a");
3085        let modified = document(1, "a").modified(true);
3086        let pinned = document(1, "a").pinned(true);
3087        let has_slot =
3088            |document: &Document<u8>, look| slot::<u8, ()>(document, look, None).is_some();
3089        assert!(has_slot(&saved, look(false, false)));
3090        assert!(has_slot(&modified, look(true, false)));
3091        assert!(!has_slot(&pinned, look(true, true)));
3092        assert!(has_slot(&pinned.clone().modified(true), look(false, false)));
3093    }
3094
3095    #[test]
3096    fn builder_defaults() {
3097        let state = state();
3098        let tabs: DocumentTabs<'_, u8, ()> = document_tabs(&state);
3099        assert!(!tabs.new_tab);
3100        assert_eq!(tabs.max_label_width, MAX_LABEL_WIDTH);
3101        assert_eq!(tabs.context_menu_keymap, context_menu::default_keymap());
3102        assert!(!tabs.is_enabled());
3103        let tabs: DocumentTabs<'_, u8, ()> = document_tabs(&state)
3104            .new_tab(true)
3105            .max_label_width(120.0)
3106            .context_menu_keymap(Keymap::new())
3107            .overflow_keymap(Keymap::new())
3108            .on_event(|_| ());
3109        assert!(tabs.new_tab);
3110        assert_eq!(tabs.max_label_width, 120.0);
3111        assert!(tabs.context_menu_keymap.is_empty());
3112        assert!(tabs.overflow_keymap.is_empty());
3113        assert!(tabs.is_enabled());
3114    }
3115
3116    #[test]
3117    fn documents_are_closable_and_unlocked_by_default() {
3118        let plain = document(1, "a");
3119        assert!(plain.closable);
3120        assert!(!plain.locked);
3121        let kept = plain.closable(false).locked(true);
3122        assert!(!kept.closable);
3123        assert!(kept.locked);
3124    }
3125
3126    /// A pinned job list that never closes or unpins, then three files.
3127    fn kept() -> State<u8> {
3128        State::new([
3129            document(0, "All jobs")
3130                .pinned(true)
3131                .closable(false)
3132                .locked(true),
3133            document(1, "a.rs"),
3134            document(2, "b.rs"),
3135            document(3, "c.rs"),
3136        ])
3137    }
3138
3139    /// The items the context menu offers on `target`, checking none is a
3140    /// disabled no-op and separators only sit between groups.
3141    fn offered(state: &mut State<u8>, target: u8) -> Vec<MenuItem> {
3142        let _ = state.update(Event::Menu(context_menu::Event::OpenFromKeyboard(target)));
3143        if !state.menu().is_open() {
3144            return Vec::new();
3145        }
3146        let entries = state.menu().menu().entries();
3147        assert!(
3148            entries
3149                .first()
3150                .is_some_and(|entry| entry.as_item().is_some())
3151        );
3152        assert!(
3153            entries
3154                .last()
3155                .is_some_and(|entry| entry.as_item().is_some())
3156        );
3157        let has_double = entries
3158            .windows(2)
3159            .any(|pair| pair[0].as_item().is_none() && pair[1].as_item().is_none());
3160        assert!(!has_double, "two separators in a row");
3161        items(state)
3162            .into_iter()
3163            .map(|(id, disabled)| {
3164                assert!(!disabled, "{id:?} is disabled");
3165                id
3166            })
3167            .collect()
3168    }
3169
3170    #[test]
3171    fn the_menu_hides_close_and_pin_on_a_kept_tab() {
3172        let mut state = kept();
3173        assert_eq!(
3174            offered(&mut state, 0),
3175            [MenuItem::CloseAll],
3176            "Close others and Close to the right would close the same tabs"
3177        );
3178        assert_eq!(
3179            offered(&mut state, 1),
3180            [
3181                MenuItem::Close,
3182                MenuItem::CloseOthers,
3183                MenuItem::CloseAll,
3184                MenuItem::Pin,
3185            ],
3186            "Close to the right would close what Close others does"
3187        );
3188        assert_eq!(
3189            offered(&mut state, 3),
3190            [
3191                MenuItem::Close,
3192                MenuItem::CloseOthers,
3193                MenuItem::CloseAll,
3194                MenuItem::Pin
3195            ]
3196        );
3197    }
3198
3199    #[test]
3200    fn a_lone_tab_beside_a_kept_one_offers_close_without_close_all() {
3201        let mut state = State::new([
3202            document(0, "All jobs")
3203                .pinned(true)
3204                .closable(false)
3205                .locked(true),
3206            document(1, "orders-etl"),
3207        ]);
3208        assert_eq!(offered(&mut state, 1), [MenuItem::Close, MenuItem::Pin]);
3209        assert_eq!(offered(&mut state, 0), [MenuItem::CloseAll]);
3210    }
3211
3212    #[test]
3213    fn a_pinned_closable_tab_offers_close_and_unpin() {
3214        let mut state = State::new([document(0, "notes").pinned(true), document(1, "a.rs")]);
3215        assert_eq!(
3216            offered(&mut state, 0),
3217            [MenuItem::Close, MenuItem::CloseAll, MenuItem::Unpin],
3218            "the bulk closes all close just a.rs"
3219        );
3220    }
3221
3222    #[test]
3223    fn a_menu_with_nothing_to_offer_does_not_open() {
3224        let mut alone = State::new([document(0, "All jobs")
3225            .pinned(true)
3226            .closable(false)
3227            .locked(true)]);
3228        assert!(offered(&mut alone, 0).is_empty());
3229        assert!(!alone.menu().is_open());
3230
3231        let mut extra = alone.with_menu_items([item(MenuItem::Custom("refresh"), "Refresh")]);
3232        assert_eq!(offered(&mut extra, 0), [MenuItem::Custom("refresh")]);
3233        assert_eq!(extra.menu().menu().entries().len(), 1, "no separators");
3234    }
3235
3236    #[test]
3237    fn close_saved_shows_only_when_it_differs_from_close_all() {
3238        let mut state = kept();
3239        assert!(!offered(&mut state, 1).contains(&MenuItem::CloseSaved));
3240
3241        state.set_modified(2, true);
3242        assert!(offered(&mut state, 1).contains(&MenuItem::CloseSaved));
3243
3244        for id in [1, 3] {
3245            state.set_modified(id, true);
3246        }
3247        assert!(
3248            !offered(&mut state, 1).contains(&MenuItem::CloseSaved),
3249            "every tab it would look at is modified"
3250        );
3251
3252        let mut pinned_only = kept();
3253        pinned_only.set_modified(0, true);
3254        assert!(
3255            !offered(&mut pinned_only, 1).contains(&MenuItem::CloseSaved),
3256            "a modified pinned tab is never closed in bulk"
3257        );
3258    }
3259
3260    #[test]
3261    fn close_requests_skip_unclosable_documents() {
3262        let mut state = State::new([
3263            document(0, "All jobs").pinned(true).closable(false),
3264            document(1, "log").closable(false),
3265            document(2, "a.rs"),
3266            document(3, "b.rs").modified(true),
3267        ]);
3268        assert_eq!(state.update(Event::Close(0)), None);
3269        assert_eq!(state.update(Event::Close(1)), None);
3270        assert_eq!(
3271            state.update(Event::Close(2)),
3272            Some(Output::CloseRequested(vec![2]))
3273        );
3274        assert_eq!(
3275            state.update(Event::CloseOthers(2)),
3276            Some(Output::CloseRequested(vec![3]))
3277        );
3278        assert_eq!(
3279            state.update(Event::CloseToTheRight(0)),
3280            Some(Output::CloseRequested(vec![2, 3]))
3281        );
3282        assert_eq!(
3283            state.update(Event::CloseSaved),
3284            Some(Output::CloseRequested(vec![2]))
3285        );
3286        assert_eq!(
3287            state.update(Event::CloseAll),
3288            Some(Output::CloseRequested(vec![2, 3]))
3289        );
3290        assert!(!offered(&mut state, 1).contains(&MenuItem::Close));
3291
3292        assert_eq!(Action::Close.event(&state.clone().with_active(1)), None);
3293        assert_eq!(Action::Close.event(&state.clone().with_active(0)), None);
3294        assert_eq!(
3295            Action::Close.event(&state.with_active(2)),
3296            Some(Event::Close(2))
3297        );
3298    }
3299
3300    #[test]
3301    fn unclosable_tabs_have_no_close_slot() {
3302        let look = Look {
3303            active: true,
3304            hovered: true,
3305            enabled: true,
3306        };
3307        let has_slot = |document: &Document<u8>| slot::<u8, ()>(document, look, None).is_some();
3308        assert!(has_slot(&document(1, "a")));
3309        assert!(!has_slot(&document(1, "a").closable(false)));
3310        assert!(has_slot(&document(1, "a").closable(false).modified(true)));
3311    }
3312
3313    #[test]
3314    fn pin_events_leave_locked_documents_alone() {
3315        let mut state = kept();
3316        let mut locked = State::new([document(5, "x").locked(true), document(6, "y")]);
3317        assert_eq!(state.update(Event::Pin(0, false)), None);
3318        assert_eq!(state.pinned_count(), 1);
3319        assert_eq!(locked.update(Event::Pin(5, true)), None);
3320        assert_eq!(locked.pinned_count(), 0);
3321        assert_eq!(
3322            locked.update(Event::Pin(6, true)),
3323            Some(Output::Pinned(6, true))
3324        );
3325    }
3326
3327    #[test]
3328    fn locked_tabs_still_move_within_their_group() {
3329        let mut state = State::new([
3330            document(0, "jobs").pinned(true).locked(true),
3331            document(1, "notes").pinned(true),
3332            document(2, "a.rs"),
3333        ]);
3334        assert_eq!(
3335            state.update(Event::Move(0, 9)),
3336            Some(Output::Moved {
3337                id: 0,
3338                from: 0,
3339                to: 1
3340            }),
3341            "clamped to the end of the pinned tabs"
3342        );
3343        assert_eq!(ids(&state), [1, 0, 2]);
3344        assert_eq!(state.update(Event::Move(2, 0)), None);
3345        assert_eq!(
3346            clamp_gap(1, 3, 2, 3),
3347            2,
3348            "a dragged pinned tab stays pinned"
3349        );
3350        assert_eq!(clamp_gap(2, 0, 2, 3), 2, "an unpinned tab stays unpinned");
3351    }
3352
3353    #[test]
3354    fn pinned_tabs_stay_unless_they_take_most_of_a_narrow_strip() {
3355        assert!(pinned_stay(100.0, 250.0, true));
3356        assert!(pinned_stay(125.0, 250.0, true));
3357        assert!(!pinned_stay(126.0, 250.0, true));
3358        assert!(pinned_stay(400.0, 250.0, false), "everything fits");
3359        assert!(pinned_stay(0.0, 0.0, true));
3360    }
3361
3362    /// One pinned tab 100 pixels wide, then six 100 pixel tabs scrolling
3363    /// in 150 pixels, laid out with the last one active.
3364    fn split() -> (Memory, Vec<(f32, f32)>) {
3365        let spans: Vec<(f32, f32)> = (0..7).map(|index| (index as f32 * 100.0, 100.0)).collect();
3366        let mut memory = Memory {
3367            fixed: 100.0,
3368            fixed_tabs: 1,
3369            ..Memory::default()
3370        };
3371        let active = memory.scroll_span(&spans, 6);
3372        memory.follow((Some(6), 7), (600.0, 150.0), active);
3373        (memory, spans)
3374    }
3375
3376    #[test]
3377    fn the_active_tab_is_revealed_after_the_pinned_tabs() {
3378        let (mut memory, spans) = split();
3379        assert_eq!(memory.scroll_span(&spans, 6), Some((500.0, 100.0)));
3380        assert_eq!(memory.offset, 450.0);
3381        assert_eq!(memory.visible_span(&spans, 6), Some((150.0, 250.0)));
3382        assert_eq!(memory.visible_span(&spans, 0), Some((0.0, 100.0)));
3383        assert_eq!(memory.visible_span(&spans, 1), None, "scrolled away");
3384        assert_eq!(
3385            memory
3386                .viewport(Rectangle::new(
3387                    Point::new(10.0, 0.0),
3388                    Size::new(300.0, 36.0)
3389                ))
3390                .x,
3391            110.0
3392        );
3393
3394        assert_eq!(memory.scroll_span(&spans, 0), None);
3395        memory.follow((Some(0), 7), (600.0, 150.0), None);
3396        assert_eq!(memory.offset, 450.0, "a pinned tab is already in view");
3397        memory.follow((Some(1), 7), (600.0, 150.0), memory.scroll_span(&spans, 1));
3398        assert_eq!(memory.offset, 0.0);
3399        assert_eq!(memory.visible_span(&spans, 1), Some((100.0, 200.0)));
3400    }
3401
3402    #[test]
3403    fn pointers_find_pinned_tabs_in_place_and_others_scrolled() {
3404        let (memory, _) = split();
3405        assert_eq!(memory.locate(-1.0), None);
3406        assert_eq!(memory.locate(50.0), Some(50.0));
3407        assert_eq!(memory.locate(105.0), Some(555.0));
3408        assert_eq!(memory.locate(250.0), None, "past the scrolling tabs");
3409        assert_eq!(memory.unscroll(50.0), 50.0);
3410        assert_eq!(memory.unscroll(400.0), 850.0);
3411
3412        let fallback = Memory {
3413            offset: 30.0,
3414            viewport_width: 200.0,
3415            ..Memory::default()
3416        };
3417        assert_eq!(fallback.locate(50.0), Some(80.0), "everything scrolls");
3418        assert_eq!(
3419            fallback.pinned_frame(Rectangle::default()).1,
3420            Vector::new(30.0, 0.0)
3421        );
3422    }
3423
3424    #[test]
3425    fn scrolled_tabs_keep_clear_of_the_pinned_divider() {
3426        let (memory, spans) = split();
3427        assert_eq!(memory.scroll_start(), 100.0 + PINNED_GAP);
3428        let clip = memory.scroll_clip(Rectangle::new(Point::ORIGIN, Size::new(400.0, 36.0)));
3429        assert_eq!(
3430            (clip.x, clip.width),
3431            (100.0 + PINNED_GAP, 150.0 - PINNED_GAP)
3432        );
3433
3434        let still = Memory {
3435            offset: 0.0,
3436            ..memory
3437        };
3438        assert_eq!(still.scroll_start(), 100.0, "nothing is cut off yet");
3439
3440        // Tab 6 starts 3 pixels after the pinned divider.
3441        let close = Memory {
3442            offset: 497.0,
3443            ..memory
3444        };
3445        assert!(
3446            !close
3447                .dividers(&spans, Some(0))
3448                .iter()
3449                .any(|x| *x > 100.0 && *x < 100.0 + PINNED_GAP),
3450            "no second line right beside the pinned one"
3451        );
3452    }
3453
3454    #[test]
3455    fn dividers_mark_the_end_of_the_pinned_tabs() {
3456        let (memory, spans) = split();
3457        assert_eq!(memory.dividers(&spans, Some(6)), [100.0]);
3458        assert_eq!(memory.dividers(&spans, Some(0)), [150.0]);
3459        assert_eq!(
3460            memory.dividers(&spans, Some(1)),
3461            [100.0, 150.0],
3462            "the active tab is scrolled away from the edge"
3463        );
3464        let still = Memory {
3465            offset: 0.0,
3466            ..memory
3467        };
3468        assert_eq!(still.dividers(&spans, Some(1)), Vec::<f32>::new());
3469    }
3470
3471    #[test]
3472    fn the_drop_indicator_stays_in_the_dragged_tab_region() {
3473        let (memory, spans) = split();
3474        let half = INDICATOR_WIDTH / 2.0;
3475        assert_eq!(memory.indicator_x(&spans, 0, 0), Some(0.0));
3476        assert_eq!(
3477            memory.indicator_x(&spans, 0, 1),
3478            Some(100.0 - INDICATOR_WIDTH),
3479            "the end of the pinned tabs"
3480        );
3481        assert_eq!(
3482            memory.indicator_x(&spans, 6, 1),
3483            Some(100.0),
3484            "the first unpinned gap is scrolled away, so it sits at the edge"
3485        );
3486        assert_eq!(memory.indicator_x(&spans, 6, 6), Some(150.0 - half));
3487        assert_eq!(
3488            memory.indicator_x(&spans, 6, 7),
3489            Some(250.0 - INDICATOR_WIDTH)
3490        );
3491        assert_eq!(memory.indicator_x(&[], 0, 0), None);
3492    }
3493}