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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/shortcut-recorder/shortcut-recorder.tsx`
//!
//! P4 Component #24: `shortcut-recorder`
//!
//! - A field that records a keyboard shortcut:
//!   - Click the field, then press a combination: the finished shortcut settles into place as
//!     key caps; a combination that is already taken asks before taking it ("Use anyway" /
//!     "Cancel"); Escape cancels, Backspace clears, and a reset button restores the default.
//!   - Shortcut model: `"mod+shift+k"` strings; `mod` is ⌘ on a Mac and Ctrl elsewhere.
//!     The modifier order is fixed: mod, ctrl, alt, shift, meta.
//!   - Reserved combos (⌘W, ⌘C, ⌘Z…) ask before taking when `warn_reserved` (on by default).
//!   - Key caps follow the platform: ⌘ on a Mac, Ctrl elsewhere (`ShortcutPlatform::Mac` /
//!     `Other`); `normalize_shortcut` maps `ctrl`/`meta` to the platform's `mod`.
//!   - `require_modifier` (on by default) rejects bare keys except function keys, with a hint.
//!
//! Known deviations from upstream:
//! - Recording reads the GPUI keystroke directly (`ctrl-shift-k` style), so there is no
//!   physical `code`-based key-id table and no held-key set; the live-caps preview shows only
//!   the settled combination. There is no `aria-live` region.

use std::rc::Rc;

use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
    AnyElement, App, ElementId, FocusHandle, IntoElement, KeyDownEvent, ParentElement, Pixels,
    RenderOnce, SharedString, Styled, TestSupportExt as _, Window,
    base::{Button as BaseButton, StyledExt as _},
    div,
    prelude::*,
    px,
};

type RecorderChangeHandler = Rc<dyn Fn(&Option<SharedString>, &mut Window, &mut App)>;

/// A shortcut string such as `"mod+shift+k"`; `mod` is ⌘ on a Mac and Ctrl elsewhere.
pub type Shortcut = SharedString;

/// Modifier order for the normalized form.
pub const SHORTCUT_MODIFIER_ORDER: [&str; 5] = ["mod", "ctrl", "alt", "shift", "meta"];

/// A key cap: what the cap shows and how it reads aloud.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShortcutToken {
    /// What the key cap shows.
    pub label: SharedString,
    /// Physical key id, matched against held keys.
    pub id: SharedString,
    pub spoken: SharedString,
}

/// The platform a shortcut reads for (`mod` = ⌘ on a Mac, Ctrl elsewhere).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShortcutPlatform {
    Mac,
    Other,
}

fn is_modifier(part: &str) -> bool {
    SHORTCUT_MODIFIER_ORDER.contains(&part)
}

/// Splits `"mod+shift+k"` into its modifiers and the key.
pub fn split_shortcut(shortcut: &str) -> (Vec<String>, String) {
    let parts: Vec<String> = shortcut
        .to_lowercase()
        .split('+')
        .map(|part| part.trim().to_string())
        .filter(|part| !part.is_empty())
        .collect();
    let key = parts
        .iter()
        .rev()
        .find(|part| !is_modifier(part))
        .cloned()
        .unwrap_or_default();
    let mods: Vec<String> = parts.into_iter().filter(|p| is_modifier(p)).collect();
    (mods, key)
}

/// One spelling per combination: on a Mac, Command is `mod`; elsewhere, Ctrl is. Modifiers
/// come in a fixed order.
pub fn normalize_shortcut(shortcut: &str, platform: ShortcutPlatform) -> String {
    let (mods, key) = split_shortcut(shortcut);
    let mut set: std::collections::BTreeSet<String> = mods.into_iter().collect();
    if platform == ShortcutPlatform::Mac && set.remove("meta") {
        set.insert("mod".to_string());
    }
    if platform == ShortcutPlatform::Other && set.remove("ctrl") {
        set.insert("mod".to_string());
    }
    let mut all: Vec<String> = SHORTCUT_MODIFIER_ORDER
        .iter()
        .filter(|m| set.contains(m.to_string().as_str()))
        .map(|m| m.to_string())
        .collect();
    if !key.is_empty() {
        all.push(key);
    }
    all.join("+")
}

/// Reads a keystroke into a shortcut string, or `None` while only modifiers are down.
pub fn shortcut_from_event(
    key: &str,
    ctrl: bool,
    alt: bool,
    shift: bool,
    platform: ShortcutPlatform,
) -> Option<String> {
    let key = key.to_lowercase();
    if key.is_empty() || ["meta", "ctrl", "alt", "shift"].contains(&key.as_str()) {
        return None;
    }
    let mut mods: Vec<&str> = Vec::new();
    if platform == ShortcutPlatform::Mac {
        if ctrl {
            mods.push("ctrl");
        }
    } else if ctrl {
        mods.push("mod");
    }
    if alt {
        mods.push("alt");
    }
    if shift {
        mods.push("shift");
    }
    let mut all: Vec<String> = mods.iter().map(|s| s.to_string()).collect();
    all.push(key);
    Some(normalize_shortcut(&all.join("+"), platform))
}

/// Key caps for a shortcut in platform order: ⌃ ⌥ ⇧ ⌘ on a Mac, Ctrl Alt Shift Win elsewhere.
pub fn shortcut_tokens(shortcut: &str, platform: ShortcutPlatform) -> Vec<ShortcutToken> {
    let (mods, key) = split_shortcut(&normalize_shortcut(shortcut, platform));
    let mut tokens: Vec<ShortcutToken> = Vec::new();
    let has = |name: &str| mods.iter().any(|m| m == name);
    if platform == ShortcutPlatform::Mac {
        if has("ctrl") {
            tokens.push(ShortcutToken {
                label: "⌃".into(),
                id: "ctrl".into(),
                spoken: "Control".into(),
            });
        }
        if has("alt") {
            tokens.push(ShortcutToken {
                label: "⌥".into(),
                id: "alt".into(),
                spoken: "Option".into(),
            });
        }
        if has("shift") {
            tokens.push(ShortcutToken {
                label: "⇧".into(),
                id: "shift".into(),
                spoken: "Shift".into(),
            });
        }
        if has("mod") || has("meta") {
            tokens.push(ShortcutToken {
                label: "⌘".into(),
                id: "meta".into(),
                spoken: "Command".into(),
            });
        }
    } else {
        if has("mod") || has("ctrl") {
            tokens.push(ShortcutToken {
                label: "Ctrl".into(),
                id: "ctrl".into(),
                spoken: "Control".into(),
            });
        }
        if has("alt") {
            tokens.push(ShortcutToken {
                label: "Alt".into(),
                id: "alt".into(),
                spoken: "Alt".into(),
            });
        }
        if has("shift") {
            tokens.push(ShortcutToken {
                label: "Shift".into(),
                id: "shift".into(),
                spoken: "Shift".into(),
            });
        }
        if has("meta") {
            tokens.push(ShortcutToken {
                label: "Win".into(),
                id: "meta".into(),
                spoken: "Windows".into(),
            });
        }
    }
    if !key.is_empty() {
        tokens.push(ShortcutToken {
            label: SharedString::from(key.to_uppercase()),
            id: SharedString::from(key.clone()),
            spoken: SharedString::from(key.to_uppercase()),
        });
    }
    tokens
}

/// `⌘⇧K` on a Mac, `Ctrl+Shift+K` elsewhere, plus a spoken form for assistive technology.
pub fn format_shortcut(shortcut: &str, platform: ShortcutPlatform) -> (String, String) {
    let tokens = shortcut_tokens(shortcut, platform);
    (
        tokens
            .iter()
            .map(|t| t.label.to_string())
            .collect::<Vec<_>>()
            .join(if platform == ShortcutPlatform::Mac {
                ""
            } else {
                "+"
            }),
        tokens
            .iter()
            .map(|t| t.spoken.to_string())
            .collect::<Vec<_>>()
            .join(" "),
    )
}

fn spoken_of(shortcut: &str) -> SharedString {
    SharedString::from(format_shortcut(shortcut, ShortcutPlatform::Other).1)
}

/// A binding the recorder asks about before taking.
#[derive(Clone, Debug, PartialEq)]
pub struct ShortcutBinding {
    pub shortcut: SharedString,
    pub label: SharedString,
}

impl ShortcutBinding {
    pub fn new(shortcut: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            shortcut: shortcut.into(),
            label: label.into(),
        }
    }
}

/// Combinations the browser or system keeps (`warn_reserved`).
pub fn shortcut_reserved_bindings() -> Vec<ShortcutBinding> {
    [
        ("mod+w", "Close tab"),
        ("mod+t", "New tab"),
        ("mod+n", "New window"),
        ("mod+q", "Quit"),
        ("mod+l", "Address bar"),
        ("mod+r", "Reload"),
        ("mod+shift+t", "Reopen tab"),
        ("mod+c", "Copy"),
        ("mod+v", "Paste"),
        ("mod+x", "Cut"),
        ("mod+z", "Undo"),
    ]
    .iter()
    .map(|(s, l)| ShortcutBinding::new(*s, *l))
    .collect()
}

/// A pending conflict: the recorded shortcut, the binding it clashes with, and whether that
/// binding is a system-reserved one.
#[derive(Clone, Debug, PartialEq)]
pub struct ShortcutPending {
    pub shortcut: SharedString,
    pub conflict: ShortcutBinding,
    pub reserved: bool,
}

#[derive(Clone)]
struct RecorderInternal {
    uncontrolled: Option<SharedString>,
    recording: bool,
    pending: Option<ShortcutPending>,
    nudge: Option<SharedString>,
    focus_handle: FocusHandle,
}

impl RecorderInternal {
    fn new(cx: &mut App) -> Self {
        Self {
            uncontrolled: None,
            recording: false,
            pending: None,
            nudge: None,
            focus_handle: cx.focus_handle(),
        }
    }
}

/// Arc `ShortcutRecorder` — a field that records a keyboard shortcut.
#[derive(IntoElement)]
pub struct ShortcutRecorder {
    id: ElementId,
    label: SharedString,
    hide_label: bool,
    value: Option<SharedString>,
    default_value: Option<SharedString>,
    reset_value: Option<SharedString>,
    bindings: Vec<ShortcutBinding>,
    warn_reserved: bool,
    require_modifier: bool,
    platform: ShortcutPlatform,
    placeholder: SharedString,
    description: Option<SharedString>,
    disabled: bool,
    width: Option<Pixels>,
    on_value_change: Option<RecorderChangeHandler>,
}

impl ShortcutRecorder {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            hide_label: false,
            value: None,
            default_value: None,
            reset_value: None,
            bindings: Vec::new(),
            warn_reserved: true,
            require_modifier: true,
            platform: ShortcutPlatform::Other,
            placeholder: "Record shortcut".into(),
            description: None,
            disabled: false,
            width: None,
            on_value_change: None,
        }
    }

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

    pub fn value(mut self, value: Option<SharedString>) -> Self {
        self.value = value;
        self
    }

    pub fn default_value(mut self, value: Option<SharedString>) -> Self {
        self.default_value = value;
        self
    }

    /// What the reset button restores. Defaults to `default_value`.
    pub fn reset_value(mut self, value: Option<SharedString>) -> Self {
        self.reset_value = value;
        self
    }

    /// Shortcuts already in use. Recording one of them asks before taking it.
    pub fn bindings(mut self, bindings: Vec<ShortcutBinding>) -> Self {
        self.bindings = bindings;
        self
    }

    /// Also warn about combinations the browser or system keeps. On by default.
    pub fn warn_reserved(mut self, warn: bool) -> Self {
        self.warn_reserved = warn;
        self
    }

    /// Require ⌘, Ctrl, or ⌥ (function keys are always allowed). On by default.
    pub fn require_modifier(mut self, require: bool) -> Self {
        self.require_modifier = require;
        self
    }

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

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

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

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

    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

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

impl RenderOnce for ShortcutRecorder {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let reduced = arc_motion::is_reduced_motion(cx);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-recorder-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| RecorderInternal::new(cx));

        // Controlled value sync.
        let current = match self.value.clone() {
            Some(ext) => {
                let for_state = Some(ext.clone());
                internal.update(cx, |s, _| s.uncontrolled = for_state);
                Some(ext)
            }
            None => internal.read(cx).uncontrolled.clone(),
        };
        let restore_to = self.reset_value.clone().or(self.default_value.clone());
        let snap = internal.read(cx).clone();

        let recording = snap.recording && !self.disabled;
        let pending = snap.pending.clone();
        let nudge = snap.nudge.clone();

        let is_ctrl_value = self.value.is_some();
        let platform_here = self.platform;
        let warn_here = self.warn_reserved;
        let require_here = self.require_modifier;
        let bindings_here = self.bindings.clone();
        let on_change_here = self.on_value_change.clone();

        let conflict_for =
            move |shortcut: &str, current: &Option<SharedString>| -> Option<ShortcutPending> {
                let normal = normalize_shortcut(shortcut, platform_here);
                if let Some(cur) = current
                    && normalize_shortcut(cur, platform_here) == normal
                {
                    return None;
                }
                let taken = bindings_here
                    .iter()
                    .find(|binding| normalize_shortcut(&binding.shortcut, platform_here) == normal);
                if let Some(taken) = taken {
                    return Some(ShortcutPending {
                        shortcut: SharedString::from(shortcut),
                        conflict: taken.clone(),
                        reserved: false,
                    });
                }
                let reserved = if warn_here {
                    shortcut_reserved_bindings().into_iter().find(|binding| {
                        normalize_shortcut(&binding.shortcut, platform_here) == normal
                    })
                } else {
                    None
                };
                reserved.map(|binding| ShortcutPending {
                    shortcut: SharedString::from(shortcut),
                    conflict: binding,
                    reserved: true,
                })
            };

        let commit_internal = internal.clone();
        let commit = move |next: Option<SharedString>, window: &mut Window, cx: &mut App| {
            commit_internal.update(cx, |s, _| {
                s.pending = None;
                s.nudge = None;
                s.recording = false;
            });
            if !is_ctrl_value {
                commit_internal.update(cx, |s, _| s.uncontrolled = next.clone());
            }
            if let Some(handler) = &on_change_here {
                handler(&next, window, cx);
            }
            window.refresh();
        };

        let shown = pending
            .as_ref()
            .map(|p| p.shortcut.clone())
            .or_else(|| current.clone());
        let tokens: Vec<ShortcutToken> = shown
            .as_ref()
            .map(|s| shortcut_tokens(s, self.platform))
            .unwrap_or_default();
        let can_reset = !recording && (pending.is_some() || current != restore_to);
        let can_clear = !recording && current.is_some() && pending.is_none();

        // ── Key caps ──────────────────────────────────────────────────────────────────────────
        let chip_els: Vec<AnyElement> = tokens
            .iter()
            .map(|token| {
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("chip-{}", token.id)),
                    ))
                    .test_support()
                    .px(px(6.0))
                    .h(px(24.0))
                    .flex()
                    .items_center()
                    .justify_center()
                    .rounded(px(6.0))
                    .border_1()
                    .border_color(if pending.is_some() {
                        colors.warning
                    } else {
                        colors.border
                    })
                    .bg(if recording {
                        colors.surface_muted
                    } else {
                        colors.surface
                    })
                    .text_size(Typography::TEXT_XS)
                    .font_medium()
                    .text_color(colors.foreground)
                    .child(token.label.clone())
                    .into_any_element()
            })
            .collect();

        let recorder_btn = BaseButton::new(ElementId::NamedChild(
            self.id.clone().into(),
            "recorder".into(),
        ))
        .accessibility_label(if recording {
            SharedString::from("Recording")
        } else {
            shown
                .as_ref()
                .map(|s| spoken_of(s))
                .unwrap_or_else(|| self.placeholder.clone())
        })
        .disabled(self.disabled)
        .on_click({
            let st = internal.clone();
            let disabled_flag = self.disabled;
            move |_, window, cx| {
                if disabled_flag {
                    return;
                }
                let focus = st.read(cx).focus_handle.clone();
                window.focus(&focus, cx);
                let was = st.read(cx).recording;
                st.update(cx, |s, _| {
                    s.recording = !was;
                    s.pending = None;
                    s.nudge = None;
                });
                window.refresh();
            }
        })
        .w_full()
        .h(px(36.0))
        .px(px(10.0))
        .flex()
        .flex_row()
        .items_center()
        .gap(px(4.0))
        .rounded(px(10.0))
        .border_1()
        .border_color(colors.border)
        .bg(if recording {
            colors.surface_muted
        } else {
            colors.surface
        })
        .when(self.disabled, |this| this.opacity(0.5))
        .when(!self.disabled, |this| this.cursor_pointer())
        .child(
            div()
                .flex()
                .flex_row()
                .items_center()
                .gap(px(4.0))
                .flex_1()
                .min_w_0()
                .children(chip_els)
                .when(tokens.is_empty(), |this| {
                    this.child(
                        div()
                            .text_size(Typography::TEXT_SM)
                            .text_color(colors.text_muted)
                            .child(if recording {
                                SharedString::from("Press keys")
                            } else {
                                SharedString::from(self.placeholder.to_string())
                            }),
                    )
                }),
        );

        // ── Reset / Clear actions ─────────────────────────────────────────────────────────────
        let mut actions: Vec<AnyElement> = Vec::new();
        if can_reset {
            let commit_reset = commit.clone();
            let restore = restore_to.clone();
            actions.push(
                BaseButton::new(ElementId::NamedChild(
                    self.id.clone().into(),
                    "reset-button".into(),
                ))
                .accessibility_label(SharedString::from(format!(
                    "Reset to {}",
                    restore
                        .as_ref()
                        .map(|r| format_shortcut(r, self.platform).0)
                        .unwrap_or_else(|| "none".to_string())
                )))
                .on_click(move |_, window, cx| {
                    commit_reset(restore.clone(), window, cx);
                })
                .size(px(24.0))
                .rounded(px(6.0))
                .cursor_pointer()
                .text_color(colors.text_muted)
                .hover(move |s| s.bg(colors.surface_muted))
                .child(
                    div()
                        .text_size(Typography::TEXT_XS)
                        .child(SharedString::from("↺")),
                )
                .into_any_element(),
            );
        }
        if can_clear {
            let commit_clear = commit.clone();
            actions.push(
                BaseButton::new(ElementId::NamedChild(
                    self.id.clone().into(),
                    "clear-button".into(),
                ))
                .accessibility_label("Clear shortcut")
                .on_click(move |_, window, cx| {
                    commit_clear(None, window, cx);
                })
                .size(px(24.0))
                .rounded(px(6.0))
                .cursor_pointer()
                .text_color(colors.text_muted)
                .hover(move |s| s.bg(colors.surface_muted))
                .child(
                    div()
                        .text_size(Typography::TEXT_XS)
                        .child(SharedString::from("×")),
                )
                .into_any_element(),
            );
        }

        // ── Pending conflict message with Use anyway / Cancel ────────────────────────────────
        let pending_msg = pending.clone();
        let _use_anyway_st = internal.clone();
        let use_anyway_commit = commit.clone();
        let cancel_st = internal.clone();
        let root_id = self.id.clone();
        let focus_row = snap.focus_handle.clone();

        div()
            .id(root_id)
            .when_some(self.width, |this, w| this.w(w))
            .when(self.width.is_none(), |this| this.w_full())
            .flex()
            .flex_col()
            .gap(px(4.0))
            .when(!self.hide_label, |this| {
                this.child(
                    div()
                        .text_size(Typography::TEXT_SM)
                        .font_medium()
                        .text_color(colors.foreground)
                        .child(self.label.clone()),
                )
            })
            .child(
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        "control".into(),
                    ))
                    .track_focus(&focus_row.clone())
                    .on_key_down({
                        let st = internal.clone();
                        let disabled_flag = self.disabled;
                        let conflict_fn = conflict_for.clone();
                        let commit_fn = commit.clone();
                        move |event: &KeyDownEvent, window, cx| {
                            if disabled_flag {
                                return;
                            }
                            let keystroke = &event.keystroke;
                            let ctrl = keystroke.modifiers.control;
                            let alt = keystroke.modifiers.alt;
                            let shift = keystroke.modifiers.shift;
                            let is_recording = st.read(cx).recording;
                            if !is_recording {
                                if keystroke.key == "backspace" && current.is_some() {
                                    commit_fn(None, window, cx);
                                }
                                return;
                            }
                            if keystroke.key == "tab" && !shift && !ctrl && !alt {
                                st.update(cx, |s, _| {
                                    s.recording = false;
                                    s.pending = None;
                                    s.nudge = None;
                                });
                                window.refresh();
                                return;
                            }
                            let bare = !ctrl && !alt && !shift;
                            if bare && keystroke.key == "escape" {
                                st.update(cx, |s, _| {
                                    s.recording = false;
                                    s.pending = None;
                                    s.nudge = None;
                                });
                                window.refresh();
                                return;
                            }
                            if bare && keystroke.key == "backspace" {
                                commit_fn(None, window, cx);
                                return;
                            }
                            let Some(shortcut_str) = shortcut_from_event(
                                &keystroke.key,
                                ctrl,
                                alt,
                                shift,
                                self.platform,
                            ) else {
                                return;
                            };
                            let (mods, key_name) = split_shortcut(&shortcut_str);
                            let strong = mods
                                .iter()
                                .any(|m| m == "mod" || m == "ctrl" || m == "alt" || m == "meta");
                            if require_here && !strong && !key_name.starts_with('f') {
                                st.update(cx, |s, _| {
                                    s.nudge = Some("Include Ctrl or Alt".into());
                                });
                                window.refresh();
                                return;
                            }
                            if let Some(pending) = conflict_fn(&shortcut_str, &current) {
                                st.update(cx, |s, _| {
                                    s.pending = Some(pending);
                                });
                                window.refresh();
                                return;
                            }
                            commit_fn(Some(SharedString::from(shortcut_str)), window, cx);
                        }
                    })
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(4.0))
                    .child(recorder_btn)
                    .children(actions),
            )
            .when_some(pending_msg, |this, pending: ShortcutPending| {
                this.child(
                    div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            "message".into(),
                        ))
                        .test_support()
                        .flex()
                        .flex_row()
                        .items_center()
                        .gap(px(6.0))
                        .text_size(Typography::TEXT_XS)
                        .text_color(colors.warning)
                        .child(SharedString::from(format!(
                            "{} {}",
                            if pending.reserved {
                                "Reserved for"
                            } else {
                                "Already used by"
                            },
                            pending.conflict.label
                        )))
                        .child(
                            BaseButton::new(ElementId::NamedChild(
                                self.id.clone().into(),
                                "use-anyway".into(),
                            ))
                            .accessibility_label("Use anyway")
                            .on_click(move |_, window, cx| {
                                use_anyway_commit(Some(pending.shortcut.clone()), window, cx);
                            })
                            .text_size(Typography::TEXT_XS)
                            .font_medium()
                            .text_color(colors.warning)
                            .cursor_pointer()
                            .child(SharedString::from("Use anyway")),
                        )
                        .child(
                            BaseButton::new(ElementId::NamedChild(
                                self.id.clone().into(),
                                "cancel-pending".into(),
                            ))
                            .accessibility_label("Cancel")
                            .on_click(move |_, window, cx| {
                                cancel_st.update(cx, |s, _| s.pending = None);
                                window.refresh();
                            })
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.text_muted)
                            .cursor_pointer()
                            .child(SharedString::from("Cancel")),
                        ),
                )
            })
            .when_some(
                nudge.filter(|_| !recording).or(if recording {
                    Some(SharedString::from("Esc to cancel, Backspace to clear"))
                } else {
                    None
                }),
                |this, hint| {
                    this.child(
                        div()
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.text_muted)
                            .child(hint),
                    )
                },
            )
            .when_some(
                self.description
                    .clone()
                    .filter(|_| !recording && pending.is_none()),
                |this, desc| {
                    this.child(
                        div()
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.text_muted)
                            .child(desc),
                    )
                },
            )
            .when(reduced, |this| this)
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};

    use super::*;

    #[test]
    fn shortcut_split_normalize_and_tokens_match_upstream() {
        // Normalize on "other" platform: ctrl -> mod.
        assert_eq!(
            normalize_shortcut("ctrl+shift+k", ShortcutPlatform::Other),
            "mod+shift+k"
        );
        // Mac: meta -> mod.
        assert_eq!(
            normalize_shortcut("meta+shift+k", ShortcutPlatform::Mac),
            "mod+shift+k"
        );
        // Modifier order is fixed.
        assert_eq!(
            normalize_shortcut("shift+alt+k", ShortcutPlatform::Other),
            "alt+shift+k"
        );
        // Tokens render caps in platform order.
        let tokens = shortcut_tokens("mod+shift+k", ShortcutPlatform::Other);
        let labels: Vec<String> = tokens.iter().map(|t| t.label.to_string()).collect();
        assert_eq!(labels, vec!["Ctrl", "Shift", "K"]);
        let mac_caps = shortcut_tokens("mod+k", ShortcutPlatform::Mac);
        let mac_labels: Vec<String> = mac_caps.iter().map(|t| t.label.to_string()).collect();
        assert_eq!(mac_labels, vec!["⌘", "K"]);
    }

    #[test]
    fn shortcut_from_event_reads_chords_and_rejects_bare_modifiers() {
        assert_eq!(
            shortcut_from_event("k", true, false, true, ShortcutPlatform::Other),
            Some("mod+shift+k".to_string())
        );
        assert_eq!(
            shortcut_from_event("shift", false, false, true, ShortcutPlatform::Other),
            None
        );
        // Function keys are always allowed bare.
        assert_eq!(
            shortcut_from_event("f4", false, false, false, ShortcutPlatform::Other),
            Some("f4".to_string())
        );
        // formatShortcut reads "⌘⇧K" on a Mac and "Ctrl+Shift+K" elsewhere.
        assert_eq!(
            format_shortcut("mod+shift+k", ShortcutPlatform::Mac).0,
            "⇧⌘K"
        );
        assert_eq!(
            format_shortcut("mod+shift+k", ShortcutPlatform::Other).0,
            "Ctrl+Shift+K"
        );
    }

    struct RecorderHost {
        events: Rc<RefCell<Vec<Option<SharedString>>>>,
        disabled: bool,
    }

    impl Render for RecorderHost {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let events = self.events.clone();
            div().w(px(420.0)).p(px(16.0)).child(
                ShortcutRecorder::new("recorder-test", "Shortcut")
                    .disabled(self.disabled)
                    .require_modifier(true)
                    .on_value_change(cx.listener({
                        let events = events.clone();
                        move |_this, value: &Option<SharedString>, _, _cx| {
                            events.borrow_mut().push(value.clone());
                        }
                    })),
            )
        }
    }

    fn recorder_element(name: &str) -> ElementId {
        ElementId::NamedChild(ElementId::Name("recorder-test".into()).into(), name.into())
    }

    #[gpui_kit::test]
    fn recorder_records_clears_and_warns_on_reserved(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let host = RecorderHost {
            events: Rc::new(RefCell::new(Vec::new())),
            disabled: false,
        };
        let events = host.events.clone();
        let (view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            // Click to record, then press Ctrl+Shift+K.
            window.click(recorder_element("recorder"), cx);
            window.render_frame(cx);
            window.press("ctrl-shift-k", cx);
            window.render_frame(cx);
        });
        assert_eq!(
            events
                .borrow()
                .last()
                .map(|v| v.clone().unwrap().to_string()),
            Some("mod+shift+k".to_string())
        );

        // Reserved combos ask before taking: Ctrl+W opens the pending message.
        cx.update(|window, cx| {
            window.click(recorder_element("recorder"), cx);
            window.render_frame(cx);
            window.press("ctrl-w", cx);
            window.render_frame(cx);
            assert!(window.try_find(recorder_element("message")).is_some());
            // "Use anyway" takes it.
            window.click(recorder_element("use-anyway"), cx);
            window.render_frame(cx);
        });
        assert_eq!(
            events
                .borrow()
                .last()
                .map(|v| v.clone().unwrap().to_string()),
            Some("mod+w".to_string())
        );

        // Escape cancels recording without changing anything.
        cx.update(|window, cx| {
            window.click(recorder_element("recorder"), cx);
            window.render_frame(cx);
            window.press("escape", cx);
            window.render_frame(cx);
        });
        assert_eq!(
            events
                .borrow()
                .last()
                .map(|v| v.clone().unwrap().to_string()),
            Some("mod+w".to_string())
        );

        // The clear button empties the value.
        cx.update(|window, cx| {
            window.click(recorder_element("clear-button"), cx);
            window.render_frame(cx);
        });
        assert_eq!(events.borrow().last(), Some(&None));

        // Disabled swallows the record click.
        view.update(cx, |host, cx| {
            host.disabled = true;
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(recorder_element("recorder"), cx);
            window.render_frame(cx);
            window.press("ctrl-k", cx);
            window.render_frame(cx);
        });
        assert_eq!(events.borrow().last(), Some(&None));
    }

    #[gpui_kit::test]
    fn recorder_reduced_motion_still_records(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });

        let host = RecorderHost {
            events: Rc::new(RefCell::new(Vec::new())),
            disabled: false,
        };
        let events = host.events.clone();
        let (_view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(recorder_element("recorder"), cx);
            window.render_frame(cx);
            window.press("ctrl-alt-p", cx);
            window.render_frame(cx);
        });
        assert_eq!(
            events
                .borrow()
                .last()
                .map(|v| v.clone().unwrap().to_string()),
            Some("mod+alt+p".to_string())
        );
    }
}