bezel-ui 0.2.24

SwiftUI-flavored components for gpui — popovers, menus, buttons, toggles, and loaders
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Tabs — an ordered strip of open things, one of them in front.
//!
//! Not [`toggle_group`](crate::widgets::Controls::toggle_group), which picks a
//! value out of a fixed set, and not
//! [`tab_bar`](crate::widgets::Layout::tab_bar), which switches between
//! sections of one page. A tab here has identity: it arrives, it can be closed,
//! it can be dragged past its neighbour, and the strip outlives any particular
//! membership.
//!
//! [`Strip`] is the order and the activation, and imports no gpui — closing,
//! cycling and reordering are `Vec` arithmetic, testable without a window. The
//! paint is [`bar`], [`tab`] and [`close`], with [`drop_mark`] for a drop
//! target and [`Reorder`] for a tab carried along its strip.
//!
//! What a tab *holds* never enters this module. `Id` is the caller's key, and
//! the body it opens is the caller's match on that key.
//!
//! ```ignore
//! ui::tabs::bar("panel-tabs").children(self.strip.tabs().iter().map(|id| {
//!     let key = SharedString::from(format!("panel-{id}"));
//!     let state = match self.strip.active() == Some(id) {
//!         true => tabs::State::Focused,
//!         false => tabs::State::Resting,
//!     };
//!     tabs::tab(&theme, key.clone(), self.label(id), state)
//!         .on_click(cx.listener(move |view, _, _, cx| view.show(id, cx)))
//!         .child(
//!             tabs::close(&theme, key, tabs::Close::OnHover)
//!                 .on_click(cx.listener(move |view, _, _, cx| view.close(id, cx))),
//!         )
//! }))
//! ```

use std::cmp::Ordering;

use gpui::{
    AnyElement, BoxShadow, Div, ElementId, Hsla, SharedString, Stateful, StyleRefinement, div,
    point, prelude::*, px,
};

use icons::Icon;
use theme::{TextStyle, Theme, Typeset};

use crate::widgets::{self, Buttons as _};

mod bar;
mod reorder;

pub use bar::TabBar;

pub use reorder::{Bar, Move, OutsideDrop, Reorder};

/// An ordered set of tabs, one of them active.
///
/// `Id` is whatever names a tab to its owner — a counter, a path, a layout
/// member. Identity is `PartialEq`, so an id that compares equal to one already
/// in the strip is the same tab.
///
/// A strip with tabs in it always has one in front: [`Self::active`] is `None`
/// only while [`Self::is_empty`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Strip<Id> {
    order: Vec<Id>,
    active: Option<Id>,
}

impl<Id> Default for Strip<Id> {
    fn default() -> Self {
        Self {
            order: Vec::new(),
            active: None,
        }
    }
}

impl<Id: Clone + PartialEq> FromIterator<Id> for Strip<Id> {
    /// The first of the run is the one in front.
    fn from_iter<T: IntoIterator<Item = Id>>(iter: T) -> Self {
        let order: Vec<Id> = iter.into_iter().collect();
        let active = order.first().cloned();
        Self { order, active }
    }
}

impl<Id: Clone + PartialEq> Strip<Id> {
    pub fn new() -> Self {
        Self::default()
    }

    /// The tabs, left to right.
    pub fn tabs(&self) -> &[Id] {
        &self.order
    }

    pub fn active(&self) -> Option<&Id> {
        self.active.as_ref()
    }

    pub fn len(&self) -> usize {
        self.order.len()
    }

    pub fn is_empty(&self) -> bool {
        self.order.is_empty()
    }

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

    pub fn index_of(&self, id: &Id) -> Option<usize> {
        self.order.iter().position(|held| held == id)
    }

    /// Bring `id` to the front, adding it at the end of the strip if it is not
    /// already there. An id that *is* there keeps its place.
    pub fn open(&mut self, id: Id) {
        if !self.contains(&id) {
            self.order.push(id.clone());
        }
        self.active = Some(id);
    }

    /// Bring an existing tab to the front. `false`, and nothing moves, when it
    /// is not in the strip.
    pub fn activate(&mut self, id: &Id) -> bool {
        let held = self.contains(id);
        if held {
            self.active = Some(id.clone());
        }
        held
    }

