use super::{form::inset_outline, overlay::rem};
use crate::{
icons::{Icon, IconSize},
motion::{self, Curve, Motion, Speed},
theme::color,
tokens::{ColorRole, SIZE_LG, SIZE_MD, TypeStyle},
typography::TypeStyled as _,
};
use gpui_kit::{
AbsoluteLength, AnyElement, App, CursorStyle, ElementId, Hsla, InteractiveElement, IntoElement,
ParentElement, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled, Window, div,
prelude::FluentBuilder as _, px,
};
use std::rc::Rc;
const FOCUS_RING: f32 = 2.;
pub const TAB_MOTION: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast01);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TabsVariant {
#[default]
Line,
Contained,
}
impl TabsVariant {
pub const ALL: [TabsVariant; 2] = [Self::Line, Self::Contained];
pub const fn name(self) -> &'static str {
match self {
Self::Line => "line",
Self::Contained => "contained",
}
}
pub const fn height(self) -> f32 {
match self {
Self::Line => SIZE_MD.px_value(),
Self::Contained => SIZE_LG.px_value(),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TabsActivation {
#[default]
Automatic,
Manual,
}
impl TabsActivation {
pub const ALL: [TabsActivation; 2] = [Self::Automatic, Self::Manual];
pub const fn name(self) -> &'static str {
match self {
Self::Automatic => "automatic",
Self::Manual => "manual",
}
}
}
pub fn automatic_target(key: &str, from: usize, disabled: &[bool]) -> Option<usize> {
let n = disabled.len();
let enabled = |i: &usize| !disabled[*i];
match key {
"home" => (0..n).find(enabled),
"end" => (0..n).rev().find(enabled),
"right" | "left" => {
let step = if key == "right" { 1 } else { n - 1 };
(1..n).map(|k| (from + k * step) % n).find(enabled)
}
_ => None,
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TabState {
pub selected: bool,
pub hovered: bool,
pub disabled: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TabLook {
pub background: Hsla,
pub text: Hsla,
pub indicator: Hsla,
pub divider: Hsla,
}
impl TabLook {
pub fn of(variant: TabsVariant, state: TabState) -> Self {
use ColorRole::*;
let clear = Hsla::transparent_black();
match variant {
TabsVariant::Line => {
let (text, indicator) = if state.disabled {
(color(TextDisabled), color(BorderSubtle01))
} else if state.selected {
(color(TextPrimary), color(BorderInteractive))
} else if state.hovered {
(color(TextPrimary), color(BorderStrong01))
} else {
(color(TextSecondary), color(BorderSubtle01))
};
Self {
background: clear,
text,
indicator,
divider: clear,
}
}
TabsVariant::Contained => {
let (background, text, indicator) = if state.disabled {
(color(ButtonDisabled), color(TextOnColorDisabled), clear)
} else if state.selected {
(color(Layer01), color(TextPrimary), color(BorderInteractive))
} else if state.hovered {
(color(LayerAccentHover01), color(TextPrimary), clear)
} else {
(color(LayerAccent01), color(TextSecondary), clear)
};
Self {
background,
text,
indicator,
divider: color(BorderStrong01),
}
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PanelLook {
pub padding: f32,
pub background: Hsla,
pub focus: Hsla,
pub focus_width: f32,
}
impl PanelLook {
pub fn of(variant: TabsVariant) -> Self {
Self {
padding: 16.,
background: match variant {
TabsVariant::Line => Hsla::transparent_black(),
TabsVariant::Contained => color(ColorRole::Layer01),
},
focus: color(ColorRole::Focus),
focus_width: 2.,
}
}
}
pub fn shows_panel(content_count: usize) -> bool {
content_count > 0
}
pub struct TabsTrigger {
value: SharedString,
label: SharedString,
disabled: bool,
icon: Option<Icon>,
}
impl TabsTrigger {
pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
value: value.into(),
label: label.into(),
disabled: false,
icon: None,
}
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
self.icon = Some(icon.into());
self
}
}
type ValueChange = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct Tabs {
id: ElementId,
variant: TabsVariant,
full_width: bool,
value: Option<SharedString>,
default_value: Option<SharedString>,
on_value_change: Option<ValueChange>,
triggers: Vec<TabsTrigger>,
contents: Vec<(SharedString, AnyElement)>,
label: SharedString,
activation: TabsActivation,
panel_gap: AbsoluteLength,
flush: bool,
}
impl Tabs {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
variant: TabsVariant::Line,
full_width: false,
value: None,
default_value: None,
on_value_change: None,
triggers: Vec::new(),
contents: Vec::new(),
label: SharedString::default(),
activation: TabsActivation::Automatic,
panel_gap: rem(0.).into(),
flush: false,
}
}
pub fn variant(mut self, variant: TabsVariant) -> Self {
self.variant = variant;
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = Some(value.into());
self
}
pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
self.default_value = Some(value.into());
self
}
pub fn on_value_change(
mut self,
f: impl Fn(SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(f));
self
}
pub fn trigger(mut self, trigger: TabsTrigger) -> Self {
self.triggers.push(trigger);
self
}
pub fn content(mut self, value: impl Into<SharedString>, content: impl IntoElement) -> Self {
self.contents
.push((value.into(), content.into_any_element()));
self
}
pub fn activation(mut self, activation: TabsActivation) -> Self {
self.activation = activation;
self
}
pub fn panel_gap(mut self, gap: impl Into<AbsoluteLength>) -> Self {
self.panel_gap = gap.into();
self
}
pub fn flush(mut self, flush: bool) -> Self {
self.flush = flush;
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
}
impl RenderOnce for Tabs {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let first = self.triggers.first().map(|t| t.value.clone());
let initial = self.default_value.clone().or(first).unwrap_or_default();
let internal = window.use_keyed_state((id.clone(), "value"), cx, |_, _| initial);
let selected = self
.value
.clone()
.unwrap_or_else(|| internal.read(cx).clone());
let variant = self.variant;
let height = variant.height();
let mut list = gpui_kit::base::Tabs::new((id.clone(), "list"))
.flex()
.flex_row()
.when(
self.full_width && variant == TabsVariant::Contained,
|this| this.w_full(),
);
let count = self.triggers.len();
let flush = self.flush;
let selected_index = self.triggers.iter().position(|t| t.value == selected);
let automatic = (self.activation == TabsActivation::Automatic).then(|| {
let values: Vec<SharedString> = self.triggers.iter().map(|t| t.value.clone()).collect();
let disabled: Vec<bool> = self.triggers.iter().map(|t| t.disabled).collect();
let internal = internal.clone();
let on_change = self.on_value_change.clone();
move |event: &gpui_kit::KeyDownEvent, window: &mut Window, cx: &mut App| {
if event.keystroke.modifiers.modified() {
return;
}
let Some(from) = selected_index else {
return;
};
let rtl = gpui_kit::base::LayoutDirection::global(cx).is_rtl();
let key = match (event.keystroke.key.as_str(), rtl) {
("left", true) => "right",
("right", true) => "left",
(key, _) => key,
};
let Some(to) = automatic_target(key, from, &disabled) else {
return;
};
if to == from {
return;
}
let value = values[to].clone();
internal.update(cx, |v, cx| {
*v = value.clone();
cx.notify();
});
if let Some(f) = &on_change {
f(value, window, cx);
}
}
});
for (index, trigger) in self.triggers.into_iter().enumerate() {
let tab_id = ElementId::NamedChild(
std::sync::Arc::new(id.clone()),
SharedString::from(format!("tab-{}", trigger.value)),
);
let hover = window.use_keyed_state((tab_id.clone(), "hover"), cx, |_, _| false);
let state = TabState {
selected: trigger.value == selected,
hovered: *hover.read(cx),
disabled: trigger.disabled,
};
let look = TabLook::of(variant, state);
let animate =
|channel: &'static str, target: Hsla, window: &mut Window, cx: &mut App| {
motion::animate_color((tab_id.clone(), channel), target, TAB_MOTION, window, cx)
};
let background = animate("bg", look.background, window, cx);
let text = animate("text", look.text, window, cx);
let indicator = animate("indicator", look.indicator, window, cx);
let value = trigger.value.clone();
let on_change = self.on_value_change.clone();
let internal = internal.clone();
let no_divider = state.selected || selected_index.is_some_and(|s| s + 1 == index);
let flush_first = flush && index == 0;
let tab = gpui_kit::base::Tab::new(tab_id.clone())
.selected(state.selected)
.disabled(trigger.disabled)
.set_position(index + 1, count)
.accessibility_label(trigger.label.clone())
.relative()
.h(rem(height))
.flex()
.flex_row()
.items_center()
.gap(rem(8.))
.px(rem(16. - FOCUS_RING))
.when(flush_first, |this| this.pl_0().ml(px(-FOCUS_RING)))
.border_2()
.border_color(Hsla::transparent_black())
.focus_visible(|s| s.border_color(color(ColorRole::Focus)))
.bg(background)
.text_color(text)
.whitespace_nowrap()
.map(|this| {
if state.selected {
this.type_style(TypeStyle::HeadingCompact01)
} else {
this.type_style(TypeStyle::BodyCompact01)
}
})
.cursor(if trigger.disabled {
CursorStyle::OperationNotAllowed
} else {
CursorStyle::PointingHand
})
.when(variant == TabsVariant::Line && index > 0, |this| {
this.ml(px(1.))
})
.when(
self.full_width && variant == TabsVariant::Contained,
|this| this.flex_1().min_w_0(),
)
.on_hover(move |hovered, _, cx| {
hover.update(cx, |h, cx| {
*h = *hovered;
cx.notify();
})
})
.on_click(move |_, window, cx| {
internal.update(cx, |v, cx| {
*v = value.clone();
cx.notify();
});
if let Some(f) = &on_change {
f(value.clone(), window, cx);
}
})
.child(div().flex_1().min_w_0().child(trigger.label.clone()))
.when_some(trigger.icon, |this, icon| {
this.child(icon.size(IconSize::S16).color(text))
})
.child(match variant {
TabsVariant::Line => div()
.absolute()
.left(px(if flush_first { 0. } else { -2. }))
.right(px(-2.))
.bottom(px(-2.))
.h(px(2.))
.bg(indicator),
TabsVariant::Contained => div()
.absolute()
.left(px(-2.))
.right(px(-2.))
.top(px(-2.))
.h(px(2.))
.bg(indicator),
})
.when(
variant == TabsVariant::Contained && index > 0 && !no_divider,
|this| {
this.child(
div()
.absolute()
.left(px(-3.))
.top(px(-2.))
.bottom(px(-2.))
.w(px(1.))
.bg(look.divider),
)
},
);
list = list.child(tab);
}
let show_panel = shows_panel(self.contents.len());
let content = self
.contents
.into_iter()
.find(|(value, _)| *value == selected)
.map(|(_, content)| content);
let panel = show_panel.then(|| {
let look = PanelLook::of(variant);
let focus = window
.use_keyed_state((id.clone(), "panel-focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
let focused = focus.is_focused(window);
div()
.id((id.clone(), "panel"))
.track_focus(&focus.tab_stop(true))
.relative()
.p(rem(if flush { 0. } else { look.padding }))
.type_style(TypeStyle::Body01)
.text_color(color(ColorRole::TextPrimary))
.bg(look.background)
.children(content)
.when(focused, |this| {
this.child(inset_outline(look.focus_width, look.focus))
})
});
div()
.flex()
.flex_col()
.gap(self.panel_gap)
.w_full()
.child(
div()
.when_some(automatic, |this, on_key| this.capture_key_down(on_key))
.child(list),
)
.children(panel)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn automatic_activation_moves_like_kit_focus() {
let disabled = [false, true, false, false];
assert_eq!(TabsActivation::default(), TabsActivation::Automatic);
assert_eq!(automatic_target("right", 0, &disabled), Some(2));
assert_eq!(automatic_target("right", 3, &disabled), Some(0));
assert_eq!(automatic_target("left", 0, &disabled), Some(3));
assert_eq!(automatic_target("left", 2, &disabled), Some(0));
assert_eq!(automatic_target("home", 3, &disabled), Some(0));
assert_eq!(automatic_target("end", 0, &disabled), Some(3));
assert_eq!(automatic_target("enter", 0, &disabled), None);
}
use crate::tokens::CarbonTheme;
fn hex(c: Hsla) -> String {
let c = c.to_rgb();
let b = |v: f32| (v * 255.).round() as u8;
format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
}
#[test]
fn line_tab_states_follow_bundle_css() {
crate::theme::tests_set(CarbonTheme::White);
let rest = TabLook::of(TabsVariant::Line, TabState::default());
assert_eq!(
(hex(rest.text), hex(rest.indicator)),
("#525252".into(), "#c6c6c6".into())
);
let hover = TabLook::of(
TabsVariant::Line,
TabState {
hovered: true,
..Default::default()
},
);
assert_eq!(
(hex(hover.text), hex(hover.indicator)),
("#161616".into(), "#8d8d8d".into())
);
let selected = TabLook::of(
TabsVariant::Line,
TabState {
selected: true,
..Default::default()
},
);
assert_eq!(hex(selected.indicator), "#0f62fe");
assert_eq!(TabsVariant::Line.height(), 40.);
assert_eq!(TabsVariant::Contained.height(), 48.);
}
#[test]
fn panel_follows_tab_content_css() {
crate::theme::tests_set(CarbonTheme::White);
let line = PanelLook::of(TabsVariant::Line);
assert_eq!((line.padding, line.background.a), (16., 0.));
assert_eq!((hex(line.focus), line.focus_width), ("#0f62fe".into(), 2.));
let contained = PanelLook::of(TabsVariant::Contained);
assert_eq!(hex(contained.background), "#f4f4f4");
assert!(!shows_panel(0));
assert!(shows_panel(1));
assert_eq!(Tabs::new("t").panel_gap, rem(0.).into());
assert!(!Tabs::new("t").flush);
assert!(Tabs::new("t").flush(true).flush);
assert_eq!(
Tabs::new("t")
.panel_gap(crate::tokens::SPACING_06)
.panel_gap,
rem(24.).into()
);
}
#[test]
fn contained_tab_states_follow_bundle_css() {
crate::theme::tests_set(CarbonTheme::White);
let rest = TabLook::of(TabsVariant::Contained, TabState::default());
assert_eq!(hex(rest.background), "#e0e0e0");
assert_eq!(hex(rest.divider), "#8d8d8d");
let selected = TabLook::of(
TabsVariant::Contained,
TabState {
selected: true,
..Default::default()
},
);
assert_eq!(
(hex(selected.background), hex(selected.indicator)),
("#f4f4f4".into(), "#0f62fe".into())
);
let disabled = TabLook::of(
TabsVariant::Contained,
TabState {
disabled: true,
..Default::default()
},
);
assert_eq!(
(hex(disabled.background), hex(disabled.text)),
("#c6c6c6".into(), "#8d8d8d".into())
);
}
}