1use std::{cell::RefCell, collections::HashMap, rc::Rc};
12
13use arc_motion::{
14 EdgeFadeMask, EdgeFadeSide, LayoutSnapshot, layout::layout_scope_key, sample_shared_layout,
15};
16use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography};
17use gpui_kit::{
18 App, BorderStyle, Bounds, ElementId, IntoElement, KeyDownEvent, ParentElement, Pixels,
19 RenderOnce, ScrollEvent, SharedString, Styled, Window,
20 base::{Button as BaseButton, StyledExt as _},
21 bounds, canvas, div,
22 prelude::*,
23 px, quad,
24};
25
26type SegmentHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
27
28#[derive(Clone)]
30pub struct Segment {
31 pub value: SharedString,
32 pub label: SharedString,
33 pub accessory: Option<SharedString>,
34}
35
36impl Segment {
37 pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
38 Self {
39 value: value.into(),
40 label: label.into(),
41 accessory: None,
42 }
43 }
44
45 pub fn accessory(mut self, accessory: impl Into<SharedString>) -> Self {
46 self.accessory = Some(accessory.into());
47 self
48 }
49}
50
51#[derive(Clone)]
52struct SegmentedInternal {
53 uncontrolled_value: SharedString,
54 scroll_offset: f32,
55 content_width: Rc<RefCell<f32>>,
56 viewport_width: Rc<RefCell<f32>>,
57 item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
58}
59
60#[derive(IntoElement)]
62pub struct SegmentedControl {
63 id: ElementId,
64 options: Vec<Segment>,
65 value: Option<SharedString>,
66 default_value: Option<SharedString>,
67 label: Option<SharedString>,
68 on_value_change: Option<SegmentHandler>,
69 on_option_intent: Option<SegmentHandler>,
70}
71
72impl SegmentedControl {
73 pub fn new(id: impl Into<ElementId>) -> Self {
74 Self {
75 id: id.into(),
76 options: Vec::new(),
77 value: None,
78 default_value: None,
79 label: None,
80 on_value_change: None,
81 on_option_intent: None,
82 }
83 }
84
85 pub fn option(mut self, segment: Segment) -> Self {
86 self.options.push(segment);
87 self
88 }
89
90 pub fn options(mut self, segments: impl IntoIterator<Item = Segment>) -> Self {
91 self.options.extend(segments);
92 self
93 }
94
95 pub fn value(mut self, value: impl Into<SharedString>) -> Self {
96 self.value = Some(value.into());
97 self
98 }
99
100 pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
101 self.default_value = Some(value.into());
102 self
103 }
104
105 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
106 self.label = Some(label.into());
107 self
108 }
109
110 pub fn on_value_change(
111 mut self,
112 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
113 ) -> Self {
114 self.on_value_change = Some(Rc::new(handler));
115 self
116 }
117
118 pub fn on_option_intent(
119 mut self,
120 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
121 ) -> Self {
122 self.on_option_intent = Some(Rc::new(handler));
123 self
124 }
125}
126
127impl RenderOnce for SegmentedControl {
128 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
129 let theme = cx.arc_theme().clone();
130 let colors = theme.colors;
131 let motion = theme.motion;
132
133 let fallback = self
134 .default_value
135 .clone()
136 .or_else(|| self.options.first().map(|s| s.value.clone()))
137 .unwrap_or_default();
138
139 let is_controlled = self.value.is_some();
140 let state_id =
141 ElementId::NamedChild(self.id.clone().into(), "__arc-segmented-state".into());
142 let internal = window.use_keyed_state(state_id, cx, |_, _| SegmentedInternal {
143 uncontrolled_value: fallback,
144 scroll_offset: 0.0,
145 content_width: Rc::new(RefCell::new(0.0)),
146 viewport_width: Rc::new(RefCell::new(0.0)),
147 item_bounds: Rc::new(RefCell::new(HashMap::new())),
148 });
149
150 let snap = internal.read(cx).clone();
151 let active = self
152 .value
153 .clone()
154 .unwrap_or_else(|| snap.uncontrolled_value.clone());
155
156 let scope = layout_scope_key(&self.id);
157 let bounds_for_pill = snap.item_bounds.clone();
158 let active_for_pill = active.clone();
159 let morph_spec = motion.spring.morph;
160 let pill_bg = colors.surface;
161 let pill_border = colors.border;
162 let pill_radius = px(14.0);
163
164 let pill_canvas = canvas(
165 |_, _, _| {},
166 move |track_rect, _, window, cx| {
167 let Some(btn_rect) = bounds_for_pill.borrow().get(&active_for_pill).copied() else {
168 window.request_animation_frame();
169 return;
170 };
171 let local_rect = bounds(btn_rect.origin - track_rect.origin, btn_rect.size);
172 let target = LayoutSnapshot::uniform_radius(local_rect, pill_radius);
173 let flip = sample_shared_layout(
174 scope.clone(),
175 "selection",
176 target,
177 Some(morph_spec),
178 window,
179 cx,
180 );
181 let paint_rect = bounds(track_rect.origin + flip.bounds.origin, flip.bounds.size);
182 window.paint_quad(quad(
183 paint_rect,
184 flip.corner_radii,
185 pill_bg,
186 gpui_kit::Edges::all(px(1.0)),
187 pill_border,
188 BorderStyle::Solid,
189 ));
190 },
191 )
192 .absolute()
193 .inset_0();
194
195 let all_values: Vec<SharedString> = self.options.iter().map(|s| s.value.clone()).collect();
196 let scroll_x = snap.scroll_offset;
197
198 let mut track = div()
199 .relative()
200 .flex()
201 .flex_row()
202 .items_center()
203 .gap(px(2.0))
204 .ml(px(-scroll_x))
205 .child(pill_canvas);
206
207 for segment in self.options {
208 let seg_val = segment.value.clone();
209 let selected = active == seg_val;
210
211 let bounds_measure = snap.item_bounds.clone();
212 let val_measure = seg_val.clone();
213 let probe = canvas(
214 move |rect, _, _| {
215 bounds_measure
216 .borrow_mut()
217 .insert(val_measure.clone(), rect);
218 },
219 |_, _, _, _| {},
220 )
221 .absolute()
222 .inset_0();
223
224 let int_click = internal.clone();
225 let int_key = internal.clone();
226 let on_change = self.on_value_change.clone();
227 let on_change_key = self.on_value_change.clone();
228 let on_intent = self.on_option_intent.clone();
229 let val_click = seg_val.clone();
230 let val_key = seg_val.clone();
231 let val_intent = seg_val.clone();
232 let vals_key = all_values.clone();
233 let hover_fg = colors.foreground;
234
235 let btn = BaseButton::new(ElementId::NamedChild(
236 self.id.clone().into(),
237 SharedString::from(format!("seg-{seg_val}")),
238 ))
239 .accessibility_label(segment.label.clone())
240 .on_click(move |_, window, cx| {
241 if !is_controlled {
242 int_click.update(cx, |s, _| s.uncontrolled_value = val_click.clone());
243 }
244 if let Some(cb) = &on_change {
245 cb(&val_click, window, cx);
246 }
247 window.refresh();
248 })
249 .relative()
250 .flex_none()
251 .min_h(ControlHeights::SM)
252 .px(px(12.0))
253 .rounded(pill_radius)
254 .flex()
255 .items_center()
256 .justify_center()
257 .gap(px(6.0))
258 .text_size(Typography::TEXT_SM)
259 .font_medium()
260 .text_color(if selected {
261 colors.foreground
262 } else {
263 colors.text_muted
264 })
265 .cursor_pointer()
266 .when(!selected, |this| {
267 this.hover(move |s| s.text_color(hover_fg))
268 })
269 .when_some(on_intent, |this, intent_cb| {
270 this.on_hover(move |hovered, window, cx| {
271 if *hovered {
272 intent_cb(&val_intent, window, cx);
273 }
274 })
275 })
276 .on_key_down(move |event: &KeyDownEvent, window, cx| {
277 if vals_key.len() < 2 {
278 return;
279 }
280 let cur = vals_key.iter().position(|v| v == &val_key).unwrap_or(0);
281 let next_idx = match event.keystroke.key.as_str() {
282 "right" | "down" => Some((cur + 1) % vals_key.len()),
283 "left" | "up" => Some((cur + vals_key.len() - 1) % vals_key.len()),
284 "home" => Some(0),
285 "end" => Some(vals_key.len() - 1),
286 _ => None,
287 };
288 if let Some(ni) = next_idx {
289 let next_val = vals_key[ni].clone();
290 if !is_controlled {
291 int_key.update(cx, |s, _| s.uncontrolled_value = next_val.clone());
292 }
293 if let Some(cb) = &on_change_key {
294 cb(&next_val, window, cx);
295 }
296 window.refresh();
297 }
298 })
299 .child(probe)
300 .child(segment.label)
301 .when_some(segment.accessory, |this, acc| {
302 this.child(
303 div()
304 .px(px(6.0))
305 .py(px(1.0))
306 .rounded(Radii::PILL)
307 .bg(colors.surface_muted)
308 .text_size(Typography::TEXT_XS)
309 .text_color(colors.text_muted)
310 .child(acc),
311 )
312 });
313
314 track = track.child(btn);
315 }
316
317 let cw_ref = snap.content_width.clone();
318 let vw_ref = snap.viewport_width.clone();
319 let bounds_for_fade = snap.item_bounds.clone();
320 let fade_bg = colors.surface_muted;
321
322 let edge_fade_overlay = canvas(
323 move |vp_rect, _, _| {
324 *vw_ref.borrow_mut() = f32::from(vp_rect.size.width);
325 let map = bounds_for_fade.borrow();
326 if let (Some(min_x), Some(max_x)) = (
327 map.values().map(|r| f32::from(r.origin.x)).reduce(f32::min),
328 map.values()
329 .map(|r| f32::from(r.origin.x + r.size.width))
330 .reduce(f32::max),
331 ) {
332 *cw_ref.borrow_mut() = (max_x - min_x).max(0.0);
333 }
334 },
335 move |vp_rect, _, window, _| {
336 let cw = *snap.content_width.borrow();
337 let vw = f32::from(vp_rect.size.width);
338 let max_scroll = (cw - vw).max(0.0);
339 let fade_start = scroll_x > 1.0;
340 let fade_end = max_scroll - scroll_x > 1.0;
341 if fade_start {
342 EdgeFadeMask::new(EdgeFadeSide::Left, px(20.0), fade_bg).paint(vp_rect, window);
343 }
344 if fade_end {
345 EdgeFadeMask::new(EdgeFadeSide::Right, px(20.0), fade_bg)
346 .paint(vp_rect, window);
347 }
348 },
349 )
350 .absolute()
351 .inset_0();
352
353 let int_wheel = internal.clone();
354 let frame = div()
355 .relative()
356 .overflow_hidden()
357 .p(px(3.0))
358 .rounded(Radii::CONTROL)
359 .border_1()
360 .border_color(colors.border)
361 .bg(colors.surface_muted)
362 .on_scroll(move |ev: &ScrollEvent, window, cx| {
363 let delta = ev.delta.pixel_delta(px(20.0));
364 let dx = if f32::from(delta.x).abs() > 0.1 {
365 -f32::from(delta.x)
366 } else {
367 -f32::from(delta.y)
368 };
369 int_wheel.update(cx, |s, _| {
370 let cw = *s.content_width.borrow();
371 let vw = *s.viewport_width.borrow();
372 let max_scroll = (cw - vw).max(0.0);
373 if max_scroll > 1.0 {
374 s.scroll_offset = (s.scroll_offset + dx).clamp(0.0, max_scroll);
375 }
376 });
377 window.refresh();
378 })
379 .child(track)
380 .child(edge_fade_overlay);
381
382 div()
383 .id(self.id)
384 .flex()
385 .flex_col()
386 .items_start()
387 .gap(Spacing::S2)
388 .when_some(self.label, |this, lbl| {
389 this.child(
390 div()
391 .text_size(Typography::TEXT_XS)
392 .text_color(colors.text_muted)
393 .child(lbl),
394 )
395 })
396 .child(frame)
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
403 use gpui_kit::{
404 Context, MouseButton, Render, Role, TestAppContext, div,
405 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
406 };
407
408 use super::*;
409
410 struct SegmentedHost {
411 selected: SharedString,
412 }
413
414 impl Render for SegmentedHost {
415 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
416 div().w(px(420.0)).p(Spacing::S4).child(
417 SegmentedControl::new("view-mode")
418 .label("View")
419 .value(self.selected.clone())
420 .options([
421 Segment::new("day", "Day"),
422 Segment::new("week", "Week").accessory("7"),
423 Segment::new("month", "Month"),
424 ])
425 .on_value_change(cx.listener(|this, v: &SharedString, _, cx| {
426 this.selected = v.clone();
427 cx.notify();
428 })),
429 )
430 }
431 }
432
433 #[gpui_kit::test]
434 fn segmented_control_switches_selection_on_click(cx: &mut TestAppContext) {
435 cx.update(|cx| {
436 gpui_kit::init(cx);
437 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
438 });
439 let (view, cx) = cx.add_window_view(|_, _| SegmentedHost {
440 selected: "day".into(),
441 });
442
443 cx.update(|window, cx| {
444 window.render_frame(cx);
445 let week = window.find_by_label("Week");
446 assert_eq!(week.role(), Some(Role::Button));
447 let pos = week.bounds().center();
448 window.pointer_down(pos, MouseButton::Left, cx);
449 window.pointer_up(pos, MouseButton::Left, cx);
450 });
451
452 assert_eq!(view.read_with(cx, |v, _| v.selected.clone()), "week");
453 }
454}