    /// Take a tab out. `false` when it was not in the strip.
    ///
    /// Closing the tab in front hands the front to its right-hand neighbour,
    /// or to the new last tab when it had none. Closing any other tab leaves
    /// the front where it is.
    pub fn close(&mut self, id: &Id) -> bool {
        let Some(at) = self.index_of(id) else {
            return false;
        };
        self.order.remove(at);
        if self.active.as_ref() == Some(id) {
            self.active = self.order.get(at).or_else(|| self.order.last()).cloned();
        }
        true
    }

    /// Step the front `step` tabs along, wrapping at both ends. Whether the
    /// front changed: an empty strip, a lone tab and a whole lap do not move.
    pub fn cycle(&mut self, step: isize) -> bool {
        if self.order.is_empty() {
            return false;
        }
        let len = self.order.len() as isize;
        let at = self
            .active
            .as_ref()
            .and_then(|id| self.index_of(id))
            .unwrap_or(0) as isize;
        let next = self
            .order
            .get((at + step).rem_euclid(len) as usize)
            .cloned();
        if next == self.active {
            return false;
        }
        self.active = next;
        true
    }

    /// Move the tab at `from` so that it sits at `to`. Out-of-range ends are
    /// ignored rather than clamped: a drag that left the strip did not mean the
    /// last slot.
    ///
    /// The front is held by identity, so reordering never changes which tab is
    /// in front.
    pub fn reorder(&mut self, from: usize, to: usize) {
        if from == to || from >= self.order.len() || to >= self.order.len() {
            return;
        }
        let moved = self.order.remove(from);
        self.order.insert(to, moved);
    }

    /// Carry `id` `travel` pixels along the strip from its slot, positive to
    /// the right, passing every neighbour whose centre its own centre crosses.
    ///
    /// Returns the tabs passed, in the order passed, and the travel left over
    /// past the new slot. `width` measures a tab; a tab it cannot measure is
    /// not passed, and neither is anything beyond it.
    pub fn carry(
        &mut self,
        id: &Id,
        travel: f32,
        width: impl Fn(&Id) -> Option<f32>,
    ) -> (Vec<Id>, f32) {
        let mut passed = Vec::new();
        let (Some(mut at), Some(own)) = (self.index_of(id), width(id)) else {
            return (passed, travel);
        };
        let mut travel = travel;
        loop {
            let next = match travel.partial_cmp(&0.0) {
                Some(Ordering::Greater) => at + 1,
                Some(Ordering::Less) if at > 0 => at - 1,
                _ => break,
            };
            let Some(neighbour) = self.order.get(next).cloned() else {
                break;
            };
            let Some(theirs) = width(&neighbour) else {
                break;
            };
            if travel.abs() <= (own + theirs) / 2.0 + GAP {
                break;
            }
            travel -= travel.signum() * (theirs + GAP);
            self.order.swap(at, next);
            passed.push(neighbour);
            at = next;
        }
        (passed, travel)
    }
}

/// What a tab shows.
#[derive(Default)]
pub struct Label {
    text: SharedString,
    lead: Option<Lead>,
    badge: Option<SharedString>,
    mark: Option<Icon>,
}

/// What stands before a tab's text.
enum Lead {
    Icon(Icon),
    Drawn(AnyElement),
}

impl Label {
    pub fn new(text: impl Into<SharedString>) -> Self {
        Self {
            text: text.into(),
            ..Default::default()
        }
    }

    /// A glyph before the text — what kind of thing the tab is on.
    pub fn with_icon(mut self, icon: impl Into<Icon>) -> Self {
        self.lead = Some(Lead::Icon(icon.into()));
        self
    }

    /// A drawn element before the text, in place of [`Self::with_icon`]'s
    /// glyph: an animated mark, a status. Centred in the icon's box, and free
    /// to paint past it.
    pub fn with_lead(mut self, lead: impl IntoElement) -> Self {
        self.lead = Some(Lead::Drawn(lead.into_any_element()));
        self
    }

    /// A quiet trailing note: a line number, a reference, a count. It does not
    /// truncate, so keep it to a few characters.
    pub fn with_badge(mut self, badge: impl Into<SharedString>) -> Self {
        self.badge = Some(badge.into());
        self
    }

