use arc_motion::{PathPoint, PolylinePath, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
App, Bounds, ContentMask, ElementId, Hsla, IntoElement, ParentElement, PathBuilder, Pixels,
RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, canvas, div, point,
prelude::*, px, rgb, size,
};
use std::{
cell::RefCell,
collections::HashMap,
rc::Rc,
sync::{Arc, Mutex, OnceLock},
};
use super::glyph_outline::{Outline, with_face};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StrokeStyle {
#[default]
Solid,
Dashed,
Dotted,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StrokeFill {
#[default]
Fade,
Wipe,
None,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StrokeTrigger {
#[default]
Mount,
Hover,
Scroll,
Loop,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WipeFrom {
#[default]
Left,
Right,
Top,
Bottom,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StrokeEase {
#[default]
Power2Out,
Linear,
Power2InOut,
Power3Out,
}
impl StrokeEase {
pub fn sample(self, t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
match self {
Self::Linear => t,
Self::Power2Out => 1.0 - (1.0 - t).powi(3),
Self::Power3Out => 1.0 - (1.0 - t).powi(4),
Self::Power2InOut => {
if t < 0.5 {
4.0 * t.powi(3)
} else {
1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
}
}
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct StrokeTextConfig {
pub stroke_color: Hsla,
pub fill_color: Option<Hsla>,
pub shadow_color: Option<Hsla>,
pub stroke_style: StrokeStyle,
pub stroke_width: f32,
pub dash_length: f32,
pub draw_duration: f64,
pub fill_delay: f64,
pub stagger: f64,
pub ease: StrokeEase,
pub trigger: StrokeTrigger,
pub fill_mode: StrokeFill,
pub wipe_from: WipeFrom,
pub font_size: f32,
pub font_weight: u16,
pub font_family: String,
pub letter_spacing: f32,
pub reverse: bool,
pub marching: bool,
pub hover_redraw: bool,
pub shadow: bool,
}
impl Default for StrokeTextConfig {
fn default() -> Self {
Self {
stroke_color: rgb(0xA78BFA).into(),
fill_color: None,
shadow_color: None,
stroke_style: StrokeStyle::Solid,
stroke_width: 1.4,
dash_length: 10.0,
draw_duration: 1.9,
fill_delay: 0.2,
stagger: 0.05,
ease: StrokeEase::Power2Out,
trigger: StrokeTrigger::Mount,
fill_mode: StrokeFill::Fade,
wipe_from: WipeFrom::Left,
font_size: 128.0,
font_weight: 800,
font_family: Typography::display_family().into(),
letter_spacing: -4.0,
reverse: false,
marching: false,
hover_redraw: true,
shadow: false,
}
}
}
impl StrokeTextConfig {
pub fn duration(&self, count: usize) -> f64 {
let tail = count.saturating_sub(1) as f64 * self.stagger.max(0.0);
let draw = self.draw_duration.max(0.05);
let end = draw + tail;
if self.fill_mode == StrokeFill::None {
end
} else {
end.max(
draw + self.fill_delay.max(0.0)
+ (draw * 0.5).max(0.4)
+ if self.fill_mode == StrokeFill::Fade {
tail
} else {
0.0
},
)
}
}
pub fn sample(&self, elapsed: f64, index: usize, count: usize, reduced: bool) -> (f32, f32) {
if reduced {
return (
1.0,
if self.fill_mode == StrokeFill::None {
0.0
} else {
1.0
},
);
}
let rank = if self.reverse {
count.saturating_sub(index + 1)
} else {
index
};
let draw = self.draw_duration.max(0.05);
let delay = rank as f64 * self.stagger.max(0.0);
let outline = self.ease.sample(((elapsed - delay) / draw) as f32);
let fill_delay = if self.fill_mode == StrokeFill::Fade {
delay
} else {
0.0
};
let t = ((elapsed - draw - self.fill_delay.max(0.0) - fill_delay) / (draw * 0.5).max(0.4))
as f32;
let fill = match self.fill_mode {
StrokeFill::None => 0.0,
StrokeFill::Fade => StrokeEase::Power2Out.sample(t),
StrokeFill::Wipe => StrokeEase::Power2InOut.sample(t),
};
(outline, fill)
}
}
#[derive(Clone, Debug)]
struct Glyph {
contours: Vec<PolylinePath>,
}
#[derive(Clone, Debug)]
struct Word {
glyphs: Vec<Glyph>,
width: f32,
height: f32,
top: f32,
}
type WordResult = Result<Arc<Word>, String>;
static WORDS: OnceLock<Mutex<HashMap<String, Arc<Word>>>> = OnceLock::new();
fn geometry_key(text: &str, config: &StrokeTextConfig) -> String {
format!(
"{}|{}|{}|{}|{}",
text, config.font_family, config.font_weight, config.font_size, config.letter_spacing
)
}
fn word(text: &str, config: &StrokeTextConfig) -> WordResult {
let key = geometry_key(text, config);
let cache = WORDS.get_or_init(Default::default);
if let Some(word) = cache
.lock()
.map_err(|_| "字形缓存不可用")?
.get(&key)
.cloned()
{
return Ok(word);
}
let result = build_word(text, config)?;
let mut cache = cache.lock().map_err(|_| "字形缓存不可用")?;
if cache.len() >= 32 {
cache.clear();
}
cache.insert(key, result.clone());
Ok(result)
}
fn build_word(text: &str, config: &StrokeTextConfig) -> WordResult {
with_face(&config.font_family, config.font_weight, |face| {
let scale = config.font_size.clamp(8.0, 512.0) / face.units_per_em() as f32;
let mut glyphs = Vec::new();
let mut width = 0.0f32;
let mut top = 0.0f32;
let mut bottom = 0.0f32;
for ch in text.chars().take(160) {
let id = face
.glyph_index(ch)
.ok_or_else(|| format!("当前字体不包含字符:{ch}"))?;
let mut outline = Outline::glyph(face, id);
for contour in &mut outline.contours {
for p in &mut contour.points {
p.x = p.x * scale + width;
p.y *= scale;
top = top.min(p.y);
bottom = bottom.max(p.y);
}
}
let advance = face
.glyph_hor_advance(id)
.unwrap_or(face.units_per_em() / 2) as f32
* scale;
glyphs.push(Glyph {
contours: outline.contours,
});
width += (advance + config.letter_spacing).max(1.0);
}
if !glyphs.is_empty() {
width -= config.letter_spacing;
}
Ok(Arc::new(Word {
glyphs,
width: width.max(1.0),
height: (bottom - top).max(1.0),
top,
}))
})
}
pub fn prepare_stroke_text(text: &str, config: &StrokeTextConfig) -> Result<(), String> {
word(text, config).map(|_| ())
}
struct State {
key: String,
generation: u64,
geometry: Option<WordResult>,
started: Option<f64>,
visible: bool,
hovered: bool,
replay: u64,
}
#[derive(IntoElement)]
pub struct StrokeText {
id: ElementId,
text: SharedString,
config: StrokeTextConfig,
replay: u64,
elapsed: Option<f64>,
}
impl StrokeText {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
config: StrokeTextConfig::default(),
replay: 0,
elapsed: None,
}
}
pub fn config(mut self, config: StrokeTextConfig) -> Self {
self.config = config;
self
}
pub fn replay(mut self, revision: u64) -> Self {
self.replay = revision;
self
}
pub fn elapsed(mut self, seconds: f64) -> Self {
self.elapsed = Some(seconds.max(0.0));
self
}
}
impl RenderOnce for StrokeText {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let now = motion_now(cx);
let reduced = is_reduced_motion(cx);
let foreground = cx.arc_theme().colors.foreground;
let state = window.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "stroke-state".into()),
cx,
|_, _| {
Rc::new(RefCell::new(State {
key: String::new(),
generation: 0,
geometry: None,
started: None,
visible: false,
hovered: false,
replay: 0,
}))
},
);
let state = state.read(cx).clone();
let key = geometry_key(&self.text, &self.config);
let changed = state.borrow().key != key;
if changed {
let mut s = state.borrow_mut();
s.key = key;
s.generation += 1;
s.geometry = None;
s.started = None;
let generation = s.generation;
drop(s);
let target = state.clone();
let text = self.text.to_string();
let config = self.config.clone();
let task = cx
.background_executor()
.spawn(async move { word(&text, &config) });
window
.spawn(cx, async move |cx| {
let result = task.await;
let _ = cx.update(|window, _| {
let mut s = target.borrow_mut();
if s.generation == generation {
s.geometry = Some(result);
s.started = None;
window.refresh();
}
});
})
.detach();
}
let mut s = state.borrow_mut();
if s.replay != self.replay {
s.replay = self.replay;
s.started = Some(now);
}
let ready = s.geometry.as_ref().is_some_and(|r| r.is_ok());
if ready
&& s.started.is_none()
&& (matches!(
self.config.trigger,
StrokeTrigger::Mount | StrokeTrigger::Loop
) || (self.config.trigger == StrokeTrigger::Scroll && s.visible))
{
s.started = Some(now);
}
let duration = self.config.duration(self.text.chars().count().min(160));
let mut elapsed = self.elapsed.unwrap_or_else(|| {
s.started.map_or(
if self.config.trigger == StrokeTrigger::Hover {
duration
} else {
0.0
},
|start| now - start,
)
});
if self.config.trigger == StrokeTrigger::Loop && !reduced {
let cycle = duration + 0.9;
let phase = elapsed.rem_euclid(cycle * 2.0);
elapsed = if phase <= cycle {
phase.min(duration)
} else {
(cycle * 2.0 - phase).min(duration)
};
}
let active = self.elapsed.is_none()
&& !reduced
&& s.visible
&& ready
&& s.started.is_some()
&& (matches!(self.config.trigger, StrokeTrigger::Loop)
|| elapsed < duration
|| (self.config.marching && self.config.stroke_style != StrokeStyle::Solid));
let geometry = s.geometry.clone();
drop(s);
if active {
window.request_animation_frame();
}
let paint_state = state.clone();
let hover_state = state.clone();
let hover_config = self.config.clone();
let config = self.config.clone();
div()
.id(self.id)
.test_support()
.role(Role::Image)
.aria_label(self.text.clone())
.relative()
.w_full()
.h(px(self.config.font_size.clamp(8.0, 512.0) * 1.35 + 24.0))
.min_w_0()
.on_hover(move |hovered, window, cx| {
let mut s = hover_state.borrow_mut();
if *hovered
&& !s.hovered
&& (hover_config.trigger == StrokeTrigger::Hover
|| (hover_config.hover_redraw
&& s.started
.is_some_and(|start| motion_now(cx) - start >= duration)))
{
s.started = Some(motion_now(cx));
window.refresh();
}
s.hovered = *hovered;
})
.child(
canvas(
move |bounds, window, _| {
let visible = !bounds.intersect(&window.content_mask().bounds).is_empty();
let mut s = paint_state.borrow_mut();
if s.visible != visible {
s.visible = visible;
window.request_animation_frame();
}
bounds
},
move |_, bounds, window, _| {
if let Some(Ok(word)) = &geometry {
paint_word(word, &config, elapsed, reduced, foreground, bounds, window);
}
},
)
.size_full(),
)
.when_some(geometry_error(&state), |el, error| {
el.child(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.text_color(foreground)
.child(error),
)
})
}
}
fn geometry_error(state: &Rc<RefCell<State>>) -> Option<SharedString> {
state
.borrow()
.geometry
.as_ref()
.and_then(|r| r.as_ref().err())
.map(|e| SharedString::from(e.clone()))
}
fn paint_word(
word: &Word,
c: &StrokeTextConfig,
elapsed: f64,
reduced: bool,
foreground: Hsla,
bounds: Bounds<Pixels>,
window: &mut Window,
) {
let scale = ((f32::from(bounds.size.width) - 24.0) / word.width)
.min((f32::from(bounds.size.height) - 24.0) / word.height)
.clamp(0.01, 1.0);
let ox = f32::from(bounds.center().x) - word.width * scale / 2.0;
let oy = f32::from(bounds.center().y) - (word.top + word.height / 2.0) * scale;
let transform = |p: PathPoint| point(px(ox + p.x * scale), px(oy + p.y * scale));
let fill_color = c.fill_color.unwrap_or(foreground);
for (index, glyph) in word.glyphs.iter().enumerate() {
let (outline, fill) = c.sample(elapsed, index, word.glyphs.len(), reduced);
let total: f32 = glyph.contours.iter().map(PolylinePath::total_length).sum();
let mut remaining = total * outline;
for contour in &glyph.contours {
let length = contour.total_length();
let visible = contour.slice(0.0, (remaining / length.max(0.001)).clamp(0.0, 1.0));
remaining -= length;
if visible.points.len() < 2 {
continue;
}
let width = c.stroke_width.clamp(0.1, 16.0) * scale;
let mut path = PathBuilder::stroke(px(width));
let phase = if c.marching && !reduced {
elapsed as f32 * c.font_size * 0.22
} else {
0.0
};
match c.stroke_style {
StrokeStyle::Solid => {
path.move_to(transform(visible.points[0]));
for p in &visible.points[1..] {
path.line_to(transform(*p));
}
}
_ => {
let on = if c.stroke_style == StrokeStyle::Dotted {
c.stroke_width.max(0.1)
} else {
(c.dash_length - c.stroke_width).max(0.5)
};
let gap = if c.stroke_style == StrokeStyle::Dotted {
c.dash_length.max(c.stroke_width * 1.8)
} else {
c.dash_length * 0.6 + c.stroke_width
};
let period = (on + gap).max(0.2);
let mut start = -phase.rem_euclid(period);
while start < visible.total_length() {
let a = start.max(0.0);
let b = (start + on).min(visible.total_length());
if b > a {
let segment = visible
.slice(a / visible.total_length(), b / visible.total_length());
if let Some(p) = segment.points.first() {
path.move_to(transform(*p));
for p in &segment.points[1..] {
path.line_to(transform(*p));
}
}
}
start += period;
}
}
}
if let Ok(path) = path.build() {
window.paint_path(path, c.stroke_color);
}
}
if fill <= 0.0 {
continue;
}
let mut color = fill_color;
if c.fill_mode == StrokeFill::Fade {
color.a *= fill;
}
let mask = if c.fill_mode == StrokeFill::Wipe {
let mut b = Bounds::new(
point(px(ox - 12.0), px(oy + word.top * scale - 12.0)),
size(
px(word.width * scale + 24.0),
px(word.height * scale + 24.0),
),
);
match c.wipe_from {
WipeFrom::Left => b.size.width *= fill,
WipeFrom::Right => {
b.origin.x += b.size.width * (1.0 - fill);
b.size.width *= fill;
}
WipeFrom::Top => b.size.height *= fill,
WipeFrom::Bottom => {
b.origin.y += b.size.height * (1.0 - fill);
b.size.height *= fill;
}
}
Some(ContentMask { bounds: b })
} else {
None
};
window.with_content_mask(mask, |window| {
if c.shadow {
let mut shadow = c.shadow_color.unwrap_or(c.stroke_color);
shadow.a *= fill * 0.25;
paint_fill(
glyph,
scale,
ox + c.font_size * 0.06 * scale * fill,
oy + c.font_size * 0.06 * scale * fill,
shadow,
window,
);
}
paint_fill(glyph, scale, ox, oy, color, window);
});
}
}
fn paint_fill(glyph: &Glyph, scale: f32, ox: f32, oy: f32, color: Hsla, window: &mut Window) {
let mut path = PathBuilder::fill();
for contour in &glyph.contours {
if let Some(p) = contour.points.first() {
path.move_to(point(px(ox + p.x * scale), px(oy + p.y * scale)));
for p in &contour.points[1..] {
path.line_to(point(px(ox + p.x * scale), px(oy + p.y * scale)));
}
path.close();
}
}
if let Ok(path) = path.build() {
window.paint_path(path, color);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stroke_timeline_matches_reference() {
let c = StrokeTextConfig::default();
assert_eq!(c.sample(0.0, 0, 6, false), (0.0, 0.0));
assert_eq!(c.sample(1.9, 0, 6, false), (1.0, 0.0));
assert_eq!(c.sample(3.3, 5, 6, false), (1.0, 1.0));
assert!((c.duration(6) - 3.3).abs() < 1e-6);
assert!((c.ease.sample(0.5) - 0.875).abs() < 1e-6);
}
#[test]
fn reverse_reduced_and_no_fill() {
let mut c = StrokeTextConfig {
reverse: true,
..Default::default()
};
assert_eq!(c.sample(0.1, 0, 6, false).0, 0.0);
assert!(c.sample(0.1, 5, 6, false).0 > 0.0);
c.fill_mode = StrokeFill::None;
assert_eq!(c.sample(0.0, 0, 6, true), (1.0, 0.0));
}
#[test]
fn real_contours_preserve_counters() {
let w = word("Arc-rs", &StrokeTextConfig::default()).unwrap();
assert_eq!(w.glyphs.len(), 6);
assert!(w.glyphs[0].contours.len() >= 2);
assert!(w.width > 200.0);
assert!(w.glyphs.iter().all(|g| !g.contours.is_empty()));
}
}