use std::{cell::RefCell, collections::HashMap, rc::Rc};
use arc_motion::{
EdgeFadeMask, EdgeFadeSide, LayoutSnapshot, layout::layout_scope_key, sample_shared_layout,
};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography};
use gpui_kit::{
App, BorderStyle, Bounds, ElementId, IntoElement, KeyDownEvent, ParentElement, Pixels,
RenderOnce, ScrollEvent, SharedString, Styled, Window,
base::{Button as BaseButton, StyledExt as _},
bounds, canvas, div,
prelude::*,
px, quad,
};
type SegmentHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
#[derive(Clone)]
pub struct Segment {
pub value: SharedString,
pub label: SharedString,
pub accessory: Option<SharedString>,
}
impl Segment {
pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
value: value.into(),
label: label.into(),
accessory: None,
}
}
pub fn accessory(mut self, accessory: impl Into<SharedString>) -> Self {
self.accessory = Some(accessory.into());
self
}
}
#[derive(Clone)]
struct SegmentedInternal {
uncontrolled_value: SharedString,
scroll_offset: f32,
content_width: Rc<RefCell<f32>>,
viewport_width: Rc<RefCell<f32>>,
item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
}
#[derive(IntoElement)]
pub struct SegmentedControl {
id: ElementId,
options: Vec<Segment>,
value: Option<SharedString>,
default_value: Option<SharedString>,
label: Option<SharedString>,
on_value_change: Option<SegmentHandler>,
on_option_intent: Option<SegmentHandler>,
}
impl SegmentedControl {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
options: Vec::new(),
value: None,
default_value: None,
label: None,
on_value_change: None,
on_option_intent: None,
}
}
pub fn option(mut self, segment: Segment) -> Self {
self.options.push(segment);
self
}
pub fn options(mut self, segments: impl IntoIterator<Item = Segment>) -> Self {
self.options.extend(segments);
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 label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
pub fn on_option_intent(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_option_intent = Some(Rc::new(handler));
self
}
}
impl RenderOnce for SegmentedControl {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let fallback = self
.default_value
.clone()
.or_else(|| self.options.first().map(|s| s.value.clone()))
.unwrap_or_default();
let is_controlled = self.value.is_some();
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-segmented-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| SegmentedInternal {
uncontrolled_value: fallback,
scroll_offset: 0.0,
content_width: Rc::new(RefCell::new(0.0)),
viewport_width: Rc::new(RefCell::new(0.0)),
item_bounds: Rc::new(RefCell::new(HashMap::new())),
});
let snap = internal.read(cx).clone();
let active = self
.value
.clone()
.unwrap_or_else(|| snap.uncontrolled_value.clone());
let scope = layout_scope_key(&self.id);
let bounds_for_pill = snap.item_bounds.clone();
let active_for_pill = active.clone();
let morph_spec = motion.spring.morph;
let pill_bg = colors.surface;
let pill_border = colors.border;
let pill_radius = px(14.0);
let pill_canvas = canvas(
|_, _, _| {},
move |track_rect, _, window, cx| {
let Some(btn_rect) = bounds_for_pill.borrow().get(&active_for_pill).copied() else {
window.request_animation_frame();
return;
};
let local_rect = bounds(btn_rect.origin - track_rect.origin, btn_rect.size);
let target = LayoutSnapshot::uniform_radius(local_rect, pill_radius);
let flip = sample_shared_layout(
scope.clone(),
"selection",
target,
Some(morph_spec),
window,
cx,
);
let paint_rect = bounds(track_rect.origin + flip.bounds.origin, flip.bounds.size);
window.paint_quad(quad(
paint_rect,
flip.corner_radii,
pill_bg,
gpui_kit::Edges::all(px(1.0)),
pill_border,
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0();
let all_values: Vec<SharedString> = self.options.iter().map(|s| s.value.clone()).collect();
let scroll_x = snap.scroll_offset;
let mut track = div()
.relative()
.flex()
.flex_row()
.items_center()
.gap(px(2.0))
.ml(px(-scroll_x))
.child(pill_canvas);
for segment in self.options {
let seg_val = segment.value.clone();
let selected = active == seg_val;
let bounds_measure = snap.item_bounds.clone();
let val_measure = seg_val.clone();
let probe = canvas(
move |rect, _, _| {
bounds_measure
.borrow_mut()
.insert(val_measure.clone(), rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let int_click = internal.clone();
let int_key = internal.clone();
let on_change = self.on_value_change.clone();
let on_change_key = self.on_value_change.clone();
let on_intent = self.on_option_intent.clone();
let val_click = seg_val.clone();
let val_key = seg_val.clone();
let val_intent = seg_val.clone();
let vals_key = all_values.clone();
let hover_fg = colors.foreground;
let btn = BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("seg-{seg_val}")),
))
.accessibility_label(segment.label.clone())
.on_click(move |_, window, cx| {
if !is_controlled {
int_click.update(cx, |s, _| s.uncontrolled_value = val_click.clone());
}
if let Some(cb) = &on_change {
cb(&val_click, window, cx);
}
window.refresh();
})
.relative()
.flex_none()
.min_h(ControlHeights::SM)
.px(px(12.0))
.rounded(pill_radius)
.flex()
.items_center()
.justify_center()
.gap(px(6.0))
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(if selected {
colors.foreground
} else {
colors.text_muted
})
.cursor_pointer()
.when(!selected, |this| {
this.hover(move |s| s.text_color(hover_fg))
})
.when_some(on_intent, |this, intent_cb| {
this.on_hover(move |hovered, window, cx| {
if *hovered {
intent_cb(&val_intent, window, cx);
}
})
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if vals_key.len() < 2 {
return;
}
let cur = vals_key.iter().position(|v| v == &val_key).unwrap_or(0);
let next_idx = match event.keystroke.key.as_str() {
"right" | "down" => Some((cur + 1) % vals_key.len()),
"left" | "up" => Some((cur + vals_key.len() - 1) % vals_key.len()),
"home" => Some(0),
"end" => Some(vals_key.len() - 1),
_ => None,
};
if let Some(ni) = next_idx {
let next_val = vals_key[ni].clone();
if !is_controlled {
int_key.update(cx, |s, _| s.uncontrolled_value = next_val.clone());
}
if let Some(cb) = &on_change_key {
cb(&next_val, window, cx);
}
window.refresh();
}
})
.child(probe)
.child(segment.label)
.when_some(segment.accessory, |this, acc| {
this.child(
div()
.px(px(6.0))
.py(px(1.0))
.rounded(Radii::PILL)
.bg(colors.surface_muted)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(acc),
)
});
track = track.child(btn);
}
let cw_ref = snap.content_width.clone();
let vw_ref = snap.viewport_width.clone();
let bounds_for_fade = snap.item_bounds.clone();
let fade_bg = colors.surface_muted;
let edge_fade_overlay = canvas(
move |vp_rect, _, _| {
*vw_ref.borrow_mut() = f32::from(vp_rect.size.width);
let map = bounds_for_fade.borrow();
if let (Some(min_x), Some(max_x)) = (
map.values().map(|r| f32::from(r.origin.x)).reduce(f32::min),
map.values()
.map(|r| f32::from(r.origin.x + r.size.width))
.reduce(f32::max),
) {
*cw_ref.borrow_mut() = (max_x - min_x).max(0.0);
}
},
move |vp_rect, _, window, _| {
let cw = *snap.content_width.borrow();
let vw = f32::from(vp_rect.size.width);
let max_scroll = (cw - vw).max(0.0);
let fade_start = scroll_x > 1.0;
let fade_end = max_scroll - scroll_x > 1.0;
if fade_start {
EdgeFadeMask::new(EdgeFadeSide::Left, px(20.0), fade_bg).paint(vp_rect, window);
}
if fade_end {
EdgeFadeMask::new(EdgeFadeSide::Right, px(20.0), fade_bg)
.paint(vp_rect, window);
}
},
)
.absolute()
.inset_0();
let int_wheel = internal.clone();
let frame = div()
.relative()
.overflow_hidden()
.p(px(3.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.on_scroll(move |ev: &ScrollEvent, window, cx| {
let delta = ev.delta.pixel_delta(px(20.0));
let dx = if f32::from(delta.x).abs() > 0.1 {
-f32::from(delta.x)
} else {
-f32::from(delta.y)
};
int_wheel.update(cx, |s, _| {
let cw = *s.content_width.borrow();
let vw = *s.viewport_width.borrow();
let max_scroll = (cw - vw).max(0.0);
if max_scroll > 1.0 {
s.scroll_offset = (s.scroll_offset + dx).clamp(0.0, max_scroll);
}
});
window.refresh();
})
.child(track)
.child(edge_fade_overlay);
div()
.id(self.id)
.flex()
.flex_col()
.items_start()
.gap(Spacing::S2)
.when_some(self.label, |this, lbl| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(lbl),
)
})
.child(frame)
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct SegmentedHost {
selected: SharedString,
}
impl Render for SegmentedHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(420.0)).p(Spacing::S4).child(
SegmentedControl::new("view-mode")
.label("View")
.value(self.selected.clone())
.options([
Segment::new("day", "Day"),
Segment::new("week", "Week").accessory("7"),
Segment::new("month", "Month"),
])
.on_value_change(cx.listener(|this, v: &SharedString, _, cx| {
this.selected = v.clone();
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn segmented_control_switches_selection_on_click(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (view, cx) = cx.add_window_view(|_, _| SegmentedHost {
selected: "day".into(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let week = window.find_by_label("Week");
assert_eq!(week.role(), Some(Role::Button));
let pos = week.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
});
assert_eq!(view.read_with(cx, |v, _| v.selected.clone()), "week");
}
}