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
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
//! 原生移植 React Bits `SlideCommit`(MIT + Commons Clause,© shadcn-ui 贡献者风格的滑动确认胶囊)。
//! 移动端「滑动确认」胶囊:拖拽手柄到行程末端触发 `on_confirm`,支持同步/异步结果、
//! pending 旋转 spinner、成功胶囊 unfurl、失败抖动回弹;独立组件,不替换 HoldToConfirm。
//! 时间统一来自共享 MotionClock;触屏平移由 GPUI 识别后合成为滚动事件(on_scroll),
//! 横向接管确认手势,纵向交还宿主滚动链。
use std::{cell::RefCell, collections::VecDeque, rc::Rc, time::Duration};

use arc_motion::{
    CubicBezier, ScalarTween, SpringSolver, TweenEase, is_reduced_motion, motion_now,
};
use arc_tokens::{ActiveArcTheme as _, SpringSpec};
use gpui_kit::{
    App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    MouseMoveEvent, MouseUpEvent, ParentElement, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, div, prelude::*,
    px, svg,
};

const PAD: f32 = 4.;
const SQUASH_MAX: f32 = 0.08;
const SQUASH_DIV: f32 = 110.;
/// 悬停膨胀(React SWELL = 1.03):hot 且未按住且 idle 时胶囊放大。
const SWELL: f32 = 1.03;
const SHAKE_MS: f64 = 450.;
const HOME_DELAY_MS: f64 = 300.;
const SPINNER_STROKE: f32 = 2.4;

/// EASE_OUT:React 源中的 `[0.23, 1, 0.32, 1]`。
fn ease_out() -> TweenEase {
    TweenEase::CubicBezier(CubicBezier::new(0.23, 1., 0.32, 1.))
}

/// 按背景亮度选择可读前景色(React `onColor`)。
fn on_color(c: Hsla) -> Hsla {
    let rgb: gpui_kit::Rgba = c.into();
    if (rgb.r * 299. + rgb.g * 587. + rgb.b * 114.) / 1000. >= 150. / 255. {
        arc_tokens::hex(0x111111, 1.)
    } else {
        arc_tokens::hex(0xffffff, 1.)
    }
}

/// `on_confirm` 的同步返回结果,对应 React 中「返回 Promise 与否」的两种路径。
#[derive(Clone, Debug)]
pub enum SlideCommitConfirm {
    /// 同步成功:直接 unfurl 成功胶囊(无 pending spinner)。
    Ok,
    /// 同步失败:直接抖动回弹并显示错误文案。
    Err(SharedString),
    /// 异步成功:先转 pending spinner,至少 `delay`(且不低于 `min_pending_ms`)后 unfurl。
    PendingOk(Duration),
    /// 异步失败:pending 后抖动回弹并显示错误文案。
    PendingErr(Duration, SharedString),
}

pub type ConfirmHandler = Rc<dyn Fn(&mut Window, &mut App) -> SlideCommitConfirm>;
pub type DoneHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
pub type ErrorHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;

#[derive(Clone, Debug)]
pub struct SlideCommitConfig {
    pub track_color: Option<Hsla>,
    pub handle_color: Option<Hsla>,
    pub success_color: Option<Hsla>,
    pub danger_color: Option<Hsla>,
    pub width: f32,
    pub height: f32,
    pub radius: f32,
    /// 0–100:映射到弹簧刚度 260–900(React `k = 260 + speed/100*640`)。
    pub speed: f32,
    /// 回弹能量:0 停在原位,0.38 填满 8% 压扁回弹。
    pub return_bounce: f32,
    /// 成功胶囊落地时轨道下沉比例;0 关闭。
    pub landing_dip: f32,
    /// 完成态停留时长(毫秒);0 表示保持直到重建组件。
    pub hold_ms: f64,
    /// 异步结果最短 pending 时长(毫秒)。
    pub min_pending_ms: f64,
    pub disabled: bool,
}

impl Default for SlideCommitConfig {
    fn default() -> Self {
        Self {
            track_color: None,
            handle_color: None,
            success_color: None,
            danger_color: None,
            width: 280.,
            height: 56.,
            radius: 28.,
            speed: 50.,
            return_bounce: 0.38,
            landing_dip: 0.026,
            hold_ms: 1500.,
            min_pending_ms: 300.,
            disabled: false,
        }
    }
}

