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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/hold-to-confirm/hold-to-confirm.tsx` & `.module.css`
//!
//! P5 Component #1: `hold-to-confirm`
//!
//! - A button that commits only after it is held for `duration` (default `1200ms`), designed for
//!   destructive or hard-to-undo actions where a stray tap must not count.
//! - Tones:
//!   - `Accent` (default): ink `foreground`, fill `accent`, on-fill `accent_foreground`, border `border_strong`.
//!   - `Danger`: ink `danger`, fill `danger`, on-fill `background`, border `oklab_mix(danger, border, 0.32)`.
//!   - `Neutral`: ink `foreground`, fill `foreground`, on-fill `background`, border `border_strong`.
//! - Motion:
//!   - Holding advances a linear fill (`0.0 -> 1.0`) from the current progress (so a quick re-press
//!     carries on from where it was instead of starting over); releasing early rewinds on
//!     `motion.spring.smooth` (`velocity = 0`).
//!   - Sliding pointer more than `24px` outside the button bounds cancels the hold just like a
//!     native press.
//!   - Adaptive press scale (`>220px -> 0.985`, else `0.97`) on `motion.spring.snappy`.
//!   - Dual-layer face (`base` + `fill` clipped to `progress * width` via `overflow_hidden`) so the
//!     icon and label flip color cleanly right at the advancing fill edge.
//!   - Finishing morphs the label width on `motion.spring.morph`, cross-fades the label vertically
//!     (`±0.3em`, `BlurFallback`), and draws a hand-drawn SVG checkmark (`M4 12.5 L9 17.5 L20 6.5`,
//!     `80ms` delay + `320ms` `ease.enter` via `PolylinePath::slice`).
//!   - Keyboard: holding `Space` or `Enter` fills and commits; releasing early rewinds.

use std::{cell::RefCell, rc::Rc, time::Duration};

use arc_motion::{
    BlurFallback, CubicBezier, PathPoint, PolylinePath, TransformOrigin, arc_spring,
    arc_spring_with_options, is_reduced_motion, motion_now, scaled_bounds, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
    App, BorderStyle, Bounds, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement,
    KeyDownEvent, KeyUpEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
    ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, component::Icon,
    div, point, prelude::*, px, quad,
};

type HoldConfirmHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
type HoldChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;

/// Pointer slack (`24px`) outside the button box before a pointer hold cancels.
pub const HOLD_TO_CONFIRM_POINTER_SLACK_PX: f32 = 24.0;

/// Tone variants for [`HoldToConfirm`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum HoldToConfirmTone {
    #[default]
    Accent,
    Danger,
    Neutral,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HoldSource {
    Pointer,
    Key,
}

#[derive(Clone)]
struct HoldToConfirmInternal {
    uncontrolled_confirmed: bool,
    last_done: bool,
    done_changed_at_secs: f64,
    holding_source: Option<HoldSource>,
    hold_started_at_secs: f64,
    hold_start_progress: f32,
    rewind_progress: f32,
    hovered: bool,
    last_text: SharedString,
    text_changed_at_secs: f64,
    previous_text: Option<SharedString>,
    button_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    measured_label_width: Rc<RefCell<f32>>,
    has_measured_label: Rc<RefCell<bool>>,
    focus_handle: FocusHandle,
}

impl HoldToConfirmInternal {
    fn new(
        initial_done: bool,
        initial_text: SharedString,
        now: f64,
        focus_handle: FocusHandle,
    ) -> Self {
        let initial_p = if initial_done { 1.0 } else { 0.0 };
        Self {
            uncontrolled_confirmed: initial_done,
            last_done: initial_done,
            done_changed_at_secs: now - 10.0,
            holding_source: None,
            hold_started_at_secs: now,
            hold_start_progress: initial_p,
            rewind_progress: initial_p,
            hovered: false,
            last_text: initial_text,
            text_changed_at_secs: now - 10.0,
            previous_text: None,
            button_bounds: Rc::new(RefCell::new(None)),
            measured_label_width: Rc::new(RefCell::new(0.0)),
            has_measured_label: Rc::new(RefCell::new(false)),
            focus_handle,
        }
    }
}

/// Computes the instantaneous linear fill progress (`0.0..=1.0`) during an active hold.
pub fn hold_linear_progress(start_progress: f32, elapsed_secs: f64, duration_secs: f64) -> f32 {
    if duration_secs <= 1e-6 {
        return 1.0;
    }
    let start = start_progress.clamp(0.0, 1.0);
    let remaining_frac = (1.0 - start).max(0.0);
    if remaining_frac <= 1e-6 {
        return 1.0;
    }
    let total_needed = f64::from(remaining_frac) * duration_secs;
    if total_needed <= 1e-6 {
        1.0
    } else {
        (start + remaining_frac * (elapsed_secs / total_needed).clamp(0.0, 1.0) as f32)
            .clamp(0.0, 1.0)
    }
}

/// Evaluates the hand-drawn checkmark (`M4 12.5 L9 17.5 L20 6.5`) progress and opacity at
/// `elapsed` seconds after confirmation (`80ms` delay, `320ms` `ease.enter` stroke, `50ms` opacity).
pub fn hold_check_draw_sample(elapsed: f64, reduced: bool) -> (f32, f32) {
    if reduced {
        return (1.0, 1.0);
    }
    let delayed = elapsed - 0.08;
    if delayed <= 0.0 {
        return (0.0, 0.0);
    }
    let op = (delayed / 0.05).clamp(0.0, 1.0) as f32;
    let t = (delayed / 0.32).clamp(0.0, 1.0) as f32;
    let len = CubicBezier::new(0.16, 1.0, 0.3, 1.0)
        .sample(t)
        .clamp(0.0, 1.0);
    (len, op)
}

fn paint_drawn_check(
    rect: Bounds<Pixels>,
    progress: f32,
    opacity: f32,
    color: Hsla,
    window: &mut Window,
) {
    if progress <= 0.001 || opacity <= 0.01 {
        return;
    }
    let w = f32::from(rect.size.width).max(1.0);
    let h = f32::from(rect.size.height).max(1.0);
    let ox = f32::from(rect.origin.x);
    let oy = f32::from(rect.origin.y);
    let poly = PolylinePath::new(vec![
        PathPoint::new(ox + 4.0 / 24.0 * w, oy + 12.5 / 24.0 * h),
        PathPoint::new(ox + 9.0 / 24.0 * w, oy + 17.5 / 24.0 * h),
        PathPoint::new(ox + 20.0 / 24.0 * w, oy + 6.5 / 24.0 * h),
    ]);
    let sliced = poly.slice(0.0, progress.clamp(0.0, 1.0));
    if sliced.points.len() < 2 {
        return;
    }
    let mut builder = PathBuilder::stroke(px(2.0));
    for (i, pt) in sliced.points.iter().enumerate() {
        let p = point(px(pt.x), px(pt.y));
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    let c = Hsla {
        a: color.a * opacity.clamp(0.0, 1.0),
        ..color
    };
    if let Ok(path) = builder.build() {
        window.paint_path(path, c);
    }
}

/// Arc `HoldToConfirm` — press-and-hold confirmation button with split-color advancing fill,
/// spring rewind on early release, label width morph, and hand-drawn checkmark.
#[derive(IntoElement)]
pub struct HoldToConfirm {
    id: ElementId,
    label: SharedString,
    confirmed_label: SharedString,
    duration: Duration,
    icon: Option<IconName>,
    tone: HoldToConfirmTone,
    confirmed: Option<bool>,
    disabled: bool,
    on_confirm: Option<HoldConfirmHandler>,
    on_hold_change: Option<HoldChangeHandler>,
}

impl HoldToConfirm {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            confirmed_label: "Done".into(),
            duration: Duration::from_millis(1200),
            icon: Some(IconName::Delete),
            tone: HoldToConfirmTone::Accent,
            confirmed: None,
            disabled: false,
            on_confirm: None,
            on_hold_change: None,
        }
    }

    pub fn confirmed_label(mut self, label: impl Into<SharedString>) -> Self {
        self.confirmed_label = label.into();
        self
    }

    pub fn duration(mut self, duration: Duration) -> Self {
        self.duration = duration.max(Duration::from_millis(100));
        self
    }

    pub fn duration_ms(mut self, ms: u64) -> Self {
        self.duration = Duration::from_millis(ms.max(100));
        self
    }

    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

    pub fn without_icon(mut self) -> Self {
        self.icon = None;
        self
    }

    pub fn tone(mut self, tone: HoldToConfirmTone) -> Self {
        self.tone = tone;
        self
    }

    pub fn confirmed(mut self, confirmed: bool) -> Self {
        self.confirmed = Some(confirmed);
        self
    }

    pub fn confirmed_opt(mut self, confirmed: Option<bool>) -> Self {
        self.confirmed = confirmed;
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn on_confirm(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_confirm = Some(Rc::new(handler));
        self
    }

    pub fn on_hold_change(
        mut self,
        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_hold_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for HoldToConfirm {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);
        let duration_secs = self.duration.as_secs_f64().max(0.1);

        let initial_done = self.confirmed.unwrap_or(false);
        let initial_text = if initial_done {
            self.confirmed_label.clone()
        } else {
            self.label.clone()
        };

        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-hold-to-confirm-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            HoldToConfirmInternal::new(initial_done, initial_text, now, cx.focus_handle())
        });

        let is_controlled = self.confirmed.is_some();
        let mut done = self
            .confirmed
            .unwrap_or_else(|| internal.read(cx).uncontrolled_confirmed);

        // Detect external `confirmed` prop transitions.
        if done != internal.read(cx).last_done {
            internal.update(cx, |s, _| {
                s.last_done = done;
                s.done_changed_at_secs = now;
                if done {
                    s.holding_source = None;
                    s.rewind_progress = 1.0;
                } else {
                    s.holding_source = None;
                }
            });
        }

        // Check if an active hold has reached 100% on this frame.
        let mut just_completed = false;
        if let Some(_src) = internal.read(cx).holding_source {
            let (start_p, started_at) = {
                let s = internal.read(cx);
                (s.hold_start_progress, s.hold_started_at_secs)
            };
            let p = hold_linear_progress(start_p, (now - started_at).max(0.0), duration_secs);
            if p >= 1.0 - 1e-4 {
                internal.update(cx, |s, _| {
                    s.holding_source = None;
                    s.rewind_progress = 1.0;
                    if !is_controlled {
                        s.uncontrolled_confirmed = true;
                    }
                    s.last_done = true;
                    s.done_changed_at_secs = now;
                });
                if !is_controlled {
                    done = true;
                }
                just_completed = true;
            } else {
                window.request_animation_frame();
            }
        }
        if just_completed {
            if let Some(cb_h) = &self.on_hold_change {
                cb_h(&false, window, cx);
            }
            if let Some(cb_c) = &self.on_confirm {
                cb_c(&(), window, cx);
            }
        }

        let text = if done {
            self.confirmed_label.clone()
        } else {
            self.label.clone()
        };

        // Detect label text swap so we can crossfade old/new text and morph width.
        if text != internal.read(cx).last_text {
            internal.update(cx, |s, _| {
                s.previous_text = Some(s.last_text.clone());
                s.last_text = text.clone();
                s.text_changed_at_secs = now;
            });
        }

        let snap = internal.read(cx).clone();
        let holding = snap.holding_source.is_some() && !done && !self.disabled;

        // Progress calculation: linear while holding, `spring.smooth` rewind when released or reset.
        let progress = if holding {
            let p = hold_linear_progress(
                snap.hold_start_progress,
                (now - snap.hold_started_at_secs).max(0.0),
                duration_secs,
            );
            let _ = arc_spring_with_options(
                (self.id.clone(), "hold-progress"),
                p,
                SpringOptions::new(motion.spring.smooth).with_initial_value(p),
                window,
                cx,
            );
            internal.update(cx, |s, _| s.rewind_progress = p);
            p
        } else {
            let target = if done { 1.0 } else { 0.0 };
            if reduced {
                let _ = arc_spring_with_options(
                    (self.id.clone(), "hold-progress"),
                    target,
                    SpringOptions::new(motion.spring.smooth).with_initial_value(target),
                    window,
                    cx,
                );
                internal.update(cx, |s, _| s.rewind_progress = target);
                target
            } else {
                let sp = arc_spring(
                    (self.id.clone(), "hold-progress"),
                    target,
                    motion.spring.smooth,
                    window,
                    cx,
                )
                .clamp(0.0, 1.0);
                internal.update(cx, |s, _| s.rewind_progress = sp);
                sp
            }
        };

        // Adaptive press scale (`>220px -> 0.985`, else `0.97`).
        let btn_w = snap
            .button_bounds
            .borrow()
            .map(|b| f32::from(b.size.width))
            .unwrap_or(180.0);
        let press_depth = if btn_w > 220.0 { 0.985 } else { 0.97 };
        let scale = if reduced {
            1.0
        } else {
            arc_spring(
                (self.id.clone(), "press-scale"),
                if holding { press_depth } else { 1.0 },
                motion.spring.snappy,
                window,
                cx,
            )
        };

        // Label width morph (`spring.morph`).
        let fallback_w = (text.chars().count() as f32 * 7.8).max(32.0);
        let measured_w = {
            let m = *snap.measured_label_width.borrow();
            if m > 1.0 { m } else { fallback_w }
        };
        let has_measured = *snap.has_measured_label.borrow();
        let text_elapsed = (now - snap.text_changed_at_secs).max(0.0);
        let morph_active = text_elapsed < 0.45 && has_measured && !reduced;
        let label_w = if morph_active {
            arc_spring(
                (self.id.clone(), "label-w"),
                measured_w,
                motion.spring.morph,
                window,
                cx,
            )
        } else {
            let _ = arc_spring_with_options(
                (self.id.clone(), "label-w"),
                measured_w,
                SpringOptions::new(motion.spring.morph).with_initial_value(measured_w),
                window,
                cx,
            );
            measured_w
        };

        // Label vertical rise (`+0.3em -> 0`) + blur fallback.
        let text_dur = if reduced {
            motion.duration.fast.as_secs_f64()
        } else {
            motion.duration.standard.as_secs_f64()
        };
        let (label_op, label_y) = if text_elapsed >= text_dur {
            (1.0_f32, 0.0_f32)
        } else {
            window.request_animation_frame();
            let t = (text_elapsed / text_dur.max(0.001)).clamp(0.0, 1.0) as f32;
            let e = if reduced {
                t
            } else {
                CubicBezier::from(motion.ease.enter).sample(t)
            };
            let blur = BlurFallback::evaluate(px(8.0 * (1.0 - e)), reduced);
            let y = if reduced {
                0.0
            } else {
                0.3 * f32::from(Typography::TEXT_SM) * (1.0 - e)
            };
            ((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
        };

        // Checkmark draw sample when `done`.
        let done_elapsed = (now - snap.done_changed_at_secs).max(0.0);
        let (check_len, check_op) = if done {
            if !reduced && done_elapsed < 0.44 {
                window.request_animation_frame();
            }
            hold_check_draw_sample(done_elapsed, reduced)
        } else {
            (0.0, 0.0)
        };

        // Tone palette resolution.
        let (ink_color, fill_color, on_fill_color, border_color) = match self.tone {
            HoldToConfirmTone::Accent => (
                colors.foreground,
                colors.accent,
                colors.accent_foreground,
                colors.border_strong,
            ),
            HoldToConfirmTone::Danger => (
                colors.danger,
                colors.danger,
                colors.background,
                oklab_mix(colors.danger, colors.border, 0.32),
            ),
            HoldToConfirmTone::Neutral => (
                colors.foreground,
                colors.foreground,
                colors.background,
                colors.border_strong,
            ),
        };
        let surface_bg = if !self.disabled && !done && snap.hovered {
            oklab_mix(fill_color, colors.surface, 0.06)
        } else {
            colors.surface
        };

        // Hidden sizer to measure natural label width without clipping.
        let measured_w_ref = snap.measured_label_width.clone();
        let has_measured_ref = snap.has_measured_label.clone();
        let sizer_el = div()
            .absolute()
            .top_0()
            .left_0()
            .opacity(0.0)
            .text_size(Typography::TEXT_SM)
            .font_medium()
            .whitespace_nowrap()
            .child(text.clone())
            .child(
                canvas(
                    move |rect, _, _| {
                        let w = f32::from(rect.size.width);
                        if w > 1.0 {
                            *measured_w_ref.borrow_mut() = w;
                            *has_measured_ref.borrow_mut() = true;
                        }
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .inset_0(),
            );

        let icon_opt = self.icon;
        let build_face = |fg: Hsla| {
            let icon_slot = div()
                .size(px(18.0))
                .flex_none()
                .flex()
                .items_center()
                .justify_center()
                .child(if done {
                    canvas(
                        |_, _, _| {},
                        move |rect, _, window, _| {
                            paint_drawn_check(rect, check_len, check_op, fg, window);
                        },
                    )
                    .size_full()
                    .into_any_element()
                } else if let Some(ic) = icon_opt {
                    Icon::new(ic)
                        .text_size(px(16.0))
                        .text_color(fg)
                        .into_any_element()
                } else {
                    div().size_full().into_any_element()
                });

            let label_slot = div()
                .relative()
                .w(px(label_w))
                .h(px(20.0))
                .overflow_hidden()
                .flex()
                .items_center()
                .child(
                    div()
                        .mt(px(label_y))
                        .opacity(label_op)
                        .text_size(Typography::TEXT_SM)
                        .font_medium()
                        .text_color(fg)
                        .whitespace_nowrap()
                        .child(text.clone()),
                );

            div()
                .px(Spacing::S4)
                .h(ControlHeights::MD)
                .flex_none()
                .flex()
                .flex_row()
                .items_center()
                .justify_center()
                .gap(Spacing::S2)
                .child(icon_slot)
                .child(label_slot)
        };

        let base_face = build_face(ink_color);
        let fill_face = build_face(on_fill_color);

        // Backdrop & advancing fill painted in a single canvas so `scaled_bounds` applies press
        // scale cleanly to both surface and border.
        let button_bounds_ref = snap.button_bounds.clone();
        let int_ptr = internal.clone();
        let on_hold_ptr = self.on_hold_change.clone();
        let backdrop_canvas = canvas(
            move |rect, _, _| {
                *button_bounds_ref.borrow_mut() = Some(rect);
            },
            move |rect, _, window, _| {
                let scaled = scaled_bounds(rect, scale, scale, TransformOrigin::CENTER);
                window.paint_quad(quad(
                    scaled,
                    Corners::all(Radii::CONTROL),
                    surface_bg,
                    Edges::all(px(1.0)),
                    border_color,
                    BorderStyle::Solid,
                ));

                // When holding via pointer, watch global pointer move (24px slack) and release.
                if holding {
                    let st_move = int_ptr.clone();
                    let cb_move = on_hold_ptr.clone();
                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        if st_move.read(cx).holding_source != Some(HoldSource::Pointer) {
                            return;
                        }
                        let out_of_slack =
                            st_move.read(cx).button_bounds.borrow().is_some_and(|b| {
                                let slack = px(HOLD_TO_CONFIRM_POINTER_SLACK_PX);
                                event.position.x < b.origin.x - slack
                                    || event.position.x > b.origin.x + b.size.width + slack
                                    || event.position.y < b.origin.y - slack
                                    || event.position.y > b.origin.y + b.size.height + slack
                            });
                        if out_of_slack {
                            let cur_p = st_move.read(cx).rewind_progress;
                            st_move.update(cx, |s, _| {
                                s.holding_source = None;
                                s.hold_start_progress = cur_p;
                            });
                            if let Some(cb) = &cb_move {
                                cb(&false, window, cx);
                            }
                            window.refresh();
                        }
                    });

                    let st_up = int_ptr.clone();
                    let cb_up = on_hold_ptr.clone();
                    window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        if st_up.read(cx).holding_source == Some(HoldSource::Pointer) {
                            let cur_p = st_up.read(cx).rewind_progress;
                            st_up.update(cx, |s, _| {
                                s.holding_source = None;
                                s.hold_start_progress = cur_p;
                            });
                            if let Some(cb) = &cb_up {
                                cb(&false, window, cx);
                            }
                            window.refresh();
                        }
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        // Clipped fill overlay: width is `progress * button_width` so the inverted face reveals
        // from left to right and flips text color right at the boundary.
        let fill_clip_w = (btn_w * progress.clamp(0.0, 1.0)).max(0.0);
        let fill_layer = div()
            .id(ElementId::NamedChild(self.id.clone().into(), "fill".into()))
            .test_support()
            .absolute()
            .top_0()
            .bottom_0()
            .left_0()
            .w(px(fill_clip_w))
            .rounded(Radii::CONTROL)
            .bg(fill_color)
            .overflow_hidden()
            .flex()
            .flex_row()
            .items_center()
            .justify_start()
            .child(fill_face);

        let disabled = self.disabled;
        let int_hover = internal.clone();
        let int_down = internal.clone();
        let int_key_down = internal.clone();
        let int_key_up = internal.clone();
        let on_hold_down = self.on_hold_change.clone();
        let on_hold_key_down = self.on_hold_change.clone();
        let on_hold_key_up = self.on_hold_change.clone();
        let focus_handle = snap.focus_handle.clone();
        let focus_for_down = snap.focus_handle;

        div()
            .id(self.id)
            .test_support()
            .role(Role::Button)
            .aria_label(text)
            .track_focus(&focus_handle)
            .relative()
            .h(ControlHeights::MD)
            .flex_none()
            .flex()
            .flex_row()
            .items_center()
            .justify_center()
            .rounded(Radii::CONTROL)
            .opacity(if disabled { 0.5 } else { 1.0 })
            .when(!disabled && !done, |this| this.cursor_pointer())
            .on_hover(move |hovered, window, cx| {
                int_hover.update(cx, |s, _| s.hovered = *hovered);
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_: &MouseDownEvent, window, cx| {
                if disabled || done {
                    return;
                }
                window.focus(&focus_for_down, cx);
                if int_down.read(cx).holding_source.is_some() {
                    return;
                }
                let t_now = motion_now(cx);
                let cur_p = int_down.read(cx).rewind_progress.clamp(0.0, 1.0);
                int_down.update(cx, |s, _| {
                    s.holding_source = Some(HoldSource::Pointer);
                    s.hold_started_at_secs = t_now;
                    s.hold_start_progress = cur_p;
                });
                if let Some(cb) = &on_hold_down {
                    cb(&true, window, cx);
                }
                window.refresh();
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if disabled || done {
                    return;
                }
                let k = event.keystroke.key.as_str();
                if k != " " && k != "space" && k != "enter" {
                    return;
                }
                if int_key_down.read(cx).holding_source.is_some() {
                    return;
                }
                let t_now = motion_now(cx);
                let cur_p = int_key_down.read(cx).rewind_progress.clamp(0.0, 1.0);
                int_key_down.update(cx, |s, _| {
                    s.holding_source = Some(HoldSource::Key);
                    s.hold_started_at_secs = t_now;
                    s.hold_start_progress = cur_p;
                });
                if let Some(cb) = &on_hold_key_down {
                    cb(&true, window, cx);
                }
                window.refresh();
            })
            .on_key_up(move |event: &KeyUpEvent, window, cx| {
                let k = event.keystroke.key.as_str();
                if k != " " && k != "space" && k != "enter" {
                    return;
                }
                if int_key_up.read(cx).holding_source == Some(HoldSource::Key) {
                    let cur_p = int_key_up.read(cx).rewind_progress;
                    int_key_up.update(cx, |s, _| {
                        s.holding_source = None;
                        s.hold_start_progress = cur_p;
                    });
                    if let Some(cb) = &on_hold_key_up {
                        cb(&false, window, cx);
                    }
                    window.refresh();
                }
            })
            .child(sizer_el)
            .child(backdrop_canvas)
            .child(base_face)
            .when(progress > 0.001, |this| this.child(fill_layer))
    }
}

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

    #[test]
    fn hold_linear_progress_resumes_from_partial_fill_and_clamps() {
        assert!((hold_linear_progress(0.0, 0.0, 1.2) - 0.0).abs() < 1e-5);
        assert!((hold_linear_progress(0.0, 0.6, 1.2) - 0.5).abs() < 1e-5);
        assert!((hold_linear_progress(0.0, 1.2, 1.2) - 1.0).abs() < 1e-5);
        // Starting from 50% fill needs only half the duration (0.6s) to reach 100%.
        assert!((hold_linear_progress(0.5, 0.3, 1.2) - 0.75).abs() < 1e-5);
        assert!((hold_linear_progress(0.5, 0.6, 1.2) - 1.0).abs() < 1e-5);
    }

    #[test]
    fn hold_check_draw_sample_waits_80ms_then_draws_to_one() {
        let (len0, op0) = hold_check_draw_sample(0.04, false);
        assert_eq!(len0, 0.0);
        assert_eq!(op0, 0.0);

        let (len_mid, op_mid) = hold_check_draw_sample(0.24, false);
        assert!(len_mid > 0.4 && len_mid < 1.0);
        assert!((op_mid - 1.0).abs() < 1e-5);

        let (len_end, op_end) = hold_check_draw_sample(0.45, false);
        assert!((len_end - 1.0).abs() < 1e-5);
        assert!((op_end - 1.0).abs() < 1e-5);

        let (len_red, op_red) = hold_check_draw_sample(0.0, true);
        assert_eq!(len_red, 1.0);
        assert_eq!(op_red, 1.0);
    }

    #[gpui_kit::test]
    async fn hold_to_confirm_completes_after_duration_and_rewinds_on_early_release(
        cx: &mut gpui_kit::TestAppContext,
    ) {
        use arc_tokens::{Accent, ThemeMode, install_arc_theme};
        use gpui_kit::{Context, Render, Window, test::TestWindowExt as _};
        use std::sync::{
            Arc,
            atomic::{AtomicUsize, Ordering},
        };

        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        struct Host {
            confirm_count: Arc<AtomicUsize>,
        }

        impl Render for Host {
            fn render(
                &mut self,
                _window: &mut Window,
                _cx: &mut Context<Self>,
            ) -> impl IntoElement {
                let count = self.confirm_count.clone();
                div().p(px(20.0)).child(
                    HoldToConfirm::new("test-hold-btn", "Hold to delete")
                        .confirmed_label("Deleted")
                        .duration_ms(400)
                        .tone(HoldToConfirmTone::Danger)
                        .on_confirm(move |_, _, _| {
                            count.fetch_add(1, Ordering::SeqCst);
                        }),
                )
            }
        }

        let confirm_count = Arc::new(AtomicUsize::new(0));
        let c_clone = confirm_count.clone();
        let (_view, cx) = cx.add_window_view(move |_, _| Host {
            confirm_count: c_clone,
        });

        let center = cx.update(|window, cx| {
            window.render_frame(cx);
            window.find("test-hold-btn").bounds().center()
        });
        cx.simulate_mouse_down(center, MouseButton::Left, gpui_kit::Modifiers::default());
        cx.update(|window, cx| window.render_frame(cx));

        // Release early at 150ms (< 400ms): should not confirm.
        cx.executor().advance_clock(Duration::from_millis(150));
        cx.update(|window, cx| window.render_frame(cx));
        cx.simulate_mouse_up(center, MouseButton::Left, gpui_kit::Modifiers::default());
        cx.update(|window, cx| window.render_frame(cx));
        assert_eq!(confirm_count.load(Ordering::SeqCst), 0);

        // Let rewind settle, then hold for the full 450ms -> confirms once.
        cx.executor().advance_clock(Duration::from_millis(500));
        cx.update(|window, cx| window.render_frame(cx));
        cx.simulate_mouse_down(center, MouseButton::Left, gpui_kit::Modifiers::default());
        cx.update(|window, cx| window.render_frame(cx));
        cx.executor().advance_clock(Duration::from_millis(450));
        cx.update(|window, cx| window.render_frame(cx));
        assert_eq!(confirm_count.load(Ordering::SeqCst), 1);
    }
}