Tabs
A segmented list for switching between panels.
Web replica of the native GPUI output
Make changes to your account here.
use gpui::{div, prelude::*, Context, Window};
use crate::ui::tabs::Tabs;
pub struct AccountView {
tab: usize,
}
impl Render for AccountView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap_4()
.child(
Tabs::new("account-tabs", self.tab)
.tab("Account")
.tab("Password")
.tab("Billing")
.on_select(cx.listener(|this, ix: &usize, _, cx| {
this.tab = *ix;
cx.notify();
})),
)
.child(match self.tab {
0 => "Make changes to your account here.",
1 => "Change your password here.",
_ => "Manage your plan and invoices.",
})
}
}Installation
Add the component
$ cargo hyuskui add tabsOr copy it by hand: paste the source below into
src/ui/tabs.rsand register it insrc/ui/mod.rs.Make sure the theme is installed
Every component reads colors from
crate::theme. If you have not runcargo hyuskui init, follow the installation guide first.
Usage
use crate::ui::tabs::*;Source
This file is yours after install. Change the styles, add variants, or delete what you do not need.
use std::{rc::Rc, time::Duration};
use gpui::{
Animation, AnimationExt, App, Bounds, ElementId, FontWeight, Pixels, SharedString, Window, div,
ease_out_quint, prelude::*, px,
};
use crate::theme::ActiveTheme;
type SelectHandler = Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>;
const SLIDE: Duration = Duration::from_millis(200);
const INSET: Pixels = px(3.0);
/// A segmented tab list. The parent view owns `selected` and renders the active panel.
/// The active pill slides between tabs when the selection changes.
#[derive(IntoElement)]
pub struct Tabs {
id: ElementId,
labels: Vec<SharedString>,
selected: usize,
on_select: Option<SelectHandler>,
}
/// Remembered across frames: where each tab was laid out, and which tab the pill is leaving.
struct TabsState {
tab_bounds: Vec<Bounds<Pixels>>,
current: usize,
previous: usize,
/// Bumped on every selection change so the slide animation restarts.
generation: usize,
}
impl Tabs {
pub fn new(id: impl Into<ElementId>, selected: usize) -> Self {
Self {
id: id.into(),
labels: Vec::new(),
selected,
on_select: None,
}
}
pub fn tab(mut self, label: impl Into<SharedString>) -> Self {
self.labels.push(label.into());
self
}
pub fn on_select(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self {
self.on_select = Some(Rc::new(handler));
self
}
}
impl RenderOnce for Tabs {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let selected = self.selected;
let state = window.use_keyed_state(self.id.clone(), cx, |_, _| TabsState {
tab_bounds: Vec::new(),
current: selected,
previous: selected,
generation: 0,
});
state.update(cx, |state, _| {
if state.current != selected {
state.previous = state.current;
state.current = selected;
state.generation += 1;
}
});
let (tab_bounds, previous, generation) = {
let state = state.read(cx);
(state.tab_bounds.clone(), state.previous, state.generation)
};
let theme = cx.theme();
let (pill_bg, active_fg, idle_fg) =
(theme.background, theme.foreground, theme.muted_foreground);
// Tab positions relative to the first tab; the row starts right after the inset.
let slot = |ix: usize| {
let origin = tab_bounds.first()?.origin.x;
tab_bounds.get(ix).map(|b| (b.origin.x - origin, b.size.width))
};
let pill = slot(selected).map(|to| {
let from = slot(previous).unwrap_or(to);
div()
.absolute()
.top(INSET)
.bottom(INSET)
.rounded(px(6.0))
.bg(pill_bg)
.shadow_sm()
.with_animation(
("tab-pill", generation),
Animation::new(SLIDE).with_easing(ease_out_quint()),
move |pill, t| {
let left = from.0 + (to.0 - from.0) * t;
let width = from.1 + (to.1 - from.1) * t;
pill.left(INSET + left).w(width)
},
)
});
// Until the first layout is measured there is no pill, so paint the active tab directly.
let measured = pill.is_some();
let row = div()
.flex()
.items_center()
.h_full()
.gap(px(2.0))
.on_children_prepainted({
let state = state.clone();
move |bounds, _, cx| {
state.update(cx, |state, cx| {
if state.tab_bounds != bounds {
state.tab_bounds = bounds;
cx.notify();
}
});
}
})
.children(self.labels.into_iter().enumerate().map(|(ix, label)| {
let active = ix == selected;
let handler = self.on_select.clone();
div()
.id(ix)
.flex()
.items_center()
.h_full()
.px(px(12.0))
.rounded(px(6.0))
.text_sm()
.font_weight(FontWeight::MEDIUM)
.cursor_pointer()
.text_color(if active { active_fg } else { idle_fg })
.when(active && !measured, |this| this.bg(pill_bg).shadow_sm())
.when(!active, |this| this.hover(move |style| style.text_color(active_fg)))
.when_some(handler, |this, handler| {
this.on_click(move |_, window, cx| handler(&ix, window, cx))
})
.child(label)
}));
div()
.id(self.id)
.relative()
.flex()
.items_center()
.h(px(36.0))
.p(INSET)
.rounded(theme.radius)
.bg(theme.muted)
.children(pill)
.child(row)
}
}