Skip to main content

arc_ui/actions/
theme_switch.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/theme-switch/theme-switch.tsx` & `.module.css`
3//!
4//! P2 Components #8–11: `theme-switch`, `theme-switch-eclipse`, `theme-switch-split`,
5//! `theme-switch-rise` (unified component with 4 `ThemeSwitchVariant` presets per `arc-rust-plan.md`).
6//!
7//! 同款 secondary Button + Sun/Moon 交叉旋转;variant 仅提供图标微移与宿主过渡标识。
8//! 页面揭幕由宿主处理,不能用微移图标冒充四种页面动效。
9//! 减弱动画关闭微移、旋转与缩放,保留短淡入。
10
11use std::rc::Rc;
12
13use arc_motion::{arc_spring, arc_transition, is_reduced_motion};
14use arc_tokens::{
15    ActiveArcLocale as _, ActiveArcTheme as _, Spacing, ThemeMode, ThemeSwitchTokens as T,
16};
17use gpui_kit::{
18    App, ElementId, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window,
19    assets::IconName, div, px, svg,
20};
21
22use crate::actions::button::{Button, ButtonSize, ButtonVariant};
23
24type ThemeChangeHandler = Rc<dyn Fn(&(ThemeMode, ThemeSwitchVariant), &mut Window, &mut App)>;
25
26/// Theme transition style preset covering all 4 Arc `theme-switch*` registry entries.
27#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
28pub enum ThemeSwitchVariant {
29    #[default]
30    Reveal,
31    Eclipse,
32    Split,
33    Rise,
34}
35
36impl ThemeSwitchVariant {
37    pub const ALL: [Self; 4] = [Self::Reveal, Self::Eclipse, Self::Split, Self::Rise];
38
39    pub const fn registry_id(self) -> &'static str {
40        match self {
41            Self::Reveal => "theme-switch",
42            Self::Eclipse => "theme-switch-eclipse",
43            Self::Split => "theme-switch-split",
44            Self::Rise => "theme-switch-rise",
45        }
46    }
47}
48
49/// Arc `ThemeSwitch` button with sun/moon vector morph and 4 transition variants.
50#[derive(IntoElement)]
51pub struct ThemeSwitch {
52    id: ElementId,
53    theme: ThemeMode,
54    variant: ThemeSwitchVariant,
55    label: Option<SharedString>,
56    icon_only: bool,
57    disabled: bool,
58    on_theme_change: Option<ThemeChangeHandler>,
59}
60
61impl ThemeSwitch {
62    pub fn new(id: impl Into<ElementId>) -> Self {
63        Self {
64            id: id.into(),
65            theme: ThemeMode::Light,
66            variant: ThemeSwitchVariant::Reveal,
67            label: None,
68            icon_only: false,
69            disabled: false,
70            on_theme_change: None,
71        }
72    }
73
74    pub fn theme(mut self, theme: ThemeMode) -> Self {
75        self.theme = theme;
76        self
77    }
78
79    pub fn variant(mut self, variant: ThemeSwitchVariant) -> Self {
80        self.variant = variant;
81        self
82    }
83
84    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
85        self.label = Some(label.into());
86        self
87    }
88
89    pub fn icon_only(mut self, icon_only: bool) -> Self {
90        self.icon_only = icon_only;
91        self
92    }
93
94    pub fn disabled(mut self, disabled: bool) -> Self {
95        self.disabled = disabled;
96        self
97    }
98
99    pub fn on_theme_change(
100        mut self,
101        handler: impl Fn(&(ThemeMode, ThemeSwitchVariant), &mut Window, &mut App) + 'static,
102    ) -> Self {
103        self.on_theme_change = Some(Rc::new(handler));
104        self
105    }
106}
107
108impl RenderOnce for ThemeSwitch {
109    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
110        let theme = cx.arc_theme().clone();
111        let motion = theme.motion;
112        let locale = cx.arc_locale();
113        let reduced = is_reduced_motion(cx);
114        let is_dark = self.theme.is_dark();
115
116        let dark_t = if reduced {
117            if is_dark { 1.0 } else { 0.0 }
118        } else {
119            arc_spring(
120                (self.id.clone(), "variant-nudge"),
121                if is_dark { 1.0 } else { 0.0 },
122                motion.spring.snappy,
123                window,
124                cx,
125            )
126        };
127
128        let (nudge_x, nudge_y, icon_scale) = if reduced {
129            (0.0, 0.0, 1.0)
130        } else {
131            match self.variant {
132                ThemeSwitchVariant::Reveal => (0.0, 0.0, 1.0 + (T::REVEAL_SCALE - 1.0) * dark_t),
133                ThemeSwitchVariant::Eclipse => (T::ECLIPSE_X * dark_t, 0.0, 1.0),
134                ThemeSwitchVariant::Split => (T::SPLIT_X * dark_t, 0.0, 1.0),
135                ThemeSwitchVariant::Rise => (0.0, T::RISE_Y * dark_t, 1.0),
136            }
137        };
138        let fade = arc_transition(
139            (self.id.clone(), "theme-fade"),
140            if is_dark { 1.0 } else { 0.0 },
141            if reduced {
142                motion.duration.instant
143            } else {
144                motion.duration.fast
145            },
146            motion.ease.enter,
147            window,
148            cx,
149        );
150        let swap = arc_spring(
151            (self.id.clone(), "theme-turn"),
152            if is_dark { 1.0 } else { 0.0 },
153            motion.spring.snappy,
154            window,
155            cx,
156        );
157
158        let next_mode = if is_dark {
159            ThemeMode::Light
160        } else {
161            ThemeMode::Dark
162        };
163        let default_a11y: SharedString = match (locale, next_mode) {
164            (arc_tokens::Locale::ZhCn, ThemeMode::Dark) => "切换至深色模式".into(),
165            (arc_tokens::Locale::ZhCn, ThemeMode::Light) => "切换至浅色模式".into(),
166            (arc_tokens::Locale::EnUs, ThemeMode::Dark) => "Switch to dark mode".into(),
167            (arc_tokens::Locale::EnUs, ThemeMode::Light) => "Switch to light mode".into(),
168        };
169        let visible_label: SharedString = self
170            .label
171            .clone()
172            .unwrap_or_else(|| locale.text("切换主题", "Switch theme").into());
173        let a11y = self.label.unwrap_or(default_a11y);
174
175        let icon_layer = |icon: IconName, opacity: f32, progress: f32, angle: f32| {
176            let scale = if reduced {
177                1.0
178            } else {
179                (T::ICON_ENTER_SCALE + (1.0 - T::ICON_ENTER_SCALE) * progress) * icon_scale
180            };
181            div()
182                .absolute()
183                .inset_0()
184                .flex()
185                .items_center()
186                .justify_center()
187                .opacity(opacity)
188                .child(
189                    svg()
190                        .path(icon.path())
191                        .size(T::ICON_SIZE)
192                        .text_color(theme.colors.foreground)
193                        .with_transformation(
194                            gpui_kit::Transformation::scale(gpui_kit::size(scale, scale))
195                                .with_rotation(gpui_kit::radians(if reduced {
196                                    0.0
197                                } else {
198                                    angle.to_radians()
199                                })),
200                        ),
201                )
202        };
203        let icon_el = div()
204            .relative()
205            .size(T::ICON_SLOT)
206            .flex_none()
207            .left(px(nudge_x))
208            .top(px(nudge_y))
209            .child(icon_layer(
210                IconName::Sun,
211                1.0 - fade,
212                1.0 - swap,
213                T::ICON_ANGLE * swap,
214            ))
215            .child(icon_layer(
216                IconName::Moon,
217                fade,
218                swap,
219                -T::ICON_ANGLE * (1.0 - swap),
220            ));
221
222        let variant = self.variant;
223        let on_change = self.on_theme_change;
224        let content_key =
225            SharedString::from(format!("{}:{}", variant.registry_id(), self.icon_only));
226
227        let mut btn = Button::new(self.id)
228            .variant(ButtonVariant::Secondary)
229            .size(ButtonSize::Sm)
230            .disabled(self.disabled)
231            .accessibility_label(a11y)
232            .content_key(content_key)
233            .child(if self.icon_only {
234                icon_el
235            } else {
236                div()
237                    .flex()
238                    .flex_row()
239                    .items_center()
240                    .gap(Spacing::S2)
241                    .child(icon_el)
242                    .child(visible_label)
243            });
244
245        if self.icon_only {
246            btn = btn.square(T::ICON_BUTTON);
247        }
248
249        if let Some(handler) = on_change {
250            btn = btn.on_click(move |_, window, cx| {
251                handler(&(next_mode, variant), window, cx);
252            });
253        }
254
255        btn
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use std::{cell::Cell, rc::Rc};
262
263    use arc_tokens::{Accent, Locale, ThemeMode, install_arc_theme, set_locale};
264    use gpui_kit::{
265        Context, MouseButton, Render, Role, TestAppContext, div,
266        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
267    };
268
269    use super::*;
270
271    struct ThemeSwitchHost {
272        mode: ThemeMode,
273        last_variant: Rc<Cell<ThemeSwitchVariant>>,
274    }
275
276    impl Render for ThemeSwitchHost {
277        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
278            let last_v = self.last_variant.clone();
279            div().p(Spacing::S4).child(
280                ThemeSwitch::new("ts-eclipse")
281                    .theme(self.mode)
282                    .variant(ThemeSwitchVariant::Eclipse)
283                    .on_theme_change(cx.listener(
284                        move |this, (next, var): &(ThemeMode, ThemeSwitchVariant), _, cx| {
285                            this.mode = *next;
286                            last_v.set(*var);
287                            cx.notify();
288                        },
289                    )),
290            )
291        }
292    }
293
294    struct IconHost;
295    impl Render for IconHost {
296        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
297            ThemeSwitch::new("disabled-theme")
298                .theme(ThemeMode::Dark)
299                .icon_only(true)
300                .disabled(true)
301                .on_theme_change(|_, _, _| panic!("禁用主题按钮不能触发"))
302        }
303    }
304    #[gpui_kit::test]
305    fn theme_switch_icon_only_has_square_bounds_and_disabled_guard(cx: &mut TestAppContext) {
306        cx.update(|cx| {
307            gpui_kit::init(cx);
308            install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
309        });
310        let (_, cx) = cx.add_window_view(|_, _| IconHost);
311        cx.update(|window, cx| {
312            window.render_frame(cx);
313            let b = window.find("disabled-theme").bounds();
314            assert_eq!(b.size, gpui_kit::size(T::ICON_BUTTON, T::ICON_BUTTON));
315            window.pointer_down(b.center(), MouseButton::Left, cx);
316            window.pointer_up(b.center(), MouseButton::Left, cx);
317        });
318    }
319
320    #[gpui_kit::test]
321    fn theme_switch_toggles_mode_and_reports_variant(cx: &mut TestAppContext) {
322        cx.update(|cx| {
323            gpui_kit::init(cx);
324            set_locale(Locale::EnUs, cx);
325            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
326        });
327        let last_variant = Rc::new(Cell::new(ThemeSwitchVariant::Reveal));
328        let (view, cx) = cx.add_window_view(|_, _| ThemeSwitchHost {
329            mode: ThemeMode::Light,
330            last_variant: last_variant.clone(),
331        });
332
333        cx.update(|window, cx| {
334            window.render_frame(cx);
335            let btn = window.find_by_label("Switch to dark mode");
336            assert_eq!(btn.role(), Some(Role::Button));
337            let pos = btn.bounds().center();
338            window.pointer_down(pos, MouseButton::Left, cx);
339            window.pointer_up(pos, MouseButton::Left, cx);
340        });
341
342        assert_eq!(view.read_with(cx, |v, _| v.mode), ThemeMode::Dark);
343        assert_eq!(last_variant.get(), ThemeSwitchVariant::Eclipse);
344    }
345}