Skip to main content

arc_ui/text/
stroke_text.rs

1//! Native adaptation of the user-supplied React Bits StrokeText choreography.
2//! Real font contours, arc-length drawing and compound fills; no WebView or GSAP runtime.
3
4use arc_motion::{PathPoint, PolylinePath, is_reduced_motion, motion_now};
5use arc_tokens::{ActiveArcTheme as _, Typography};
6use gpui_kit::{
7    App, Bounds, ContentMask, ElementId, Hsla, IntoElement, ParentElement, PathBuilder, Pixels,
8    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, canvas, div, point,
9    prelude::*, px, rgb, size,
10};
11use std::{
12    cell::RefCell,
13    collections::HashMap,
14    rc::Rc,
15    sync::{Arc, Mutex, OnceLock},
16};
17
18use super::glyph_outline::{Outline, with_face};
19
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum StrokeStyle {
22    #[default]
23    Solid,
24    Dashed,
25    Dotted,
26}
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub enum StrokeFill {
29    #[default]
30    Fade,
31    Wipe,
32    None,
33}
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum StrokeTrigger {
36    #[default]
37    Mount,
38    Hover,
39    Scroll,
40    Loop,
41}
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub enum WipeFrom {
44    #[default]
45    Left,
46    Right,
47    Top,
48    Bottom,
49}
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
51pub enum StrokeEase {
52    #[default]
53    Power2Out,
54    Linear,
55    Power2InOut,
56    Power3Out,
57}
58impl StrokeEase {
59    pub fn sample(self, t: f32) -> f32 {
60        let t = t.clamp(0.0, 1.0);
61        match self {
62            Self::Linear => t,
63            Self::Power2Out => 1.0 - (1.0 - t).powi(3),
64            Self::Power3Out => 1.0 - (1.0 - t).powi(4),
65            Self::Power2InOut => {
66                if t < 0.5 {
67                    4.0 * t.powi(3)
68                } else {
69                    1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
70                }
71            }
72        }
73    }
74}
75
76/// 与参考示例一致的配置;颜色为 None 时跟随当前主题前景色。
77#[derive(Clone, Debug, PartialEq)]
78pub struct StrokeTextConfig {
79    pub stroke_color: Hsla,
80    pub fill_color: Option<Hsla>,
81    pub shadow_color: Option<Hsla>,
82    pub stroke_style: StrokeStyle,
83    pub stroke_width: f32,
84    pub dash_length: f32,
85    pub draw_duration: f64,
86    pub fill_delay: f64,
87    pub stagger: f64,
88    pub ease: StrokeEase,
89    pub trigger: StrokeTrigger,
90    pub fill_mode: StrokeFill,
91    pub wipe_from: WipeFrom,
92    pub font_size: f32,
93    pub font_weight: u16,
94    pub font_family: String,
95    pub letter_spacing: f32,
96    pub reverse: bool,
97    pub marching: bool,
98    pub hover_redraw: bool,
99    pub shadow: bool,
100}
101impl Default for StrokeTextConfig {
102    fn default() -> Self {
103        Self {
104            stroke_color: rgb(0xA78BFA).into(),
105            fill_color: None,
106            shadow_color: None,
107            stroke_style: StrokeStyle::Solid,
108            stroke_width: 1.4,
109            dash_length: 10.0,
110            draw_duration: 1.9,
111            fill_delay: 0.2,
112            stagger: 0.05,
113            ease: StrokeEase::Power2Out,
114            trigger: StrokeTrigger::Mount,
115            fill_mode: StrokeFill::Fade,
116            wipe_from: WipeFrom::Left,
117            font_size: 128.0,
118            font_weight: 800,
119            font_family: Typography::display_family().into(),
120            letter_spacing: -4.0,
121            reverse: false,
122            marching: false,
123            hover_redraw: true,
124            shadow: false,
125        }
126    }
127}
128impl StrokeTextConfig {
129    pub fn duration(&self, count: usize) -> f64 {
130        let tail = count.saturating_sub(1) as f64 * self.stagger.max(0.0);
131        let draw = self.draw_duration.max(0.05);
132        let end = draw + tail;
133        if self.fill_mode == StrokeFill::None {
134            end
135        } else {
136            end.max(
137                draw + self.fill_delay.max(0.0)
138                    + (draw * 0.5).max(0.4)
139                    + if self.fill_mode == StrokeFill::Fade {
140                        tail
141                    } else {
142                        0.0
143                    },
144            )
145        }
146    }
147    pub fn sample(&self, elapsed: f64, index: usize, count: usize, reduced: bool) -> (f32, f32) {
148        if reduced {
149            return (
150                1.0,
151                if self.fill_mode == StrokeFill::None {
152                    0.0
153                } else {
154                    1.0
155                },
156            );
157        }
158        let rank = if self.reverse {
159            count.saturating_sub(index + 1)
160        } else {
161            index
162        };
163        let draw = self.draw_duration.max(0.05);
164        let delay = rank as f64 * self.stagger.max(0.0);
165        let outline = self.ease.sample(((elapsed - delay) / draw) as f32);
166        let fill_delay = if self.fill_mode == StrokeFill::Fade {
167            delay
168        } else {
169            0.0
170        };
171        let t = ((elapsed - draw - self.fill_delay.max(0.0) - fill_delay) / (draw * 0.5).max(0.4))
172            as f32;
173        let fill = match self.fill_mode {
174            StrokeFill::None => 0.0,
175            StrokeFill::Fade => StrokeEase::Power2Out.sample(t),
176            StrokeFill::Wipe => StrokeEase::Power2InOut.sample(t),
177        };
178        (outline, fill)
179    }
180}
181
182#[derive(Clone, Debug)]
183struct Glyph {
184    contours: Vec<PolylinePath>,
185}
186#[derive(Clone, Debug)]
187struct Word {
188    glyphs: Vec<Glyph>,
189    width: f32,
190    height: f32,
191    top: f32,
192}
193type WordResult = Result<Arc<Word>, String>;
194static WORDS: OnceLock<Mutex<HashMap<String, Arc<Word>>>> = OnceLock::new();
195fn geometry_key(text: &str, config: &StrokeTextConfig) -> String {
196    format!(
197        "{}|{}|{}|{}|{}",
198        text, config.font_family, config.font_weight, config.font_size, config.letter_spacing
199    )
200}
201fn word(text: &str, config: &StrokeTextConfig) -> WordResult {
202    let key = geometry_key(text, config);
203    let cache = WORDS.get_or_init(Default::default);
204    if let Some(word) = cache
205        .lock()
206        .map_err(|_| "字形缓存不可用")?
207        .get(&key)
208        .cloned()
209    {
210        return Ok(word);
211    }
212    let result = build_word(text, config)?;
213    let mut cache = cache.lock().map_err(|_| "字形缓存不可用")?;
214    // 编辑文案时限制缓存,避免每次按键都永久保留一套路径。
215    if cache.len() >= 32 {
216        cache.clear();
217    }
218    cache.insert(key, result.clone());
219    Ok(result)
220}
221fn build_word(text: &str, config: &StrokeTextConfig) -> WordResult {
222    with_face(&config.font_family, config.font_weight, |face| {
223        let scale = config.font_size.clamp(8.0, 512.0) / face.units_per_em() as f32;
224        let mut glyphs = Vec::new();
225        let mut width = 0.0f32;
226        let mut top = 0.0f32;
227        let mut bottom = 0.0f32;
228        for ch in text.chars().take(160) {
229            let id = face
230                .glyph_index(ch)
231                .ok_or_else(|| format!("当前字体不包含字符:{ch}"))?;
232            let mut outline = Outline::glyph(face, id);
233            for contour in &mut outline.contours {
234                for p in &mut contour.points {
235                    p.x = p.x * scale + width;
236                    p.y *= scale;
237                    top = top.min(p.y);
238                    bottom = bottom.max(p.y);
239                }
240            }
241            let advance = face
242                .glyph_hor_advance(id)
243                .unwrap_or(face.units_per_em() / 2) as f32
244                * scale;
245            glyphs.push(Glyph {
246                contours: outline.contours,
247            });
248            width += (advance + config.letter_spacing).max(1.0);
249        }
250        if !glyphs.is_empty() {
251            width -= config.letter_spacing;
252        }
253        Ok(Arc::new(Word {
254            glyphs,
255            width: width.max(1.0),
256            height: (bottom - top).max(1.0),
257            top,
258        }))
259    })
260}
261
262/// 可提前在后台预热,启动窗和组件共享同一个字体数据库。
263pub fn prepare_stroke_text(text: &str, config: &StrokeTextConfig) -> Result<(), String> {
264    word(text, config).map(|_| ())
265}
266
267struct State {
268    key: String,
269    generation: u64,
270    geometry: Option<WordResult>,
271    started: Option<f64>,
272    visible: bool,
273    hovered: bool,
274    replay: u64,
275}
276
277#[derive(IntoElement)]
278pub struct StrokeText {
279    id: ElementId,
280    text: SharedString,
281    config: StrokeTextConfig,
282    replay: u64,
283    elapsed: Option<f64>,
284}
285impl StrokeText {
286    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
287        Self {
288            id: id.into(),
289            text: text.into(),
290            config: StrokeTextConfig::default(),
291            replay: 0,
292            elapsed: None,
293        }
294    }
295    pub fn config(mut self, config: StrokeTextConfig) -> Self {
296        self.config = config;
297        self
298    }
299    pub fn replay(mut self, revision: u64) -> Self {
300        self.replay = revision;
301        self
302    }
303    /// 固定时间采样,供静态预览和回归截图使用。
304    pub fn elapsed(mut self, seconds: f64) -> Self {
305        self.elapsed = Some(seconds.max(0.0));
306        self
307    }
308}
309impl RenderOnce for StrokeText {
310    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
311        let now = motion_now(cx);
312        let reduced = is_reduced_motion(cx);
313        let foreground = cx.arc_theme().colors.foreground;
314        let state = window.use_keyed_state(
315            ElementId::NamedChild(self.id.clone().into(), "stroke-state".into()),
316            cx,
317            |_, _| {
318                Rc::new(RefCell::new(State {
319                    key: String::new(),
320                    generation: 0,
321                    geometry: None,
322                    started: None,
323                    visible: false,
324                    hovered: false,
325                    replay: 0,
326                }))
327            },
328        );
329        let state = state.read(cx).clone();
330        let key = geometry_key(&self.text, &self.config);
331        let changed = state.borrow().key != key;
332        if changed {
333            let mut s = state.borrow_mut();
334            s.key = key;
335            s.generation += 1;
336            s.geometry = None;
337            s.started = None;
338            let generation = s.generation;
339            drop(s);
340            let target = state.clone();
341            let text = self.text.to_string();
342            let config = self.config.clone();
343            let task = cx
344                .background_executor()
345                .spawn(async move { word(&text, &config) });
346            window
347                .spawn(cx, async move |cx| {
348                    let result = task.await;
349                    let _ = cx.update(|window, _| {
350                        let mut s = target.borrow_mut();
351                        if s.generation == generation {
352                            s.geometry = Some(result);
353                            s.started = None;
354                            window.refresh();
355                        }
356                    });
357                })
358                .detach();
359        }
360        let mut s = state.borrow_mut();
361        if s.replay != self.replay {
362            s.replay = self.replay;
363            s.started = Some(now);
364        }
365        let ready = s.geometry.as_ref().is_some_and(|r| r.is_ok());
366        if ready
367            && s.started.is_none()
368            && (matches!(
369                self.config.trigger,
370                StrokeTrigger::Mount | StrokeTrigger::Loop
371            ) || (self.config.trigger == StrokeTrigger::Scroll && s.visible))
372        {
373            s.started = Some(now);
374        }
375        let duration = self.config.duration(self.text.chars().count().min(160));
376        let mut elapsed = self.elapsed.unwrap_or_else(|| {
377            s.started.map_or(
378                if self.config.trigger == StrokeTrigger::Hover {
379                    duration
380                } else {
381                    0.0
382                },
383                |start| now - start,
384            )
385        });
386        if self.config.trigger == StrokeTrigger::Loop && !reduced {
387            let cycle = duration + 0.9;
388            let phase = elapsed.rem_euclid(cycle * 2.0);
389            elapsed = if phase <= cycle {
390                phase.min(duration)
391            } else {
392                (cycle * 2.0 - phase).min(duration)
393            };
394        }
395        let active = self.elapsed.is_none()
396            && !reduced
397            && s.visible
398            && ready
399            && s.started.is_some()
400            && (matches!(self.config.trigger, StrokeTrigger::Loop)
401                || elapsed < duration
402                || (self.config.marching && self.config.stroke_style != StrokeStyle::Solid));
403        let geometry = s.geometry.clone();
404        drop(s);
405        if active {
406            window.request_animation_frame();
407        }
408        let paint_state = state.clone();
409        let hover_state = state.clone();
410        let hover_config = self.config.clone();
411        let config = self.config.clone();
412        div()
413            .id(self.id)
414            .test_support()
415            .role(Role::Image)
416            .aria_label(self.text.clone())
417            .relative()
418            .w_full()
419            .h(px(self.config.font_size.clamp(8.0, 512.0) * 1.35 + 24.0))
420            .min_w_0()
421            .on_hover(move |hovered, window, cx| {
422                let mut s = hover_state.borrow_mut();
423                if *hovered
424                    && !s.hovered
425                    && (hover_config.trigger == StrokeTrigger::Hover
426                        || (hover_config.hover_redraw
427                            && s.started
428                                .is_some_and(|start| motion_now(cx) - start >= duration)))
429                {
430                    s.started = Some(motion_now(cx));
431                    window.refresh();
432                }
433                s.hovered = *hovered;
434            })
435            .child(
436                canvas(
437                    move |bounds, window, _| {
438                        let visible = !bounds.intersect(&window.content_mask().bounds).is_empty();
439                        let mut s = paint_state.borrow_mut();
440                        if s.visible != visible {
441                            s.visible = visible;
442                            window.request_animation_frame();
443                        }
444                        bounds
445                    },
446                    move |_, bounds, window, _| {
447                        if let Some(Ok(word)) = &geometry {
448                            paint_word(word, &config, elapsed, reduced, foreground, bounds, window);
449                        }
450                    },
451                )
452                .size_full(),
453            )
454            .when_some(geometry_error(&state), |el, error| {
455                el.child(
456                    div()
457                        .absolute()
458                        .inset_0()
459                        .flex()
460                        .items_center()
461                        .justify_center()
462                        .text_color(foreground)
463                        .child(error),
464                )
465            })
466    }
467}
468fn geometry_error(state: &Rc<RefCell<State>>) -> Option<SharedString> {
469    state
470        .borrow()
471        .geometry
472        .as_ref()
473        .and_then(|r| r.as_ref().err())
474        .map(|e| SharedString::from(e.clone()))
475}
476
477fn paint_word(
478    word: &Word,
479    c: &StrokeTextConfig,
480    elapsed: f64,
481    reduced: bool,
482    foreground: Hsla,
483    bounds: Bounds<Pixels>,
484    window: &mut Window,
485) {
486    let scale = ((f32::from(bounds.size.width) - 24.0) / word.width)
487        .min((f32::from(bounds.size.height) - 24.0) / word.height)
488        .clamp(0.01, 1.0);
489    let ox = f32::from(bounds.center().x) - word.width * scale / 2.0;
490    let oy = f32::from(bounds.center().y) - (word.top + word.height / 2.0) * scale;
491    let transform = |p: PathPoint| point(px(ox + p.x * scale), px(oy + p.y * scale));
492    let fill_color = c.fill_color.unwrap_or(foreground);
493    for (index, glyph) in word.glyphs.iter().enumerate() {
494        let (outline, fill) = c.sample(elapsed, index, word.glyphs.len(), reduced);
495        let total: f32 = glyph.contours.iter().map(PolylinePath::total_length).sum();
496        let mut remaining = total * outline;
497        for contour in &glyph.contours {
498            let length = contour.total_length();
499            let visible = contour.slice(0.0, (remaining / length.max(0.001)).clamp(0.0, 1.0));
500            remaining -= length;
501            if visible.points.len() < 2 {
502                continue;
503            }
504            let width = c.stroke_width.clamp(0.1, 16.0) * scale;
505            let mut path = PathBuilder::stroke(px(width));
506            let phase = if c.marching && !reduced {
507                elapsed as f32 * c.font_size * 0.22
508            } else {
509                0.0
510            };
511            match c.stroke_style {
512                StrokeStyle::Solid => {
513                    path.move_to(transform(visible.points[0]));
514                    for p in &visible.points[1..] {
515                        path.line_to(transform(*p));
516                    }
517                }
518                _ => {
519                    let on = if c.stroke_style == StrokeStyle::Dotted {
520                        c.stroke_width.max(0.1)
521                    } else {
522                        (c.dash_length - c.stroke_width).max(0.5)
523                    };
524                    let gap = if c.stroke_style == StrokeStyle::Dotted {
525                        c.dash_length.max(c.stroke_width * 1.8)
526                    } else {
527                        c.dash_length * 0.6 + c.stroke_width
528                    };
529                    let period = (on + gap).max(0.2);
530                    let mut start = -phase.rem_euclid(period);
531                    while start < visible.total_length() {
532                        let a = start.max(0.0);
533                        let b = (start + on).min(visible.total_length());
534                        if b > a {
535                            let segment = visible
536                                .slice(a / visible.total_length(), b / visible.total_length());
537                            if let Some(p) = segment.points.first() {
538                                path.move_to(transform(*p));
539                                for p in &segment.points[1..] {
540                                    path.line_to(transform(*p));
541                                }
542                            }
543                        }
544                        start += period;
545                    }
546                }
547            }
548            if let Ok(path) = path.build() {
549                window.paint_path(path, c.stroke_color);
550            }
551        }
552        if fill <= 0.0 {
553            continue;
554        }
555        let mut color = fill_color;
556        if c.fill_mode == StrokeFill::Fade {
557            color.a *= fill;
558        }
559        let mask = if c.fill_mode == StrokeFill::Wipe {
560            let mut b = Bounds::new(
561                point(px(ox - 12.0), px(oy + word.top * scale - 12.0)),
562                size(
563                    px(word.width * scale + 24.0),
564                    px(word.height * scale + 24.0),
565                ),
566            );
567            match c.wipe_from {
568                WipeFrom::Left => b.size.width *= fill,
569                WipeFrom::Right => {
570                    b.origin.x += b.size.width * (1.0 - fill);
571                    b.size.width *= fill;
572                }
573                WipeFrom::Top => b.size.height *= fill,
574                WipeFrom::Bottom => {
575                    b.origin.y += b.size.height * (1.0 - fill);
576                    b.size.height *= fill;
577                }
578            }
579            Some(ContentMask { bounds: b })
580        } else {
581            None
582        };
583        window.with_content_mask(mask, |window| {
584            if c.shadow {
585                let mut shadow = c.shadow_color.unwrap_or(c.stroke_color);
586                shadow.a *= fill * 0.25;
587                paint_fill(
588                    glyph,
589                    scale,
590                    ox + c.font_size * 0.06 * scale * fill,
591                    oy + c.font_size * 0.06 * scale * fill,
592                    shadow,
593                    window,
594                );
595            }
596            paint_fill(glyph, scale, ox, oy, color, window);
597        });
598    }
599}
600fn paint_fill(glyph: &Glyph, scale: f32, ox: f32, oy: f32, color: Hsla, window: &mut Window) {
601    let mut path = PathBuilder::fill();
602    for contour in &glyph.contours {
603        if let Some(p) = contour.points.first() {
604            path.move_to(point(px(ox + p.x * scale), px(oy + p.y * scale)));
605            for p in &contour.points[1..] {
606                path.line_to(point(px(ox + p.x * scale), px(oy + p.y * scale)));
607            }
608            path.close();
609        }
610    }
611    if let Ok(path) = path.build() {
612        window.paint_path(path, color);
613    }
614}
615
616#[cfg(test)]
617mod tests {
618    use super::*;
619    #[test]
620    fn stroke_timeline_matches_reference() {
621        let c = StrokeTextConfig::default();
622        assert_eq!(c.sample(0.0, 0, 6, false), (0.0, 0.0));
623        assert_eq!(c.sample(1.9, 0, 6, false), (1.0, 0.0));
624        assert_eq!(c.sample(3.3, 5, 6, false), (1.0, 1.0));
625        assert!((c.duration(6) - 3.3).abs() < 1e-6);
626        assert!((c.ease.sample(0.5) - 0.875).abs() < 1e-6);
627    }
628    #[test]
629    fn reverse_reduced_and_no_fill() {
630        let mut c = StrokeTextConfig {
631            reverse: true,
632            ..Default::default()
633        };
634        assert_eq!(c.sample(0.1, 0, 6, false).0, 0.0);
635        assert!(c.sample(0.1, 5, 6, false).0 > 0.0);
636        c.fill_mode = StrokeFill::None;
637        assert_eq!(c.sample(0.0, 0, 6, true), (1.0, 0.0));
638    }
639    #[test]
640    fn real_contours_preserve_counters() {
641        let w = word("Arc-rs", &StrokeTextConfig::default()).unwrap();
642        assert_eq!(w.glyphs.len(), 6);
643        assert!(w.glyphs[0].contours.len() >= 2);
644        assert!(w.width > 200.0);
645        assert!(w.glyphs.iter().all(|g| !g.contours.is_empty()));
646    }
647}