impl SlideCommitConfig {
    fn normalized(&self) -> Self {
        let mut c = self.clone();
        let d = Self::default();
        macro_rules! norm {
            ($f:ident, $lo:expr, $hi:expr) => {
                c.$f = if c.$f.is_finite() {
                    c.$f.clamp($lo, $hi)
                } else {
                    d.$f
                };
            };
        }
        norm!(width, 160., 640.);
        norm!(height, 40., 120.);
        let max_radius = c.height / 2.;
        norm!(radius, 0., max_radius);
        norm!(speed, 0., 100.);
        norm!(return_bounce, 0., 0.5);
        norm!(landing_dip, 0., 0.2);
        c.hold_ms = if c.hold_ms.is_finite() {
            c.hold_ms.max(0.)
        } else {
            d.hold_ms
        };
        c.min_pending_ms = if c.min_pending_ms.is_finite() {
            c.min_pending_ms.max(0.)
        } else {
            d.min_pending_ms
        };
        c
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Phase {
    Idle,
    Pending,
    Done,
    Error,
}

/// 手柄位置通道:支持物理弹簧(带初速度)与贝塞尔补间(带延迟)。
struct Channel {
    value: f32,
    target: f32,
    start: f64,
    duration: f64,
    spring: Option<SpringSolver>,
    tween: ScalarTween,
}

impl Channel {
    fn new(v: f32) -> Self {
        Self {
            value: v,
            target: v,
            start: 0.,
            duration: 0.,
            spring: None,
            tween: ScalarTween::new(v),
        }
    }
    fn set(&mut self, v: f32) {
        *self = Self::new(v);
    }
    fn spring(&mut self, target: f32, now: f64, spec: SpringSpec, velocity: f32) {
        self.target = target;
        self.start = now;
        self.duration = 1.;
        self.spring = Some(SpringSolver::new(
            spec,
            self.value as f64,
            target as f64,
            velocity as f64,
        ));
    }
    fn ease(&mut self, target: f32, now: f64, duration: f64, delay: f64, reduced: bool) {
        self.spring = None;
        self.tween = ScalarTween::new(self.value);
        self.tween.retarget(
            target,
            now,
            duration as f32,
            delay as f32,
            ease_out(),
            reduced,
        );
        self.target = target;
        self.start = now;
        self.duration = duration;
    }
    fn tick(&mut self, now: f64) -> bool {
        if let Some(s) = &self.spring {
            let sample = s.sample((now - self.start).max(0.));
            self.value = sample.value;
            if sample.settled {
                self.set(self.target);
                return false;
            }
            return true;
        }
        if self.tween.settled(now) {
            if self.value != self.target {
                self.set(self.target);
            }
            return false;
        }
        self.value = self.tween.sample(now);
        true
    }
}

/// 关键帧时间线(shake / landing dip):段间使用 EASE_OUT。
struct Timed {
    start: f64,
    duration: f64,
    keys: Vec<(f32, f32)>,
}

impl Timed {
    fn sample(&self, now: f64) -> f32 {
        let u = (((now - self.start) / self.duration).clamp(0., 1.)) as f32;
        if u <= 0. {
            return self.keys[0].1;
        }
        if u >= 1. {
            return self.keys[self.keys.len() - 1].1;
        }
        for w in self.keys.windows(2) {
            if u >= w[0].0 && u <= w[1].0 {
                let t = (u - w[0].0) / (w[1].0 - w[0].0).max(1e-6);
                return w[0].1 + (w[1].1 - w[0].1) * ease_out().sample(t);
            }
        }
        self.keys[self.keys.len() - 1].1
    }
    fn done(&self, now: f64) -> bool {
        now >= self.start + self.duration
    }
}

/// React `SHAKE = [0, -5, 5, -3, 3, -1, 0]`。
fn shake_timeline(now: f64) -> Timed {
    Timed {
        start: now,
        duration: SHAKE_MS / 1000.,
        keys: vec![
            (0., 0.),
            (1. / 6., -5.),
            (2. / 6., 5.),
            (3. / 6., -3.),
            (4. / 6., 3.),
            (5. / 6., -1.),
            (1., 0.),
        ],
    }
}

struct Grip {
    /// 手势起始手柄位置(触屏累计位移的基准)。
    x_start: f32,
    /// 鼠标:首次移动时计算的抓取偏移;触屏:越过 10px 意图锁后的哨兵值。
    grab: Option<f32>,
    /// 触屏累计横向位移。
    ax: f32,
    moved: bool,
    vertical: bool,
    hist: VecDeque<(f64, f32)>,
}

struct PendingWait {
    /// 冗余的 run 令牌:advance 到期时与 `self.run` 比对,防止陈旧定时结果。
    #[allow(dead_code)]
    run: u32,
    ok: bool,
    reason: SharedString,
    deadline: f64,
}

enum Event {
    Done,
    Error(SharedString),
}

struct State {
    config: SlideCommitConfig,
    label: SharedString,
    done_label: SharedString,
    error_label: SharedString,
    on_confirm: Option<ConfirmHandler>,
    on_done: Option<DoneHandler>,
    on_error: Option<ErrorHandler>,
    bounds: Bounds<gpui_kit::Pixels>,
    phase: Phase,
    phase_start: f64,
    run: u32,
    x: Channel,
    anchor: Channel,
    shown: Channel,
    spin: Channel,
    done_fade: Channel,
    err_fade: Channel,
    shake: Option<Timed>,
    pulse: Option<Timed>,
    grip: Option<Grip>,
    pending: Option<PendingWait>,
    settle_deadline: Option<(u32, f64)>,
    home_deadline: Option<f64>,
    error_reset: Option<f64>,
    /// 指针悬停(React hot):mouse 指针在胶囊上且非触屏。
    hot: bool,
    focus: FocusHandle,
}

impl State {
    fn travel(&self) -> f32 {
        let c = &self.config;
        let grip = (c.height - PAD * 2.).max(1.);
        let inner = (c.width - PAD * 2.).max(grip + 1.);
        (inner - grip).max(1.)
    }
    fn interactive(&self) -> bool {
        !self.config.disabled && self.phase == Phase::Idle
    }
    fn spring_specs(&self) -> (SpringSpec, SpringSpec) {
        let k = 260. + self.config.speed * 6.4;
        let mass = 0.9;
        let critical = 2. * (k * mass).sqrt();
        (
            SpringSpec::physics_with_mass(k, critical, mass),
            SpringSpec::physics_with_mass(k, critical * (1. - self.config.return_bounce), mass),
        )
    }
    fn go_home(&mut self, velocity: f32, now: f64, reduced: bool) {
        if reduced {
            self.x.ease(0., now, 0.2, 0., true);
        } else {
            let (_, home) = self.spring_specs();
            self.x.spring(0., now, home, velocity.min(0.));
        }
    }
    fn settle(&mut self, now: f64, reduced: bool) {
        self.phase = Phase::Idle;
        self.done_fade.ease(0., now, 0.2, 0., reduced);
        self.shown.ease(1., now, 0.2, 0.12, reduced);
        self.err_fade.ease(0., now, 0.2, 0., reduced);
        if reduced {
            self.anchor.set(0.);
        } else {
            self.anchor
                .spring(0., now, SpringSpec::duration(0.3, 0.), 0.);
        }
    }
    fn resolve(&mut self, via_key: bool, now: f64, reduced: bool) -> Vec<Event> {
        self.phase = Phase::Done;
        self.anchor.set(self.x.value);
        self.spin.ease(0., now, 0.12, 0., reduced);
        self.done_fade.ease(1., now, 0.2, 0., reduced);
        if reduced {
            self.x.set(0.);
        } else {
            let (commit, _) = self.spring_specs();
            self.x.spring(0., now, commit, 0.);
            if !via_key && self.config.landing_dip > 0. {
                self.pulse = Some(Timed {
                    start: now + 0.1,
                    duration: 0.46,
                    keys: vec![(0., 1.), (0.62, 1. - self.config.landing_dip), (1., 1.)],
                });
            }
        }
        if self.config.hold_ms > 0. {
            self.settle_deadline = Some((self.run, now + self.config.hold_ms / 1000.));
        }
        vec![Event::Done]
    }
    fn reject(&mut self, reason: SharedString, now: f64, reduced: bool) -> Vec<Event> {
        self.phase = Phase::Error;
        self.spin.ease(0., now, 0.12, 0., reduced);
        self.shown.ease(1., now, 0.2, 0.12, reduced);
        self.err_fade.ease(1., now, 0.2, 0., reduced);
        if reduced {
            self.go_home(0., now, true);
        } else {
            self.shake = Some(shake_timeline(now));
            self.home_deadline = Some(now + HOME_DELAY_MS / 1000.);
        }
        self.error_reset = Some(now + (self.config.hold_ms.max(1500.)) / 1000.);
        vec![Event::Error(reason)]
    }
    /// 把 `on_confirm` 的结果接到状态机上;返回需要通知宿主的事件。
    fn begin_confirm(
        &mut self,
        outcome: SlideCommitConfirm,
        now: f64,
        reduced: bool,
    ) -> Vec<Event> {
        match outcome {
            SlideCommitConfirm::Ok => self.resolve(false, now, reduced),
            SlideCommitConfirm::Err(reason) => self.reject(reason, now, reduced),
            SlideCommitConfirm::PendingOk(delay) => {
                self.enter_pending(true, SharedString::new(""), delay, now, reduced);
                Vec::new()
            }
            SlideCommitConfirm::PendingErr(delay, reason) => {
                self.enter_pending(false, reason, delay, now, reduced);
                Vec::new()
            }
        }
    }
    fn enter_pending(
        &mut self,
        ok: bool,
        reason: SharedString,
        delay: Duration,
        now: f64,
        reduced: bool,
    ) {
        self.phase = Phase::Pending;
        self.phase_start = now;
        self.shown.ease(0., now, 0.2, 0., reduced);
        self.spin.ease(1., now, 0.2, 0., reduced);
        let min = self.config.min_pending_ms / 1000.;
        self.pending = Some(PendingWait {
            run: self.run,
            ok,
            reason,
            deadline: now + (min.max(delay.as_secs_f64())),
        });
    }
    /// 拖拽到达行程末端后开始确认流程;返回 run 令牌,宿主回调随后经 `begin_confirm` 回填。
    fn commit(&mut self, now: f64, reduced: bool) -> u32 {
        self.run += 1;
        self.settle_deadline = None;
        self.x.set(self.travel());
        self.shown.ease(0., now, 0.12, 0., reduced);
        self.run
    }
    /// 松手:到达末端则确认,否则按速度回弹。
    fn release(&mut self, velocity: f32, now: f64, reduced: bool) -> Option<u32> {
        let g = self.grip.take()?;
        let travel = self.travel();
        if self.x.value >= travel - 0.01 {
            return Some(self.commit(now, reduced));
        }
        if g.moved {
            self.go_home(velocity, now, reduced);
        } else if self.x.value > 0.01 {
            // GPUI 偏差:React 的 x.stop 会把回弹中的手柄冻结在半程;这里始终送它回家。
            self.go_home(0., now, reduced);
        }
        None
    }
    fn velocity_of(&self) -> f32 {
        let g = match &self.grip {
            Some(g) => g,
            None => return 0.,
        };
        match (g.hist.front(), g.hist.back()) {
            (Some(a), Some(b)) => {
                ((b.1 - a.1) / ((b.0 - a.0).max(0.001) as f32)).clamp(-1500., 1500.)
            }
            _ => 0.,
        }
    }
    /// 逐帧推进;返回 (是否仍在动画, 待宿主事件)。
    fn advance(&mut self, now: f64, reduced: bool) -> (bool, Vec<Event>) {
        let mut running = self.x.tick(now)
            | self.anchor.tick(now)
            | self.shown.tick(now)
            | self.spin.tick(now)
            | self.done_fade.tick(now)
            | self.err_fade.tick(now);
        for slot in [&mut self.shake, &mut self.pulse] {
            if let Some(a) = slot {
                if a.done(now) {
                    *slot = None;
                } else {
                    running = true;
                }
            }
        }
        let mut events = Vec::new();
        match self.phase {
            Phase::Pending => {
                // spinner 旋转/呼吸持续出帧。
                running = true;
                if let Some(p) = self.pending.take() {
                    if now >= p.deadline {
                        if p.ok {
                            events.extend(self.resolve(false, now, reduced));
                        } else {
                            events.extend(self.reject(p.reason.clone(), now, reduced));
                        }
                    } else {
                        self.pending = Some(p);
                    }
                }
            }
            Phase::Done => {
                if let Some((_, at)) = self.settle_deadline {
                    if now >= at {
                        self.settle_deadline = None;
                        self.settle(now, reduced);
                    } else {
                        running = true;
                    }
                }
            }
            Phase::Error => {
                if let Some(at) = self.home_deadline {
                    if now >= at {
                        self.home_deadline = None;
                        self.go_home(0., now, reduced);
                    } else {
                        running = true;
                    }
                }
                if let Some(at) = self.error_reset {
                    if now >= at {
                        self.error_reset = None;
                        self.home_deadline = None;
                        self.phase = Phase::Idle;
                        self.err_fade.ease(0., now, 0.2, 0., reduced);
                    } else {
                        running = true;
                    }
                }
            }
            Phase::Idle => {}
        }
        (running, events)
    }
}

/// 移动端滑动确认胶囊:把手柄拖到最右触发 `on_confirm`,异步结果期间转 spinner,
/// 成功 unfurl 绿色胶囊(`hold_ms` 后收拢),失败抖动回弹并以 danger 色提示。
#[derive(IntoElement)]
pub struct SlideCommit {
    id: ElementId,
    label: SharedString,
    done_label: SharedString,
    error_label: SharedString,
    config: SlideCommitConfig,
    on_confirm: Option<ConfirmHandler>,
    on_done: Option<DoneHandler>,
    on_error: Option<ErrorHandler>,
}

impl SlideCommit {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            label: "Slide to pay".into(),
            done_label: "Paid".into(),
            error_label: "Payment failed".into(),
            config: Default::default(),
            on_confirm: None,
            on_done: None,
            on_error: None,
        }
    }
    pub fn label(mut self, v: impl Into<SharedString>) -> Self {
        self.label = v.into();
        self
    }
    pub fn done_label(mut self, v: impl Into<SharedString>) -> Self {
        self.done_label = v.into();
        self
    }
    pub fn error_label(mut self, v: impl Into<SharedString>) -> Self {
        self.error_label = v.into();
        self
    }
    pub fn config(mut self, c: SlideCommitConfig) -> Self {
        self.config = c;
        self
    }
    /// 到达末端时调用;同步返回结果即可驱动状态机(对应 React 的 Promise 语义)。
    pub fn on_confirm(
        mut self,
        v: impl Fn(&mut Window, &mut App) -> SlideCommitConfirm + 'static,
    ) -> Self {
        self.on_confirm = Some(Rc::new(v));
        self
    }
    pub fn on_done(mut self, v: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_done = Some(Rc::new(v));
        self
    }
    pub fn on_error(mut self, v: impl Fn(&SharedString, &mut Window, &mut App) + 'static) -> Self {
        self.on_error = Some(Rc::new(v));
        self
    }
}

