1use std::rc::Rc;
16
17use arc_motion::{arc_spring, is_reduced_motion};
18use arc_tokens::{ActiveArcLocale as _, ActiveArcTheme as _, Spacing, ThemeMode};
19use gpui_kit::{
20 App, ElementId, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window, div, px,
21};
22
23use crate::actions::{
24 button::{Button, ButtonSize, ButtonVariant},
25 icon_morph::{IconMorph, IconMorphName},
26};
27
28type ThemeChangeHandler = Rc<dyn Fn(&(ThemeMode, ThemeSwitchVariant), &mut Window, &mut App)>;
29
30#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
32pub enum ThemeSwitchVariant {
33 #[default]
34 Reveal,
35 Eclipse,
36 Split,
37 Rise,
38}
39
40impl ThemeSwitchVariant {
41 pub const ALL: [Self; 4] = [Self::Reveal, Self::Eclipse, Self::Split, Self::Rise];
42
43 pub const fn registry_id(self) -> &'static str {
44 match self {
45 Self::Reveal => "theme-switch",
46 Self::Eclipse => "theme-switch-eclipse",
47 Self::Split => "theme-switch-split",
48 Self::Rise => "theme-switch-rise",
49 }
50 }
51}
52
53#[derive(IntoElement)]
55pub struct ThemeSwitch {
56 id: ElementId,
57 theme: ThemeMode,
58 variant: ThemeSwitchVariant,
59 label: Option<SharedString>,
60 icon_only: bool,
61 disabled: bool,
62 on_theme_change: Option<ThemeChangeHandler>,
63}
64
65impl ThemeSwitch {
66 pub fn new(id: impl Into<ElementId>) -> Self {
67 Self {
68 id: id.into(),
69 theme: ThemeMode::Light,
70 variant: ThemeSwitchVariant::Reveal,
71 label: None,
72 icon_only: false,
73 disabled: false,
74 on_theme_change: None,
75 }
76 }
77
78 pub fn theme(mut self, theme: ThemeMode) -> Self {
79 self.theme = theme;
80 self
81 }
82
83 pub fn variant(mut self, variant: ThemeSwitchVariant) -> Self {
84 self.variant = variant;
85 self
86 }
87
88 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
89 self.label = Some(label.into());
90 self
91 }
92
93 pub fn icon_only(mut self, icon_only: bool) -> Self {
94 self.icon_only = icon_only;
95 self
96 }
97
98 pub fn disabled(mut self, disabled: bool) -> Self {
99 self.disabled = disabled;
100 self
101 }
102
103 pub fn on_theme_change(
104 mut self,
105 handler: impl Fn(&(ThemeMode, ThemeSwitchVariant), &mut Window, &mut App) + 'static,
106 ) -> Self {
107 self.on_theme_change = Some(Rc::new(handler));
108 self
109 }
110}
111
112impl RenderOnce for ThemeSwitch {
113 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
114 let theme = cx.arc_theme().clone();
115 let motion = theme.motion;
116 let locale = cx.arc_locale();
117 let reduced = is_reduced_motion(cx);
118 let is_dark = self.theme.is_dark();
119
120 let dark_t = if reduced {
121 if is_dark { 1.0 } else { 0.0 }
122 } else {
123 arc_spring(
124 (self.id.clone(), "variant-nudge"),
125 if is_dark { 1.0 } else { 0.0 },
126 motion.spring.snappy,
127 window,
128 cx,
129 )
130 };
131
132 let (nudge_x, nudge_y, icon_size) = match self.variant {
133 ThemeSwitchVariant::Reveal => (0.0, 0.0, 18.0 * (1.0 + 0.08 * dark_t)),
134 ThemeSwitchVariant::Eclipse => (-2.0 * dark_t, 0.0, 18.0),
135 ThemeSwitchVariant::Split => (1.0 * dark_t, 0.0, 18.0),
136 ThemeSwitchVariant::Rise => (0.0, -2.0 * dark_t, 18.0),
137 };
138
139 let next_mode = if is_dark {
140 ThemeMode::Light
141 } else {
142 ThemeMode::Dark
143 };
144 let default_a11y: SharedString = match (locale, next_mode) {
145 (arc_tokens::Locale::ZhCn, ThemeMode::Dark) => "切换至深色模式".into(),
146 (arc_tokens::Locale::ZhCn, ThemeMode::Light) => "切换至浅色模式".into(),
147 (arc_tokens::Locale::EnUs, ThemeMode::Dark) => "Switch to dark mode".into(),
148 (arc_tokens::Locale::EnUs, ThemeMode::Light) => "Switch to light mode".into(),
149 };
150 let visible_label: SharedString = self
151 .label
152 .clone()
153 .unwrap_or_else(|| locale.text("切换主题", "Switch theme").into());
154 let a11y = self.label.unwrap_or(default_a11y);
155
156 let icon_el = div()
157 .w(px(20.0))
158 .h(px(20.0))
159 .flex_none()
160 .flex()
161 .items_center()
162 .justify_center()
163 .ml(px(nudge_x))
164 .mt(px(nudge_y))
165 .child(
166 IconMorph::new(
167 ElementId::NamedChild(self.id.clone().into(), "sun-moon".into()),
168 IconMorphName::Theme,
169 )
170 .state(is_dark)
171 .size(px(icon_size))
172 .stroke_width(1.75),
173 );
174
175 let variant = self.variant;
176 let on_change = self.on_theme_change;
177 let content_key = SharedString::from(format!(
178 "{}:{}:{}",
179 variant.registry_id(),
180 if is_dark { "dark" } else { "light" },
181 self.icon_only
182 ));
183
184 let mut btn = Button::new(self.id)
185 .variant(ButtonVariant::Secondary)
186 .size(ButtonSize::Sm)
187 .disabled(self.disabled)
188 .accessibility_label(a11y)
189 .content_key(content_key)
190 .child(if self.icon_only {
191 icon_el
192 } else {
193 div()
194 .flex()
195 .flex_row()
196 .items_center()
197 .gap(Spacing::S2)
198 .child(icon_el)
199 .child(visible_label)
200 });
201
202 if let Some(handler) = on_change {
203 btn = btn.on_click(move |_, window, cx| {
204 handler(&(next_mode, variant), window, cx);
205 });
206 }
207
208 btn
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use std::{cell::Cell, rc::Rc};
215
216 use arc_tokens::{Accent, Locale, ThemeMode, install_arc_theme, set_locale};
217 use gpui_kit::{
218 Context, MouseButton, Render, Role, TestAppContext, div,
219 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
220 };
221
222 use super::*;
223
224 struct ThemeSwitchHost {
225 mode: ThemeMode,
226 last_variant: Rc<Cell<ThemeSwitchVariant>>,
227 }
228
229 impl Render for ThemeSwitchHost {
230 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
231 let last_v = self.last_variant.clone();
232 div().p(Spacing::S4).child(
233 ThemeSwitch::new("ts-eclipse")
234 .theme(self.mode)
235 .variant(ThemeSwitchVariant::Eclipse)
236 .on_theme_change(cx.listener(
237 move |this, (next, var): &(ThemeMode, ThemeSwitchVariant), _, cx| {
238 this.mode = *next;
239 last_v.set(*var);
240 cx.notify();
241 },
242 )),
243 )
244 }
245 }
246
247 #[gpui_kit::test]
248 fn theme_switch_toggles_mode_and_reports_variant(cx: &mut TestAppContext) {
249 cx.update(|cx| {
250 gpui_kit::init(cx);
251 set_locale(Locale::EnUs, cx);
252 install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
253 });
254 let last_variant = Rc::new(Cell::new(ThemeSwitchVariant::Reveal));
255 let (view, cx) = cx.add_window_view(|_, _| ThemeSwitchHost {
256 mode: ThemeMode::Light,
257 last_variant: last_variant.clone(),
258 });
259
260 cx.update(|window, cx| {
261 window.render_frame(cx);
262 let btn = window.find_by_label("Switch to dark mode");
263 assert_eq!(btn.role(), Some(Role::Button));
264 let pos = btn.bounds().center();
265 window.pointer_down(pos, MouseButton::Left, cx);
266 window.pointer_up(pos, MouseButton::Left, cx);
267 });
268
269 assert_eq!(view.read_with(cx, |v, _| v.mode), ThemeMode::Dark);
270 assert_eq!(last_variant.get(), ThemeSwitchVariant::Eclipse);
271 }
272}