use std::{cell::RefCell, rc::Rc};
use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, CubicBezierSpec, hex, oklab_mix};
use gpui_kit::{
App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};
pub const FLIP_POINT: f32 = 0.4;
pub const PRESS_SCALE: f32 = 0.97;
pub const COUNT_SIZE_RATIO: f32 = 0.5;
const EASE_OUT: CubicBezierSpec = CubicBezierSpec::new(0.23, 1.0, 0.32, 1.0);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PulseHeartGlyph {
Heart,
Star,
Thumb,
}
#[derive(Clone, Copy, Debug)]
pub struct PulseHeartConfig {
pub size: f32,
pub corner: f32,
pub duration_ms: f32,
pub dot_size: f32,
pub overshoot: f32,
pub beat: f32,
pub roll_duration_ms: f32,
pub show_count: bool,
pub idle_outline: bool,
pub liked_color: Hsla,
pub idle_color: Hsla,
pub pill_color: Hsla,
pub text_color: Hsla,
pub disabled: bool,
}
impl Default for PulseHeartConfig {
fn default() -> Self {
Self {
size: 40.0,
corner: 32.0,
duration_ms: 560.0,
dot_size: 0.3,
overshoot: 1.7,
beat: 3.0,
roll_duration_ms: 350.0,
show_count: true,
idle_outline: true,
liked_color: hex(0xff4d6d, 1.0),
idle_color: Hsla::transparent_black(),
pill_color: Hsla::transparent_black(),
text_color: Hsla::transparent_black(),
disabled: false,
}
}
}
impl PulseHeartConfig {
fn resolve_theme(mut self, colors: arc_tokens::ArcColors) -> Self {
if self.idle_color.a == 0.0 {
self.idle_color = colors.text_secondary;
}
if self.text_color.a == 0.0 {
self.text_color = colors.foreground;
}
self
}
fn normalized(mut self) -> Self {
self.size = self.size.clamp(20.0, 96.0);
self.corner = self.corner.clamp(0.0, self.size);
self.duration_ms = self.duration_ms.clamp(120.0, 2000.0);
self.dot_size = self.dot_size.clamp(0.0, 0.9);
self.overshoot = self.overshoot.clamp(0.0, 4.0);
self.beat = self.beat.clamp(0.0, 20.0);
self.roll_duration_ms = self.roll_duration_ms.clamp(60.0, 1000.0);
self
}
}
pub type PulseHeartChange = (bool, i64);
type ChangeHandler = Rc<dyn Fn(&PulseHeartChange, &mut Window, &mut App)>;
fn back_ease(u: f32, c: f32) -> f32 {
let t = u.clamp(0.0, 1.0);
let s = t - 1.0;
1.0 + (c + 1.0) * s * s * s + c * s * s
}
pub fn pulse_swell(t: f32, overshoot: f32) -> f32 {
if t <= 0.0 {
return 0.0;
}
if t < FLIP_POINT {
let u = t / FLIP_POINT;
1.0 - (1.0 - u) * (1.0 - u) * (1.0 - u)
} else {
1.0 - back_ease((t - FLIP_POINT) / (1.0 - FLIP_POINT), overshoot)
}
}
pub fn pulse_format_count(n: i64) -> String {
let neg = n < 0;
let digits = n.unsigned_abs().to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3 + 1);
if neg {
out.push('-');
}
for (i, ch) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(ch);
}
out
}
#[derive(Clone)]
struct PulseState {
uncontrolled_liked: bool,
uncontrolled_count: i64,
run_started_at: Option<f64>,
pending: Option<(bool, i64)>,
roll: Option<(i64, i64, f64)>,
hovered: bool,
pressed: bool,
}
impl PulseState {
fn new(default_liked: bool, count: i64) -> Self {
Self {
uncontrolled_liked: default_liked,
uncontrolled_count: count,
run_started_at: None,
pending: None,
roll: None,
hovered: false,
pressed: false,
}
}
}
#[derive(IntoElement)]
pub struct PulseHeart {
id: ElementId,
label: SharedString,
liked: Option<bool>,
default_liked: bool,
count: i64,
config: PulseHeartConfig,
on_change: Option<ChangeHandler>,
}
impl PulseHeart {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
label: "Like".into(),
liked: None,
default_liked: false,
count: 0,
config: PulseHeartConfig::default(),
on_change: None,
}
}
pub fn label(mut self, v: impl Into<SharedString>) -> Self {
self.label = v.into();
self
}
pub fn liked(mut self, v: bool) -> Self {
self.liked = Some(v);
self
}
pub fn default_liked(mut self, v: bool) -> Self {
self.default_liked = v;
self
}
pub fn count(mut self, v: i64) -> Self {
self.count = v;
self
}
pub fn config(mut self, cfg: PulseHeartConfig) -> Self {
self.config = cfg;
self
}
pub fn on_change(
mut self,
handler: impl Fn(&PulseHeartChange, &mut Window, &mut App) + 'static,
) -> Self {
self.on_change = Some(Rc::new(handler));
self
}
}
pub fn pulse_roll_plan(from: i64, to: i64) -> (usize, bool) {
let up = to > from;
let a = pulse_format_count(from);
let b = pulse_format_count(to);
if a.len() == b.len() {
let changed: Vec<usize> = a
.chars()
.zip(b.chars())
.enumerate()
.filter_map(|(i, (ca, cb))| (ca != cb).then_some(i))
.collect();
if changed.len() == 1 {
return (changed[0], up);
}
}
(usize::MAX, up)
}
impl RenderOnce for PulseHeart {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let cfg = self
.config
.normalized()
.resolve_theme(cx.arc_theme().colors);
let state_id = ElementId::NamedChild(self.id.clone().into(), "pulse-state".into());
let state_cell = window
.use_keyed_state(state_id, cx, |_, _| {
Rc::new(RefCell::new(PulseState::new(
self.default_liked,
self.count,
)))
})
.read(cx)
.clone();
let is_controlled = self.liked.is_some();
let (logical_liked, logical_count) = {
let st = state_cell.borrow();
(
self.liked.unwrap_or(st.uncontrolled_liked),
if is_controlled {
self.count
} else {
st.uncontrolled_count
},
)
};
{
let mut st = state_cell.borrow_mut();
let shown_target = st.pending.unwrap_or((logical_liked, logical_count));
let shown_count = shown_target.1;
if shown_count != logical_count && st.roll.is_none() {
st.roll = Some((shown_count, logical_count, now));
} else if shown_count == logical_count {
st.roll = None;
}
}
let run_secs = (f64::from(cfg.duration_ms) / 1000.0).max(1e-3);
let mut running = false;
let (shown_liked, shown_count) = {
let mut st = state_cell.borrow_mut();
if let Some(start) = st.run_started_at {
let t = ((now - start) / run_secs) as f32;
if t >= 1.0 {
st.run_started_at = None;
let done = st.pending.take();
if let Some((liked, count)) = done {
if !is_controlled {
st.uncontrolled_liked = liked;
st.uncontrolled_count = count;
}
(liked, count)
} else {
(logical_liked, logical_count)
}
} else {
running = true;
st.pending.unwrap_or((logical_liked, logical_count))
}
} else {
(logical_liked, logical_count)
}
};
if running || state_cell.borrow().roll.is_some() {
window.request_animation_frame();
}
let run_t = state_cell
.borrow()
.run_started_at
.map(|start| (((now - start) / run_secs) as f32).clamp(0.0, 1.0))
.unwrap_or(1.0);
let swell = if running && !reduced {
pulse_swell(run_t, cfg.overshoot)
} else {
0.0
};
let glyph_scale = (1.0 - (1.0 - cfg.dot_size) * swell).clamp(cfg.dot_size, 1.35);
let pill_scale = 1.0 - (cfg.beat / 100.0) * swell;
let roll_secs = (f64::from(cfg.roll_duration_ms) / 1000.0).max(1e-3);
let roll_state = state_cell.borrow().roll;
let roll_info = roll_state.map(|(from, to, at)| {
let u = (((now - at) / roll_secs) as f32).clamp(0.0, 1.0);
let (idx, up) = pulse_roll_plan(from, to);
(to, idx, up, u)
});
if roll_info
.as_ref()
.map(|(_, _, _, u)| *u >= 1.0)
.unwrap_or(false)
{
state_cell.borrow_mut().roll = None;
}
let roll = roll_info.filter(|r| r.3 < 1.0);
let shown_display = roll.as_ref().map(|_| shown_count).unwrap_or(shown_count);
let text = pulse_format_count(shown_display);
let next_text = roll
.as_ref()
.map(|(to, _, _, _)| pulse_format_count(*to))
.unwrap_or_else(|| text.clone());
let liked = shown_liked;
let glyph_color = if liked {
cfg.liked_color
} else if !reduced && cfg.idle_outline && state_cell.borrow().hovered && !cfg.disabled {
oklab_mix(cfg.idle_color, cfg.liked_color, 0.45)
} else {
cfg.idle_color
};
let glyph_alpha = if !liked && !cfg.idle_outline {
0.55
} else {
1.0
};
let glyph_paint = Hsla {
a: glyph_color.a * glyph_alpha,
..glyph_color
};
let press = if reduced {
1.0
} else {
let pressed = state_cell.borrow().pressed && !cfg.disabled;
if pressed { PRESS_SCALE } else { 1.0 }
};
let stroke_w = (1.5 * cfg.size / 24.0).max(1.0);
let gap = cfg.size * 0.25;
let pad_x0 = cfg.size * 0.3;
let pad_end = if cfg.show_count {
cfg.size * 0.4
} else {
cfg.size * 0.3
};
let font_size = cfg.size * COUNT_SIZE_RATIO;
let corner = if cfg.show_count {
px(cfg.corner)
} else {
px(cfg.size.min(cfg.corner + cfg.size * 0.1))
};
let glyph = self.glyph_kind();
let glyph_id = ElementId::NamedChild(self.id.clone().into(), "glyph".into());
let pill_id = ElementId::NamedChild(self.id.clone().into(), "pill".into());
let glyph_canvas = div().id(glyph_id).size(px(cfg.size)).flex_none().child(
canvas(
move |_, _, _| {},
move |rect, _, window, _| {
let ox = f32::from(rect.origin.x);
let oy = f32::from(rect.origin.y);
let s = f32::from(rect.size.width).min(f32::from(rect.size.height)) / 24.0;
if s <= 0.0 {
return;
}
let cv = PulseCanvas { ox, oy, scale: s };
draw_pulse_glyph(cv, glyph, glyph_scale, stroke_w, glyph_paint, liked, window);
},
)
.size_full(),
);
let count_el = if cfg.show_count {
Some(
div()
.relative()
.text_size(px(font_size))
.font_semibold()
.text_color(cfg.text_color)
.child(render_count_cells(
self.id.clone(),
&text,
&next_text,
roll.as_ref().map(|(_, idx, up, u)| (*idx, *up, *u)),
reduced,
font_size,
)),
)
} else {
None
};
let pill_inner = div()
.id(pill_id)
.flex()
.items_center()
.gap(px(gap))
.pl(px(pad_x0))
.pr(px(pad_end))
.rounded(corner)
.bg(cfg.pill_color)
.child(glyph_canvas)
.when_some(count_el, |el, c| el.child(c));
let beat_pad = (cfg.beat / 100.0) * swell;
let _ = pill_scale;
let press_scale_pad = 1.0 - press;
let root = div()
.id(self.id.clone())
.test_support()
.role(Role::Button)
.aria_label(format!(
"{}, {}",
self.label,
pulse_format_count(logical_count)
))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.when(cfg.disabled, |el| el.opacity(0.55))
.when(!cfg.disabled, |el| {
el.on_hover({
let cell = state_cell.clone();
move |hovered: &bool, window, _| {
cell.borrow_mut().hovered = *hovered;
if !*hovered {
cell.borrow_mut().pressed = false;
}
window.refresh();
}
})
.on_mouse_down(MouseButton::Left, {
let cell = state_cell.clone();
let disabled = cfg.disabled;
move |_, window, _| {
if disabled {
return;
}
cell.borrow_mut().pressed = true;
window.refresh();
}
})
.on_mouse_up(MouseButton::Left, {
let cell = state_cell.clone();
let on_change = self.on_change.clone();
move |_, window, cx| {
let now_t = motion_now(cx);
let mut payload = None;
{
let mut st = cell.borrow_mut();
st.pressed = false;
if !cfg.disabled && st.run_started_at.is_none() {
let base = if is_controlled {
(logical_liked, logical_count)
} else {
(st.uncontrolled_liked, st.uncontrolled_count)
};
let next_liked = !base.0;
let next_count = base.1 + if next_liked { 1 } else { -1 };
if !is_controlled {
st.uncontrolled_liked = next_liked;
st.uncontrolled_count = next_count;
}
if !reduced {
st.run_started_at = Some(now_t);
st.pending = Some((next_liked, next_count));
} else if !is_controlled {
}
payload = Some((next_liked, next_count));
}
}
if let Some(p) = payload
&& let Some(cb) = &on_change
{
cb(&p, window, cx);
}
window.refresh();
}
})
.on_mouse_up_out(MouseButton::Left, {
let cell = state_cell.clone();
move |_, window, _| {
cell.borrow_mut().pressed = false;
window.refresh();
}
})
})
.pl(px(
beat_pad * cfg.size * 0.5 + press_scale_pad * cfg.size * 0.15
))
.pr(px(
beat_pad * cfg.size * 0.5 + press_scale_pad * cfg.size * 0.15
))
.pt(px(
beat_pad * cfg.size * 0.5 + press_scale_pad * cfg.size * 0.3
))
.pb(px(
beat_pad * cfg.size * 0.5 + press_scale_pad * cfg.size * 0.3
))
.rounded(corner)
.child(pill_inner);
let _ = EASE_OUT;
root
}
}
impl PulseHeart {
fn glyph_kind(&self) -> PulseHeartGlyph {
PulseHeartGlyph::Heart
}
}
fn render_count_cells(
parent: ElementId,
text: &str,
next_text: &str,
roll: Option<(usize, bool, f32)>,
reduced: bool,
line_h: f32,
) -> gpui_kit::AnyElement {
let chars: Vec<char> = text.chars().collect();
let next_chars: Vec<char> = next_text.chars().collect();
let ease = CubicBezier::from_spec(EASE_OUT);
let mut cells: Vec<gpui_kit::AnyElement> = Vec::with_capacity(chars.len());
for (i, ch) in chars.iter().enumerate() {
let id = ElementId::NamedChild(parent.clone().into(), format!("cell-{i}").into());
let is_rolling = match roll {
Some((idx, _, _)) => idx != usize::MAX && idx == i,
None => false,
};
if !is_rolling || reduced {
cells.push(
div()
.h(px(line_h))
.line_height(px(line_h))
.child(ch.to_string())
.into_any_element(),
);
continue;
}
let (_, up, u) = roll.unwrap();
let e = ease.sample(u.clamp(0.0, 1.0));
let old_ch = *ch;
let new_ch = next_chars.get(i).copied().unwrap_or(old_ch);
let y = if up { -e } else { e };
cells.push(
div()
.id(id)
.relative()
.overflow_hidden()
.h(px(line_h))
.child(
div()
.relative()
.flex()
.flex_col()
.top(px(y * line_h))
.child(
div()
.h(px(line_h))
.line_height(px(line_h))
.child(old_ch.to_string()),
)
.child(
div()
.h(px(line_h))
.line_height(px(line_h))
.child(new_ch.to_string()),
),
)
.into_any_element(),
);
}
div().flex().children(cells).into_any_element()
}
#[derive(Clone, Copy)]
struct PulseCanvas {
ox: f32,
oy: f32,
scale: f32,
}
impl PulseCanvas {
fn stroke_polyline(
self,
sw: f32,
pts: &[(f32, f32)],
closed: bool,
color: Hsla,
window: &mut Window,
) {
if color.a <= 0.005 || pts.len() < 2 {
return;
}
let mut b = gpui_kit::PathBuilder::stroke(px(sw * self.scale));
for (i, (x, y)) in pts.iter().enumerate() {
let p = point(px(self.ox + x * self.scale), px(self.oy + y * self.scale));
if i == 0 {
b.move_to(p);
} else {
b.line_to(p);
}
}
if closed {
b.close();
}
if let Ok(path) = b.build() {
window.paint_path(path, color);
}
}
fn fill_polygon(self, pts: &[(f32, f32)], color: Hsla, window: &mut Window) {
if color.a <= 0.005 || pts.len() < 3 {
return;
}
let mut b = gpui_kit::PathBuilder::fill();
for (i, (x, y)) in pts.iter().enumerate() {
let p = point(px(self.ox + x * self.scale), px(self.oy + y * self.scale));
if i == 0 {
b.move_to(p);
} else {
b.line_to(p);
}
}
b.close();
if let Ok(path) = b.build() {
window.paint_path(path, color);
}
}
}
fn pulse_heart_points(scale: f32) -> Vec<(f32, f32)> {
let mut pts = Vec::with_capacity(32);
for i in 0..32 {
let t = std::f32::consts::TAU * (i as f32 / 32.0);
let hx = 16.0 * t.sin().powi(3);
let hy =
-(13.0 * t.cos() - 5.0 * (2.0 * t).cos() - 2.0 * (3.0 * t).cos() - (4.0 * t).cos());
pts.push((12.0 + hx * 0.60 * scale, 11.4 + hy * 0.56 * scale));
}
pts
}
fn pulse_star_points(scale: f32) -> Vec<(f32, f32)> {
let (cx, cy) = (12.0, 12.6);
let (r_out, r_in) = (9.2 * scale, 3.9 * scale);
let mut pts = Vec::with_capacity(11);
for i in 0..10 {
let a = -std::f32::consts::FRAC_PI_2 + (i as f32) * std::f32::consts::PI / 5.0;
let r = if i % 2 == 0 { r_out } else { r_in };
pts.push((cx + r * a.cos(), cy + r * a.sin()));
}
pts
}
fn pulse_thumb_points(scale: f32) -> Vec<(f32, f32)> {
let o = |v: f32| 12.0 + (v - 12.0) * scale;
vec![
(o(7.0), o(11.0)),
(o(7.0), o(21.0)),
(o(4.0), o(21.0)),
(o(4.0), o(11.0)),
(o(7.0), o(11.0)),
(o(9.0), o(11.0)),
(o(9.0), o(4.0)),
(o(10.2), o(2.8)),
(o(11.6), o(3.0)),
(o(13.0), o(5.0)),
(o(13.0), o(11.0)),
(o(19.4), o(11.0)),
(o(20.6), o(12.0)),
(o(19.8), o(15.4)),
(o(17.6), o(19.6)),
(o(16.6), o(21.0)),
(o(7.0), o(21.0)),
]
}
#[allow(clippy::too_many_arguments)]
fn draw_pulse_glyph(
cv: PulseCanvas,
glyph: PulseHeartGlyph,
scale: f32,
stroke_w: f32,
color: Hsla,
liked: bool,
window: &mut Window,
) {
let fill = if liked || color.a < 0.99 {
color
} else {
Hsla::transparent_black()
};
match glyph {
PulseHeartGlyph::Heart => {
let pts = pulse_heart_points(scale);
if liked {
cv.fill_polygon(&pts, color, window);
}
cv.stroke_polyline(stroke_w, &pts, true, color, window);
}
PulseHeartGlyph::Star => {
let pts = pulse_star_points(scale);
if liked {
cv.fill_polygon(&pts, color, window);
}
cv.stroke_polyline(stroke_w, &pts, true, color, window);
}
PulseHeartGlyph::Thumb => {
let pts = pulse_thumb_points(1.0);
if liked {
cv.fill_polygon(&pts, color, window);
}
cv.stroke_polyline(stroke_w, &pts, false, color, window);
}
}
let _ = fill;
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestWindowExt as _},
};
use super::*;
#[gpui_kit::test]
fn pulse_heart_theme_defaults_keep_background_transparent(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
install_arc_theme(mode, Accent::Neutral, cx);
let colors = cx.arc_theme().colors;
let cfg = PulseHeartConfig::default().resolve_theme(colors);
assert_eq!(cfg.pill_color.a, 0.0);
assert_eq!(cfg.text_color, colors.foreground);
assert_eq!(cfg.idle_color, colors.text_secondary);
let custom = PulseHeartConfig {
pill_color: colors.danger,
text_color: colors.background,
..Default::default()
}
.resolve_theme(colors);
assert_eq!(custom.pill_color, colors.danger);
assert_eq!(custom.text_color, colors.background);
}
});
}
struct Host {
events: Rc<std::cell::RefCell<Vec<(bool, i64)>>>,
count: i64,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let events = self.events.clone();
let count = self.count;
div().size_full().child(
PulseHeart::new("ph-test")
.count(count)
.on_change(cx.listener(move |_, payload: &PulseHeartChange, _, _| {
events.borrow_mut().push(*payload);
})),
)
}
}
fn setup(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
}
#[gpui_kit::test]
fn pulse_swell_matches_source_envelope() {
assert!((pulse_swell(0.0, 1.7)).abs() < 1e-5);
assert!((pulse_swell(FLIP_POINT, 1.7) - 1.0).abs() < 1e-4);
let rebound = pulse_swell(0.75, 1.7);
assert!(rebound < 0.0, "overshoot 应越过静止点:{rebound}");
assert!((pulse_swell(1.0, 1.7)).abs() < 1e-4);
assert!(pulse_swell(0.75, 0.0) <= 1.0 + 1e-4);
assert!((pulse_swell(1.0, 0.0)).abs() < 1e-4);
}
#[gpui_kit::test]
fn pulse_format_and_roll_plan() {
assert_eq!(pulse_format_count(1204), "1,204");
assert_eq!(pulse_format_count(-42), "-42");
assert_eq!(pulse_format_count(7), "7");
let (idx, up) = pulse_roll_plan(1203, 1204);
assert_ne!(idx, usize::MAX);
assert!(up);
let (idx2, _) = pulse_roll_plan(999, 1000);
assert_eq!(idx2, usize::MAX);
}
#[gpui_kit::test]
fn pulse_press_toggles_and_reports(cx: &mut TestAppContext) {
setup(cx);
let events = Rc::new(std::cell::RefCell::new(Vec::new()));
let (view, cx) = cx.add_window_view(|_, _| Host {
events: events.clone(),
count: 1204,
});
cx.update(|window, cx| {
window.render_frame(cx);
let b = window.find("ph-test").bounds();
let pos = b.center();
window.pointer_down(pos, gpui_kit::MouseButton::Left, cx);
window.pointer_up(pos, gpui_kit::MouseButton::Left, cx);
window.render_frame(cx);
let ev = events.borrow().clone();
assert_eq!(ev, vec![(true, 1205)]);
});
assert_eq!(view.read_with(cx, |v, _| v.count), 1204);
}
#[gpui_kit::test]
fn pulse_button_has_button_role(cx: &mut TestAppContext) {
setup(cx);
let events = Rc::new(std::cell::RefCell::new(Vec::new()));
let (_view, cx) = cx.add_window_view(|_, _| Host { events, count: 3 });
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(window.find("ph-test").role(), Some(Role::Button));
});
}
}