fn notify_events(events: Vec<Event>, state: &State, window: &mut Window, cx: &mut App) {
    for e in events {
        match e {
            Event::Done => {
                if let Some(cb) = &state.on_done {
                    cb(&(), window, cx);
                }
            }
            Event::Error(reason) => {
                if let Some(cb) = &state.on_error {
                    cb(&reason, window, cx);
                }
            }
        }
    }
}

/// 把拖拽/触屏位移应用到手柄;返回是否产生了可见移动。
fn drag_to(s: &mut State, next: f32, now: f64) -> bool {
    let Some(g) = s.grip.as_mut() else {
        return false;
    };
    let prev = s.x.value;
    let moved_flag = (next - prev).abs() > 0.5;
    g.moved |= moved_flag;
    g.hist.push_back((now, next));
    while g.hist.len() > 4 {
        g.hist.pop_front();
    }
    s.x.set(next);
    moved_flag
}

fn release_and_confirm(cell: &Rc<RefCell<State>>, window: &mut Window, cx: &mut App) {
    let now = motion_now(cx);
    let red = is_reduced_motion(cx);
    let events = {
        let run = {
            let mut s = cell.borrow_mut();
            let v = s.velocity_of();
            s.release(v, now, red)
        };
        match run {
            Some(run) => confirm_with_host(cell, run, window, cx, now, red),
            None => Vec::new(),
        }
    };
    if !events.is_empty() {
        let s = cell.borrow();
        notify_events(events, &s, window, cx);
    }
    window.refresh();
}

