Skip to main content

arc_ui/text/
fold_text.rs

1//! FoldText:把 React Bits 的 3D 折纸文字移植到原生 GPUI。
2//!
3//! 关键差异:GPUI 没有 3D 变换管线,也没有 `perspective` / `transform-origin`。
4//! 这里不复用 2D 的 `scaleY = cos θ` 近似,而是拿真实字形轮廓逐顶点做
5//! 「绕铰链轴旋转 → 透视投影」,因此折叠中途的近大远小、翻过背面都是真算出来的。
6
7use std::{
8    cell::RefCell,
9    collections::HashMap,
10    rc::Rc,
11    sync::{Arc, Mutex, OnceLock},
12};
13
14use arc_motion::{PathPoint, PolylinePath, is_reduced_motion, motion_now};
15use arc_tokens::{ActiveArcTheme as _, Typography};
16use gpui_kit::{
17    App, Bounds, ContentMask, ElementId, Hsla, InteractiveElement as _, IntoElement,
18    MouseMoveEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
19    TestSupportExt as _, Window, canvas, div, point, prelude::*, px, size,
20};
21
22use super::glyph_outline::{Outline, with_face};
23
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
25pub enum FoldStyle {
26    /// 整块面板绕一条边翻开。
27    #[default]
28    Paper,
29    /// 上下(或左右)两片各自翻开,错开 0.24s。
30    Blinds,
31    /// 翻整整半圈,中途抬起靠近相机。
32    Flip,
33}
34
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
36pub enum FoldSplit {
37    #[default]
38    Char,
39    Word,
40    Line,
41}
42
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub enum FoldHinge {
45    #[default]
46    Top,
47    Bottom,
48    Left,
49    Right,
50}
51
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
53pub enum FoldTrigger {
54    #[default]
55    Mount,
56    Hover,
57    Scroll,
58    Loop,
59}
60
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
62pub enum FoldStaggerFrom {
63    #[default]
64    Start,
65    Center,
66    End,
67    Edges,
68    Random,
69}
70
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
72pub enum FoldEase {
73    #[default]
74    Power3Out,
75    Power2Out,
76    Power1Out,
77    Linear,
78}
79
80impl FoldEase {
81    pub fn sample(self, t: f32) -> f32 {
82        let t = t.clamp(0.0, 1.0);
83        match self {
84            Self::Linear => t,
85            Self::Power1Out => 1.0 - (1.0 - t).powi(2),
86            Self::Power2Out => 1.0 - (1.0 - t).powi(3),
87            Self::Power3Out => 1.0 - (1.0 - t).powi(4),
88        }
89    }
90}
91
92/// 与参考实现同名同义的配置;颜色为空时跟随当前文字色。
93#[derive(Clone, Debug, PartialEq)]
94pub struct FoldTextConfig {
95    pub fold_style: FoldStyle,
96    pub split_by: FoldSplit,
97    pub hinge: FoldHinge,
98    pub trigger: FoldTrigger,
99    pub stagger_from: FoldStaggerFrom,
100    pub fold_angle: f32,
101    pub duration: f64,
102    pub stagger: f64,
103    pub ease: FoldEase,
104    pub perspective: f32,
105    pub crease_shading: f32,
106    pub loop_delay: f64,
107    pub hover_refold: bool,
108    pub refold_radius: f32,
109    pub refold_angle: f32,
110    pub font_size: f32,
111    pub font_weight: u16,
112    pub letter_spacing: f32,
113    pub font_family: String,
114    pub color: Option<Hsla>,
115}
116
117impl Default for FoldTextConfig {
118    fn default() -> Self {
119        Self {
120            fold_style: FoldStyle::Paper,
121            split_by: FoldSplit::Char,
122            hinge: FoldHinge::Top,
123            trigger: FoldTrigger::Mount,
124            stagger_from: FoldStaggerFrom::Start,
125            fold_angle: 92.0,
126            duration: 0.65,
127            stagger: 0.045,
128            ease: FoldEase::Power3Out,
129            perspective: 700.0,
130            crease_shading: 0.55,
131            loop_delay: 1.4,
132            hover_refold: false,
133            refold_radius: 140.0,
134            refold_angle: 45.0,
135            font_size: 80.0,
136            font_weight: 800,
137            letter_spacing: -2.0,
138            font_family: Typography::display_family().into(),
139            color: None,
140        }
141    }
142}
143
144impl FoldTextConfig {
145    /// 单片文字的展开时长(含缓动,不含错开)。
146    fn piece_duration(&self) -> f64 {
147        self.duration.max(0.08)
148    }
149
150    /// 整段文字展开完成所需时间:时长 + 最后一个面板的错开。
151    pub fn unfold_span(&self, count: usize) -> f64 {
152        self.piece_duration() + self.stagger.max(0.0) * count.saturating_sub(1) as f64
153    }
154
155    /// 循环模式下的一次完整周期:展开 → 保持 → 折回。
156    pub fn cycle_span(&self, count: usize) -> f64 {
157        let unfold = self.unfold_span(count);
158        let fold =
159            self.piece_duration() * 0.75 + self.stagger.max(0.0) * count.saturating_sub(1) as f64;
160        unfold + self.loop_delay.max(0.0) + fold
161    }
162
163    fn safe_angle(&self) -> f32 {
164        if self.fold_style == FoldStyle::Flip {
165            180.0
166        } else {
167            self.fold_angle.clamp(0.0, 180.0)
168        }
169    }
170
171    /// 单片在给定时刻的展开进度(0=完全折起,1=摊平)。
172    fn piece_progress(&self, elapsed: f64, rank: usize, reduced: bool) -> f32 {
173        if reduced {
174            return 1.0;
175        }
176        let local = (elapsed - self.stagger.max(0.0) * rank as f64) / self.piece_duration();
177        self.ease.sample(local as f32)
178    }
179
180    /// 循环模式下单片折回的进度。
181    fn piece_fold(&self, elapsed: f64, rank: usize, count: usize, reduced: bool) -> f32 {
182        if reduced || self.trigger != FoldTrigger::Loop {
183            return 0.0;
184        }
185        let unfold = self.unfold_span(count);
186        let fold = self.piece_duration() * 0.75;
187        let local =
188            (elapsed - unfold - self.loop_delay.max(0.0) - self.stagger.max(0.0) * rank as f64)
189                / fold;
190        FoldEase::Power2Out.sample(local as f32)
191    }
192
193    /// 错开起点换算成「第几个才开始」,用序号排序而不是直接乘。
194    pub fn stagger_rank(&self, index: usize, count: usize) -> usize {
195        let last = count.saturating_sub(1);
196        match self.stagger_from {
197            FoldStaggerFrom::Start => index,
198            FoldStaggerFrom::End => last.saturating_sub(index),
199            FoldStaggerFrom::Center => {
200                let mid = last as f32 / 2.0;
201                ((index as f32 - mid).abs().round() as usize).min(last)
202            }
203            FoldStaggerFrom::Edges => {
204                let mid = last as f32 / 2.0;
205                (mid - (index as f32 - mid).abs()).round().max(0.0) as usize
206            }
207            // 固定种子:截图与测试里同一份文本每次得到同样的顺序。
208            FoldStaggerFrom::Random => {
209                let mut seed = (index as u32).wrapping_mul(2_654_435_761) ^ 0x9E37_79B9;
210                seed ^= seed >> 15;
211                seed = seed.wrapping_mul(2_246_822_519);
212                seed ^= seed >> 13;
213                (seed as usize) % count.max(1)
214            }
215        }
216    }
217}
218
219#[derive(Clone, Copy, Debug)]
220struct Bbox {
221    left: f32,
222    top: f32,
223    right: f32,
224    bottom: f32,
225}
226
227impl Bbox {
228    fn width(self) -> f32 {
229        (self.right - self.left).max(0.001)
230    }
231    fn height(self) -> f32 {
232        (self.bottom - self.top).max(0.001)
233    }
234    fn center(self) -> (f32, f32) {
235        (
236            (self.left + self.right) / 2.0,
237            (self.top + self.bottom) / 2.0,
238        )
239    }
240}
241
242#[derive(Clone, Debug)]
243struct Glyph {
244    contours: Vec<PolylinePath>,
245}
246
247#[derive(Clone, Debug)]
248struct Piece {
249    glyphs: Vec<Glyph>,
250    bbox: Bbox,
251}
252
253#[derive(Clone, Debug)]
254struct Layout {
255    pieces: Vec<Piece>,
256    bbox: Bbox,
257}
258
259type LayoutResult = Result<Arc<Layout>, String>;
260
261static LAYOUTS: OnceLock<Mutex<HashMap<String, Arc<Layout>>>> = OnceLock::new();
262
263fn layout_key(text: &str, config: &FoldTextConfig) -> String {
264    format!(
265        "{}|{:?}|{:?}|{}|{}|{}",
266        text,
267        config.split_by,
268        config.fold_style,
269        config.font_family,
270        config.font_weight,
271        config.font_size
272    )
273}
274
275fn cached_layout(text: &str, config: &FoldTextConfig) -> LayoutResult {
276    let key = layout_key(text, config);
277    let cache = LAYOUTS.get_or_init(Default::default);
278    if let Some(hit) = cache
279        .lock()
280        .map_err(|_| "字形缓存不可用")?
281        .get(&key)
282        .cloned()
283    {
284        return Ok(hit);
285    }
286    let built = build_layout(text, config)?;
287    let mut cache = cache.lock().map_err(|_| "字形缓存不可用")?;
288    if cache.len() >= 32 {
289        cache.clear();
290    }
291    cache.insert(key, built.clone());
292    Ok(built)
293}
294
295/// 排版:先按 `\n` 折行,再按 `split_by` 切成面板。
296fn build_layout(text: &str, config: &FoldTextConfig) -> LayoutResult {
297    let scale = config.font_size.clamp(8.0, 512.0);
298    let metrics = with_face(&config.font_family, config.font_weight, |face| {
299        let unit = scale / face.units_per_em() as f32;
300        let line_height = scale * 1.12;
301        let space = face
302            .glyph_index(' ')
303            .and_then(|id| face.glyph_hor_advance(id))
304            .unwrap_or(face.units_per_em() / 3) as f32
305            * unit;
306
307        // 每行内按面板切分;空格只推进笔位,不单独成为面板。
308        let mut pieces = Vec::new();
309        let mut lines = 0usize;
310        let mut union = Bbox {
311            left: f32::MAX,
312            top: f32::MAX,
313            right: f32::MIN,
314            bottom: f32::MIN,
315        };
316
317        for (line_index, line) in text.split('\n').enumerate() {
318            lines = line_index + 1;
319            let mut pen_x = 0.0f32;
320            let line_top = line_index as f32 * line_height;
321            match config.split_by {
322                FoldSplit::Char => {
323                    for ch in line.chars() {
324                        if ch.is_whitespace() {
325                            pen_x += space + config.letter_spacing;
326                            continue;
327                        }
328                        let id = face
329                            .glyph_index(ch)
330                            .ok_or_else(|| format!("当前字体不包含字符:{ch}"))?;
331                        let mut outline = Outline::glyph(face, id);
332                        let ink = scale_outline(&mut outline, unit, pen_x, line_top);
333                        let advance = face.glyph_hor_advance(id).unwrap_or(0) as f32 * unit;
334                        let bbox = ink.unwrap_or(Bbox {
335                            left: pen_x,
336                            top: line_top,
337                            right: pen_x + advance,
338                            bottom: line_top + scale,
339                        });
340                        union = union_or(union, bbox);
341                        pieces.push(Piece {
342                            glyphs: vec![Glyph {
343                                contours: outline.contours,
344                            }],
345                            bbox,
346                        });
347                        pen_x += advance + config.letter_spacing;
348                    }
349                }
350                FoldSplit::Word | FoldSplit::Line => {
351                    let groups: Vec<&str> = if config.split_by == FoldSplit::Line {
352                        vec![line]
353                    } else {
354                        line.split_whitespace().collect()
355                    };
356                    for (group_index, group) in groups.into_iter().enumerate() {
357                        if group.is_empty() {
358                            continue;
359                        }
360                        // 词与词之间补一个空格宽度,保持与整行排版一致。
361                        if group_index > 0 {
362                            pen_x += space + config.letter_spacing;
363                        }
364                        let mut glyphs = Vec::new();
365                        let mut ink: Option<Bbox> = None;
366                        for ch in group.chars() {
367                            if ch.is_whitespace() {
368                                pen_x += space + config.letter_spacing;
369                                continue;
370                            }
371                            let id = face
372                                .glyph_index(ch)
373                                .ok_or_else(|| format!("当前字体不包含字符:{ch}"))?;
374                            let mut outline = Outline::glyph(face, id);
375                            if let Some(b) = scale_outline(&mut outline, unit, pen_x, line_top) {
376                                ink = Some(match ink {
377                                    Some(prev) => union_or(prev, b),
378                                    None => b,
379                                });
380                            }
381                            glyphs.push(Glyph {
382                                contours: outline.contours,
383                            });
384                            let advance = face.glyph_hor_advance(id).unwrap_or(0) as f32 * unit;
385                            pen_x += advance + config.letter_spacing;
386                        }
387                        if let Some(bbox) = ink {
388                            union = union_or(union, bbox);
389                            pieces.push(Piece { glyphs, bbox });
390                        }
391                    }
392                }
393            }
394        }
395
396        Ok((pieces, lines, union))
397    })?;
398
399    let (mut pieces, lines, union) = metrics;
400    if pieces.is_empty() {
401        return Err("没有可折叠的文字".to_string());
402    }
403    let bbox = if union.left == f32::MAX {
404        Bbox {
405            left: 0.0,
406            top: 0.0,
407            right: scale,
408            bottom: scale,
409        }
410    } else {
411        union
412    };
413    // 统一下移,让 bbox 顶部为 0,便于按容器垂直居中。
414    for piece in &mut pieces {
415        for glyph in &mut piece.glyphs {
416            for contour in &mut glyph.contours {
417                for p in &mut contour.points {
418                    p.y -= bbox.top;
419                }
420            }
421        }
422        piece.bbox.top -= bbox.top;
423        piece.bbox.bottom -= bbox.top;
424    }
425    let _ = lines;
426    Ok(Arc::new(Layout {
427        pieces,
428        bbox: Bbox {
429            left: bbox.left,
430            top: 0.0,
431            right: bbox.right,
432            bottom: bbox.bottom - bbox.top,
433        },
434    }))
435}
436
437fn union_or(a: Bbox, b: Bbox) -> Bbox {
438    Bbox {
439        left: a.left.min(b.left),
440        top: a.top.min(b.top),
441        right: a.right.max(b.right),
442        bottom: a.bottom.max(b.bottom),
443    }
444}
445
446/// 把字体单位换算成像素并平移到排版位置,同时返回该字形的 ink 范围。
447fn scale_outline(outline: &mut Outline, unit: f32, pen_x: f32, line_top: f32) -> Option<Bbox> {
448    if outline.contours.is_empty() {
449        return None;
450    }
451    let mut bbox = Bbox {
452        left: f32::MAX,
453        top: f32::MAX,
454        right: f32::MIN,
455        bottom: f32::MIN,
456    };
457    for contour in &mut outline.contours {
458        for p in &mut contour.points {
459            p.x = p.x * unit + pen_x;
460            p.y = p.y * unit + line_top;
461            bbox.left = bbox.left.min(p.x);
462            bbox.top = bbox.top.min(p.y);
463            bbox.right = bbox.right.max(p.x);
464            bbox.bottom = bbox.bottom.max(p.y);
465        }
466    }
467    (bbox.left != f32::MAX).then_some(bbox)
468}
469
470/// 提前在后台预热,避免首帧卡在字体查询上。
471pub fn prepare_fold_text(text: &str, config: &FoldTextConfig) -> Result<(), String> {
472    cached_layout(text, config).map(|_| ())
473}
474
475struct State {
476    key: String,
477    generation: u64,
478    geometry: Option<LayoutResult>,
479    started: Option<f64>,
480    visible: bool,
481    hovered: bool,
482    replay: u64,
483    pointer: Option<(f32, f32)>,
484    /// 每片当前的回来量(0 摊平,1 最折)。
485    refold: Vec<f32>,
486    /// 每片目标值,指针移动时更新,帧内指数收敛。
487    aim: Vec<f32>,
488    /// 上一帧时间戳,用于把 refold 的缓动做成与帧率无关。
489    last_frame: f64,
490    /// 每片面心的屏幕坐标,指针靠近时算距离用。
491    centers: Vec<(f32, f32)>,
492}
493
494impl State {
495    fn new() -> Self {
496        Self {
497            key: String::new(),
498            generation: 0,
499            geometry: None,
500            started: None,
501            visible: false,
502            hovered: false,
503            replay: 0,
504            pointer: None,
505            refold: Vec::new(),
506            aim: Vec::new(),
507            last_frame: 0.0,
508            centers: Vec::new(),
509        }
510    }
511}
512
513/// 一片要绘制的面板:字形 + 铰链位置 + 该片自己的时序。
514struct Panel<'a> {
515    glyphs: &'a [Glyph],
516    bbox: Bbox,
517    /// 铰链在屏幕坐标里的位置。
518    hinge: (f32, f32),
519    /// 透视原点(面板中心)。
520    origin: (f32, f32),
521    angle: f32,
522    opacity: f32,
523    crease: f32,
524    /// 只画上半 / 下半(blinds);None 表示整片。
525    slat: Option<Slat>,
526}
527
528#[derive(Clone, Copy, PartialEq, Eq)]
529enum Slat {
530    Upper,
531    Lower,
532}
533
534#[derive(IntoElement)]
535pub struct FoldText {
536    id: ElementId,
537    text: SharedString,
538    config: FoldTextConfig,
539    replay: u64,
540    elapsed: Option<f64>,
541}
542
543impl FoldText {
544    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
545        Self {
546            id: id.into(),
547            text: text.into(),
548            config: FoldTextConfig::default(),
549            replay: 0,
550            elapsed: None,
551        }
552    }
553
554    pub fn config(mut self, config: FoldTextConfig) -> Self {
555        self.config = config;
556        self
557    }
558
559    pub fn replay(mut self, revision: u64) -> Self {
560        self.replay = revision;
561        self
562    }
563
564    /// 固定采样时刻,供静态预览与截图验收。
565    pub fn elapsed(mut self, seconds: f64) -> Self {
566        self.elapsed = Some(seconds.max(0.0));
567        self
568    }
569}
570
571impl RenderOnce for FoldText {
572    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
573        let now = motion_now(cx);
574        let reduced = is_reduced_motion(cx);
575        let foreground = cx.arc_theme().colors.foreground;
576        let state = window.use_keyed_state(
577            ElementId::NamedChild(self.id.clone().into(), "fold-state".into()),
578            cx,
579            |_, _| Rc::new(RefCell::new(State::new())),
580        );
581        let state = state.read(cx).clone();
582
583        let key = layout_key(&self.text, &self.config);
584        let changed = state.borrow().key != key;
585        if changed {
586            let mut s = state.borrow_mut();
587            s.key = key;
588            s.generation += 1;
589            s.geometry = None;
590            s.started = None;
591            s.refold.clear();
592            s.aim.clear();
593            s.centers.clear();
594            let generation = s.generation;
595            drop(s);
596            let target = state.clone();
597            let text = self.text.to_string();
598            let config = self.config.clone();
599            let task = cx
600                .background_executor()
601                .spawn(async move { cached_layout(&text, &config) });
602            window
603                .spawn(cx, async move |cx| {
604                    let result = task.await;
605                    let _ = cx.update(|window, _| {
606                        let mut s = target.borrow_mut();
607                        if s.generation == generation {
608                            s.geometry = Some(result);
609                            s.started = None;
610                            window.refresh();
611                        }
612                    });
613                })
614                .detach();
615        }
616
617        let mut s = state.borrow_mut();
618        if s.replay != self.replay {
619            s.replay = self.replay;
620            s.started = Some(now);
621        }
622        let ready = s.geometry.as_ref().is_some_and(|r| r.is_ok());
623        let piece_count = s
624            .geometry
625            .as_ref()
626            .and_then(|r| r.as_ref().ok())
627            .map(|l| l.pieces.len())
628            .unwrap_or(0);
629        let starts_on_its_own =
630            matches!(self.config.trigger, FoldTrigger::Mount | FoldTrigger::Loop)
631                || (self.config.trigger == FoldTrigger::Scroll && s.visible);
632        if ready && s.started.is_none() && starts_on_its_own {
633            s.started = Some(now);
634        }
635        if s.refold.len() != piece_count {
636            s.refold = vec![0.0; piece_count];
637            s.aim = vec![0.0; piece_count];
638        }
639
640        let cycle = self.config.cycle_span(piece_count);
641        let elapsed = self.elapsed.unwrap_or_else(|| {
642            s.started.map_or(
643                if self.config.trigger == FoldTrigger::Hover {
644                    cycle.max(self.config.unfold_span(piece_count))
645                } else {
646                    0.0
647                },
648                |start| now - start,
649            )
650        });
651        let looping =
652            self.config.trigger == FoldTrigger::Loop && self.elapsed.is_none() && !reduced;
653        let phase = if looping {
654            elapsed.rem_euclid(cycle.max(0.1))
655        } else {
656            elapsed
657        };
658        // 只在「已经开始且还没播完」时请求帧;hover 未触发时不该空转。
659        let animating = self.elapsed.is_none()
660            && !reduced
661            && s.visible
662            && ready
663            && s.started.is_some()
664            && (looping || elapsed < self.config.unfold_span(piece_count) + 0.05);
665        drop(s);
666        if animating {
667            window.request_animation_frame();
668        }
669
670        let paint_state = state.clone();
671        let hover_state = state.clone();
672        let move_state = state.clone();
673        let config = self.config.clone();
674        let color = self.config.color.unwrap_or(foreground);
675        let height = {
676            let line_count = self.text.chars().filter(|c| *c == '\n').count() as f32 + 1.0;
677            self.config.font_size.clamp(8.0, 512.0) * 1.12 * line_count + 24.0
678        };
679
680        div()
681            .id(self.id)
682            .test_support()
683            .role(Role::Image)
684            .aria_label(self.text.clone())
685            .relative()
686            .w_full()
687            .min_w_0()
688            .h(px(height))
689            .on_hover(move |hovered, window, cx| {
690                let mut s = hover_state.borrow_mut();
691                let was = s.hovered;
692                s.hovered = *hovered;
693                if !*hovered {
694                    s.pointer = None;
695                    for aim in &mut s.aim {
696                        *aim = 0.0;
697                    }
698                }
699                if was != *hovered {
700                    window.refresh();
701                }
702                let _ = cx;
703            })
704            .on_mouse_move(move |event: &MouseMoveEvent, window, _| {
705                let mut s = move_state.borrow_mut();
706                s.pointer = Some((f32::from(event.position.x), f32::from(event.position.y)));
707                window.refresh();
708            })
709            .child(
710                canvas(
711                    move |bounds, window, _| {
712                        let visible = !bounds.intersect(&window.content_mask().bounds).is_empty();
713                        let mut s = paint_state.borrow_mut();
714                        if s.visible != visible {
715                            s.visible = visible;
716                            window.request_animation_frame();
717                        }
718                        bounds
719                    },
720                    move |bounds, _, window, cx| {
721                        let geometry = state.borrow().geometry.clone();
722                        let Some(Ok(layout)) = geometry else { return };
723                        paint_layout(
724                            &layout,
725                            &config,
726                            phase,
727                            reduced,
728                            color,
729                            bounds,
730                            motion_now(cx),
731                            &state,
732                            window,
733                        );
734                    },
735                )
736                .size_full(),
737            )
738    }
739}
740
741/// 逐片、逐顶点做旋转与透视投影,然后填充真实字形轮廓。
742#[allow(clippy::too_many_arguments)]
743fn paint_layout(
744    layout: &Layout,
745    config: &FoldTextConfig,
746    elapsed: f64,
747    reduced: bool,
748    color: Hsla,
749    bounds: Bounds<Pixels>,
750    now: f64,
751    state: &Rc<RefCell<State>>,
752    window: &mut Window,
753) {
754    let count = layout.pieces.len();
755    let box_w = f32::from(bounds.size.width);
756    let box_h = f32::from(bounds.size.height);
757    let fit = (box_w - 24.0) / layout.bbox.width().max(1.0);
758    let fit_h = (box_h - 24.0) / layout.bbox.height().max(1.0);
759    let scale = fit.min(fit_h).clamp(0.01, 1.0);
760    let offset_x = f32::from(bounds.origin.x) + (box_w - layout.bbox.width() * scale) / 2.0
761        - layout.bbox.left * scale;
762    let offset_y = f32::from(bounds.origin.y) + (box_h - layout.bbox.height() * scale) / 2.0;
763    let to_screen = |x: f32, y: f32| (offset_x + x * scale, offset_y + y * scale);
764
765    let perspective = config.perspective.clamp(120.0, 4000.0);
766    let axis_x = matches!(config.hinge, FoldHinge::Top | FoldHinge::Bottom);
767    let reduced_angle = reduced;
768
769    // 每片面心缓存:指针在附近时按距离算回来量。
770
771    let mut need_more_frames = false;
772    {
773        let mut s = state.borrow_mut();
774        if s.centers.len() != count {
775            s.centers = vec![(0.0, 0.0); count];
776        }
777        for (index, piece) in layout.pieces.iter().enumerate() {
778            let (cx, cy) = piece.bbox.center();
779            let (sx, sy) = to_screen(cx, cy);
780            s.centers[index] = (sx, sy);
781        }
782        // 指针 → 目标回来量;没有指针时全部归零。
783        let pointer = s.pointer;
784        let radius = config.refold_radius.max(1.0);
785        let want = config.hover_refold && !reduced && pointer.is_some();
786        for index in 0..count {
787            let mut target = 0.0;
788            if want && let Some((px, py)) = pointer {
789                let (cx, cy) = s.centers[index];
790                let distance = ((cx - px).powi(2) + (cy - py).powi(2)).sqrt() / radius;
791                if distance < 1.0 {
792                    // 与参考实现同一条 smoothstep:中心最强,边缘平滑归零。
793                    target = 1.0 - distance * distance * (3.0 - 2.0 * distance);
794                }
795            }
796            s.aim[index] = target;
797        }
798        // 指数收敛:与帧率无关,收敛后停帧。
799        let dt = (now - s.last_frame).clamp(0.0, 0.064) as f32;
800        s.last_frame = now;
801        for index in 0..count {
802            let aim = s.aim[index];
803            let current = s.refold[index];
804            let rate: f32 = if aim > current { 14.0 } else { 6.0 };
805            let next = current + (aim - current) * (1.0 - (-rate * dt).exp());
806            s.refold[index] = if (aim - next).abs() < 0.002 {
807                aim
808            } else {
809                next
810            };
811            if s.refold[index] != aim {
812                need_more_frames = true;
813            }
814        }
815    }
816    if need_more_frames {
817        window.request_animation_frame();
818    }
819
820    let refold_values = state.borrow().refold.clone();
821    let slat_delay = 0.24f64;
822
823    for (index, piece) in layout.pieces.iter().enumerate() {
824        let rank = config.stagger_rank(index, count);
825        let progress = config.piece_progress(elapsed, rank, reduced)
826            * (1.0 - config.piece_fold(elapsed, rank, count, reduced));
827        let tilt = refold_values.get(index).copied().unwrap_or(0.0) * config.refold_angle.max(0.0);
828        let crease_amount =
829            config.crease_shading.clamp(0.0, 1.0) * (1.0 - progress + tilt / 90.0).clamp(0.0, 1.0);
830        let opacity = progress.clamp(0.0, 1.0);
831
832        // 折起时几乎不可见:不画也能省掉大量路径填充。
833        if opacity <= 0.004 {
834            continue;
835        }
836
837        let (ox, oy) = to_screen(piece.bbox.center().0, piece.bbox.center().1);
838        // flip 是「绕自身中心翻面」(CSS 里 transform-origin: 50% 50%),
839        // 其余折法绕 hinge 边,混用会让翻面的字整体跑到面板外面。
840        let anchor = if config.fold_style == FoldStyle::Flip {
841            piece.bbox.center()
842        } else {
843            hinge_point(piece.bbox, config.hinge)
844        };
845        let (hx, hy) = to_screen(anchor.0, anchor.1);
846
847        if config.fold_style == FoldStyle::Blinds {
848            // 两片各占一半,错开 0.24s:先画上片,再画下片。
849            for (slat_index, slat) in [Slat::Upper, Slat::Lower].into_iter().enumerate() {
850                let offset = slat_index as f64 * slat_delay;
851                let local = config.piece_progress(elapsed - offset, rank, reduced)
852                    * (1.0 - config.piece_fold(elapsed - offset, rank, count, reduced));
853                let slat_opacity = local.clamp(0.0, 1.0);
854                if slat_opacity <= 0.004 {
855                    continue;
856                }
857                let (shx, shy) = slat_hinge(piece.bbox, slat, config.hinge);
858                let (shx, shy) = to_screen(shx, shy);
859                let panel = Panel {
860                    glyphs: &piece.glyphs,
861                    bbox: piece.bbox,
862                    hinge: (shx, shy),
863                    origin: (ox, oy),
864                    angle: (1.0 - local) * config.safe_angle() + tilt,
865                    opacity: slat_opacity,
866                    crease: crease_amount,
867                    slat: Some(slat),
868                };
869                draw_panel(
870                    &panel,
871                    config,
872                    axis_x,
873                    perspective,
874                    scale,
875                    to_screen,
876                    color,
877                    window,
878                );
879            }
880            continue;
881        }
882
883        let lift = if config.fold_style == FoldStyle::Flip && !reduced_angle {
884            config.font_size
885                * scale
886                * 0.45
887                * (std::f32::consts::PI * progress.clamp(0.0, 1.0)).sin()
888        } else {
889            0.0
890        };
891        let panel = Panel {
892            glyphs: &piece.glyphs,
893            bbox: piece.bbox,
894            hinge: (hx, hy),
895            origin: (ox, oy),
896            angle: (1.0 - progress) * config.safe_angle() + tilt,
897            opacity,
898            crease: crease_amount,
899            slat: None,
900        };
901        draw_panel_with_lift(
902            &panel,
903            config,
904            axis_x,
905            perspective,
906            scale,
907            to_screen,
908            lift,
909            color,
910            window,
911        );
912    }
913}
914
915fn hinge_point(bbox: Bbox, hinge: FoldHinge) -> (f32, f32) {
916    match hinge {
917        FoldHinge::Top => (bbox.center().0, bbox.top),
918        FoldHinge::Bottom => (bbox.center().0, bbox.bottom),
919        FoldHinge::Left => (bbox.left, bbox.center().1),
920        FoldHinge::Right => (bbox.right, bbox.center().1),
921    }
922}
923
924/// blinds 的两片绕着「上四分之一 / 下四分之三」的水平(或垂直)线翻开。
925fn slat_hinge(bbox: Bbox, slat: Slat, hinge: FoldHinge) -> (f32, f32) {
926    let (cx, cy) = bbox.center();
927    let quarter = match slat {
928        Slat::Upper => 0.25,
929        Slat::Lower => 0.75,
930    };
931    match hinge {
932        FoldHinge::Top | FoldHinge::Bottom => (cx, bbox.top + bbox.height() * quarter),
933        FoldHinge::Left | FoldHinge::Right => (bbox.left + bbox.width() * quarter, cy),
934    }
935}
936
937#[allow(clippy::too_many_arguments)]
938fn draw_panel(
939    panel: &Panel<'_>,
940    config: &FoldTextConfig,
941    axis_x: bool,
942    perspective: f32,
943    scale: f32,
944    to_screen: impl Fn(f32, f32) -> (f32, f32),
945    color: Hsla,
946    window: &mut Window,
947) {
948    draw_panel_with_lift(
949        panel,
950        config,
951        axis_x,
952        perspective,
953        scale,
954        to_screen,
955        0.0,
956        color,
957        window,
958    );
959}
960
961#[allow(clippy::too_many_arguments)]
962fn draw_panel_with_lift(
963    panel: &Panel<'_>,
964    _config: &FoldTextConfig,
965    axis_x: bool,
966    perspective: f32,
967    scale: f32,
968    to_screen: impl Fn(f32, f32) -> (f32, f32),
969    lift: f32,
970    color: Hsla,
971    window: &mut Window,
972) {
973    let theta = panel.angle.to_radians();
974    let (sin, cos) = (theta.sin(), theta.cos());
975    let (hx, hy) = panel.hinge;
976    let (ox, oy) = panel.origin;
977
978    // 绕铰链轴旋转,再以面板中心作透视原点投影。
979    let project = |x: f32, y: f32| -> (f32, f32) {
980        let (sx, sy) = to_screen(x, y);
981        let (rx, ry, depth) = if axis_x {
982            let dy = sy - hy;
983            (sx, hy + dy * cos, dy * sin)
984        } else {
985            let dx = sx - hx;
986            (hx + dx * cos, sy, dx * sin)
987        };
988        let depth = depth - lift;
989        let k = perspective / (perspective + depth).max(1.0);
990        (ox + (rx - ox) * k, oy + (ry - oy) * k)
991    };
992
993    let mut fill = PathBuilder::fill();
994    let mut any = false;
995    for glyph in panel.glyphs {
996        for contour in &glyph.contours {
997            let points: Vec<PathPoint> = match panel.slat {
998                None => contour.points.clone(),
999                Some(slat) => clip_half(contour.points.as_slice(), panel.bbox, slat, axis_x),
1000            };
1001            if points.len() < 3 {
1002                continue;
1003            }
1004            let first = project(points[0].x, points[0].y);
1005            fill.move_to(point(px(first.0), px(first.1)));
1006            for p in &points[1..] {
1007                let (x, y) = project(p.x, p.y);
1008                fill.line_to(point(px(x), px(y)));
1009            }
1010            fill.close();
1011            any = true;
1012        }
1013    }
1014    if !any {
1015        return;
1016    }
1017    let Ok(path) = fill.build() else { return };
1018
1019    let mut ink = color;
1020    ink.a *= panel.opacity;
1021    window.paint_path(path.clone(), ink);
1022
1023    // 折痕:参考实现用 `background-clip: text` 的渐变压在字上。这里没有渐变填充,
1024    // 改成沿折叠方向切 8 条带、各叠一层线性衰减的黑,再在远端补一条白色高光。
1025    // 带数少于 6 时,压扁的字形上会看出横向接缝。
1026    if panel.crease > 0.01 && panel.opacity > 0.05 {
1027        let shade = panel.crease * panel.opacity;
1028        const BANDS: usize = 8;
1029        for band in 0..BANDS {
1030            let from = band as f32 / BANDS as f32;
1031            // 相邻带的边界必须严格相接:多 1% 就会叠出一条更深的细线。
1032            let span = 1.0 / BANDS as f32;
1033            // 越靠近铰链越暗(纸面被抬起的阴影),远端几乎不留。
1034            let alpha = shade * 0.58 * (1.0 - from).powf(1.4);
1035            if alpha <= 0.008 {
1036                continue;
1037            }
1038            let Some(rect) = band_mask(panel.bbox, from, span, axis_x, &project) else {
1039                continue;
1040            };
1041            let dark = Hsla {
1042                h: 0.0,
1043                s: 0.0,
1044                l: 0.0,
1045                a: alpha.min(0.75),
1046            };
1047            window.with_content_mask(Some(ContentMask { bounds: rect }), |window| {
1048                window.paint_path(path.clone(), dark);
1049            });
1050        }
1051        // 远端(折叠边对面)的高光:纸被掀起时那一侧会亮。
1052        if let Some(rect) = band_mask(panel.bbox, 0.86, 0.14, axis_x, &project) {
1053            let highlight = Hsla {
1054                h: 0.0,
1055                s: 0.0,
1056                l: 1.0,
1057                a: (shade * 0.22).min(0.22),
1058            };
1059            window.with_content_mask(Some(ContentMask { bounds: rect }), |window| {
1060                window.paint_path(path.clone(), highlight);
1061            });
1062        }
1063    }
1064    let _ = scale;
1065}
1066
1067/// 把字形沿折叠方向切成上半 / 下半(或左半 / 右半),保证两片合起来严丝合缝。
1068fn clip_half(points: &[PathPoint], bbox: Bbox, slat: Slat, axis_x: bool) -> Vec<PathPoint> {
1069    // 两片在中线各多留 4%:两片的铰链不同,完全对齐时会有 1px 背景缝漏出来,
1070    // 重叠一点等于「两张纸叠着」,比露白更像纸。
1071    const OVERLAP: f32 = 0.04;
1072    if axis_x {
1073        let mid = bbox.top + bbox.height() * (0.5 + OVERLAP);
1074        let low = bbox.top + bbox.height() * (0.5 - OVERLAP);
1075        match slat {
1076            Slat::Upper => clip_polygon(points, mid, true, false),
1077            Slat::Lower => clip_polygon(points, low, false, false),
1078        }
1079    } else {
1080        let mid = bbox.left + bbox.width() * (0.5 + OVERLAP);
1081        let low = bbox.left + bbox.width() * (0.5 - OVERLAP);
1082        match slat {
1083            Slat::Upper => clip_polygon(points, mid, true, true),
1084            Slat::Lower => clip_polygon(points, low, false, true),
1085        }
1086    }
1087}
1088
1089/// Sutherland–Hodgman:沿一条轴对齐的直线裁剪多边形。
1090fn clip_polygon(points: &[PathPoint], at: f32, keep_less: bool, on_x: bool) -> Vec<PathPoint> {
1091    if points.is_empty() {
1092        return Vec::new();
1093    }
1094    let coord = |p: &PathPoint| if on_x { p.x } else { p.y };
1095    let inside = |p: &PathPoint| {
1096        if keep_less {
1097            coord(p) <= at
1098        } else {
1099            coord(p) >= at
1100        }
1101    };
1102    let mut out: Vec<PathPoint> = Vec::with_capacity(points.len() + 2);
1103    for index in 0..points.len() {
1104        let current = points[index];
1105        let previous = points[(index + points.len() - 1) % points.len()];
1106        let current_in = inside(&current);
1107        let previous_in = inside(&previous);
1108        if current_in != previous_in {
1109            let c0 = coord(&previous);
1110            let c1 = coord(&current);
1111            let t = if (c1 - c0).abs() < f32::EPSILON {
1112                0.0
1113            } else {
1114                (at - c0) / (c1 - c0)
1115            };
1116            let cut = PathPoint::new(
1117                previous.x + (current.x - previous.x) * t,
1118                previous.y + (current.y - previous.y) * t,
1119            );
1120            out.push(cut);
1121        }
1122        if current_in {
1123            out.push(current);
1124        }
1125    }
1126    out
1127}
1128
1129/// 折痕分带的裁剪矩形:取该带变换后的包围盒,略放大避免压边。
1130fn band_mask(
1131    bbox: Bbox,
1132    from: f32,
1133    span: f32,
1134    axis_x: bool,
1135    project: &impl Fn(f32, f32) -> (f32, f32),
1136) -> Option<Bounds<Pixels>> {
1137    let (y0, y1) = if axis_x {
1138        (
1139            bbox.top + bbox.height() * from,
1140            bbox.top + bbox.height() * (from + span),
1141        )
1142    } else {
1143        (bbox.top, bbox.bottom)
1144    };
1145    let (x0, x1) = if axis_x {
1146        (bbox.left, bbox.right)
1147    } else {
1148        (
1149            bbox.left + bbox.width() * from,
1150            bbox.left + bbox.width() * (from + span),
1151        )
1152    };
1153    let corners = [(x0, y0), (x1, y0), (x0, y1), (x1, y1)];
1154    let mut min_x = f32::MAX;
1155    let mut min_y = f32::MAX;
1156    let mut max_x = f32::MIN;
1157    let mut max_y = f32::MIN;
1158    for (x, y) in corners {
1159        let (px_, py_) = project(x, y);
1160        min_x = min_x.min(px_);
1161        min_y = min_y.min(py_);
1162        max_x = max_x.max(px_);
1163        max_y = max_y.max(py_);
1164    }
1165    if min_x == f32::MAX {
1166        return None;
1167    }
1168    // 不留余量:相邻带的矩形共边,pad 会在接缝处叠出更深的线。
1169    let pad = 0.0;
1170    Some(Bounds::new(
1171        point(px(min_x - pad), px(min_y - pad)),
1172        size(
1173            px((max_x - min_x) + pad * 2.0),
1174            px((max_y - min_y) + pad * 2.0),
1175        ),
1176    ))
1177}
1178
1179#[cfg(test)]
1180mod tests {
1181    use super::*;
1182
1183    #[test]
1184    fn unfold_timeline_matches_reference() {
1185        let config = FoldTextConfig::default();
1186        // 默认 0.65s 展开、0.045s 错开:第 4 个面板 0.135s 后才开始。
1187        assert_eq!(config.piece_progress(0.0, 0, false), 0.0);
1188        assert_eq!(config.piece_progress(0.65, 0, false), 1.0);
1189        assert!(config.piece_progress(0.10, 3, false) < 0.55);
1190        assert!((config.unfold_span(4) - (0.65 + 0.135)).abs() < 1e-9);
1191        // 减弱动画直接呈现终态。
1192        assert_eq!(config.piece_progress(0.0, 0, true), 1.0);
1193    }
1194
1195    #[test]
1196    fn stagger_origins_pick_the_right_order() {
1197        let mut config = FoldTextConfig::default();
1198        assert_eq!(config.stagger_rank(0, 5), 0);
1199        config.stagger_from = FoldStaggerFrom::End;
1200        assert_eq!(config.stagger_rank(0, 5), 4);
1201        config.stagger_from = FoldStaggerFrom::Center;
1202        // 中间那块最早,两端最晚。
1203        assert_eq!(config.stagger_rank(2, 5), 0);
1204        assert_eq!(config.stagger_rank(0, 5), 2);
1205        config.stagger_from = FoldStaggerFrom::Edges;
1206        assert_eq!(config.stagger_rank(0, 5), 0);
1207        assert_eq!(config.stagger_rank(2, 5), 2);
1208        // 随机起点必须可复现,否则截图和测试都不稳定。
1209        config.stagger_from = FoldStaggerFrom::Random;
1210        let a: Vec<_> = (0..8).map(|i| config.stagger_rank(i, 8)).collect();
1211        let b: Vec<_> = (0..8).map(|i| config.stagger_rank(i, 8)).collect();
1212        assert_eq!(a, b);
1213        assert!(a.iter().all(|rank| *rank < 8));
1214    }
1215
1216    #[test]
1217    fn layout_splits_by_grapheme_word_and_line() {
1218        let config = FoldTextConfig::default();
1219        let by_char = cached_layout("Arc", &config).unwrap();
1220        assert_eq!(by_char.pieces.len(), 3);
1221
1222        let words = FoldTextConfig {
1223            split_by: FoldSplit::Word,
1224            ..Default::default()
1225        };
1226        assert_eq!(cached_layout("Arc rs", &words).unwrap().pieces.len(), 2);
1227
1228        let lines = FoldTextConfig {
1229            split_by: FoldSplit::Line,
1230            ..Default::default()
1231        };
1232        let two_lines = cached_layout("Arc\nrs", &lines).unwrap();
1233        assert_eq!(two_lines.pieces.len(), 2);
1234        assert!(two_lines.bbox.height() > config.font_size);
1235    }
1236
1237    #[test]
1238    fn every_piece_reports_its_own_ink_box() {
1239        let layout = cached_layout("Fold", &FoldTextConfig::default()).unwrap();
1240        for piece in &layout.pieces {
1241            assert!(piece.bbox.width() > 0.5, "{:?}", piece.bbox);
1242            assert!(piece.bbox.height() > 0.5, "{:?}", piece.bbox);
1243        }
1244        // 逐字排版的方向必须递增,否则铰链会叠在一起。
1245        assert!(layout.pieces[0].bbox.left < layout.pieces[1].bbox.left);
1246    }
1247
1248    #[test]
1249    fn slat_clipping_splits_a_contour_in_two() {
1250        let square = vec![
1251            PathPoint::new(0.0, 0.0),
1252            PathPoint::new(10.0, 0.0),
1253            PathPoint::new(10.0, 10.0),
1254            PathPoint::new(0.0, 10.0),
1255        ];
1256        let upper = clip_polygon(&square, 5.0, true, false);
1257        let lower = clip_polygon(&square, 5.0, false, false);
1258        assert!(upper.iter().all(|p| p.y <= 5.0));
1259        assert!(lower.iter().all(|p| p.y >= 5.0));
1260        assert_eq!(upper.len(), 4);
1261        assert_eq!(lower.len(), 4);
1262    }
1263}