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 checked: bool,
120 disabled: bool,
121 checked_icon: Option<AnyElement>,
122 unchecked_icon: Option<AnyElement>,
123 thumb_content: Option<AnyElement>,
124 colors: SwitchColors,
125 focus: Option<FocusHandle>,
126 interaction_source: Option<Entity<InteractionSource>>,
127 on_change: Option<Change>,
128 decorative: bool,
129}
130
131impl Switch {
132 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, checked: bool) -> Self {
133 Self {
134 id: id.into(),
135 label: label.into(),
136 checked,
137 disabled: false,
138 checked_icon: None,
139 unchecked_icon: None,
140 thumb_content: None,
141 colors: SwitchColors::default(),
142 focus: None,
143 interaction_source: None,
144 on_change: None,
145 decorative: false,
146 }
147 }
148
149 #[cfg(feature = "surfaces")]
150 pub(crate) fn decorative(mut self, decorative: bool) -> Self {
151 self.decorative = decorative;
152 self
153 }
154
155 pub fn disabled(mut self, disabled: bool) -> Self {
156 self.disabled = disabled;
157 self
158 }
159
160 pub fn checked_icon(mut self, icon: impl IntoElement) -> Self {
161 self.checked_icon = Some(icon.into_any_element());
162 self
163 }
164
165 pub fn unchecked_icon(mut self, icon: impl IntoElement) -> Self {
166 self.unchecked_icon = Some(icon.into_any_element());
167 self
168 }
169
170 pub fn thumb_content(mut self, content: impl IntoElement) -> Self {
173 self.thumb_content = Some(content.into_any_element());
174 self
175 }
176
177 pub fn colors(mut self, colors: SwitchColors) -> Self {
178 self.colors = colors;
179 self
180 }
181
182 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
184 self.focus = Some(focus.clone());
185 self
186 }
187
188 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
190 self.interaction_source = Some(source.clone());
191 self
192 }
193
194 pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
195 self.on_change = Some(Rc::new(handler));
196 self
197 }
198
199 fn thumb_decoration(&mut self) -> Option<AnyElement> {
200 let icon = if self.checked {
201 self.checked_icon.take()
202 } else {
203 self.unchecked_icon.take()
204 };
205 self.thumb_content
206 .take()
207 .map(|content| {
208 div()
209 .id("switch-thumb-content")
210 .role(gpui::Role::Group)
211 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
212 .size(px(16.))
213 .overflow_hidden()
214 .flex()
215 .items_center()
216 .justify_center()
217 .child(content)
218 .into_any_element()
219 })
220 .or(icon)
221 }
222
223 fn thumb_geometry(
224 &self,
225 has_decoration: bool,
226 active: bool,
227 motion: MotionSpec,
228 window: &mut Window,
229 cx: &mut App,
230 ) -> (f32, Pixels) {
231 let normal_size = if self.checked || has_decoration {
232 24.
233 } else {
234 16.
235 };
236 let diameter = animate(
237 (self.id.clone(), "thumb-diameter"),
238 if active { 28. } else { normal_size },
239 if active { MotionSpec::Instant } else { motion },
240 window,
241 cx,
242 )
243 .clamp(16., 28.);
244 let offset = animate(
245 (self.id.clone(), "thumb-offset"),
246 match (active, self.checked) {
247 (true, false) => 2.,
248 (true, true) => 22.,
249 (false, true) => 24.,
250 (false, false) => (32. - normal_size) / 2.,
251 },
252 if active { MotionSpec::Instant } else { motion },
253 window,
254 cx,
255 );
256 (diameter, px(offset.clamp(2., 50. - diameter)))
258 }
259}
260
261#[allow(clippy::too_many_arguments)]
262fn render_state_layer(
263 diameter: f32,
264 checked: bool,
265 disabled: bool,
266 active: bool,
267 group: &SharedString,
268 ink: Rc<RefCell<FeedbackState>>,
269 direction: Direction,
270 window: &Window,
271 cx: &App,
272) -> Stateful<Div> {
273 use ColorRole::*;
274 let accent = tone(if checked { Primary } else { OnSurface }, window, cx);
275 div()
276 .id("switch-state-layer")
277 .absolute()
278 .size(px(40.))
279 .left(px((diameter - 40.) / 2.))
280 .top(px((diameter - 40.) / 2.))
281 .rounded_full()
282 .when(!disabled, |layer| {
283 let static_pressed = active && cx.reduce_motion();
284 layer
285 .when(static_pressed, |layer| {
286 layer.bg(accent.opacity(StateLayer::Pressed.opacity()))
287 })
288 .when(!static_pressed, |layer| {
289 layer.group_hover(group.clone(), move |style| {
290 style.bg(accent.opacity(StateLayer::Hover.opacity()))
291 })
292 })
293 .when(cx.reduce_motion(), |layer| {
294 layer.group_active(group.clone(), move |style| {
295 style.bg(accent.opacity(StateLayer::Pressed.opacity()))
296 })
297 })
298 })
299 .child(ripple_ink(
300 ink,
301 accent,
302 gpui_material_theme::CornerRole::Full.shape(),
303 direction,
304 ))
305}
306
307#[allow(clippy::too_many_arguments)]
308fn render_track(
309 id: &ElementId,
310 palette: SwitchPalette,
311 diameter: f32,
312 offset: Pixels,
313 direction: Direction,
314 state_layer: Stateful<Div>,
315 decoration: Option<AnyElement>,
316) -> impl IntoElement + use<> {
317 let handle = div()
318 .absolute()
319 .top_0()
320 .h_full()
321 .w(px(diameter))
322 .flex()
323 .items_center()
324 .justify_center()
325 .when(direction == Direction::Ltr, |handle| handle.left(offset))
326 .when(direction == Direction::Rtl, |handle| handle.right(offset))
327 .child(
328 div()
329 .id((id.clone(), "switch-thumb"))
330 .relative()
331 .test_support()
332 .size(px(diameter))
333 .rounded_full()
334 .bg(palette.thumb)
335 .text_color(palette.content)
336 .text_size(px(16.))
337 .flex()
338 .items_center()
339 .justify_center()
340 .child(state_layer)
341 .children(decoration),
342 );
343 div()
344 .id((id.clone(), "switch-track"))
345 .test_support()
346 .relative()
347 .w(px(52.))
348 .h(px(32.))
349 .rounded_full()
350 .bg(palette.track)
351 .when(palette.border.a > 0., |track| {
352 track.child(
353 div()
354 .absolute()
355 .inset_0()
356 .rounded_full()
357 .border_2()
358 .border_color(palette.border),
359 )
360 })
361 .child(handle)
362}
363
364impl RenderOnce for Switch {
365 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
366 let theme = current_material_theme(window, cx);
367 let direction = theme.layout.direction;
368 let reduced = self.disabled || cx.reduce_motion();
369 let motion = theme
370 .motion
371 .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
372 let effects = theme
373 .motion
374 .spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
375 let tint = animate(
376 (self.id.clone(), "switch-color"),
377 f32::from(self.checked),
378 effects,
379 window,
380 cx,
381 )
382 .clamp(0., 1.);
383 let palette = self
384 .colors
385 .resolve(self.checked, self.disabled, tint, window, cx);
386 let decoration = self.thumb_decoration();
387 if self.decorative {
388 let (diameter, offset) =
389 self.thumb_geometry(decoration.is_some(), false, motion, window, cx);
390 let track = render_track(
391 &self.id,
392 palette,
393 diameter,
394 offset,
395 direction,
396 div().id("switch-state-layer"),
397 decoration,
398 );
399 return div()
400 .id(self.id)
401 .flex_none()
402 .child(track)
403 .into_any_element();
404 }
405 let ripple = ripple_state(&self.id, !self.disabled, window, cx);
406 let focus = self.focus.take().unwrap_or_else(|| {
407 window
408 .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
409 .read(cx)
410 .clone()
411 });
412 let tracker = self
413 .interaction_source
414 .as_ref()
415 .map(|source| InteractionSource::track(source, &self.id, window, cx));
416 let observes_input = tracker.is_some();
417 ripple
418 .borrow_mut()
419 .track(!self.disabled, &focus, tracker, window, cx);
420 let active = ripple.borrow().pressed();
421 let (diameter, offset) =
422 self.thumb_geometry(decoration.is_some(), active, motion, window, cx);
423 let group: SharedString = format!("material-switch/{}", self.id).into();
424 let state_layer = render_state_layer(
425 diameter,
426 self.checked,
427 self.disabled,
428 active,
429 &group,
430 ripple.clone(),
431 direction,
432 window,
433 cx,
434 );
435 let track = render_track(
436 &self.id,
437 palette,
438 diameter,
439 offset,
440 direction,
441 state_layer,
442 decoration,
443 );
444 let control = BaseSwitch::new(self.id)
445 .checked(self.checked)
446 .disabled(self.disabled)
447 .track_focus(&focus)
448 .group(group)
449 .accessibility_label(self.label.clone())
450 .when(!self.disabled, |control| {
451 feedback_target(
452 control,
453 ripple,
454 observes_input,
455 observes_input.then_some(focus),
456 )
457 })
458 .border_2()
459 .border_color(gpui::transparent_black())
460 .rounded_md()
461 .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
462 .child(
463 row(direction)
464 .id("switch-row")
465 .min_h(px(48.))
466 .px_1()
467 .child(track)
468 .child(selection_label(self.label, self.disabled, window, cx)),
469 );
470 match self.on_change {
471 Some(handler) if !self.disabled => {
472 let next = !self.checked;
473 let pending = Rc::new(Cell::new(next));
474 let pending_arg = pending.clone();
475 let handler = Rc::new(ThemeScope::bind_action(
476 move |window, cx| handler(pending_arg.get(), window, cx),
477 window,
478 cx,
479 ));
480 let change = handler.clone();
481 let a11y_pending = pending.clone();
482 control
483 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
484 a11y_pending.set(next);
485 change(window, cx)
486 })
487 .on_change(move |checked, _, window, cx| {
488 pending.set(checked);
489 handler(window, cx)
490 })
491 .into_any_element()
492 }
493 _ => control.into_any_element(),
494 }
495 }
496}