/// 调用宿主 `on_confirm`(借用在锁外),并把结果接回状态机;只返回事件,由调用方统一通知。
fn confirm_with_host(
    cell: &Rc<RefCell<State>>,
    run: u32,
    window: &mut Window,
    cx: &mut App,
    now: f64,
    reduced: bool,
) -> Vec<Event> {
    let outcome = {
        let s = cell.borrow();
        if s.run != run {
            return Vec::new();
        }
        match &s.on_confirm {
            Some(cb) => cb(window, cx),
            None => SlideCommitConfirm::Ok,
        }
    };
    cell.borrow_mut().begin_confirm(outcome, now, reduced)
}

fn commit_and_confirm(cell: &Rc<RefCell<State>>, window: &mut Window, cx: &mut App) {
    let now = motion_now(cx);
    let red = is_reduced_motion(cx);
    let events = {
        let run = {
            let mut s = cell.borrow_mut();
            if !s.interactive() {
                return;
            }
            s.commit(now, red)
        };
        confirm_with_host(cell, run, window, cx, now, red)
    };
    if !events.is_empty() {
        let s = cell.borrow();
        notify_events(events, &s, window, cx);
    }
    window.refresh();
}

impl RenderOnce for SlideCommit {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let now = motion_now(cx);
        let reduced = is_reduced_motion(cx);
        let colors = cx.arc_theme().colors;
        let config = self.config.normalized();
        let id = self.id.clone();

        let cell = window
            .use_keyed_state(
                ElementId::NamedChild(id.clone().into(), "state".into()),
                cx,
                |_, cx| {
                    Rc::new(RefCell::new(State {
                        config: SlideCommitConfig::default(),
                        label: "".into(),
                        done_label: "".into(),
                        error_label: "".into(),
                        on_confirm: None,
                        on_done: None,
                        on_error: None,
                        bounds: Bounds::default(),
                        phase: Phase::Idle,
                        phase_start: 0.,
                        run: 0,
                        x: Channel::new(0.),
                        anchor: Channel::new(0.),
                        shown: Channel::new(1.),
                        spin: Channel::new(0.),
                        done_fade: Channel::new(0.),
                        err_fade: Channel::new(0.),
                        shake: None,
                        pulse: None,
                        grip: None,
                        pending: None,
                        settle_deadline: None,
                        home_deadline: None,
                        error_reset: None,
                        hot: false,
                        focus: cx.focus_handle().tab_index(0).tab_stop(true),
                    }))
                },
            )
            .read(cx)
            .clone();

        // 同步 props 并推进动画。
        let (running, events) = {
            let mut s = cell.borrow_mut();
            s.config = config.clone();
            s.label = self.label.clone();
            s.done_label = self.done_label.clone();
            s.error_label = self.error_label.clone();
            s.on_confirm = self.on_confirm.clone();
            s.on_done = self.on_done.clone();
            s.on_error = self.on_error.clone();
            s.advance(now, reduced)
        };
        if running {
            window.request_animation_frame();
        }
        if !events.is_empty() {
            // advance 只能由本帧触发(pending 到期 / settle 到期),锁外通知宿主。
            let s = cell.borrow();
            notify_events(events, &s, window, cx);
        }

