use std::rc::Rc;
use crate::{Button, ButtonSize, ButtonVariant};
use arc_motion::{arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions};
use arc_tokens::{
ActiveArcTheme as _, MusicPlayerTokens as Tokens, Spacing, SpringSpec, Typography,
};
use gpui_kit::{
App, BorderStyle, Bounds, ContentMask, Edges, ElementId, FocusHandle, Hsla, IntoElement,
MouseButton, MouseMoveEvent, MouseUpEvent, Orientation, ParentElement, Pixels, Point,
RenderOnce, Rgba, Role, SharedString, Styled, TestSupportExt as _, TextAlign, TextRun, Window,
assets::IconName, bounds, canvas, div, point, prelude::*, px, quad, size,
};
use gpui_kit::{ImageSource, ObjectFit, base::StyledExt as _, img};
#[derive(Clone)]
pub struct MusicTrack {
pub title: SharedString,
pub artist: SharedString,
pub duration: f32,
pub cover: Option<ImageSource>,
}
impl MusicTrack {
pub fn new(
title: impl Into<SharedString>,
artist: impl Into<SharedString>,
duration: f32,
) -> Self {
Self {
title: title.into(),
artist: artist.into(),
duration,
cover: None,
}
}
pub fn cover(mut self, cover: impl Into<ImageSource>) -> Self {
self.cover = Some(cover.into());
self
}
}
impl Default for MusicTrack {
fn default() -> Self {
Self::new("Cirrus", "Open Skies", 216.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MusicPlayerEvent {
Playing(bool),
Seek(f32),
Volume(f32),
Muted(bool),
Previous,
Next,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MusicPlayerState {
pub playing: bool,
pub position: f32,
pub volume: f32,
pub muted: bool,
}
impl Default for MusicPlayerState {
fn default() -> Self {
Self {
playing: false,
position: 0.0,
volume: 65.0,
muted: false,
}
}
}
impl MusicPlayerState {
pub fn apply(&mut self, event: MusicPlayerEvent, duration: f32) {
match event {
MusicPlayerEvent::Playing(value) => self.playing = value,
MusicPlayerEvent::Seek(value) => {
self.position = finite(value, 0.0).clamp(0.0, duration.max(0.0))
}
MusicPlayerEvent::Volume(value) => {
self.volume = finite(value, 0.0).clamp(0.0, 100.0);
self.muted = self.volume == 0.0;
}
MusicPlayerEvent::Muted(value) => {
self.muted = value;
if !value && self.volume == 0.0 {
self.volume = Self::default().volume;
}
}
MusicPlayerEvent::Previous | MusicPlayerEvent::Next => self.position = 0.0,
}
}
fn normalized(mut self, duration: f32) -> Self {
self.position = finite(self.position, 0.0).clamp(0.0, duration);
self.volume = finite(self.volume, 65.0).clamp(0.0, 100.0);
self
}
}
#[derive(Clone, Debug)]
pub struct MusicPlayerConfig {
pub width: f32,
pub max_stretch: f32,
pub bounce: f32,
pub disabled: bool,
}
impl Default for MusicPlayerConfig {
fn default() -> Self {
Self {
width: Tokens::WIDTH.as_f32(),
max_stretch: 30.0,
bounce: 0.5,
disabled: false,
}
}
}
type PlayerHandler = Rc<dyn Fn(&MusicPlayerEvent, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct MusicPlayer {
id: ElementId,
track: MusicTrack,
config: MusicPlayerConfig,
value: Option<MusicPlayerState>,
initial: MusicPlayerState,
on_event: Option<PlayerHandler>,
}
impl MusicPlayer {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
track: MusicTrack::default(),
config: Default::default(),
value: None,
initial: Default::default(),
on_event: None,
}
}
pub fn track(mut self, track: MusicTrack) -> Self {
self.track = track;
self
}
pub fn config(mut self, config: MusicPlayerConfig) -> Self {
self.config = config;
self
}
pub fn state(mut self, state: MusicPlayerState) -> Self {
self.value = Some(state);
self
}
pub fn default_state(mut self, state: MusicPlayerState) -> Self {
self.initial = state;
self
}
pub fn on_event(
mut self,
handler: impl Fn(&MusicPlayerEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_event = Some(Rc::new(handler));
self
}
}
fn player_event(
state: &gpui_kit::Entity<MusicPlayerState>,
event: MusicPlayerEvent,
duration: f32,
handler: &Option<PlayerHandler>,
window: &mut Window,
cx: &mut App,
) {
state.update(cx, |s, _| s.apply(event, duration));
if let Some(handler) = handler {
handler(&event, window, cx);
}
window.refresh();
}
fn time_label(seconds: f32) -> String {
let seconds = finite(seconds, 0.0).max(0.0) as u64;
format!("{}:{:02}", seconds / 60, seconds % 60)
}
impl RenderOnce for MusicPlayer {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let colors = cx.arc_theme().colors;
let duration = finite(self.track.duration, 0.0).clamp(0.0, 86_400.0);
let local =
window.use_keyed_state((self.id.clone(), "player-state"), cx, |_, _| self.initial);
if let Some(value) = self.value {
local.update(cx, |s, _| *s = value.normalized(duration));
}
let s = local.read(cx).normalized(duration);
let configured_width =
finite(self.config.width, Tokens::WIDTH.as_f32()).clamp(280.0, 1600.0);
let measured = window.use_keyed_state((self.id.clone(), "player-width"), cx, |_, _| {
configured_width
});
let width = (*measured.read(cx)).min(configured_width);
let stacked = width < Tokens::STACK_BELOW;
let compact = width < Tokens::COMPACT_BELOW;
let cover = if compact {
Tokens::COMPACT_COVER
} else {
Tokens::COVER
};
let padding = Spacing::S5;
let detail_width = (width
- 2.0
- 2.0 * padding.as_f32()
- if stacked {
0.0
} else {
cover.as_f32() + Spacing::S6.as_f32()
})
.max(120.0);
let disabled = self.config.disabled;
let event_handler = |event: MusicPlayerEvent| {
let local = local.clone();
let handler = self.on_event.clone();
move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| {
player_event(&local, event, duration, &handler, window, cx);
}
};
let transport = |part: &'static str,
label: &'static str,
icon: gpui_kit::AnyElement,
primary: bool,
event| {
Button::new((self.id.clone(), part))
.accessibility_label(label)
.variant(if primary {
ButtonVariant::Secondary
} else {
ButtonVariant::Ghost
})
.size(if primary {
ButtonSize::Lg
} else {
ButtonSize::Sm
})
.disabled(disabled)
.child(
div()
.w(if primary { Spacing::S8 } else { Spacing::S5 })
.h(if primary { Spacing::S12 } else { Spacing::S8 })
.flex()
.items_center()
.justify_center()
.child(icon),
)
.on_click(event_handler(event))
};
let mut rail = PlayerRailConfig {
length: detail_width,
max_value: duration,
left_icon: None,
right_icon: None,
value_position: PlayerRailValuePosition::None,
thickness: Tokens::RAIL_THICKNESS,
active_thickness: Tokens::RAIL_ACTIVE_THICKNESS,
max_stretch: self.config.max_stretch,
bounce: self.config.bounce,
disabled: disabled || duration <= 0.0,
..Default::default()
};
let seek_state = local.clone();
let seek_handler = self.on_event.clone();
let seek = PlayerRail::new((self.id.clone(), "progress"))
.compact()
.aria_label("播放进度")
.value(s.position)
.config(rail.clone())
.format_value(move |value| time_label(value).into())
.on_change(move |value, window, cx| {
player_event(
&seek_state,
MusicPlayerEvent::Seek(*value),
duration,
&seek_handler,
window,
cx,
)
});
rail.length = if stacked {
(detail_width - 160.0).max(96.0)
} else {
(detail_width * 0.32).max(96.0)
};
rail.max_value = 100.0;
rail.disabled = disabled;
rail.max_stretch = self.config.max_stretch.min(16.0);
let volume_state = local.clone();
let volume_handler = self.on_event.clone();
let volume = PlayerRail::new((self.id.clone(), "volume"))
.compact()
.aria_label("播放器音量")
.value(if s.muted { 0.0 } else { s.volume })
.config(rail)
.format_value(|v| format!("{v:.0}%").into())
.on_change(move |value, window, cx| {
player_event(
&volume_state,
MusicPlayerEvent::Volume(*value),
duration,
&volume_handler,
window,
cx,
)
});
let cover_element = div()
.id((self.id.clone(), "cover"))
.test_support()
.w(cover)
.h(cover)
.flex_shrink_0()
.rounded(Tokens::COVER_RADIUS)
.bg(colors.surface_muted)
.flex()
.items_center()
.justify_center()
.when_some(self.track.cover, |this, source| {
this.child(
img(source)
.size_full()
.rounded(Tokens::COVER_RADIUS)
.object_fit(ObjectFit::Cover),
)
});
let detail = div()
.min_w_0()
.flex_1()
.flex()
.flex_col()
.justify_between()
.when(!stacked, |this| this.h(Tokens::COVER))
.when(stacked, |this| this.w_full().flex_none().gap(Spacing::S4))
.child(
div()
.flex()
.flex_col()
.gap(Spacing::S1)
.child(
div()
.id((self.id.clone(), "title"))
.test_support()
.text_size(Typography::TEXT_XL)
.font_semibold()
.child(self.track.title),
)
.child(
div()
.text_size(Typography::TEXT_BASE)
.text_color(colors.text_muted)
.child(self.track.artist),
),
)
.child(
div()
.w_full()
.flex()
.flex_col()
.child(div().h(Spacing::S10).child(seek))
.child(
div()
.w_full()
.flex()
.justify_between()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(time_label(s.position))
.child(format!("−{}", time_label(duration - s.position))),
)
.child(
div()
.w_full()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S2)
.when(stacked || detail_width < 340.0, |this| {
this.flex_col().items_start()
})
.child(
div()
.flex()
.items_center()
.gap(Spacing::S2)
.child(transport(
"previous",
"上一首",
skip_icon(false, colors.foreground),
false,
MusicPlayerEvent::Previous,
))
.child(transport(
"play",
if s.playing { "暂停" } else { "播放" },
gpui_kit::svg()
.path(
if s.playing {
IconName::Pause
} else {
IconName::Play
}
.path(),
)
.size(Spacing::S6)
.text_color(colors.foreground)
.into_any_element(),
true,
MusicPlayerEvent::Playing(!s.playing),
))
.child(transport(
"next",
"下一首",
skip_icon(true, colors.foreground),
false,
MusicPlayerEvent::Next,
)),
)
.child(
div()
.flex()
.items_center()
.gap(Spacing::S1)
.child(
Button::new((self.id.clone(), "mute"))
.accessibility_label(if s.muted {
"取消静音"
} else {
"静音"
})
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.icon(if s.muted || s.volume == 0.0 {
IconName::VolumeX
} else {
IconName::Volume2
})
.disabled(disabled)
.on_click(event_handler(MusicPlayerEvent::Muted(
!s.muted,
))),
)
.child(
div().h(Spacing::S12).flex().items_center().child(volume),
)
.child(
gpui_kit::svg()
.path(IconName::Volume2.path())
.size(Spacing::S4)
.text_color(colors.text_muted),
),
),
),
);
div()
.id(self.id)
.test_support()
.relative()
.w_full()
.max_w(px(configured_width))
.p(padding)
.flex()
.gap(Spacing::S6)
.when(stacked, |this| this.flex_col().items_center())
.bg(colors.surface_raised)
.text_color(colors.foreground)
.border_1()
.border_color(colors.border)
.rounded(Tokens::RADIUS)
.child(cover_element)
.child(detail)
.child(
canvas(
move |bounds, _, cx| {
let next = bounds.size.width.as_f32();
if (*measured.read(cx) - next).abs() > 0.5 {
measured.update(cx, |v, cx| {
*v = next;
cx.notify();
});
}
},
|_, _, _, _| {},
)
.absolute()
.size_full(),
)
}
}
fn skip_icon(next: bool, color: Hsla) -> gpui_kit::AnyElement {
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let x = rect.left();
let y = rect.top();
let mut path = gpui_kit::PathBuilder::stroke(px(1.8));
let x_at = |v| x + rect.size.width * if next { v } else { 1.0 - v };
path.move_to(point(x_at(0.72), y + rect.size.height * 0.18));
path.line_to(point(x_at(0.72), y + rect.size.height * 0.82));
path.move_to(point(x_at(0.2), y + rect.size.height * 0.2));
path.line_to(point(x_at(0.6), y + rect.size.height * 0.5));
path.line_to(point(x_at(0.2), y + rect.size.height * 0.8));
path.close();
if let Ok(path) = path.build() {
window.paint_path(path, color);
}
},
)
.size(Spacing::S6)
.into_any_element()
}
type Handler = Rc<dyn Fn(&f32, &mut Window, &mut App)>;
type Formatter = Rc<dyn Fn(f32) -> SharedString>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlayerRailValuePosition {
#[default]
Top,
Bubble,
Inside,
None,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlayerRailIconPlacement {
#[default]
Outside,
Inside,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub enum PlayerRailTicks {
#[default]
None,
Auto,
Values(Vec<f32>),
}
#[derive(Clone, Debug)]
pub struct PlayerRailConfig {
pub starting_value: f32,
pub max_value: f32,
pub is_stepped: bool,
pub step_size: f32,
pub orientation: Orientation,
pub left_icon: Option<IconName>,
pub right_icon: Option<IconName>,
pub icon_placement: PlayerRailIconPlacement,
pub value_position: PlayerRailValuePosition,
pub ticks: PlayerRailTicks,
pub thumb: bool,
pub fill_from: Option<f32>,
pub thickness: f32,
pub active_thickness: f32,
pub radius: Option<f32>,
pub rest_opacity: f32,
pub grow_on_hover: bool,
pub max_stretch: f32,
pub bounce: f32,
pub jump_to_click: bool,
pub wheel: bool,
pub track_color: Option<Hsla>,
pub range_color: Option<Hsla>,
pub icon_color: Option<Hsla>,
pub content_color: Option<Hsla>,
pub fill_content_color: Option<Hsla>,
pub thumb_color: Option<Hsla>,
pub disabled: bool,
pub length: f32,
}
impl Default for PlayerRailConfig {
fn default() -> Self {
Self {
starting_value: 0.0,
max_value: 100.0,
is_stepped: false,
step_size: 1.0,
orientation: Orientation::Horizontal,
left_icon: Some(IconName::VolumeX),
right_icon: Some(IconName::Volume2),
icon_placement: PlayerRailIconPlacement::Outside,
value_position: PlayerRailValuePosition::Top,
ticks: PlayerRailTicks::None,
thumb: false,
fill_from: None,
thickness: 6.0,
active_thickness: 12.0,
radius: None,
rest_opacity: 0.7,
grow_on_hover: true,
max_stretch: 50.0,
bounce: 0.5,
jump_to_click: true,
wheel: false,
track_color: None,
range_color: None,
icon_color: None,
content_color: None,
fill_content_color: None,
thumb_color: None,
disabled: false,
length: 192.0,
}
}
}
fn finite(value: f32, fallback: f32) -> f32 {
if value.is_finite() { value } else { fallback }
}
impl PlayerRailConfig {
fn normalized(&self) -> Self {
let mut c = self.clone();
c.starting_value = finite(c.starting_value, 0.0);
c.max_value = finite(c.max_value, 100.0);
if c.starting_value > c.max_value {
std::mem::swap(&mut c.starting_value, &mut c.max_value);
}
c.step_size = finite(c.step_size, 1.0).max(0.0);
c.thickness = finite(c.thickness, 6.0).clamp(1.0, 96.0);
c.active_thickness = finite(c.active_thickness, 12.0).clamp(1.0, 96.0);
c.radius = c.radius.map(|v| finite(v, 0.0).max(0.0));
c.rest_opacity = finite(c.rest_opacity, 0.7).clamp(0.0, 1.0);
c.max_stretch = finite(c.max_stretch, 50.0).clamp(0.0, 200.0);
c.bounce = finite(c.bounce, 0.5).clamp(0.0, 0.95);
c.length = finite(c.length, 192.0).clamp(80.0, 1600.0);
c.fill_from = c
.fill_from
.map(|v| finite(v, c.starting_value).clamp(c.starting_value, c.max_value));
c
}
fn span(&self) -> f32 {
(self.max_value - self.starting_value).max(f32::EPSILON)
}
fn fraction(&self, value: f32) -> f32 {
((value - self.starting_value) / self.span()).clamp(0.0, 1.0)
}
fn snap(&self, value: f32) -> f32 {
let value = finite(value, self.starting_value).clamp(self.starting_value, self.max_value);
if self.is_stepped && self.step_size > 0.0 {
(self.starting_value
+ ((value - self.starting_value) / self.step_size).round() * self.step_size)
.clamp(self.starting_value, self.max_value)
} else {
value
}
}
fn unit(&self) -> f32 {
if self.is_stepped && self.step_size > 0.0 {
self.step_size
} else {
self.span() / 100.0
}
}
fn marks(&self) -> Vec<f32> {
let values: Vec<f32> = match &self.ticks {
PlayerRailTicks::None => return Vec::new(),
PlayerRailTicks::Values(values) => values.iter().take(512).copied().collect(),
PlayerRailTicks::Auto => {
let count = if self.is_stepped && self.step_size > 0.0 {
((self.max_value - self.starting_value) / self.step_size).round()
} else {
0.0
};
if count > 0.0 && count <= 40.0 {
(0..=count as usize)
.map(|i| self.starting_value + i as f32 * self.step_size)
.collect()
} else {
(0..=10)
.map(|i| self.starting_value + i as f32 / 10.0 * self.span())
.collect()
}
}
};
let mut marks: Vec<_> = values
.into_iter()
.filter(|v| v.is_finite())
.map(|v| self.fraction(v))
.filter(|v| *v > 0.001 && *v < 0.999)
.collect();
marks.sort_by(f32::total_cmp);
marks.dedup();
marks
}
}
fn rubber(distance: f32, limit: f32) -> f32 {
if limit > 0.0 {
(distance.max(0.0) / (2.0 * limit)).tanh() * limit
} else {
0.0
}
}
#[derive(Clone)]
struct State {
value: f32,
latest: f32,
focus: FocusHandle,
hovered: bool,
dragging: bool,
drag_origin: f32,
drag_from: f32,
stretch: f32,
side: f32,
impulse: Option<f32>,
pulse: Option<(f32, f64)>,
rail: Option<Bounds<Pixels>>,
wheel_deadline: Option<f64>,
}
impl State {
fn new(value: f32, focus: FocusHandle) -> Self {
Self {
value,
latest: value,
focus,
hovered: false,
dragging: false,
drag_origin: 0.0,
drag_from: 0.0,
stretch: 0.0,
side: 1.0,
impulse: None,
pulse: None,
rail: None,
wheel_deadline: None,
}
}
fn bump(&mut self, side: f32, c: &PlayerRailConfig, now: f64) {
if c.max_stretch > 0.0
&& !self.dragging
&& self.pulse.is_none_or(|(_, started)| now - started > 0.28)
{
self.side = side;
self.impulse = Some(c.max_stretch * 5.5);
self.pulse = Some((side, now));
}
}
}
#[derive(IntoElement)]
pub struct PlayerRail {
id: ElementId,
label: SharedString,
config: PlayerRailConfig,
value: Option<f32>,
default_value: f32,
formatter: Option<Formatter>,
on_change: Option<Handler>,
on_change_end: Option<Handler>,
compact: bool,
}
impl PlayerRail {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
label: "Slider".into(),
config: Default::default(),
value: None,
default_value: 50.0,
formatter: None,
on_change: None,
on_change_end: None,
compact: false,
}
}
fn compact(mut self) -> Self {
self.compact = true;
self
}
pub fn config(mut self, config: PlayerRailConfig) -> Self {
self.config = config;
self
}
pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn value(mut self, value: f32) -> Self {
self.value = Some(value);
self
}
pub fn default_value(mut self, value: f32) -> Self {
self.default_value = value;
self
}
pub fn format_value(mut self, formatter: impl Fn(f32) -> SharedString + 'static) -> Self {
self.formatter = Some(Rc::new(formatter));
self
}
pub fn on_change(mut self, handler: impl Fn(&f32, &mut Window, &mut App) + 'static) -> Self {
self.on_change = Some(Rc::new(handler));
self
}
pub fn on_change_end(
mut self,
handler: impl Fn(&f32, &mut Window, &mut App) + 'static,
) -> Self {
self.on_change_end = Some(Rc::new(handler));
self
}
}
fn axis(position: Point<Pixels>, rect: Bounds<Pixels>, vertical: bool) -> f32 {
if vertical {
(rect.bottom() - position.y).as_f32()
} else {
(position.x - rect.left()).as_f32()
}
}
fn length(rect: Bounds<Pixels>, vertical: bool) -> f32 {
if vertical {
rect.size.height.as_f32()
} else {
rect.size.width.as_f32()
}
.max(1.0)
}
fn alpha(mut color: Hsla, opacity: f32) -> Hsla {
color.a *= opacity.clamp(0.0, 1.0);
color
}
fn commit(
state: &gpui_kit::Entity<State>,
next: f32,
controlled: bool,
handler: &Option<Handler>,
window: &mut Window,
cx: &mut App,
) {
let changed = (state.read(cx).latest - next).abs() > f32::EPSILON;
state.update(cx, |s, _| {
s.latest = next;
if !controlled {
s.value = next;
}
});
if changed && let Some(handler) = handler {
handler(&next, window, cx);
}
window.refresh();
}
impl RenderOnce for PlayerRail {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let c = self.config.normalized();
let colors = cx.arc_theme().colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let controlled = self.value.is_some();
let initial = finite(self.default_value, 50.0).clamp(c.starting_value, c.max_value);
let state = window.use_keyed_state((self.id.clone(), "react-bits-state"), cx, |_, cx| {
State::new(initial, cx.focus_handle())
});
if c.disabled {
state.update(cx, |s, _| {
s.dragging = false;
s.stretch = 0.0;
s.wheel_deadline = None;
s.impulse = None;
});
}
let current = finite(self.value.unwrap_or(state.read(cx).value), initial)
.clamp(c.starting_value, c.max_value);
if !state.read(cx).dragging && state.read(cx).wheel_deadline.is_none() {
state.update(cx, |s, _| s.latest = current);
}
let s = state.read(cx).clone();
let focused = s.focus.is_focused(window) && !c.disabled;
let active = !c.disabled && ((s.hovered && c.grow_on_hover) || s.dragging || focused);
let target = c.fraction(current);
let spring = |period: f32, zeta: f32| {
let omega = std::f32::consts::TAU / period;
SpringSpec::physics(omega * omega, 2.0 * zeta * omega)
};
let shown = arc_spring_with_options(
(self.id.clone(), "fill"),
target,
SpringOptions::new(spring(
if s.dragging { 0.09 } else { 0.3 },
if s.dragging { 1.0 } else { 0.86 },
))
.with_rest_thresholds(0.0004, 0.002),
window,
cx,
)
.value
.clamp(0.0, 1.0);
let activation = arc_spring_with_options(
(self.id.clone(), "active"),
if active { 1.0 } else { 0.0 },
SpringOptions::new(spring(0.32, 0.9)).with_rest_thresholds(0.002, 0.005),
window,
cx,
)
.value
.clamp(0.0, 1.0);
let mut options = SpringOptions::new(spring(0.42, 1.0 - 0.9 * c.bounce))
.with_travel(!s.dragging)
.with_rest_thresholds(0.05, 0.5);
if let Some(impulse) = s.impulse {
options = options.with_initial_velocity(impulse);
state.update(cx, |s, _| s.impulse = None);
}
let stretch = arc_spring_with_options(
(self.id.clone(), "stretch"),
if reduced { 0.0 } else { s.stretch },
options,
window,
cx,
)
.value;
let stretch = if reduced || c.max_stretch == 0.0 {
0.0
} else {
stretch
};
let formatted = self.formatter.as_ref().map_or_else(
|| {
if c.is_stepped && c.step_size > 0.0 {
let text = format!("{}", c.step_size);
let decimals = text.split('.').nth(1).map_or(0, str::len).min(6);
format!("{current:.decimals$}").into()
} else {
format!("{current:.0}").into()
}
},
|f| f(current),
);
let vertical = c.orientation == Orientation::Vertical;
let thickness = c.thickness + (c.active_thickness - c.thickness) * activation;
let cross = c.thickness.max(c.active_thickness).max(34.0);
let opacity = (c.rest_opacity + (1.0 - c.rest_opacity) * activation)
* if c.disabled { 0.45 } else { 1.0 };
let track_color = c.track_color.unwrap_or(colors.control_track);
let fill_color = c.range_color.unwrap_or(colors.foreground);
let content = c.content_color.unwrap_or(colors.foreground);
let fill_content = c.fill_content_color.unwrap_or_else(|| {
let rgb: Rgba = fill_color.into();
if rgb.a < 0.5 {
content
} else if (0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b) > 0.55 {
if colors.foreground.l < colors.background.l {
colors.foreground
} else {
colors.background
}
} else if colors.foreground.l > colors.background.l {
colors.foreground
} else {
colors.background
}
});
let focus = s.focus.clone();
let pre = state.clone();
let paint_state = state.clone();
let paint_c = c.clone();
let move_state = state.clone();
let move_c = c.clone();
let move_change = self.on_change.clone();
let up_state = state.clone();
let up_commit = self.on_change_end.clone();
let marks = c.marks();
let paint_text = formatted.clone();
let side = s.side;
let pulse = s
.pulse
.filter(|_| !reduced)
.map_or((1.0, 1.0), |(side, started)| {
let t = ((now - started) / 0.28) as f32;
if (0.0..1.0).contains(&t) {
window.request_animation_frame();
let scale = 1.0 + (t * std::f32::consts::PI).sin() * 0.35;
if side > 0.0 {
(1.0, scale)
} else {
(scale, 1.0)
}
} else {
(1.0, 1.0)
}
});
let drawing = canvas(
move |rect, _, cx| {
let outside = c.icon_placement == PlayerRailIconPlacement::Outside;
let start = if outside && c.left_icon.is_some() {
32.0
} else {
0.0
};
let end = if outside && c.right_icon.is_some() {
32.0
} else {
0.0
};
let rail = if vertical {
bounds(
point(
rect.center().x - px(cross * 0.5),
rect.top() + px(end + 24.0),
),
size(
px(cross),
(rect.size.height - px(start + end + 48.0)).max(px(1.0)),
),
)
} else {
bounds(
point(rect.left() + px(start), rect.center().y - px(cross * 0.5)),
size((rect.size.width - px(start + end)).max(px(1.0)), px(cross)),
)
};
pre.update(cx, |s, _| s.rail = Some(rail));
rail
},
move |_, rail, window, cx| {
if paint_state.read(cx).dragging && !paint_c.disabled {
let st = move_state.clone();
let c = move_c.clone();
let cb = move_change.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() || !st.read(cx).dragging {
return;
}
if event.pressed_button != Some(MouseButton::Left) {
st.update(cx, |s, _| {
s.dragging = false;
s.stretch = 0.0;
});
window.refresh();
return;
}
let Some(rect) = st.read(cx).rail else {
return;
};
let len = length(rect, vertical);
let at = axis(event.position, rect, vertical);
let snapshot = st.read(cx).clone();
let fraction = snapshot.drag_from + (at - snapshot.drag_origin) / len;
let over = if fraction < 0.0 {
-fraction * len
} else {
(fraction - 1.0).max(0.0) * len
};
st.update(cx, |s, cx| {
let side = if fraction < 0.0 { -1.0 } else { 1.0 };
if over > 0.0 && (s.stretch == 0.0 || s.side != side) {
s.pulse = Some((side, motion_now(cx)));
}
if over > 0.0 {
s.side = side;
}
s.stretch = if is_reduced_motion(cx) {
0.0
} else {
rubber(over, c.max_stretch)
};
});
commit(
&st,
c.snap(c.starting_value + fraction.clamp(0.0, 1.0) * c.span()),
controlled,
&cb,
window,
cx,
);
});
let st = up_state.clone();
let cb = up_commit.clone();
window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
if !phase.bubble()
|| event.button != MouseButton::Left
|| !st.read(cx).dragging
{
return;
}
let value = st.read(cx).latest;
st.update(cx, |s, _| {
s.dragging = false;
s.stretch = 0.0;
});
if let Some(cb) = &cb {
cb(&value, window, cx);
}
window.refresh();
});
}
let c = &paint_c;
let len = length(rail, vertical);
let along = 1.0 + stretch / len;
let across = 1.0 - 0.22 * (stretch / c.max_stretch.max(1.0)).clamp(-1.0, 1.0);
let thick = (thickness * across).max(1.0);
let start = if side > 0.0 { 0.0 } else { -stretch };
let end = start + len * along;
let segment = |from: f32, to: f32, width: f32| {
if vertical {
bounds(
point(rail.center().x - px(width * 0.5), rail.bottom() - px(to)),
size(px(width), px((to - from).max(0.0))),
)
} else {
bounds(
point(rail.left() + px(from), rail.center().y - px(width * 0.5)),
size(px((to - from).max(0.0)), px(width)),
)
}
};
let track = segment(start, end, thick);
let round = c.radius.unwrap_or(thick * 0.5).min(thick * 0.5);
paint_rect(track, round, alpha(track_color, opacity), window);
let origin = c.fraction(c.fill_from.unwrap_or(c.starting_value));
let low = start + origin.min(shown) * len * along;
let high = start + origin.max(shown) * len * along;
let fill = segment(low, high, thick);
let reveal = ((thickness - 14.0) / 10.0).clamp(0.0, 1.0);
let paint_content = |ink: Hsla, window: &mut Window, cx: &mut App| {
for fraction in &marks {
let pos = start + fraction * len * along;
let tick = segment(pos - 1.5, pos + 1.5, 3.0);
paint_rect(tick, 1.5, alpha(ink, opacity * 0.4), window);
}
if reveal > 0.0 {
let pad = (thickness * 0.32).round().max(8.0) + 10.0;
let color = alpha(ink, opacity * reveal);
if c.icon_placement == PlayerRailIconPlacement::Inside {
if let Some(icon) = c.left_icon {
paint_icon(
icon,
center_on(rail, vertical, start + pad),
20.0,
color,
window,
cx,
);
}
if c.value_position != PlayerRailValuePosition::Inside
&& let Some(icon) = c.right_icon
{
paint_icon(
icon,
center_on(rail, vertical, end - pad),
20.0,
color,
window,
cx,
);
}
}
if c.value_position == PlayerRailValuePosition::Inside {
paint_label(
paint_text.clone(),
center_on(
rail,
vertical,
end - pad - if vertical { 0.0 } else { 10.0 },
),
color,
window,
cx,
);
}
}
};
window.with_content_mask(Some(ContentMask { bounds: track }), |window| {
paint_content(content, window, cx);
});
if high - low > 0.01 {
window.with_content_mask(Some(ContentMask { bounds: fill }), |window| {
paint_rect(track, round, alpha(fill_color, opacity), window);
paint_content(fill_content, window, cx);
});
}
let position = start + shown * len * along;
let center = center_on(rail, vertical, position);
if c.thumb {
let d =
(c.active_thickness + 6.0).clamp(16.0, 28.0) * (1.0 + 0.12 * activation);
paint_rect(
bounds(center - point(px(d * 0.5), px(d * 0.5)), size(px(d), px(d))),
d * 0.5,
alpha(c.thumb_color.unwrap_or(colors.control_thumb), opacity),
window,
);
}
if c.icon_placement == PlayerRailIconPlacement::Outside {
if let Some(icon) = c.left_icon {
paint_icon(
icon,
center_on(
rail,
vertical,
-22.0 - if side < 0.0 { stretch } else { 0.0 },
),
20.0 * pulse.0 * (1.0 + 0.08 * activation),
alpha(c.icon_color.unwrap_or(colors.foreground), opacity),
window,
cx,
);
}
if let Some(icon) = c.right_icon {
paint_icon(
icon,
center_on(
rail,
vertical,
len + 22.0 + if side > 0.0 { stretch } else { 0.0 },
),
20.0 * pulse.1 * (1.0 + 0.08 * activation),
alpha(c.icon_color.unwrap_or(colors.foreground), opacity),
window,
cx,
);
}
}
if c.value_position == PlayerRailValuePosition::Top {
paint_label(
paint_text.clone(),
point(rail.center().x, rail.top() - px(14.0)),
alpha(content, 0.6),
window,
cx,
);
}
let bubble_alpha = (activation * 1.4 - 0.2).clamp(0.0, 1.0);
if c.value_position == PlayerRailValuePosition::Bubble && bubble_alpha > 0.0 {
let offset = if c.thumb {
(c.active_thickness + 6.0).clamp(16.0, 28.0) * 1.12
} else {
c.active_thickness
} * 0.5
+ 20.0;
let at = if vertical {
center + point(px(offset), px(0.0))
} else {
center - point(px(0.0), px(offset))
};
let scale = 0.7 + 0.3 * activation;
let w = (paint_text.chars().count() as f32 * 7.0 + 16.0).max(30.0) * scale;
paint_rect(
bounds(
at - point(px(w * 0.5), px(12.0 * scale)),
size(px(w), px(24.0 * scale)),
),
8.0,
alpha(fill_color, bubble_alpha),
window,
);
paint_label(
paint_text.clone(),
at,
alpha(fill_content, bubble_alpha),
window,
cx,
);
}
if focused {
let outline = bounds(
track.origin - point(px(4.0), px(4.0)),
track.size + size(px(8.0), px(8.0)),
);
window.paint_quad(quad(
outline,
px(round + 4.0),
Hsla::transparent_black(),
Edges::all(px(2.0)),
colors.focus_outline,
BorderStyle::Solid,
));
}
},
);
let st_down = state.clone();
let c_down = self.config.normalized();
let cb_down = self.on_change.clone();
let st_key = state.clone();
let c_key = self.config.normalized();
let cb_key = self.on_change.clone();
let end_key = self.on_change_end.clone();
let st_wheel = state.clone();
let c_wheel = self.config.normalized();
let cb_wheel = self.on_change.clone();
let end_wheel = self.on_change_end.clone();
let st_hover = state.clone();
let disabled = self.config.disabled;
let root = div()
.id(self.id)
.test_support()
.track_focus(&focus.tab_stop(!disabled))
.role(Role::Slider)
.aria_label(self.label)
.aria_min_numeric_value(f64::from(c_down.starting_value))
.aria_max_numeric_value(f64::from(c_down.max_value))
.aria_numeric_value(f64::from(current))
.aria_numeric_value_step(f64::from(c_down.unit()))
.aria_value(formatted)
.aria_orientation(c_down.orientation)
.w(px(if vertical {
cross + 72.0
} else {
c_down.length
}))
.h(px(if vertical {
c_down.length + 96.0
} else {
cross + if self.compact { 0.0 } else { 56.0 }
}))
.when(!disabled, |this| {
this.cursor(if s.dragging {
gpui_kit::CursorStyle::ClosedHand
} else {
gpui_kit::CursorStyle::OpenHand
})
})
.on_hover(move |hovered, window, cx| {
st_hover.update(cx, |s, _| s.hovered = *hovered);
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |event, window, cx| {
if c_down.disabled {
return;
}
let Some(rect) = st_down.read(cx).rail else {
return;
};
if !rect.contains(&event.position) {
return;
}
let at = axis(event.position, rect, vertical);
let fraction = if c_down.jump_to_click {
at / length(rect, vertical)
} else {
c_down.fraction(st_down.read(cx).latest)
};
window.focus(&st_down.read(cx).focus.clone(), cx);
st_down.update(cx, |s, _| {
s.dragging = true;
s.drag_origin = at;
s.drag_from = fraction;
s.wheel_deadline = None;
s.stretch = 0.0;
});
if c_down.jump_to_click {
commit(
&st_down,
c_down.snap(c_down.starting_value + fraction * c_down.span()),
controlled,
&cb_down,
window,
cx,
);
}
window.refresh();
cx.stop_propagation();
})
.on_key_down(move |event, window, cx| {
if c_key.disabled {
return;
}
let value = st_key.read(cx).latest;
let unit = c_key.unit();
let large = unit.max(c_key.span() / 10.0);
let wanted = match event.keystroke.key.as_str() {
"right" | "up" => value + unit,
"left" | "down" => value - unit,
"pageup" => value + large,
"pagedown" => value - large,
"home" => c_key.starting_value,
"end" => c_key.max_value,
_ => return,
};
cx.stop_propagation();
let next = c_key.snap(wanted);
if (next - value).abs() > f32::EPSILON {
commit(&st_key, next, controlled, &cb_key, window, cx);
if let Some(cb) = &end_key {
cb(&next, window, cx);
}
} else if !is_reduced_motion(cx) {
let now = motion_now(cx);
st_key.update(cx, |s, _| s.bump((wanted - value).signum(), &c_key, now));
window.refresh();
}
})
.on_scroll(move |event, window, cx| {
if c_wheel.disabled || !c_wheel.wheel {
return;
}
let delta = event.delta.pixel_delta(px(20.0));
let delta = if delta.y.abs() >= delta.x.abs() {
-delta.y.as_f32()
} else {
delta.x.as_f32()
};
if delta == 0.0 {
return;
}
cx.stop_propagation();
let value = st_wheel.read(cx).latest;
let amount = if c_wheel.is_stepped && c_wheel.step_size > 0.0 {
delta.signum() * c_wheel.step_size
} else {
delta * c_wheel.span() / 800.0
};
let next = c_wheel.snap(value + amount);
let now = motion_now(cx);
if (next - value).abs() > f32::EPSILON {
let deadline = now + 0.2;
st_wheel.update(cx, |s, _| s.wheel_deadline = Some(deadline));
commit(&st_wheel, next, controlled, &cb_wheel, window, cx);
let weak = st_wheel.downgrade();
let cb = end_wheel.clone();
window
.spawn(cx, async move |cx| {
cx.background_executor()
.timer(std::time::Duration::from_millis(200))
.await;
let _ = cx.update(|window, cx| {
let Some(st) = weak.upgrade() else {
return;
};
if st.read(cx).wheel_deadline != Some(deadline) {
return;
}
let value = st.read(cx).latest;
st.update(cx, |s, _| s.wheel_deadline = None);
if let Some(cb) = cb {
cb(&value, window, cx);
}
});
})
.detach();
} else if !is_reduced_motion(cx) {
st_wheel.update(cx, |s, _| s.bump(delta.signum(), &c_wheel, now));
window.refresh();
}
});
root.child(drawing.w_full().h_full())
}
}
fn center_on(rail: Bounds<Pixels>, vertical: bool, at: f32) -> Point<Pixels> {
if vertical {
point(rail.center().x, rail.bottom() - px(at))
} else {
point(rail.left() + px(at), rail.center().y)
}
}
fn paint_rect(rect: Bounds<Pixels>, radius: f32, color: Hsla, window: &mut Window) {
let radius = radius
.min(rect.size.width.as_f32().min(rect.size.height.as_f32()) * 0.5)
.max(0.0);
window.paint_quad(quad(
rect,
px(radius),
color,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
}
fn paint_icon(
icon: IconName,
center: Point<Pixels>,
d: f32,
color: Hsla,
window: &mut Window,
cx: &App,
) {
let _ = window.paint_svg(
bounds(center - point(px(d * 0.5), px(d * 0.5)), size(px(d), px(d))),
icon.path(),
None,
Default::default(),
color,
cx,
);
}
fn paint_label(
text: SharedString,
center: Point<Pixels>,
color: Hsla,
window: &mut Window,
cx: &mut App,
) {
let text: SharedString = text.replace(['\n', '\r'], " ").into();
let line = window.text_system().shape_line(
text.clone(),
px(12.0),
&[TextRun {
len: text.len(),
font: window.text_style().font(),
color,
..Default::default()
}],
None,
);
let _ = line.paint(
center - point(line.width * 0.5, px(8.0)),
px(16.0),
TextAlign::Left,
None,
window,
cx,
);
}
#[cfg(test)]
mod tests {
use super::*;
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, TestAppContext,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use std::cell::Cell;
struct PlayerHost {
state: MusicPlayerState,
disabled: bool,
controlled: bool,
events: Rc<std::cell::RefCell<Vec<MusicPlayerEvent>>>,
}
impl Render for PlayerHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let events = self.events.clone();
div().w_full().p(Spacing::S4).child(
MusicPlayer::new("full-player")
.track(MusicTrack::new("Cirrus", "Open Skies", 216.0))
.config(MusicPlayerConfig {
disabled: self.disabled,
..Default::default()
})
.when(self.controlled, |player| player.state(self.state))
.on_event(cx.listener(move |this, event: &MusicPlayerEvent, _, cx| {
events.borrow_mut().push(*event);
if this.controlled {
this.state.apply(*event, 216.0);
}
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn music_player_full_transport_seek_volume_and_disabled(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let events = Rc::new(std::cell::RefCell::new(Vec::new()));
let (view, cx) = cx.add_window_view(|_, _| PlayerHost {
state: MusicPlayerState {
position: 85.0,
..Default::default()
},
disabled: false,
controlled: true,
events: events.clone(),
});
cx.simulate_resize(size(px(900.0), px(600.0)));
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
let click_label = |label: &str, window: &mut Window, cx: &mut App| {
let at = window.find_by_label(label).bounds().center();
window.pointer_down(at, MouseButton::Left, cx);
window.pointer_up(at, MouseButton::Left, cx);
};
click_label("播放", window, cx);
window.render_frame(cx);
assert!(view.read(cx).state.playing);
click_label("暂停", window, cx);
window.render_frame(cx);
assert!(!view.read(cx).state.playing);
click_label("下一首", window, cx);
window.render_frame(cx);
assert_eq!(view.read(cx).state.position, 0.0);
click_label("上一首", window, cx);
window.render_frame(cx);
click_label("静音", window, cx);
window.render_frame(cx);
assert!(view.read(cx).state.muted);
click_label("取消静音", window, cx);
window.render_frame(cx);
assert!(!view.read(cx).state.muted);
let seek = window.find_by_label("播放进度").bounds();
window.pointer_down(seek.center(), MouseButton::Left, cx);
window.render_frame(cx);
window.pointer_up(seek.center(), MouseButton::Left, cx);
window.press("end", cx);
window.render_frame(cx);
assert_eq!(view.read(cx).state.position, 216.0);
let volume = window.find_by_label("播放器音量").bounds();
window.pointer_down(volume.center(), MouseButton::Left, cx);
window.render_frame(cx);
window.pointer_up(volume.center(), MouseButton::Left, cx);
window.press("home", cx);
window.render_frame(cx);
assert_eq!(view.read(cx).state.volume, 0.0);
assert!(view.read(cx).state.muted);
let count = events.borrow().len();
view.update(cx, |v, cx| {
v.disabled = true;
cx.notify();
});
window.render_frame(cx);
click_label("播放", window, cx);
window.render_frame(cx);
assert_eq!(events.borrow().len(), count);
assert!(events.borrow().contains(&MusicPlayerEvent::Previous));
assert!(events.borrow().contains(&MusicPlayerEvent::Next));
});
}
#[gpui_kit::test]
fn music_player_uncontrolled_persists_and_resizes_in_both_themes(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let (_, cx) = cx.add_window_view(|_, _| PlayerHost {
state: Default::default(),
disabled: false,
controlled: false,
events: Rc::new(std::cell::RefCell::new(Vec::new())),
});
for width in [900.0, 600.0, 360.0, 900.0] {
cx.simulate_resize(size(px(width), px(800.0)));
for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
cx.update(|window, cx| {
install_arc_theme(mode, Accent::Neutral, cx);
for _ in 0..3 {
window.render_frame(cx);
}
let player = window.find("full-player").bounds();
let seek = window.find_by_label("播放进度").bounds();
let next = window.find_by_label("下一首").bounds();
let volume = window.find_by_label("播放器音量").bounds();
assert!(player.size.width <= px(width));
assert!(seek.right() <= player.right(), "进度不溢出播放器");
assert!(volume.right() <= player.right(), "音量不溢出播放器");
assert!(
next.right() <= volume.left() || next.bottom() <= volume.top(),
"切歌与音量不重叠"
);
});
}
}
cx.update(|window, cx| {
let at = window.find_by_label("播放").bounds().center();
window.pointer_down(at, MouseButton::Left, cx);
window.pointer_up(at, MouseButton::Left, cx);
window.render_frame(cx);
window.render_frame(cx);
assert!(window.find_by_label("暂停").bounds().size.width > px(0.0));
});
}
#[test]
fn music_player_state_and_time_are_sanitized() {
let mut state = MusicPlayerState::default();
state.apply(MusicPlayerEvent::Seek(f32::NAN), 216.0);
assert_eq!(state.position, 0.0);
state.apply(MusicPlayerEvent::Seek(999.0), 216.0);
assert_eq!(state.position, 216.0);
state.apply(MusicPlayerEvent::Volume(-1.0), 216.0);
assert!(state.muted);
state.apply(MusicPlayerEvent::Muted(false), 216.0);
assert_eq!(state.volume, 65.0);
assert_eq!(time_label(85.0), "1:25");
assert_eq!(time_label(131.0), "2:11");
}
struct Host {
value: f32,
config: PlayerRailConfig,
commits: Rc<Cell<usize>>,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let commits = self.commits.clone();
div().p(px(80.0)).child(
PlayerRail::new("rb-test")
.aria_label("RB test")
.value(self.value)
.config(self.config.clone())
.on_change(cx.listener(|this, value: &f32, _, cx| {
this.value = *value;
cx.notify();
}))
.on_change_end(move |_, _, _| commits.set(commits.get() + 1)),
)
}
}
#[gpui_kit::test]
fn music_player_drag_keyboard_vertical_and_disabled(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let commits = Rc::new(Cell::new(0));
let (view, cx) = cx.add_window_view(|_, _| Host {
value: 50.0,
config: PlayerRailConfig {
is_stepped: true,
step_size: 10.0,
..Default::default()
},
commits: commits.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let control = window.find_by_label("RB test");
assert_eq!(control.role(), Some(Role::Slider));
let rect = control.bounds();
let center = rect.center();
window.pointer_down(center, MouseButton::Left, cx);
window.render_frame(cx);
let end = point(rect.right() + px(70.0), center.y);
window.pointer_move(end, Some(MouseButton::Left), cx);
window.render_frame(cx);
window.pointer_up(end, MouseButton::Left, cx);
assert_eq!(view.read(cx).value, 100.0);
assert_eq!(commits.get(), 1);
window.press("home", cx);
window.press("right", cx);
assert_eq!(view.read(cx).value, 10.0);
assert_eq!(commits.get(), 3);
view.update(cx, |v, cx| {
v.config.orientation = Orientation::Vertical;
v.config.jump_to_click = false;
v.value = 50.0;
cx.notify();
});
window.render_frame(cx);
let rect = window.find_by_label("RB test").bounds();
window.pointer_down(rect.center(), MouseButton::Left, cx);
assert_eq!(view.read(cx).value, 50.0, "相对拖动按下不跳值");
window.render_frame(cx);
let top = point(rect.center().x, rect.top() - px(50.0));
window.pointer_move(top, Some(MouseButton::Left), cx);
window.render_frame(cx);
window.pointer_up(top, MouseButton::Left, cx);
assert_eq!(view.read(cx).value, 100.0, "竖向上拖增加数值");
assert_eq!(commits.get(), 4);
view.update(cx, |v, cx| {
v.config.disabled = true;
cx.notify();
});
window.render_frame(cx);
window.press("home", cx);
assert_eq!(view.read(cx).value, 100.0);
assert_eq!(commits.get(), 4);
});
}
#[gpui_kit::test]
fn music_player_wheel_debounces_commit(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let commits = Rc::new(Cell::new(0));
let (view, cx) = cx.add_window_view(|_, _| Host {
value: 50.0,
config: PlayerRailConfig {
wheel: true,
is_stepped: true,
step_size: 10.0,
..Default::default()
},
commits: commits.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
window.scroll(
"rb-test",
gpui_kit::ScrollDelta::Pixels(point(px(0.0), px(-30.0))),
cx,
);
window.render_frame(cx);
window.scroll(
"rb-test",
gpui_kit::ScrollDelta::Pixels(point(px(0.0), px(-30.0))),
cx,
);
window.render_frame(cx);
assert_eq!(view.read(cx).value, 70.0);
assert_eq!(commits.get(), 0);
});
cx.executor().run_until_parked();
cx.executor()
.advance_clock(std::time::Duration::from_millis(250));
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
});
cx.executor().run_until_parked();
cx.update(|window, cx| {
window.render_frame(cx);
});
assert_eq!(commits.get(), 1);
}
#[gpui_kit::test]
fn music_player_centered_fill_and_theme_geometry(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let (_, cx) = cx.add_window_view(|_, _| Host {
value: 25.0,
config: PlayerRailConfig {
fill_from: Some(50.0),
thickness: 32.0,
active_thickness: 40.0,
ticks: PlayerRailTicks::Auto,
icon_placement: PlayerRailIconPlacement::Inside,
value_position: PlayerRailValuePosition::Inside,
..Default::default()
},
commits: Rc::new(Cell::new(0)),
});
for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
cx.update(|window, cx| {
install_arc_theme(mode, Accent::Neutral, cx);
window.render_frame(cx);
let fill = alpha(cx.arc_theme().colors.foreground, 0.7);
let quads = window.painted_quads();
let painted = quads
.iter()
.find(|q| q.background == fill.into() && q.bounds.size.height.as_f32() >= 32.0)
.expect("填充必须有实际绘制几何");
assert!(painted.bounds.size.width.as_f32() > 50.0);
assert!(painted.corner_radii.top_left.as_f32() <= 16.0);
});
}
}
#[test]
fn music_player_defaults_and_continuous_values() {
let c = PlayerRailConfig::default();
assert_eq!(c.snap(22.25), 22.25);
assert_eq!(c.max_stretch, 50.0);
assert!(!c.thumb);
assert_eq!(c.value_position, PlayerRailValuePosition::Top);
}
#[test]
fn music_player_snap_ticks_and_invalid_inputs() {
let mut c = PlayerRailConfig {
starting_value: 100.0,
max_value: -100.0,
is_stepped: true,
step_size: 10.0,
ticks: PlayerRailTicks::Auto,
thickness: f32::NAN,
bounce: 4.0,
..Default::default()
}
.normalized();
assert_eq!(c.snap(-94.0), -90.0);
assert_eq!(c.fraction(0.0), 0.5);
assert_eq!(c.marks().len(), 19);
assert_eq!(c.thickness, 6.0);
assert_eq!(c.bounce, 0.95);
c.ticks = PlayerRailTicks::Values(vec![f32::NAN, -200.0, 0.0, 0.0, 200.0]);
assert_eq!(c.marks(), vec![0.5]);
}
#[test]
fn music_player_rubber_matches_source_sigmoid() {
for d in [0.0, 5.0, 20.0, 50.0, 200.0] {
let reference = 2.0 * (1.0 / (1.0 + (-d / 50.0_f32).exp()) - 0.5) * 50.0;
assert!((rubber(d, 50.0) - reference).abs() < 0.0001);
}
assert_eq!(rubber(100.0, 0.0), 0.0);
assert!(rubber(f32::MAX, 50.0).is_finite());
}
}