    /// A mark beside the label — unsaved work, a running job, something
    /// unread.
    ///
    /// Painted at [`MARK_SIZE`] in the tab's own tone, outside the truncating
    /// label so a long name cannot hide it. Lucide's round glyphs are outlines;
    /// [`Icon::solid`] fills one.
    pub fn mark(mut self, mark: impl Into<Icon>) -> Self {
        self.mark = Some(mark.into());
        self
    }
}

/// How a tab reads.
///
/// `Front` and `Focused` are separate because a window can hold several strips:
/// a background pane's own front tab still has to say what is under it, while
/// only one tab in the window has the keyboard.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
    /// Behind another tab of its strip.
    Resting,
    /// In front of its strip, in a pane without the keyboard.
    Front,
    /// The tab holding the keyboard. One per window.
    Focused,
}

impl State {
    /// The label's ink.
    pub fn tint(self, theme: &Theme) -> Hsla {
        match self {
            Self::Resting => theme.text_muted,
            Self::Front | Self::Focused => theme.text,
        }
    }
}

/// What a reorderable strip's tabs stand on — see [`Bar::on_track`]. A track
/// and its tabs are capsules, a [`Track::Flat`]'s rounded as a control is; the
/// tabs share its width equally down to
/// [`TRACK_MIN_WIDTH`], their labels centred, and a line parts two resting
/// neighbours.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Track {
    /// The segmented control's track, its border drawn.
    Bordered,
    /// The same wash with no border.
    Bare,
    /// No wash and no border.
    Flat,
}

/// When a tab's `×` is on show.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Close {
    Always,
    OnHover,
}

/// The edge of a tab a drop lands on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Side {
    Leading,
    Trailing,
}

impl Side {
    /// Where a tab moved from `from` to `to` lands on the tab whose place it
    /// takes: its trailing edge moving right, its leading edge moving left.
    /// `None` when it stays put.
    pub fn of(from: usize, to: usize) -> Option<Self> {
        match from.cmp(&to) {
            Ordering::Less => Some(Self::Trailing),
            Ordering::Greater => Some(Self::Leading),
            Ordering::Equal => None,
        }
    }
}

/// A [`tab`]'s drop mark, for its `drag_over` style: a 1px accent line on
/// `side`, in the gap beside the tab. A shadow, so the tab's layout does not
/// move.
pub fn drop_mark(style: StyleRefinement, side: Side, theme: &Theme) -> StyleRefinement {
    let x = match side {
        Side::Leading => px(-1.0),
        Side::Trailing => px(1.0),
    };
    style.shadow(vec![BoxShadow {
        color: theme.accent.opacity(0.6),
        offset: point(x, px(0.0)),
        blur_radius: px(0.0),
        spread_radius: px(0.0),
        inset: false,
    }])
}

/// How wide one tab grows before its label truncates.
pub const MAX_WIDTH: f32 = 180.0;

/// The narrowest a tab on a [`Track`] gets before its strip scrolls.
pub const TRACK_MIN_WIDTH: f32 = 120.0;

/// How tall a [`Track`] stands. Its tabs fill it inside its border and
/// [`TRACK_PAD`].
pub const TRACK_HEIGHT: f32 = 30.0;

/// The padding between a [`Track`]'s border and its tabs.
const TRACK_PAD: f32 = 1.0;

/// The box [`Label::mark`] paints in. Lucide's `circle-small` inks 14 of its 24
/// units, which puts a solid one at 6px across.
pub const MARK_SIZE: f32 = 10.0;

/// Gap between tabs.
const GAP: f32 = 2.0;
/// Inset at a tab's ends, and the gap between what it holds.
pub const TAB_PAD: f32 = 8.0;
/// The box a tab's icon, or what stands in its place, is laid in.
const ICON_SIZE: f32 = 14.0;

/// The strip. Tabs go in it; a `+`, a `···` and anything else on the row are
/// the caller's, outside this.
///
/// It scrolls sideways once the tabs no longer fit, by wheel and trackpad; it
/// draws no scrollbar. Without [`TabBar::track_scroll`] it keeps its offset
/// across renders under `id`.
/// `min_w_0` is what allows
/// that — a flex child's `min-width: auto` refuses to shrink below its content,
/// so without it the strip grows past its row instead of scrolling.
pub fn bar(id: impl Into<ElementId>) -> TabBar {
    TabBar::new(id.into())
}