        let s = cell.borrow();
        let width = config.width;
        let height = config.height;
        let grip = (height - PAD * 2.).max(1.);
        let inner = (width - PAD * 2.).max(grip + 1.);
        let travel = (inner - grip).max(1.);
        let r = config.radius.min(height / 2.);
        let grip_r = (r - PAD).max(0.);
        let font_size = ((height * 0.25).round() as i32).clamp(13, 17) as f32;
        let icon_size = (grip * 0.42).round();
        let check_size = (grip * 0.38).round();

        let phase = s.phase;
        let held = s.grip.is_some();
        let dragging = held && s.grip.as_ref().is_some_and(|g| g.grab.is_some());
        let x = s.x.value;
        let seen = x.clamp(0., travel);
        let anchor = s.anchor.value;
        let edge = seen + grip + (anchor - seen).clamp(0., travel);
        // 负向过冲的压扁(React squash);悬停膨胀(React swell = 1.03,
        // hot && !held && idle && !reduce 时生效)。
        let swell = if s.hot && s.grip.is_none() && phase == Phase::Idle && !reduced {
            SWELL
        } else {
            1.
        };
        let q = 1. - ((-x).max(0.) / SQUASH_DIV).min(SQUASH_MAX);
        let capsule_w = (seen + (edge - seen) * q * swell).max(grip * 0.2);
        let capsule_h = grip * swell / q.max(1e-3);
        let content_center = seen + ((seen + edge) / 2. - seen) * q;
        let content_left = content_center - inner / 2.;
        // 行程 55% 后文案淡出,箭头在最后 40% 淡出。
        let say = (1. - seen / (travel * 0.55)).clamp(0., 1.);
        let arrow_op = s.shown.value * (1. - (seen - travel * 0.55) / (travel * 0.4)).clamp(0., 1.);
        let spin_op = s.spin.value;
        let done_op = s.done_fade.value;
        let err_op = s.err_fade.value;
        let percent = ((seen / travel * 100.).round() as i32).clamp(0, 100);
        // 落地下沉/抖动只作用于轨道外框。
        let pulse_scale = s.pulse.as_ref().map(|a| a.sample(now)).unwrap_or(1.);
        let shake_dx = s.shake.as_ref().map(|a| a.sample(now)).unwrap_or(0.);
        let pending_spin_angle = if phase == Phase::Pending {
            (((now - s.phase_start) % 1.) as f32 * std::f32::consts::TAU) as f32
        } else {
            0.
        };
        let breathe = if reduced && phase == Phase::Pending {
            (0.7 + 0.3 * f32::sin((now * std::f64::consts::TAU / 1.4) as f32)) as f32
        } else {
            1.
        };
        let interactive = s.interactive();
        let focus = s.focus.clone();
        let cell_for_probe = cell.clone();
        let cell_for_touch = cell.clone();
        let cell_for_down = cell.clone();
        let cell_for_key = cell.clone();
        let cell_for_hover = cell.clone();
        drop(s);

        let track_color = config.track_color.unwrap_or(colors.surface_muted);
        let ink = config.handle_color.unwrap_or(colors.foreground);
        let success = config.success_color.unwrap_or(colors.success);
        let danger = config.danger_color.unwrap_or(colors.danger);
        let capsule_bg = match phase {
            Phase::Done => success,
            Phase::Error => danger,
            _ => ink,
        };
        let on_ink = on_color(capsule_bg);
        let say_color = match phase {
            Phase::Error => danger,
            _ => ink.opacity(0.45),
        };

        // pending spinner:canvas 画细圆环 + 旋转亮弧。
        let ring_color = on_ink.opacity((spin_op * breathe) as f32 * 0.25);
        let arc_color = on_ink.opacity((spin_op * breathe) as f32);
        let arc_angle = pending_spin_angle;
        let radius_px = (icon_size / 2. - SPINNER_STROKE).max(1.);
        let spinner = canvas(
            |_, _, _| {},
            move |bounds, _, window, _| {
                if ring_color.a <= 0.01 {
                    return;
                }
                let cx0 = f32::from(bounds.size.width) / 2.;
                let cy0 = f32::from(bounds.size.height) / 2.;
                let circle = (0..=40).map(|i| {
                    let a = (i as f32 / 40.) * std::f32::consts::TAU;
                    gpui_kit::point(px(cx0 + a.cos() * radius_px), px(cy0 + a.sin() * radius_px))
                });
                if let Some(builder) = arc_motion::PolylinePath::new(
                    circle
                        .map(|p| arc_motion::PathPoint::new(f32::from(p.x), f32::from(p.y)))
                        .collect(),
                )
                .to_stroke_builder(
                    bounds.origin.x,
                    bounds.origin.y,
                    px(SPINNER_STROKE),
                ) && let Ok(path) = builder.build()
                {
                    window.paint_path(path, ring_color);
                }
                let arc = (0..=16).map(|i| {
                    let a = arc_angle - std::f32::consts::FRAC_PI_2
                        + (i as f32 / 16.) * std::f32::consts::FRAC_PI_2;
                    gpui_kit::point(px(cx0 + a.cos() * radius_px), px(cy0 + a.sin() * radius_px))
                });
                if let Some(builder) = arc_motion::PolylinePath::new(
                    arc.map(|p| arc_motion::PathPoint::new(f32::from(p.x), f32::from(p.y)))
                        .collect(),
                )
                .to_stroke_builder(
                    bounds.origin.x,
                    bounds.origin.y,
                    px(SPINNER_STROKE),
                ) && let Ok(path) = builder.build()
                {
                    window.paint_path(path, arc_color);
                }
            },
        )
        .absolute()
        .size(px(icon_size));

