1use std::cell::{Cell, RefCell};
2use std::rc::Rc;
3
4use gpui::{
5 AccessibleAction, AnyElement, App, Div, ElementId, Entity, FocusHandle, Hsla,
6 InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Stateful,
7 StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
8};
9use gpui_base::{Switch as BaseSwitch, TestSupportExt};
10use gpui_material_foundation::{InteractionSource, ThemeScope, animate, current_material_theme};
11use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed, StateLayer};
12
13use crate::action::{Change, FeedbackState, feedback_target, ripple_ink, ripple_state};
14
15use super::{focus_style, row, selection_label, tone};
16
17#[derive(Clone, Copy, Debug, Default, PartialEq)]
19pub struct SwitchStateColors {
20 pub track: Option<Hsla>,
21 pub border: Option<Hsla>,
22 pub thumb: Option<Hsla>,
23 pub content: Option<Hsla>,
24}
25
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
28pub struct SwitchColors {
29 pub unchecked: SwitchStateColors,
30 pub checked: SwitchStateColors,
31 pub disabled_unchecked: SwitchStateColors,
32 pub disabled_checked: SwitchStateColors,
33}
34
35struct SwitchPalette {
36 track: Hsla,
37 border: Hsla,
38 thumb: Hsla,
39 content: Hsla,
40}
41
42impl SwitchStateColors {
43 fn resolve(self, defaults: SwitchPalette) -> SwitchPalette {
44 SwitchPalette {
45 track: self.track.unwrap_or(defaults.track),
46 border: self.border.unwrap_or(defaults.border),
47 thumb: self.thumb.unwrap_or(defaults.thumb),
48 content: self.content.unwrap_or(defaults.content),
49 }
50 }
51}
52
53impl SwitchColors {
54 fn resolve(
55 self,
56 checked: bool,
57 disabled: bool,
58 tint: f32,
59 window: &Window,
60 cx: &App,
61 ) -> SwitchPalette {
62 use ColorRole::*;
63 let color = |role| tone(role, window, cx);
64 if disabled {
65 let muted = |role, opacity| color(Surface).blend(color(role).opacity(opacity));
67 return if checked {
68 self.disabled_checked.resolve(SwitchPalette {
69 track: muted(OnSurface, 0.12),
70 border: gpui::transparent_black(),
71 thumb: color(Surface),
72 content: muted(OnSurface, 0.38),
73 })
74 } else {
75 self.disabled_unchecked.resolve(SwitchPalette {
76 track: muted(SurfaceContainerHighest, 0.12),
77 border: muted(OnSurface, 0.12),
78 thumb: muted(OnSurface, 0.38),
79 content: muted(SurfaceContainerHighest, 0.38),
80 })
81 };
82 }
83
84 let unchecked = self.unchecked.resolve(SwitchPalette {
85 track: color(SurfaceContainerHighest),
86 border: color(Outline),
87 thumb: color(Outline),
88 content: color(SurfaceContainerHighest),
89 });
90 let on = self.checked.resolve(SwitchPalette {
91 track: color(Primary),
92 border: unchecked.border.opacity(0.),
93 thumb: color(OnPrimary),
94 content: color(OnPrimaryContainer),
95 });
96 let mix = |off, on| match tint {
97 0. => off,
98 1. => on,
99 _ => crate::motion::mix(off, on, tint),
100 };
101 SwitchPalette {
102 track: mix(unchecked.track, on.track),
103 border: mix(unchecked.border, on.border),
104 thumb: mix(unchecked.thumb, on.thumb),
105 content: if checked {
106 on.content
107 } else {
108 unchecked.content
109 },
110 }
111 }
112}
113
114#[derive(IntoElement)]
116pub struct Switch {
117 id: ElementId,
118 label: SharedString,
119 show_label: bool,
120 label_content: Option<AnyElement>,
121 checked: bool,
122 disabled: bool,
123 checked_icon: Option<AnyElement>,
124 unchecked_icon: Option<AnyElement>,
125 thumb_content: Option<AnyElement>,
126 colors: SwitchColors,
127 focus: Option<FocusHandle>,
128 interaction_source: Option<Entity<InteractionSource>>,
129 on_change: Option<Change>,
130 decorative: bool,
131}
132
133impl Switch {
134 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, checked: bool) -> Self {
135 Self {
136 id: id.into(),
137 label: label.into(),
138 show_label: true,
139 label_content: None,
140 checked,
141 disabled: false,
142 checked_icon: None,
143 unchecked_icon: None,
144 thumb_content: None,
145 colors: SwitchColors::default(),
146 focus: None,
147 interaction_source: None,
148 on_change: None,
149 decorative: false,
150 }
151 }
152
153 #[cfg(feature = "surfaces")]
154 pub(crate) fn decorative(mut self, decorative: bool) -> Self {
155 self.decorative = decorative;
156 self
157 }
158
159 pub fn show_label(mut self, show: bool) -> Self {
162 self.show_label = show;
163 self
164 }
165
166 pub fn label_content(mut self, content: impl IntoElement) -> Self {
168 self.label_content = Some(content.into_any_element());
169 self
170 }
171
172 pub fn disabled(mut self, disabled: bool) -> Self {
173 self.disabled = disabled;
174 self
175 }
176
177 pub fn checked_icon(mut self, icon: impl IntoElement) -> Self {
178 self.checked_icon = Some(icon.into_any_element());
179 self
180 }
181
182 pub fn unchecked_icon(mut self, icon: impl IntoElement) -> Self {
183 self.unchecked_icon = Some(icon.into_any_element());
184 self
185 }
186
187 pub fn thumb_content(mut self, content: impl IntoElement) -> Self {
190 self.thumb_content = Some(content.into_any_element());
191 self
192 }
193
194 pub fn colors(mut self, colors: SwitchColors) -> Self {
195 self.colors = colors;
196 self
197 }
198
199 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
201 self.focus = Some(focus.clone());
202 self
203 }
204
205 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
207 self.interaction_source = Some(source.clone());
208 self
209 }
210
211 pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
212 self.on_change = Some(Rc::new(handler));
213 self
214 }
215
216 fn thumb_decoration(&mut self) -> Option<AnyElement> {
217 let icon = if self.checked {
218 self.checked_icon.take()
219 } else {
220 self.unchecked_icon.take()
221 };
222 self.thumb_content
223 .take()
224 .map(|content| {
225 div()
226 .id("switch-thumb-content")
227 .role(gpui::Role::Group)
228 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
229 .size(px(16.))
230 .overflow_hidden()
231 .flex()
232 .items_center()
233 .justify_center()
234 .child(content)
235 .into_any_element()
236 })
237 .or(icon)
238 }
239
240 fn thumb_geometry(
241 &self,
242 has_decoration: bool,
243 active: bool,
244 motion: MotionSpec,
245 window: &mut Window,
246 cx: &mut App,
247 ) -> (f32, Pixels) {
248 let normal_size = if self.checked || has_decoration {
249 24.
250 } else {
251 16.
252 };
253 let diameter = animate(
254 (self.id.clone(), "thumb-diameter"),
255 if active { 28. } else { normal_size },
256 if active { MotionSpec::Instant } else { motion },
257 window,
258 cx,
259 )
260 .clamp(16., 28.);
261 let offset = animate(
262 (self.id.clone(), "thumb-offset"),
263 match (active, self.checked) {
264 (true, false) => 2.,
265 (true, true) => 22.,
266 (false, true) => 24.,
267 (false, false) => (32. - normal_size) / 2.,
268 },
269 if active { MotionSpec::Instant } else { motion },
270 window,
271 cx,
272 );
273 (diameter, px(offset.clamp(2., 50. - diameter)))
275 }
276}
277
278#[allow(clippy::too_many_arguments)]
279fn render_state_layer(
280 diameter: f32,
281 checked: bool,
282 disabled: bool,
283 active: bool,
284 group: &SharedString,
285 ink: Rc<RefCell<FeedbackState>>,
286 direction: Direction,
287 window: &Window,
288 cx: &App,
289) -> Stateful<Div> {
290 use ColorRole::*;
291 let accent = tone(if checked { Primary } else { OnSurface }, window, cx);
292 div()
293 .id("switch-state-layer")
294 .absolute()
295 .size(px(40.))
296 .left(px((diameter - 40.) / 2.))
297 .top(px((diameter - 40.) / 2.))
298 .rounded_full()
299 .when(!disabled, |layer| {
300 let static_pressed = active && cx.reduce_motion();
301 layer
302 .when(static_pressed, |layer| {
303 layer.bg(accent.opacity(StateLayer::Pressed.opacity()))
304 })
305 .when(!static_pressed, |layer| {
306 layer.group_hover(group.clone(), move |style| {
307 style.bg(accent.opacity(StateLayer::Hover.opacity()))
308 })
309 })
310 .when(cx.reduce_motion(), |layer| {
311 layer.group_active(group.clone(), move |style| {
312 style.bg(accent.opacity(StateLayer::Pressed.opacity()))
313 })
314 })
315 })
316 .child(ripple_ink(
317 ink,
318 accent,
319 gpui_material_theme::CornerRole::Full.shape(),
320 direction,
321 ))
322}
323
324#[allow(clippy::too_many_arguments)]
325fn render_track(
326 id: &ElementId,
327 palette: SwitchPalette,
328 diameter: f32,
329 offset: Pixels,
330 direction: Direction,
331 state_layer: Stateful<Div>,
332 decoration: Option<AnyElement>,
333) -> impl IntoElement + use<> {
334 let handle = div()
335 .absolute()
336 .top_0()
337 .h_full()
338 .w(px(diameter))
339 .flex()
340 .items_center()
341 .justify_center()
342 .when(direction == Direction::Ltr, |handle| handle.left(offset))
343 .when(direction == Direction::Rtl, |handle| handle.right(offset))
344 .child(
345 div()
346 .id((id.clone(), "switch-thumb"))
347 .relative()
348 .test_support()
349 .size(px(diameter))
350 .rounded_full()
351 .bg(palette.thumb)
352 .text_color(palette.content)
353 .text_size(px(16.))
354 .flex()
355 .items_center()
356 .justify_center()
357 .child(state_layer)
358 .children(decoration),
359 );
360 div()
361 .id((id.clone(), "switch-track"))
362 .test_support()
363 .relative()
364 .w(px(52.))
365 .h(px(32.))
366 .rounded_full()
367 .bg(palette.track)
368 .when(palette.border.a > 0., |track| {
369 track.child(
370 div()
371 .absolute()
372 .inset_0()
373 .rounded_full()
374 .border_2()
375 .border_color(palette.border),
376 )
377 })
378 .child(handle)
379}
380
381impl RenderOnce for Switch {
382 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
383 let theme = current_material_theme(window, cx);
384 let direction = theme.layout.direction;
385 let reduced = self.disabled || cx.reduce_motion();
386 let motion = theme
387 .motion
388 .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
389 let effects = theme
390 .motion
391 .spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
392 let tint = animate(
393 (self.id.clone(), "switch-color"),
394 f32::from(self.checked),
395 effects,
396 window,
397 cx,
398 )
399 .clamp(0., 1.);
400 let palette = self
401 .colors
402 .resolve(self.checked, self.disabled, tint, window, cx);
403 let decoration = self.thumb_decoration();
404 if self.decorative {
405 let (diameter, offset) =
406 self.thumb_geometry(decoration.is_some(), false, motion, window, cx);
407 let track = render_track(
408 &self.id,
409 palette,
410 diameter,
411 offset,
412 direction,
413 div().id("switch-state-layer"),
414 decoration,
415 );
416 return div()
417 .id(self.id)
418 .flex_none()
419 .child(track)
420 .into_any_element();
421 }
422 let ripple = ripple_state(&self.id, !self.disabled, window, cx);
423 let focus = self.focus.take().unwrap_or_else(|| {
424 window
425 .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
426 .read(cx)
427 .clone()
428 });
429 let tracker = self
430 .interaction_source
431 .as_ref()
432 .map(|source| InteractionSource::track(source, &self.id, window, cx));
433 let observes_input = tracker.is_some();
434 ripple
435 .borrow_mut()
436 .track(!self.disabled, &focus, tracker, window, cx);
437 let active = ripple.borrow().pressed();
438 let (diameter, offset) =
439 self.thumb_geometry(decoration.is_some(), active, motion, window, cx);
440 let group: SharedString = format!("material-switch/{}", self.id).into();
441 let state_layer = render_state_layer(
442 diameter,
443 self.checked,
444 self.disabled,
445 active,
446 &group,
447 ripple.clone(),
448 direction,
449 window,
450 cx,
451 );
452 let track = render_track(
453 &self.id,
454 palette,
455 diameter,
456 offset,
457 direction,
458 state_layer,
459 decoration,
460 );
461 let control = BaseSwitch::new(self.id)
462 .checked(self.checked)
463 .disabled(self.disabled)
464 .track_focus(&focus)
465 .group(group)
466 .accessibility_label(self.label.clone())
467 .when(!self.disabled, |control| {
468 feedback_target(
469 control,
470 ripple,
471 observes_input,
472 observes_input.then_some(focus),
473 )
474 })
475 .border_2()
476 .border_color(gpui::transparent_black())
477 .rounded_md()
478 .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
479 .child(
480 row(direction, self.show_label)
481 .id("switch-row")
482 .min_h(px(48.))
483 .px_1()
484 .child(track)
485 .children(self.show_label.then(|| {
486 selection_label(self.label, self.label_content, self.disabled, window, cx)
487 })),
488 );
489 match self.on_change {
490 Some(handler) if !self.disabled => {
491 let next = !self.checked;
492 let pending = Rc::new(Cell::new(next));
493 let pending_arg = pending.clone();
494 let handler = Rc::new(ThemeScope::bind_action(
495 move |window, cx| handler(pending_arg.get(), window, cx),
496 window,
497 cx,
498 ));
499 let change = handler.clone();
500 let a11y_pending = pending.clone();
501 control
502 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
503 a11y_pending.set(next);
504 change(window, cx)
505 })
506 .on_change(move |checked, _, window, cx| {
507 pending.set(checked);
508 handler(window, cx)
509 })
510 .into_any_element()
511 }
512 _ => control.into_any_element(),
513 }
514 }
515}