arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
//! FoldText:把 React Bits 的 3D 折纸文字移植到原生 GPUI。
//!
//! 关键差异:GPUI 没有 3D 变换管线,也没有 `perspective` / `transform-origin`。
//! 这里不复用 2D 的 `scaleY = cos θ` 近似,而是拿真实字形轮廓逐顶点做
//! 「绕铰链轴旋转 → 透视投影」,因此折叠中途的近大远小、翻过背面都是真算出来的。

use std::{
    cell::RefCell,
    collections::HashMap,
    rc::Rc,
    sync::{Arc, Mutex, OnceLock},
};

use arc_motion::{PathPoint, PolylinePath, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
    App, Bounds, ContentMask, ElementId, Hsla, InteractiveElement as _, IntoElement,
    MouseMoveEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window, canvas, div, point, prelude::*, px, size,
};

use super::glyph_outline::{Outline, with_face};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldStyle {
    /// 整块面板绕一条边翻开。
    #[default]
    Paper,
    /// 上下(或左右)两片各自翻开,错开 0.24s。
    Blinds,
    /// 翻整整半圈,中途抬起靠近相机。
    Flip,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldSplit {
    #[default]
    Char,
    Word,
    Line,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldHinge {
    #[default]
    Top,
    Bottom,
    Left,
    Right,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldTrigger {
    #[default]
    Mount,
    Hover,
    Scroll,
    Loop,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldStaggerFrom {
    #[default]
    Start,
    Center,
    End,
    Edges,
    Random,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FoldEase {
    #[default]
    Power3Out,
    Power2Out,
    Power1Out,
    Linear,
}

impl FoldEase {
    pub fn sample(self, t: f32) -> f32 {
        let t = t.clamp(0.0, 1.0);
        match self {
            Self::Linear => t,
            Self::Power1Out => 1.0 - (1.0 - t).powi(2),
            Self::Power2Out => 1.0 - (1.0 - t).powi(3),
            Self::Power3Out => 1.0 - (1.0 - t).powi(4),
        }
    }
}

/// 与参考实现同名同义的配置;颜色为空时跟随当前文字色。
#[derive(Clone, Debug, PartialEq)]
pub struct FoldTextConfig {
    pub fold_style: FoldStyle,
    pub split_by: FoldSplit,
    pub hinge: FoldHinge,
    pub trigger: FoldTrigger,
    pub stagger_from: FoldStaggerFrom,
    pub fold_angle: f32,
    pub duration: f64,
    pub stagger: f64,
    pub ease: FoldEase,
    pub perspective: f32,
    pub crease_shading: f32,
    pub loop_delay: f64,
    pub hover_refold: bool,
    pub refold_radius: f32,
    pub refold_angle: f32,
    pub font_size: f32,
    pub font_weight: u16,
    pub letter_spacing: f32,
    pub font_family: String,
    pub color: Option<Hsla>,
}

impl Default for FoldTextConfig {
    fn default() -> Self {
        Self {
            fold_style: FoldStyle::Paper,
            split_by: FoldSplit::Char,
            hinge: FoldHinge::Top,
            trigger: FoldTrigger::Mount,
            stagger_from: FoldStaggerFrom::Start,
            fold_angle: 92.0,
            duration: 0.65,
            stagger: 0.045,
            ease: FoldEase::Power3Out,
            perspective: 700.0,
            crease_shading: 0.55,
            loop_delay: 1.4,
            hover_refold: false,
            refold_radius: 140.0,
            refold_angle: 45.0,
            font_size: 80.0,
            font_weight: 800,
            letter_spacing: -2.0,
            font_family: Typography::display_family().into(),
            color: None,
        }
    }
}

impl FoldTextConfig {
    /// 单片文字的展开时长(含缓动,不含错开)。
    fn piece_duration(&self) -> f64 {
        self.duration.max(0.08)
    }

    /// 整段文字展开完成所需时间:时长 + 最后一个面板的错开。
    pub fn unfold_span(&self, count: usize) -> f64 {
        self.piece_duration() + self.stagger.max(0.0) * count.saturating_sub(1) as f64
    }

    /// 循环模式下的一次完整周期:展开 → 保持 → 折回。
    pub fn cycle_span(&self, count: usize) -> f64 {
        let unfold = self.unfold_span(count);
        let fold =
            self.piece_duration() * 0.75 + self.stagger.max(0.0) * count.saturating_sub(1) as f64;
        unfold + self.loop_delay.max(0.0) + fold
    }

    fn safe_angle(&self) -> f32 {
        if self.fold_style == FoldStyle::Flip {
            180.0
        } else {
            self.fold_angle.clamp(0.0, 180.0)
        }
    }

    /// 单片在给定时刻的展开进度(0=完全折起,1=摊平)。
    fn piece_progress(&self, elapsed: f64, rank: usize, reduced: bool) -> f32 {
        if reduced {
            return 1.0;
        }
        let local = (elapsed - self.stagger.max(0.0) * rank as f64) / self.piece_duration();
        self.ease.sample(local as f32)
    }

    /// 循环模式下单片折回的进度。
    fn piece_fold(&self, elapsed: f64, rank: usize, count: usize, reduced: bool) -> f32 {
        if reduced || self.trigger != FoldTrigger::Loop {
            return 0.0;
        }
        let unfold = self.unfold_span(count);
        let fold = self.piece_duration() * 0.75;
        let local =
            (elapsed - unfold - self.loop_delay.max(0.0) - self.stagger.max(0.0) * rank as f64)
                / fold;
        FoldEase::Power2Out.sample(local as f32)
    }

    /// 错开起点换算成「第几个才开始」,用序号排序而不是直接乘。
    pub fn stagger_rank(&self, index: usize, count: usize) -> usize {
        let last = count.saturating_sub(1);
        match self.stagger_from {
            FoldStaggerFrom::Start => index,
            FoldStaggerFrom::End => last.saturating_sub(index),
            FoldStaggerFrom::Center => {
                let mid = last as f32 / 2.0;
                ((index as f32 - mid).abs().round() as usize).min(last)
            }
            FoldStaggerFrom::Edges => {
                let mid = last as f32 / 2.0;
                (mid - (index as f32 - mid).abs()).round().max(0.0) as usize
            }
            // 固定种子:截图与测试里同一份文本每次得到同样的顺序。
            FoldStaggerFrom::Random => {
                let mut seed = (index as u32).wrapping_mul(2_654_435_761) ^ 0x9E37_79B9;
                seed ^= seed >> 15;
                seed = seed.wrapping_mul(2_246_822_519);
                seed ^= seed >> 13;
                (seed as usize) % count.max(1)
            }
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct Bbox {
    left: f32,
    top: f32,
    right: f32,
    bottom: f32,
}

impl Bbox {
    fn width(self) -> f32 {
        (self.right - self.left).max(0.001)
    }
    fn height(self) -> f32 {
        (self.bottom - self.top).max(0.001)
    }
    fn center(self) -> (f32, f32) {
        (
            (self.left + self.right) / 2.0,
            (self.top + self.bottom) / 2.0,
        )
    }
}

#[derive(Clone, Debug)]
struct Glyph {
    contours: Vec<PolylinePath>,
}

#[derive(Clone, Debug)]
struct Piece {
    glyphs: Vec<Glyph>,
    bbox: Bbox,
}

#[derive(Clone, Debug)]
struct Layout {
    pieces: Vec<Piece>,
    bbox: Bbox,
}

type LayoutResult = Result<Arc<Layout>, String>;

static LAYOUTS: OnceLock<Mutex<HashMap<String, Arc<Layout>>>> = OnceLock::new();

fn layout_key(text: &str, config: &FoldTextConfig) -> String {
    format!(
        "{}|{:?}|{:?}|{}|{}|{}",
        text,
        config.split_by,
        config.fold_style,
        config.font_family,
        config.font_weight,
        config.font_size
    )
}

fn cached_layout(text: &str, config: &FoldTextConfig) -> LayoutResult {
    let key = layout_key(text, config);
    let cache = LAYOUTS.get_or_init(Default::default);
    if let Some(hit) = cache
        .lock()
        .map_err(|_| "字形缓存不可用")?
        .get(&key)
        .cloned()
    {
        return Ok(hit);
    }
    let built = build_layout(text, config)?;
    let mut cache = cache.lock().map_err(|_| "字形缓存不可用")?;
    if cache.len() >= 32 {
        cache.clear();
    }
    cache.insert(key, built.clone());
    Ok(built)
}

/// 排版:先按 `\n` 折行,再按 `split_by` 切成面板。
fn build_layout(text: &str, config: &FoldTextConfig) -> LayoutResult {
    let scale = config.font_size.clamp(8.0, 512.0);
    let metrics = with_face(&config.font_family, config.font_weight, |face| {
        let unit = scale / face.units_per_em() as f32;
        let line_height = scale * 1.12;
        let space = face
            .glyph_index(' ')
            .and_then(|id| face.glyph_hor_advance(id))
            .unwrap_or(face.units_per_em() / 3) as f32
            * unit;

        // 每行内按面板切分;空格只推进笔位,不单独成为面板。
        let mut pieces = Vec::new();
        let mut lines = 0usize;
        let mut union = Bbox {
            left: f32::MAX,
            top: f32::MAX,
            right: f32::MIN,
            bottom: f32::MIN,
        };

        for (line_index, line) in text.split('\n').enumerate() {
            lines = line_index + 1;
            let mut pen_x = 0.0f32;
            let line_top = line_index as f32 * line_height;
            match config.split_by {
                FoldSplit::Char => {
                    for ch in line.chars() {
                        if ch.is_whitespace() {
                            pen_x += space + config.letter_spacing;
                            continue;
                        }
                        let id = face
                            .glyph_index(ch)
                            .ok_or_else(|| format!("当前字体不包含字符:{ch}"))?;
                        let mut outline = Outline::glyph(face, id);
                        let ink = scale_outline(&mut outline, unit, pen_x, line_top);
                        let advance = face.glyph_hor_advance(id).unwrap_or(0) as f32 * unit;
                        let bbox = ink.unwrap_or(Bbox {
                            left: pen_x,
                            top: line_top,
                            right: pen_x + advance,
                            bottom: line_top + scale,
                        });
                        union = union_or(union, bbox);
                        pieces.push(Piece {
                            glyphs: vec![Glyph {
                                contours: outline.contours,
                            }],
                            bbox,
                        });
                        pen_x += advance + config.letter_spacing;
                    }
                }
                FoldSplit::Word | FoldSplit::Line => {
                    let groups: Vec<&str> = if config.split_by == FoldSplit::Line {
                        vec![line]
                    } else {
                        line.split_whitespace().collect()
                    };
                    for (group_index, group) in groups.into_iter().enumerate() {
                        if group.is_empty() {
                            continue;
                        }
                        // 词与词之间补一个空格宽度,保持与整行排版一致。
                        if group_index > 0 {
                            pen_x += space + config.letter_spacing;
                        }
                        let mut glyphs = Vec::new();
                        let mut ink: Option<Bbox> = None;
                        for ch in group.chars() {
                            if ch.is_whitespace() {
                                pen_x += space + config.letter_spacing;
                                continue;
                            }
                            let id = face
                                .glyph_index(ch)
                                .ok_or_else(|| format!("当前字体不包含字符:{ch}"))?;
                            let mut outline = Outline::glyph(face, id);
                            if let Some(b) = scale_outline(&mut outline, unit, pen_x, line_top) {
                                ink = Some(match ink {
                                    Some(prev) => union_or(prev, b),
                                    None => b,
                                });
                            }
                            glyphs.push(Glyph {
                                contours: outline.contours,
                            });
                            let advance = face.glyph_hor_advance(id).unwrap_or(0) as f32 * unit;
                            pen_x += advance + config.letter_spacing;
                        }
                        if let Some(bbox) = ink {
                            union = union_or(union, bbox);
                            pieces.push(Piece { glyphs, bbox });
                        }
                    }
                }
            }
        }

        Ok((pieces, lines, union))
    })?;

    let (mut pieces, lines, union) = metrics;
    if pieces.is_empty() {
        return Err("没有可折叠的文字".to_string());
    }
    let bbox = if union.left == f32::MAX {
        Bbox {
            left: 0.0,
            top: 0.0,
            right: scale,
            bottom: scale,
        }
    } else {
        union
    };
    // 统一下移,让 bbox 顶部为 0,便于按容器垂直居中。
    for piece in &mut pieces {
        for glyph in &mut piece.glyphs {
            for contour in &mut glyph.contours {
                for p in &mut contour.points {
                    p.y -= bbox.top;
                }
            }
        }
        piece.bbox.top -= bbox.top;
        piece.bbox.bottom -= bbox.top;
    }
    let _ = lines;
    Ok(Arc::new(Layout {
        pieces,
        bbox: Bbox {
            left: bbox.left,
            top: 0.0,
            right: bbox.right,
            bottom: bbox.bottom - bbox.top,
        },
    }))
}

fn union_or(a: Bbox, b: Bbox) -> Bbox {
    Bbox {
        left: a.left.min(b.left),
        top: a.top.min(b.top),
        right: a.right.max(b.right),
        bottom: a.bottom.max(b.bottom),
    }
}

/// 把字体单位换算成像素并平移到排版位置,同时返回该字形的 ink 范围。
fn scale_outline(outline: &mut Outline, unit: f32, pen_x: f32, line_top: f32) -> Option<Bbox> {
    if outline.contours.is_empty() {
        return None;
    }
    let mut bbox = Bbox {
        left: f32::MAX,
        top: f32::MAX,
        right: f32::MIN,
        bottom: f32::MIN,
    };
    for contour in &mut outline.contours {
        for p in &mut contour.points {
            p.x = p.x * unit + pen_x;
            p.y = p.y * unit + line_top;
            bbox.left = bbox.left.min(p.x);
            bbox.top = bbox.top.min(p.y);
            bbox.right = bbox.right.max(p.x);
            bbox.bottom = bbox.bottom.max(p.y);
        }
    }
    (bbox.left != f32::MAX).then_some(bbox)
}

/// 提前在后台预热,避免首帧卡在字体查询上。
pub fn prepare_fold_text(text: &str, config: &FoldTextConfig) -> Result<(), String> {
    cached_layout(text, config).map(|_| ())
}

struct State {
    key: String,
    generation: u64,
    geometry: Option<LayoutResult>,
    started: Option<f64>,
    visible: bool,
    hovered: bool,
    replay: u64,
    pointer: Option<(f32, f32)>,
    /// 每片当前的回来量(0 摊平,1 最折)。
    refold: Vec<f32>,
    /// 每片目标值,指针移动时更新,帧内指数收敛。
    aim: Vec<f32>,
    /// 上一帧时间戳,用于把 refold 的缓动做成与帧率无关。
    last_frame: f64,
    /// 每片面心的屏幕坐标,指针靠近时算距离用。
    centers: Vec<(f32, f32)>,
}

impl State {
    fn new() -> Self {
        Self {
            key: String::new(),
            generation: 0,
            geometry: None,
            started: None,
            visible: false,
            hovered: false,
            replay: 0,
            pointer: None,
            refold: Vec::new(),
            aim: Vec::new(),
            last_frame: 0.0,
            centers: Vec::new(),
        }
    }
}

/// 一片要绘制的面板:字形 + 铰链位置 + 该片自己的时序。
struct Panel<'a> {
    glyphs: &'a [Glyph],
    bbox: Bbox,
    /// 铰链在屏幕坐标里的位置。
    hinge: (f32, f32),
    /// 透视原点(面板中心)。
    origin: (f32, f32),
    angle: f32,
    opacity: f32,
    crease: f32,
    /// 只画上半 / 下半(blinds);None 表示整片。
    slat: Option<Slat>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Slat {
    Upper,
    Lower,
}

#[derive(IntoElement)]
pub struct FoldText {
    id: ElementId,
    text: SharedString,
    config: FoldTextConfig,
    replay: u64,
    elapsed: Option<f64>,
}

impl FoldText {
    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            text: text.into(),
            config: FoldTextConfig::default(),
            replay: 0,
            elapsed: None,
        }
    }

    pub fn config(mut self, config: FoldTextConfig) -> 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 FoldText {
    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(), "fold-state".into()),
            cx,
            |_, _| Rc::new(RefCell::new(State::new())),
        );
        let state = state.read(cx).clone();

        let key = layout_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;
            s.refold.clear();
            s.aim.clear();
            s.centers.clear();
            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 { cached_layout(&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());
        let piece_count = s
            .geometry
            .as_ref()
            .and_then(|r| r.as_ref().ok())
            .map(|l| l.pieces.len())
            .unwrap_or(0);
        let starts_on_its_own =
            matches!(self.config.trigger, FoldTrigger::Mount | FoldTrigger::Loop)
                || (self.config.trigger == FoldTrigger::Scroll && s.visible);
        if ready && s.started.is_none() && starts_on_its_own {
            s.started = Some(now);
        }
        if s.refold.len() != piece_count {
            s.refold = vec![0.0; piece_count];
            s.aim = vec![0.0; piece_count];
        }

        let cycle = self.config.cycle_span(piece_count);
        let elapsed = self.elapsed.unwrap_or_else(|| {
            s.started.map_or(
                if self.config.trigger == FoldTrigger::Hover {
                    cycle.max(self.config.unfold_span(piece_count))
                } else {
                    0.0
                },
                |start| now - start,
            )
        });
        let looping =
            self.config.trigger == FoldTrigger::Loop && self.elapsed.is_none() && !reduced;
        let phase = if looping {
            elapsed.rem_euclid(cycle.max(0.1))
        } else {
            elapsed
        };
        // 只在「已经开始且还没播完」时请求帧;hover 未触发时不该空转。
        let animating = self.elapsed.is_none()
            && !reduced
            && s.visible
            && ready
            && s.started.is_some()
            && (looping || elapsed < self.config.unfold_span(piece_count) + 0.05);
        drop(s);
        if animating {
            window.request_animation_frame();
        }

        let paint_state = state.clone();
        let hover_state = state.clone();
        let move_state = state.clone();
        let config = self.config.clone();
        let color = self.config.color.unwrap_or(foreground);
        let height = {
            let line_count = self.text.chars().filter(|c| *c == '\n').count() as f32 + 1.0;
            self.config.font_size.clamp(8.0, 512.0) * 1.12 * line_count + 24.0
        };

        div()
            .id(self.id)
            .test_support()
            .role(Role::Image)
            .aria_label(self.text.clone())
            .relative()
            .w_full()
            .min_w_0()
            .h(px(height))
            .on_hover(move |hovered, window, cx| {
                let mut s = hover_state.borrow_mut();
                let was = s.hovered;
                s.hovered = *hovered;
                if !*hovered {
                    s.pointer = None;
                    for aim in &mut s.aim {
                        *aim = 0.0;
                    }
                }
                if was != *hovered {
                    window.refresh();
                }
                let _ = cx;
            })
            .on_mouse_move(move |event: &MouseMoveEvent, window, _| {
                let mut s = move_state.borrow_mut();
                s.pointer = Some((f32::from(event.position.x), f32::from(event.position.y)));
                window.refresh();
            })
            .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, cx| {
                        let geometry = state.borrow().geometry.clone();
                        let Some(Ok(layout)) = geometry else { return };
                        paint_layout(
                            &layout,
                            &config,
                            phase,
                            reduced,
                            color,
                            bounds,
                            motion_now(cx),
                            &state,
                            window,
                        );
                    },
                )
                .size_full(),
            )
    }
}

/// 逐片、逐顶点做旋转与透视投影,然后填充真实字形轮廓。
#[allow(clippy::too_many_arguments)]
fn paint_layout(
    layout: &Layout,
    config: &FoldTextConfig,
    elapsed: f64,
    reduced: bool,
    color: Hsla,
    bounds: Bounds<Pixels>,
    now: f64,
    state: &Rc<RefCell<State>>,
    window: &mut Window,
) {
    let count = layout.pieces.len();
    let box_w = f32::from(bounds.size.width);
    let box_h = f32::from(bounds.size.height);
    let fit = (box_w - 24.0) / layout.bbox.width().max(1.0);
    let fit_h = (box_h - 24.0) / layout.bbox.height().max(1.0);
    let scale = fit.min(fit_h).clamp(0.01, 1.0);
    let offset_x = f32::from(bounds.origin.x) + (box_w - layout.bbox.width() * scale) / 2.0
        - layout.bbox.left * scale;
    let offset_y = f32::from(bounds.origin.y) + (box_h - layout.bbox.height() * scale) / 2.0;
    let to_screen = |x: f32, y: f32| (offset_x + x * scale, offset_y + y * scale);

    let perspective = config.perspective.clamp(120.0, 4000.0);
    let axis_x = matches!(config.hinge, FoldHinge::Top | FoldHinge::Bottom);
    let reduced_angle = reduced;

    // 每片面心缓存:指针在附近时按距离算回来量。

    let mut need_more_frames = false;
    {
        let mut s = state.borrow_mut();
        if s.centers.len() != count {
            s.centers = vec![(0.0, 0.0); count];
        }
        for (index, piece) in layout.pieces.iter().enumerate() {
            let (cx, cy) = piece.bbox.center();
            let (sx, sy) = to_screen(cx, cy);
            s.centers[index] = (sx, sy);
        }
        // 指针 → 目标回来量;没有指针时全部归零。
        let pointer = s.pointer;
        let radius = config.refold_radius.max(1.0);
        let want = config.hover_refold && !reduced && pointer.is_some();
        for index in 0..count {
            let mut target = 0.0;
            if want && let Some((px, py)) = pointer {
                let (cx, cy) = s.centers[index];
                let distance = ((cx - px).powi(2) + (cy - py).powi(2)).sqrt() / radius;
                if distance < 1.0 {
                    // 与参考实现同一条 smoothstep:中心最强,边缘平滑归零。
                    target = 1.0 - distance * distance * (3.0 - 2.0 * distance);
                }
            }
            s.aim[index] = target;
        }
        // 指数收敛:与帧率无关,收敛后停帧。
        let dt = (now - s.last_frame).clamp(0.0, 0.064) as f32;
        s.last_frame = now;
        for index in 0..count {
            let aim = s.aim[index];
            let current = s.refold[index];
            let rate: f32 = if aim > current { 14.0 } else { 6.0 };
            let next = current + (aim - current) * (1.0 - (-rate * dt).exp());
            s.refold[index] = if (aim - next).abs() < 0.002 {
                aim
            } else {
                next
            };
            if s.refold[index] != aim {
                need_more_frames = true;
            }
        }
    }
    if need_more_frames {
        window.request_animation_frame();
    }

    let refold_values = state.borrow().refold.clone();
    let slat_delay = 0.24f64;

    for (index, piece) in layout.pieces.iter().enumerate() {
        let rank = config.stagger_rank(index, count);
        let progress = config.piece_progress(elapsed, rank, reduced)
            * (1.0 - config.piece_fold(elapsed, rank, count, reduced));
        let tilt = refold_values.get(index).copied().unwrap_or(0.0) * config.refold_angle.max(0.0);
        let crease_amount =
            config.crease_shading.clamp(0.0, 1.0) * (1.0 - progress + tilt / 90.0).clamp(0.0, 1.0);
        let opacity = progress.clamp(0.0, 1.0);

        // 折起时几乎不可见:不画也能省掉大量路径填充。
        if opacity <= 0.004 {
            continue;
        }

        let (ox, oy) = to_screen(piece.bbox.center().0, piece.bbox.center().1);
        // flip 是「绕自身中心翻面」(CSS 里 transform-origin: 50% 50%),
        // 其余折法绕 hinge 边,混用会让翻面的字整体跑到面板外面。
        let anchor = if config.fold_style == FoldStyle::Flip {
            piece.bbox.center()
        } else {
            hinge_point(piece.bbox, config.hinge)
        };
        let (hx, hy) = to_screen(anchor.0, anchor.1);

        if config.fold_style == FoldStyle::Blinds {
            // 两片各占一半,错开 0.24s:先画上片,再画下片。
            for (slat_index, slat) in [Slat::Upper, Slat::Lower].into_iter().enumerate() {
                let offset = slat_index as f64 * slat_delay;
                let local = config.piece_progress(elapsed - offset, rank, reduced)
                    * (1.0 - config.piece_fold(elapsed - offset, rank, count, reduced));
                let slat_opacity = local.clamp(0.0, 1.0);
                if slat_opacity <= 0.004 {
                    continue;
                }
                let (shx, shy) = slat_hinge(piece.bbox, slat, config.hinge);
                let (shx, shy) = to_screen(shx, shy);
                let panel = Panel {
                    glyphs: &piece.glyphs,
                    bbox: piece.bbox,
                    hinge: (shx, shy),
                    origin: (ox, oy),
                    angle: (1.0 - local) * config.safe_angle() + tilt,
                    opacity: slat_opacity,
                    crease: crease_amount,
                    slat: Some(slat),
                };
                draw_panel(
                    &panel,
                    config,
                    axis_x,
                    perspective,
                    scale,
                    to_screen,
                    color,
                    window,
                );
            }
            continue;
        }

        let lift = if config.fold_style == FoldStyle::Flip && !reduced_angle {
            config.font_size
                * scale
                * 0.45
                * (std::f32::consts::PI * progress.clamp(0.0, 1.0)).sin()
        } else {
            0.0
        };
        let panel = Panel {
            glyphs: &piece.glyphs,
            bbox: piece.bbox,
            hinge: (hx, hy),
            origin: (ox, oy),
            angle: (1.0 - progress) * config.safe_angle() + tilt,
            opacity,
            crease: crease_amount,
            slat: None,
        };
        draw_panel_with_lift(
            &panel,
            config,
            axis_x,
            perspective,
            scale,
            to_screen,
            lift,
            color,
            window,
        );
    }
}

fn hinge_point(bbox: Bbox, hinge: FoldHinge) -> (f32, f32) {
    match hinge {
        FoldHinge::Top => (bbox.center().0, bbox.top),
        FoldHinge::Bottom => (bbox.center().0, bbox.bottom),
        FoldHinge::Left => (bbox.left, bbox.center().1),
        FoldHinge::Right => (bbox.right, bbox.center().1),
    }
}

/// blinds 的两片绕着「上四分之一 / 下四分之三」的水平(或垂直)线翻开。
fn slat_hinge(bbox: Bbox, slat: Slat, hinge: FoldHinge) -> (f32, f32) {
    let (cx, cy) = bbox.center();
    let quarter = match slat {
        Slat::Upper => 0.25,
        Slat::Lower => 0.75,
    };
    match hinge {
        FoldHinge::Top | FoldHinge::Bottom => (cx, bbox.top + bbox.height() * quarter),
        FoldHinge::Left | FoldHinge::Right => (bbox.left + bbox.width() * quarter, cy),
    }
}

#[allow(clippy::too_many_arguments)]
fn draw_panel(
    panel: &Panel<'_>,
    config: &FoldTextConfig,
    axis_x: bool,
    perspective: f32,
    scale: f32,
    to_screen: impl Fn(f32, f32) -> (f32, f32),
    color: Hsla,
    window: &mut Window,
) {
    draw_panel_with_lift(
        panel,
        config,
        axis_x,
        perspective,
        scale,
        to_screen,
        0.0,
        color,
        window,
    );
}

#[allow(clippy::too_many_arguments)]
fn draw_panel_with_lift(
    panel: &Panel<'_>,
    _config: &FoldTextConfig,
    axis_x: bool,
    perspective: f32,
    scale: f32,
    to_screen: impl Fn(f32, f32) -> (f32, f32),
    lift: f32,
    color: Hsla,
    window: &mut Window,
) {
    let theta = panel.angle.to_radians();
    let (sin, cos) = (theta.sin(), theta.cos());
    let (hx, hy) = panel.hinge;
    let (ox, oy) = panel.origin;

    // 绕铰链轴旋转,再以面板中心作透视原点投影。
    let project = |x: f32, y: f32| -> (f32, f32) {
        let (sx, sy) = to_screen(x, y);
        let (rx, ry, depth) = if axis_x {
            let dy = sy - hy;
            (sx, hy + dy * cos, dy * sin)
        } else {
            let dx = sx - hx;
            (hx + dx * cos, sy, dx * sin)
        };
        let depth = depth - lift;
        let k = perspective / (perspective + depth).max(1.0);
        (ox + (rx - ox) * k, oy + (ry - oy) * k)
    };

    let mut fill = PathBuilder::fill();
    let mut any = false;
    for glyph in panel.glyphs {
        for contour in &glyph.contours {
            let points: Vec<PathPoint> = match panel.slat {
                None => contour.points.clone(),
                Some(slat) => clip_half(contour.points.as_slice(), panel.bbox, slat, axis_x),
            };
            if points.len() < 3 {
                continue;
            }
            let first = project(points[0].x, points[0].y);
            fill.move_to(point(px(first.0), px(first.1)));
            for p in &points[1..] {
                let (x, y) = project(p.x, p.y);
                fill.line_to(point(px(x), px(y)));
            }
            fill.close();
            any = true;
        }
    }
    if !any {
        return;
    }
    let Ok(path) = fill.build() else { return };

    let mut ink = color;
    ink.a *= panel.opacity;
    window.paint_path(path.clone(), ink);

    // 折痕:参考实现用 `background-clip: text` 的渐变压在字上。这里没有渐变填充,
    // 改成沿折叠方向切 8 条带、各叠一层线性衰减的黑,再在远端补一条白色高光。
    // 带数少于 6 时,压扁的字形上会看出横向接缝。
    if panel.crease > 0.01 && panel.opacity > 0.05 {
        let shade = panel.crease * panel.opacity;
        const BANDS: usize = 8;
        for band in 0..BANDS {
            let from = band as f32 / BANDS as f32;
            // 相邻带的边界必须严格相接:多 1% 就会叠出一条更深的细线。
            let span = 1.0 / BANDS as f32;
            // 越靠近铰链越暗(纸面被抬起的阴影),远端几乎不留。
            let alpha = shade * 0.58 * (1.0 - from).powf(1.4);
            if alpha <= 0.008 {
                continue;
            }
            let Some(rect) = band_mask(panel.bbox, from, span, axis_x, &project) else {
                continue;
            };
            let dark = Hsla {
                h: 0.0,
                s: 0.0,
                l: 0.0,
                a: alpha.min(0.75),
            };
            window.with_content_mask(Some(ContentMask { bounds: rect }), |window| {
                window.paint_path(path.clone(), dark);
            });
        }
        // 远端(折叠边对面)的高光:纸被掀起时那一侧会亮。
        if let Some(rect) = band_mask(panel.bbox, 0.86, 0.14, axis_x, &project) {
            let highlight = Hsla {
                h: 0.0,
                s: 0.0,
                l: 1.0,
                a: (shade * 0.22).min(0.22),
            };
            window.with_content_mask(Some(ContentMask { bounds: rect }), |window| {
                window.paint_path(path.clone(), highlight);
            });
        }
    }
    let _ = scale;
}

/// 把字形沿折叠方向切成上半 / 下半(或左半 / 右半),保证两片合起来严丝合缝。
fn clip_half(points: &[PathPoint], bbox: Bbox, slat: Slat, axis_x: bool) -> Vec<PathPoint> {
    // 两片在中线各多留 4%:两片的铰链不同,完全对齐时会有 1px 背景缝漏出来,
    // 重叠一点等于「两张纸叠着」,比露白更像纸。
    const OVERLAP: f32 = 0.04;
    if axis_x {
        let mid = bbox.top + bbox.height() * (0.5 + OVERLAP);
        let low = bbox.top + bbox.height() * (0.5 - OVERLAP);
        match slat {
            Slat::Upper => clip_polygon(points, mid, true, false),
            Slat::Lower => clip_polygon(points, low, false, false),
        }
    } else {
        let mid = bbox.left + bbox.width() * (0.5 + OVERLAP);
        let low = bbox.left + bbox.width() * (0.5 - OVERLAP);
        match slat {
            Slat::Upper => clip_polygon(points, mid, true, true),
            Slat::Lower => clip_polygon(points, low, false, true),
        }
    }
}

/// Sutherland–Hodgman:沿一条轴对齐的直线裁剪多边形。
fn clip_polygon(points: &[PathPoint], at: f32, keep_less: bool, on_x: bool) -> Vec<PathPoint> {
    if points.is_empty() {
        return Vec::new();
    }
    let coord = |p: &PathPoint| if on_x { p.x } else { p.y };
    let inside = |p: &PathPoint| {
        if keep_less {
            coord(p) <= at
        } else {
            coord(p) >= at
        }
    };
    let mut out: Vec<PathPoint> = Vec::with_capacity(points.len() + 2);
    for index in 0..points.len() {
        let current = points[index];
        let previous = points[(index + points.len() - 1) % points.len()];
        let current_in = inside(&current);
        let previous_in = inside(&previous);
        if current_in != previous_in {
            let c0 = coord(&previous);
            let c1 = coord(&current);
            let t = if (c1 - c0).abs() < f32::EPSILON {
                0.0
            } else {
                (at - c0) / (c1 - c0)
            };
            let cut = PathPoint::new(
                previous.x + (current.x - previous.x) * t,
                previous.y + (current.y - previous.y) * t,
            );
            out.push(cut);
        }
        if current_in {
            out.push(current);
        }
    }
    out
}

/// 折痕分带的裁剪矩形:取该带变换后的包围盒,略放大避免压边。
fn band_mask(
    bbox: Bbox,
    from: f32,
    span: f32,
    axis_x: bool,
    project: &impl Fn(f32, f32) -> (f32, f32),
) -> Option<Bounds<Pixels>> {
    let (y0, y1) = if axis_x {
        (
            bbox.top + bbox.height() * from,
            bbox.top + bbox.height() * (from + span),
        )
    } else {
        (bbox.top, bbox.bottom)
    };
    let (x0, x1) = if axis_x {
        (bbox.left, bbox.right)
    } else {
        (
            bbox.left + bbox.width() * from,
            bbox.left + bbox.width() * (from + span),
        )
    };
    let corners = [(x0, y0), (x1, y0), (x0, y1), (x1, y1)];
    let mut min_x = f32::MAX;
    let mut min_y = f32::MAX;
    let mut max_x = f32::MIN;
    let mut max_y = f32::MIN;
    for (x, y) in corners {
        let (px_, py_) = project(x, y);
        min_x = min_x.min(px_);
        min_y = min_y.min(py_);
        max_x = max_x.max(px_);
        max_y = max_y.max(py_);
    }
    if min_x == f32::MAX {
        return None;
    }
    // 不留余量:相邻带的矩形共边,pad 会在接缝处叠出更深的线。
    let pad = 0.0;
    Some(Bounds::new(
        point(px(min_x - pad), px(min_y - pad)),
        size(
            px((max_x - min_x) + pad * 2.0),
            px((max_y - min_y) + pad * 2.0),
        ),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unfold_timeline_matches_reference() {
        let config = FoldTextConfig::default();
        // 默认 0.65s 展开、0.045s 错开:第 4 个面板 0.135s 后才开始。
        assert_eq!(config.piece_progress(0.0, 0, false), 0.0);
        assert_eq!(config.piece_progress(0.65, 0, false), 1.0);
        assert!(config.piece_progress(0.10, 3, false) < 0.55);
        assert!((config.unfold_span(4) - (0.65 + 0.135)).abs() < 1e-9);
        // 减弱动画直接呈现终态。
        assert_eq!(config.piece_progress(0.0, 0, true), 1.0);
    }

    #[test]
    fn stagger_origins_pick_the_right_order() {
        let mut config = FoldTextConfig::default();
        assert_eq!(config.stagger_rank(0, 5), 0);
        config.stagger_from = FoldStaggerFrom::End;
        assert_eq!(config.stagger_rank(0, 5), 4);
        config.stagger_from = FoldStaggerFrom::Center;
        // 中间那块最早,两端最晚。
        assert_eq!(config.stagger_rank(2, 5), 0);
        assert_eq!(config.stagger_rank(0, 5), 2);
        config.stagger_from = FoldStaggerFrom::Edges;
        assert_eq!(config.stagger_rank(0, 5), 0);
        assert_eq!(config.stagger_rank(2, 5), 2);
        // 随机起点必须可复现,否则截图和测试都不稳定。
        config.stagger_from = FoldStaggerFrom::Random;
        let a: Vec<_> = (0..8).map(|i| config.stagger_rank(i, 8)).collect();
        let b: Vec<_> = (0..8).map(|i| config.stagger_rank(i, 8)).collect();
        assert_eq!(a, b);
        assert!(a.iter().all(|rank| *rank < 8));
    }

    #[test]
    fn layout_splits_by_grapheme_word_and_line() {
        let config = FoldTextConfig::default();
        let by_char = cached_layout("Arc", &config).unwrap();
        assert_eq!(by_char.pieces.len(), 3);

        let words = FoldTextConfig {
            split_by: FoldSplit::Word,
            ..Default::default()
        };
        assert_eq!(cached_layout("Arc rs", &words).unwrap().pieces.len(), 2);

        let lines = FoldTextConfig {
            split_by: FoldSplit::Line,
            ..Default::default()
        };
        let two_lines = cached_layout("Arc\nrs", &lines).unwrap();
        assert_eq!(two_lines.pieces.len(), 2);
        assert!(two_lines.bbox.height() > config.font_size);
    }

    #[test]
    fn every_piece_reports_its_own_ink_box() {
        let layout = cached_layout("Fold", &FoldTextConfig::default()).unwrap();
        for piece in &layout.pieces {
            assert!(piece.bbox.width() > 0.5, "{:?}", piece.bbox);
            assert!(piece.bbox.height() > 0.5, "{:?}", piece.bbox);
        }
        // 逐字排版的方向必须递增,否则铰链会叠在一起。
        assert!(layout.pieces[0].bbox.left < layout.pieces[1].bbox.left);
    }

    #[test]
    fn slat_clipping_splits_a_contour_in_two() {
        let square = vec![
            PathPoint::new(0.0, 0.0),
            PathPoint::new(10.0, 0.0),
            PathPoint::new(10.0, 10.0),
            PathPoint::new(0.0, 10.0),
        ];
        let upper = clip_polygon(&square, 5.0, true, false);
        let lower = clip_polygon(&square, 5.0, false, false);
        assert!(upper.iter().all(|p| p.y <= 5.0));
        assert!(lower.iter().all(|p| p.y >= 5.0));
        assert_eq!(upper.len(), 4);
        assert_eq!(lower.len(), 4);
    }
}