        // 拖拽探针:握持期间接管全局 mouse move/up(触屏走 on_scroll)。
        let probe = canvas(
            {
                let cell = cell_for_probe.clone();
                move |bounds, _, _| {
                    cell.borrow_mut().bounds = bounds;
                }
            },
            move |_, _, window, _| {
                if cell_for_probe.borrow().grip.is_none() {
                    return;
                }
                let st = cell_for_probe.clone();
                window.on_mouse_event(move |e: &MouseMoveEvent, phase, window, cx| {
                    if !phase.bubble() {
                        return;
                    }
                    if st.borrow().grip.is_none() {
                        return;
                    }
                    if e.pressed_button != Some(MouseButton::Left) {
                        release_and_confirm(&st, window, cx);
                        return;
                    }
                    let now = motion_now(cx);
                    let red = is_reduced_motion(cx);
                    #[allow(unused_assignments)]
                    #[allow(unused_assignments)]
                    let mut moved = false;
                    {
                        let mut s = st.borrow_mut();
                        if !s.interactive() && s.grip.is_some() {
                            // pending 中被取消:直接松手回家。
                            s.grip = None;
                            s.go_home(0., now, red);
                            moved = true;
                        } else {
                            let travel = s.travel();
                            let at = f32::from(e.position.x) - f32::from(s.bounds.origin.x);
                            let cur = s.x.value.clamp(0., travel);
                            let Some(g) = s.grip.as_mut() else {
                                return;
                            };
                            if g.grab.is_none() {
                                g.grab = Some(at - cur);
                                return;
                            }
                            let next = (at - g.grab.unwrap()).clamp(0., travel);
                            moved = drag_to(&mut s, next, now);
                        }
                    }
                    if moved {
                        cx.stop_propagation();
                        window.refresh();
                    }
                });
                let st = cell_for_probe.clone();
                window.on_mouse_event(move |e: &MouseUpEvent, phase, window, cx| {
                    if phase.bubble() && e.button == MouseButton::Left {
                        release_and_confirm(&st, window, cx);
                    }
                });
            },
        )
        .absolute()
        .size_full();

        let label_el = div()
            .absolute()
            .inset_0()
            .flex()
            .items_center()
            .justify_center()
            .whitespace_nowrap()
            .text_size(px(font_size))
            .font_medium()
            .child(
                div()
                    .text_color(say_color)
                    .opacity(say * (1. - err_op))
                    .child(self.label.clone()),
            )
            .child(
                div()
                    .absolute()
                    .text_color(danger)
                    .opacity(err_op)
                    .child(self.error_label.clone()),
            );

        let content = div()
            .absolute()
            .left(px(content_left))
            .w(px(inner))
            .h_full()
            .when(phase == Phase::Done, |el| {
                el.flex()
                    .items_center()
                    .justify_center()
                    .gap(px(8.))
                    .opacity(done_op)
                    .child(
                        svg()
                            .path(IconName::Check.path())
                            .size(px(check_size))
                            .text_color(on_ink),
                    )
                    .child(
                        div()
                            .text_size(px(font_size))
                            .font_semibold()
                            .whitespace_nowrap()
                            .text_color(on_ink)
                            .child(self.done_label.clone()),
                    )
            })
            .when(phase != Phase::Done, |el| {
                el.child(
                    div()
                        .absolute()
                        .inset_0()
                        .flex()
                        .items_center()
                        .justify_center()
                        .opacity(arrow_op)
                        .child(
                            svg()
                                .path(IconName::ArrowRight.path())
                                .size(px(icon_size))
                                .text_color(on_ink),
                        ),
                )
                .when(spin_op > 0.01, |el| {
                    el.child(
                        div()
                            .absolute()
                            .inset_0()
                            .flex()
                            .items_center()
                            .justify_center()
                            .child(spinner),
                    )
                })
            });

        let capsule = div()
            .id(ElementId::NamedChild(id.clone().into(), "capsule".into()))
            .test_support()
            .role(Role::Slider)
            .aria_label(self.label.clone())
            .aria_value(format!("{}%, {}%", percent, self.label))
            .when(interactive, |el| {
                el.track_focus(&focus).tab_stop(true).cursor_grab()
            })
            .when(!interactive, |el| el.tab_stop(false).cursor_default())
            .when(dragging, |el| el.cursor_grabbing())
            .when(focus.is_focused(window), |el| {
                el.border_2().border_color(track_color)
            })
            .absolute()
            .left(px(PAD))
            .top(px(PAD + (grip - capsule_h) / 2.))
            .w(px(capsule_w))
            .h(px(capsule_h))
            .rounded(px(grip_r.min(capsule_h / 2.)))
            .bg(capsule_bg)
            .overflow_hidden()
            .on_key_down(move |e: &KeyDownEvent, window, cx| {
                let key = e.keystroke.key.as_str();
                let now = motion_now(cx);
                let red = is_reduced_motion(cx);
                let step = {
                    let mut s = cell_for_key.borrow_mut();
                    if !s.interactive() {
                        return;
                    }
                    let travel = s.travel();
                    match key {
                        "end" => Some(()),
                        "right" | "up" => {
                            let next = (s.x.value + travel / 10.).min(travel);
                            s.x.set(next);
                            if next >= travel - 0.01 {
                                Some(())
                            } else {
                                None
                            }
                        }
                        "left" | "down" => {
                            let v = s.x.value;
                            s.x.set((v - travel / 10.).max(0.));
                            None
                        }
                        "home" | "escape" => {
                            s.grip = None;
                            s.go_home(0., now, red);
                            None
                        }
                        _ => return,
                    }
                };
                cx.stop_propagation();
                window.prevent_default();
                if let Some(()) = step {
                    commit_and_confirm(&cell_for_key, window, cx);
                }
                window.refresh();
            })
            .child(content);

