use std::rc::Rc;
use arc_motion::{arc_spring, arc_transition, is_reduced_motion};
use arc_tokens::{
ActiveArcLocale as _, ActiveArcTheme as _, Spacing, ThemeMode, ThemeSwitchTokens as T,
};
use gpui_kit::{
App, ElementId, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window,
assets::IconName, div, px, svg,
};
use crate::actions::button::{Button, ButtonSize, ButtonVariant};
type ThemeChangeHandler = Rc<dyn Fn(&(ThemeMode, ThemeSwitchVariant), &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ThemeSwitchVariant {
#[default]
Reveal,
Eclipse,
Split,
Rise,
}
impl ThemeSwitchVariant {
pub const ALL: [Self; 4] = [Self::Reveal, Self::Eclipse, Self::Split, Self::Rise];
pub const fn registry_id(self) -> &'static str {
match self {
Self::Reveal => "theme-switch",
Self::Eclipse => "theme-switch-eclipse",
Self::Split => "theme-switch-split",
Self::Rise => "theme-switch-rise",
}
}
}
#[derive(IntoElement)]
pub struct ThemeSwitch {
id: ElementId,
theme: ThemeMode,
variant: ThemeSwitchVariant,
label: Option<SharedString>,
icon_only: bool,
disabled: bool,
on_theme_change: Option<ThemeChangeHandler>,
}
impl ThemeSwitch {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
theme: ThemeMode::Light,
variant: ThemeSwitchVariant::Reveal,
label: None,
icon_only: false,
disabled: false,
on_theme_change: None,
}
}
pub fn theme(mut self, theme: ThemeMode) -> Self {
self.theme = theme;
self
}
pub fn variant(mut self, variant: ThemeSwitchVariant) -> Self {
self.variant = variant;
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn icon_only(mut self, icon_only: bool) -> Self {
self.icon_only = icon_only;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_theme_change(
mut self,
handler: impl Fn(&(ThemeMode, ThemeSwitchVariant), &mut Window, &mut App) + 'static,
) -> Self {
self.on_theme_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for ThemeSwitch {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let motion = theme.motion;
let locale = cx.arc_locale();
let reduced = is_reduced_motion(cx);
let is_dark = self.theme.is_dark();
let dark_t = if reduced {
if is_dark { 1.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "variant-nudge"),
if is_dark { 1.0 } else { 0.0 },
motion.spring.snappy,
window,
cx,
)
};
let (nudge_x, nudge_y, icon_scale) = if reduced {
(0.0, 0.0, 1.0)
} else {
match self.variant {
ThemeSwitchVariant::Reveal => (0.0, 0.0, 1.0 + (T::REVEAL_SCALE - 1.0) * dark_t),
ThemeSwitchVariant::Eclipse => (T::ECLIPSE_X * dark_t, 0.0, 1.0),
ThemeSwitchVariant::Split => (T::SPLIT_X * dark_t, 0.0, 1.0),
ThemeSwitchVariant::Rise => (0.0, T::RISE_Y * dark_t, 1.0),
}
};
let fade = arc_transition(
(self.id.clone(), "theme-fade"),
if is_dark { 1.0 } else { 0.0 },
if reduced {
motion.duration.instant
} else {
motion.duration.fast
},
motion.ease.enter,
window,
cx,
);
let swap = arc_spring(
(self.id.clone(), "theme-turn"),
if is_dark { 1.0 } else { 0.0 },
motion.spring.snappy,
window,
cx,
);
let next_mode = if is_dark {
ThemeMode::Light
} else {
ThemeMode::Dark
};
let default_a11y: SharedString = match (locale, next_mode) {
(arc_tokens::Locale::ZhCn, ThemeMode::Dark) => "切换至深色模式".into(),
(arc_tokens::Locale::ZhCn, ThemeMode::Light) => "切换至浅色模式".into(),
(arc_tokens::Locale::EnUs, ThemeMode::Dark) => "Switch to dark mode".into(),
(arc_tokens::Locale::EnUs, ThemeMode::Light) => "Switch to light mode".into(),
};
let visible_label: SharedString = self
.label
.clone()
.unwrap_or_else(|| locale.text("切换主题", "Switch theme").into());
let a11y = self.label.unwrap_or(default_a11y);
let icon_layer = |icon: IconName, opacity: f32, progress: f32, angle: f32| {
let scale = if reduced {
1.0
} else {
(T::ICON_ENTER_SCALE + (1.0 - T::ICON_ENTER_SCALE) * progress) * icon_scale
};
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.opacity(opacity)
.child(
svg()
.path(icon.path())
.size(T::ICON_SIZE)
.text_color(theme.colors.foreground)
.with_transformation(
gpui_kit::Transformation::scale(gpui_kit::size(scale, scale))
.with_rotation(gpui_kit::radians(if reduced {
0.0
} else {
angle.to_radians()
})),
),
)
};
let icon_el = div()
.relative()
.size(T::ICON_SLOT)
.flex_none()
.left(px(nudge_x))
.top(px(nudge_y))
.child(icon_layer(
IconName::Sun,
1.0 - fade,
1.0 - swap,
T::ICON_ANGLE * swap,
))
.child(icon_layer(
IconName::Moon,
fade,
swap,
-T::ICON_ANGLE * (1.0 - swap),
));
let variant = self.variant;
let on_change = self.on_theme_change;
let content_key =
SharedString::from(format!("{}:{}", variant.registry_id(), self.icon_only));
let mut btn = Button::new(self.id)
.variant(ButtonVariant::Secondary)
.size(ButtonSize::Sm)
.disabled(self.disabled)
.accessibility_label(a11y)
.content_key(content_key)
.child(if self.icon_only {
icon_el
} else {
div()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.child(icon_el)
.child(visible_label)
});
if self.icon_only {
btn = btn.square(T::ICON_BUTTON);
}
if let Some(handler) = on_change {
btn = btn.on_click(move |_, window, cx| {
handler(&(next_mode, variant), window, cx);
});
}
btn
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, Locale, ThemeMode, install_arc_theme, set_locale};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct ThemeSwitchHost {
mode: ThemeMode,
last_variant: Rc<Cell<ThemeSwitchVariant>>,
}
impl Render for ThemeSwitchHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let last_v = self.last_variant.clone();
div().p(Spacing::S4).child(
ThemeSwitch::new("ts-eclipse")
.theme(self.mode)
.variant(ThemeSwitchVariant::Eclipse)
.on_theme_change(cx.listener(
move |this, (next, var): &(ThemeMode, ThemeSwitchVariant), _, cx| {
this.mode = *next;
last_v.set(*var);
cx.notify();
},
)),
)
}
}
struct IconHost;
impl Render for IconHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
ThemeSwitch::new("disabled-theme")
.theme(ThemeMode::Dark)
.icon_only(true)
.disabled(true)
.on_theme_change(|_, _, _| panic!("禁用主题按钮不能触发"))
}
}
#[gpui_kit::test]
fn theme_switch_icon_only_has_square_bounds_and_disabled_guard(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
});
let (_, cx) = cx.add_window_view(|_, _| IconHost);
cx.update(|window, cx| {
window.render_frame(cx);
let b = window.find("disabled-theme").bounds();
assert_eq!(b.size, gpui_kit::size(T::ICON_BUTTON, T::ICON_BUTTON));
window.pointer_down(b.center(), MouseButton::Left, cx);
window.pointer_up(b.center(), MouseButton::Left, cx);
});
}
#[gpui_kit::test]
fn theme_switch_toggles_mode_and_reports_variant(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
set_locale(Locale::EnUs, cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let last_variant = Rc::new(Cell::new(ThemeSwitchVariant::Reveal));
let (view, cx) = cx.add_window_view(|_, _| ThemeSwitchHost {
mode: ThemeMode::Light,
last_variant: last_variant.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let btn = window.find_by_label("Switch to dark mode");
assert_eq!(btn.role(), Some(Role::Button));
let pos = btn.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
});
assert_eq!(view.read_with(cx, |v, _| v.mode), ThemeMode::Dark);
assert_eq!(last_variant.get(), ThemeSwitchVariant::Eclipse);
}
}