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