        let track = div()
            .id(ElementId::NamedChild(id.clone().into(), "track".into()))
            .test_support()
            .relative()
            .w(px(width * pulse_scale))
            .h(px(height * pulse_scale))
            .ml(px(shake_dx))
            .rounded(px(r * pulse_scale))
            .bg(track_color)
            .overflow_hidden()
            .opacity(if config.disabled { 0.55 } else { 1. })
            .when(interactive && !dragging, |el| el.cursor_grab())
            .when(phase == Phase::Pending || phase == Phase::Done, |el| {
                el.cursor_default()
            })
            .on_hover(move |hovered, window, _cx| {
                // React onPointerEnter/Leave(仅鼠标,fine pointer):hot 驱动 swell。
                let mut s = cell_for_hover.borrow_mut();
                if s.hot != *hovered {
                    s.hot = *hovered;
                    drop(s);
                    window.refresh();
                }
            })
            .on_mouse_down(MouseButton::Left, move |_, window, _cx| {
                let mut s = cell_for_down.borrow_mut();
                if !s.interactive() {
                    return;
                }
                // 按下即冻结进行中的动画(React x.stop)。
                let v = s.x.value;
                s.x.set(v);
                s.grip = Some(Grip {
                    x_start: v,
                    grab: None,
                    ax: 0.,
                    moved: false,
                    vertical: false,
                    hist: VecDeque::with_capacity(4),
                });
                drop(s);
                window.refresh();
            })
            .child(probe)
            .child(label_el)
            .child(capsule);

