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