/// One tab, up to the `×`: pass the same `key` to [`close`] and chain the
/// result on as a child.
///
/// `key` names both the element and the hover group [`Close::OnHover`] reads,
/// so the two are derived from one string rather than written twice.
///
/// Every tab but a [`State::Focused`] one takes its own `hover`, and gpui panics
/// on a second one: reach for [`Close::OnHover`]'s group, or a `group_hover` of
/// your own, rather than chaining `.hover(..)` onto what this returns.
pub fn tab(
    theme: &Theme,
    key: impl Into<SharedString>,
    label: Label,
    state: State,
) -> Stateful<Div> {
    let key = key.into();
    let group = group_of(&key);
    let tint = state.tint(theme);
    let wash = theme.element_hover;
    chip(theme, state)
        .id(ElementId::from(SharedString::from(format!("tab-{key}"))))
        .group(group)
        // Sized to its label, not to the bar: a tab stretched across the strip
        // reads as a field rather than a label.
        .flex_none()
        .max_w(px(MAX_WIDTH))
        .cursor_pointer()
        .when(state != State::Focused, |el| {
            el.hover(move |el| el.bg(wash))
        })
        .children(label.lead.map(|lead| {
            match lead {
                Lead::Icon(icon) => crate::icons::icon(icon)
                    .size(px(ICON_SIZE))
                    .flex_none()
                    .text_color(theme.text_muted)
                    .into_any_element(),
                Lead::Drawn(drawn) => div()
                    .size(px(ICON_SIZE))
                    .flex_none()
                    .flex()
                    .items_center()
                    .justify_center()
                    .child(drawn)
                    .into_any_element(),
            }
        }))
        .child(div().min_w_0().truncate().child(label.text))
        .children(label.mark.map(|mark| {
            crate::icons::icon(mark)
                .size(px(MARK_SIZE))
                .flex_none()
                .text_color(tint)
        }))
        .children(label.badge.map(|badge| {
            div()
                .flex_none()
                .text_style(TextStyle::Caption)
                .text_color(theme.text_faint)
                .child(badge)
        }))
}

/// A tab's frame without its label: its height, inset, corners and ring
/// slot, the label's ink for `state`, and the selected wash and ring while
/// [`State::Focused`]. What [`tab`] is drawn on, for a label that is not a
/// [`Label`].
pub fn chip(theme: &Theme, state: State) -> Div {
    div()
        .flex()
        .flex_row()
        .items_center()
        .gap(px(6.0))
        .h(px(Theme::BUTTON_HEIGHT))
        .px(px(TAB_PAD))
        .rounded(px(Theme::control_radius()))
        // The slot `focus::focusable` fills, kept whether or not it is filled:
        // gpui sizes border-box, so a border that arrived with the ring would
        // shift the label by a pixel.
        .border_1()
        .border_color(widgets::RING_SLOT)
        .text_style(TextStyle::Callout)
        .text_color(state.tint(theme))
        .when(state == State::Focused, |el| {
            el.bg(theme.card_selected_bg())
                .shadow(theme::glass_selected_shadows())
        })
}

/// A tab's `×`, for the `key` its [`tab`] was built with. The click is the
/// caller's. It stops mouse-down propagation, so a press on it neither clicks
/// nor picks up the tab under it.
pub fn close(theme: &Theme, key: impl Into<SharedString>, when: Close) -> Stateful<Div> {
    let key = key.into();
    let button = theme
        .ghost(ElementId::from(SharedString::from(format!(
            "tab-close-{key}"
        ))))
        .flex_none()
        .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
        .p(px(2.0))
        .child(
            crate::icons::icon(crate::icons::glyph::X)
                .size(px(11.0))
                .text_color(theme.text_muted),
        );
    match when {
        Close::Always => button,
        Close::OnHover => button
            .invisible()
            .group_hover(group_of(&key), |el| el.visible()),
    }
}

/// The hover group a tab and its `×` share.
fn group_of(key: &SharedString) -> SharedString {
    SharedString::from(format!("tab-{key}"))
}