        // 触屏平移:横向接管确认手势,纵向交还宿主滚动链。
        div()
            .id(id)
            .test_support()
            .role(Role::Group)
            .aria_label(format!(
                "{} · {}%",
                self.label,
                ((seen / travel * 100.).round() as i32).clamp(0, 100)
            ))
            .relative()
            .w(px(width))
            .h(px(height))
            .flex_none()
            .flex()
            .items_center()
            .justify_center()
            .on_scroll(move |e, window, cx| {
                if !window.last_input_was_touch() {
                    return;
                }
                let delta = e.delta.pixel_delta(px(16.));
                let dx = f32::from(delta.x);
                let dy = f32::from(delta.y);
                let now = motion_now(cx);
                let red = is_reduced_motion(cx);
                let ended = matches!(
                    e.touch_phase,
                    gpui_kit::TouchPhase::Ended | gpui_kit::TouchPhase::Cancelled
                );
                if ended {
                    let run = {
                        let mut s = cell_for_touch.borrow_mut();
                        let v = s.velocity_of();
                        s.release(v, now, red)
                    };
                    if let Some(run) = run {
                        confirm_with_host(&cell_for_touch, run, window, cx, now, red);
                    }
                    cx.stop_propagation();
                    window.refresh();
                    return;
                }
                #[allow(unused_assignments)]
                let mut moved = false;
                {
                    let mut s = cell_for_touch.borrow_mut();
                    if !s.interactive() {
                        return;
                    }
                    let travel = s.travel();
                    if e.touch_phase == gpui_kit::TouchPhase::Started {
                        let x0 = s.x.value;
                        s.x.set(x0);
                        s.grip = Some(Grip {
                            x_start: x0,
                            grab: None,
                            ax: 0.,
                            moved: false,
                            vertical: false,
                            hist: VecDeque::with_capacity(4),
                        });
                    }
                    let Some(g) = s.grip.as_mut() else {
                        return;
                    };
                    if g.vertical {
                        return;
                    }
                    if g.grab.is_none() {
                        if dy.abs() >= 10. && dy.abs() > dx.abs() {
                            g.vertical = true;
                            return;
                        }
                        if dx.abs() < 10. || dx.abs() < dy.abs() {
                            return;
                        }
                        g.grab = Some(10.);
                    }
                    g.ax += dx;
                    let next = (g.x_start + g.ax - g.grab.unwrap()).clamp(0., travel);
                    moved = drag_to(&mut s, next, now);
                }
                if moved {
                    cx.stop_propagation();
                    window.refresh();
                }
            })
            .child(track)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, Render, TestAppContext, point,
        test::{TestEventExt as _, TestWindowExt as _},
    };

    struct Host {
        disabled: bool,
        mode: &'static str,
        events: Vec<String>,
        events_log: std::rc::Rc<std::cell::RefCell<Vec<String>>>,
    }

    fn host(mode: &'static str) -> Host {
        Host {
            disabled: false,
            mode,
            events: vec![],
            events_log: std::rc::Rc::new(std::cell::RefCell::new(vec![])),
        }
    }

    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let mode = self.mode;
            let log = self.events_log.clone();
            div().w(px(360.)).p(px(8.)).child(
                SlideCommit::new("sc-test")
                    .label("Slide to pay")
                    .done_label("Paid")
                    .error_label("Payment failed")
                    .config(SlideCommitConfig {
                        disabled: self.disabled,
                        ..Default::default()
                    })
                    .on_confirm(move |_, _| match mode {
                        "async" => SlideCommitConfirm::PendingOk(Duration::from_millis(800)),
                        "fail" => SlideCommitConfirm::Err("declined".into()),
                        "async_fail" => SlideCommitConfirm::PendingErr(
                            Duration::from_millis(500),
                            "timeout".into(),
                        ),
                        _ => SlideCommitConfirm::Ok,
                    })
                    .on_done(cx.listener(|this, _: &(), _, cx| {
                        this.events.push("done".into());
                        cx.notify();
                    }))
                    .on_error(move |reason, _, _| {
                        log.borrow_mut().push(reason.to_string());
                    }),
            )
        }
    }

    fn drag_to_end(window: &mut Window, cx: &mut App) {
        window.render_frame(cx);
        let track = window.find(track_id()).bounds();
        let cy = track.center().y;
        window.pointer_down(
            point(px(f32::from(track.left()) + 20.), cy),
            MouseButton::Left,
            cx,
        );
        window.render_frame(cx);
        window.pointer_move(
            point(px(f32::from(track.left()) + 40.), cy),
            Some(MouseButton::Left),
            cx,
        );
        window.render_frame(cx);
        window.pointer_move(
            point(px(f32::from(track.right()) + 60.), cy),
            Some(MouseButton::Left),
            cx,
        );
        window.render_frame(cx);
        window.pointer_up(
            point(px(f32::from(track.right()) + 60.), cy),
            MouseButton::Left,
            cx,
        );
        window.render_frame(cx);
    }

    fn capsule_id() -> ElementId {
        ElementId::NamedChild(ElementId::from("sc-test").into(), "capsule".into())
    }

    fn track_id() -> ElementId {
        ElementId::NamedChild(ElementId::from("sc-test").into(), "track".into())
    }

    fn setup(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
        });
    }

    #[gpui_kit::test]
    fn slide_commit_drag_commit_and_hold(cx: &mut TestAppContext) {
        setup(cx);
        let (view, cx) = cx.add_window_view(|_, _| host("sync"));
        cx.update(|w, cx| {
            w.render_frame(cx);
            let track = w.find(track_id()).bounds();
            let cy = track.center().y;
            w.pointer_down(
                point(px(f32::from(track.left()) + 20.), cy),
                MouseButton::Left,
                cx,
            );
            w.render_frame(cx);
            // 首次移动只锁定抓取偏移,第二次移动才推进手柄。
            w.pointer_move(
                point(px(f32::from(track.left()) + 40.), cy),
                Some(MouseButton::Left),
                cx,
            );
            w.render_frame(cx);
            w.pointer_move(
                point(px(f32::from(track.right()) + 60.), cy),
                Some(MouseButton::Left),
                cx,
            );
            w.render_frame(cx);
            assert!(f32::from(w.find(capsule_id()).bounds().size.width) > 60.);
            w.pointer_up(
                point(px(f32::from(track.right()) + 60.), cy),
                MouseButton::Left,
                cx,
            );
            w.render_frame(cx);
            assert_eq!(view.read(cx).events, vec!["done"]);
        });
        // holdMs 1500 后收拢回 Idle,再等 anchor 回弹结束。
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(1700));
        cx.update(|w, cx| {
            w.render_frame(cx);
            assert_eq!(view.read(cx).events, vec!["done"]);
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(400));
        cx.update(|w, cx| {
            w.render_frame(cx);
            w.render_frame(cx);
            let grip = (56.0f32 - 8.).max(1.);
            assert!((f32::from(w.find(capsule_id()).bounds().size.width) - grip).abs() < 2.);
        });
    }

    #[gpui_kit::test]
    fn slide_commit_release_early_returns_home(cx: &mut TestAppContext) {
        setup(cx);
        let (view, cx) = cx.add_window_view(|_, _| host("sync"));
        cx.update(|w, cx| {
            w.render_frame(cx);
            let track = w.find(track_id()).bounds();
            let cy = track.center().y;
            w.pointer_down(
                point(px(f32::from(track.left()) + 20.), cy),
                MouseButton::Left,
                cx,
            );
            w.render_frame(cx);
            w.pointer_move(
                point(px(f32::from(track.left()) + 40.), cy),
                Some(MouseButton::Left),
                cx,
            );
            w.render_frame(cx);
            w.pointer_move(
                point(px(f32::from(track.left()) + 100.), cy),
                Some(MouseButton::Left),
                cx,
            );
            w.render_frame(cx);
            assert!(f32::from(w.find(capsule_id()).bounds().size.width) > 60.);
            w.pointer_up(
                point(px(f32::from(track.left()) + 100.), cy),
                MouseButton::Left,
                cx,
            );
            assert!(view.read(cx).events.is_empty());
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(500));
        cx.update(|w, cx| {
            w.render_frame(cx);
            let grip = (56.0f32 - 8.).max(1.);
            assert!((f32::from(w.find(capsule_id()).bounds().size.width) - grip).abs() < 2.);
        });
    }

    #[gpui_kit::test]
    fn slide_commit_keyboard_end_commits(cx: &mut TestAppContext) {
        setup(cx);
        let (view, cx) = cx.add_window_view(|_, _| host("sync"));
        cx.update(|w, cx| {
            w.render_frame(cx);
            w.focus_next(cx);
            w.press("end", cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).events, vec!["done"]);
        });
    }

    #[gpui_kit::test]
    fn slide_commit_disabled_ignores_input(cx: &mut TestAppContext) {
        setup(cx);
        let (view, cx) = cx.add_window_view(|_, _| Host {
            disabled: true,
            ..host("sync")
        });
        cx.update(|w, cx| {
            w.render_frame(cx);
            w.focus_next(cx);
            w.press("end", cx);
            w.render_frame(cx);
            assert!(view.read(cx).events.is_empty());
        });
    }

    #[gpui_kit::test]
    fn slide_commit_async_pending_then_done(cx: &mut TestAppContext) {
        setup(cx);
        let (view, cx) = cx.add_window_view(|_, _| host("async"));
        cx.update(|w, cx| {
            drag_to_end(w, cx);
            // pending 期间不触发 on_done。
            assert!(view.read(cx).events.is_empty());
        });
        // min_pending 300 + delay 800 → 1000ms 内完成。
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(1000));
        cx.update(|w, cx| {
            w.render_frame(cx);
            w.render_frame(cx);
            assert_eq!(view.read(cx).events, vec!["done"]);
        });
    }

    #[gpui_kit::test]
    fn slide_commit_async_error_shakes_and_homes(cx: &mut TestAppContext) {
        setup(cx);
        let (view, cx) = cx.add_window_view(|_, _| host("async_fail"));
        cx.update(|w, cx| {
            drag_to_end(w, cx);
            assert!(view.read(cx).events.is_empty());
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(800));
        cx.update(|w, cx| {
            w.render_frame(cx);
            w.render_frame(cx);
            assert!(view.read(cx).events.is_empty());
        });
        // error_reset = max(holdMs, 1500) 后回到 Idle,手柄回弹归位。
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(1600));
        cx.update(|w, cx| {
            w.render_frame(cx);
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(900));
        cx.update(|w, cx| {
            w.render_frame(cx);
            w.render_frame(cx);
            let grip = (56.0f32 - 8.).max(1.);
            assert!((f32::from(w.find(capsule_id()).bounds().size.width) - grip).abs() < 2.);
        });
    }
}