Skip to main content

arc_ui/actions/
shortcut_recorder.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/shortcut-recorder/shortcut-recorder.tsx`
3//!
4//! P4 Component #24: `shortcut-recorder`
5//!
6//! - A field that records a keyboard shortcut:
7//!   - Click the field, then press a combination: the finished shortcut settles into place as
8//!     key caps; a combination that is already taken asks before taking it ("Use anyway" /
9//!     "Cancel"); Escape cancels, Backspace clears, and a reset button restores the default.
10//!   - Shortcut model: `"mod+shift+k"` strings; `mod` is ⌘ on a Mac and Ctrl elsewhere.
11//!     The modifier order is fixed: mod, ctrl, alt, shift, meta.
12//!   - Reserved combos (⌘W, ⌘C, ⌘Z…) ask before taking when `warn_reserved` (on by default).
13//!   - Key caps follow the platform: ⌘ on a Mac, Ctrl elsewhere (`ShortcutPlatform::Mac` /
14//!     `Other`); `normalize_shortcut` maps `ctrl`/`meta` to the platform's `mod`.
15//!   - `require_modifier` (on by default) rejects bare keys except function keys, with a hint.
16//!
17//! Known deviations from upstream:
18//! - Recording reads the GPUI keystroke directly (`ctrl-shift-k` style), so there is no
19//!   physical `code`-based key-id table and no held-key set; the live-caps preview shows only
20//!   the settled combination. There is no `aria-live` region.
21
22use std::rc::Rc;
23
24use arc_tokens::{ActiveArcTheme as _, Typography};
25use gpui_kit::{
26    AnyElement, App, ElementId, FocusHandle, IntoElement, KeyDownEvent, ParentElement, Pixels,
27    RenderOnce, SharedString, Styled, TestSupportExt as _, Window,
28    base::{Button as BaseButton, StyledExt as _},
29    div,
30    prelude::*,
31    px,
32};
33
34type RecorderChangeHandler = Rc<dyn Fn(&Option<SharedString>, &mut Window, &mut App)>;
35
36/// A shortcut string such as `"mod+shift+k"`; `mod` is ⌘ on a Mac and Ctrl elsewhere.
37pub type Shortcut = SharedString;
38
39/// Modifier order for the normalized form.
40pub const SHORTCUT_MODIFIER_ORDER: [&str; 5] = ["mod", "ctrl", "alt", "shift", "meta"];
41
42/// A key cap: what the cap shows and how it reads aloud.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct ShortcutToken {
45    /// What the key cap shows.
46    pub label: SharedString,
47    /// Physical key id, matched against held keys.
48    pub id: SharedString,
49    pub spoken: SharedString,
50}
51
52/// The platform a shortcut reads for (`mod` = ⌘ on a Mac, Ctrl elsewhere).
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum ShortcutPlatform {
55    Mac,
56    Other,
57}
58
59fn is_modifier(part: &str) -> bool {
60    SHORTCUT_MODIFIER_ORDER.contains(&part)
61}
62
63/// Splits `"mod+shift+k"` into its modifiers and the key.
64pub fn split_shortcut(shortcut: &str) -> (Vec<String>, String) {
65    let parts: Vec<String> = shortcut
66        .to_lowercase()
67        .split('+')
68        .map(|part| part.trim().to_string())
69        .filter(|part| !part.is_empty())
70        .collect();
71    let key = parts
72        .iter()
73        .rev()
74        .find(|part| !is_modifier(part))
75        .cloned()
76        .unwrap_or_default();
77    let mods: Vec<String> = parts.into_iter().filter(|p| is_modifier(p)).collect();
78    (mods, key)
79}
80
81/// One spelling per combination: on a Mac, Command is `mod`; elsewhere, Ctrl is. Modifiers
82/// come in a fixed order.
83pub fn normalize_shortcut(shortcut: &str, platform: ShortcutPlatform) -> String {
84    let (mods, key) = split_shortcut(shortcut);
85    let mut set: std::collections::BTreeSet<String> = mods.into_iter().collect();
86    if platform == ShortcutPlatform::Mac && set.remove("meta") {
87        set.insert("mod".to_string());
88    }
89    if platform == ShortcutPlatform::Other && set.remove("ctrl") {
90        set.insert("mod".to_string());
91    }
92    let mut all: Vec<String> = SHORTCUT_MODIFIER_ORDER
93        .iter()
94        .filter(|m| set.contains(m.to_string().as_str()))
95        .map(|m| m.to_string())
96        .collect();
97    if !key.is_empty() {
98        all.push(key);
99    }
100    all.join("+")
101}
102
103/// Reads a keystroke into a shortcut string, or `None` while only modifiers are down.
104pub fn shortcut_from_event(
105    key: &str,
106    ctrl: bool,
107    alt: bool,
108    shift: bool,
109    platform: ShortcutPlatform,
110) -> Option<String> {
111    let key = key.to_lowercase();
112    if key.is_empty() || ["meta", "ctrl", "alt", "shift"].contains(&key.as_str()) {
113        return None;
114    }
115    let mut mods: Vec<&str> = Vec::new();
116    if platform == ShortcutPlatform::Mac {
117        if ctrl {
118            mods.push("ctrl");
119        }
120    } else if ctrl {
121        mods.push("mod");
122    }
123    if alt {
124        mods.push("alt");
125    }
126    if shift {
127        mods.push("shift");
128    }
129    let mut all: Vec<String> = mods.iter().map(|s| s.to_string()).collect();
130    all.push(key);
131    Some(normalize_shortcut(&all.join("+"), platform))
132}
133
134/// Key caps for a shortcut in platform order: ⌃ ⌥ ⇧ ⌘ on a Mac, Ctrl Alt Shift Win elsewhere.
135pub fn shortcut_tokens(shortcut: &str, platform: ShortcutPlatform) -> Vec<ShortcutToken> {
136    let (mods, key) = split_shortcut(&normalize_shortcut(shortcut, platform));
137    let mut tokens: Vec<ShortcutToken> = Vec::new();
138    let has = |name: &str| mods.iter().any(|m| m == name);
139    if platform == ShortcutPlatform::Mac {
140        if has("ctrl") {
141            tokens.push(ShortcutToken {
142                label: "⌃".into(),
143                id: "ctrl".into(),
144                spoken: "Control".into(),
145            });
146        }
147        if has("alt") {
148            tokens.push(ShortcutToken {
149                label: "⌥".into(),
150                id: "alt".into(),
151                spoken: "Option".into(),
152            });
153        }
154        if has("shift") {
155            tokens.push(ShortcutToken {
156                label: "⇧".into(),
157                id: "shift".into(),
158                spoken: "Shift".into(),
159            });
160        }
161        if has("mod") || has("meta") {
162            tokens.push(ShortcutToken {
163                label: "⌘".into(),
164                id: "meta".into(),
165                spoken: "Command".into(),
166            });
167        }
168    } else {
169        if has("mod") || has("ctrl") {
170            tokens.push(ShortcutToken {
171                label: "Ctrl".into(),
172                id: "ctrl".into(),
173                spoken: "Control".into(),
174            });
175        }
176        if has("alt") {
177            tokens.push(ShortcutToken {
178                label: "Alt".into(),
179                id: "alt".into(),
180                spoken: "Alt".into(),
181            });
182        }
183        if has("shift") {
184            tokens.push(ShortcutToken {
185                label: "Shift".into(),
186                id: "shift".into(),
187                spoken: "Shift".into(),
188            });
189        }
190        if has("meta") {
191            tokens.push(ShortcutToken {
192                label: "Win".into(),
193                id: "meta".into(),
194                spoken: "Windows".into(),
195            });
196        }
197    }
198    if !key.is_empty() {
199        tokens.push(ShortcutToken {
200            label: SharedString::from(key.to_uppercase()),
201            id: SharedString::from(key.clone()),
202            spoken: SharedString::from(key.to_uppercase()),
203        });
204    }
205    tokens
206}
207
208/// `⌘⇧K` on a Mac, `Ctrl+Shift+K` elsewhere, plus a spoken form for assistive technology.
209pub fn format_shortcut(shortcut: &str, platform: ShortcutPlatform) -> (String, String) {
210    let tokens = shortcut_tokens(shortcut, platform);
211    (
212        tokens
213            .iter()
214            .map(|t| t.label.to_string())
215            .collect::<Vec<_>>()
216            .join(if platform == ShortcutPlatform::Mac {
217                ""
218            } else {
219                "+"
220            }),
221        tokens
222            .iter()
223            .map(|t| t.spoken.to_string())
224            .collect::<Vec<_>>()
225            .join(" "),
226    )
227}
228
229fn spoken_of(shortcut: &str) -> SharedString {
230    SharedString::from(format_shortcut(shortcut, ShortcutPlatform::Other).1)
231}
232
233/// A binding the recorder asks about before taking.
234#[derive(Clone, Debug, PartialEq)]
235pub struct ShortcutBinding {
236    pub shortcut: SharedString,
237    pub label: SharedString,
238}
239
240impl ShortcutBinding {
241    pub fn new(shortcut: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
242        Self {
243            shortcut: shortcut.into(),
244            label: label.into(),
245        }
246    }
247}
248
249/// Combinations the browser or system keeps (`warn_reserved`).
250pub fn shortcut_reserved_bindings() -> Vec<ShortcutBinding> {
251    [
252        ("mod+w", "Close tab"),
253        ("mod+t", "New tab"),
254        ("mod+n", "New window"),
255        ("mod+q", "Quit"),
256        ("mod+l", "Address bar"),
257        ("mod+r", "Reload"),
258        ("mod+shift+t", "Reopen tab"),
259        ("mod+c", "Copy"),
260        ("mod+v", "Paste"),
261        ("mod+x", "Cut"),
262        ("mod+z", "Undo"),
263    ]
264    .iter()
265    .map(|(s, l)| ShortcutBinding::new(*s, *l))
266    .collect()
267}
268
269/// A pending conflict: the recorded shortcut, the binding it clashes with, and whether that
270/// binding is a system-reserved one.
271#[derive(Clone, Debug, PartialEq)]
272pub struct ShortcutPending {
273    pub shortcut: SharedString,
274    pub conflict: ShortcutBinding,
275    pub reserved: bool,
276}
277
278#[derive(Clone)]
279struct RecorderInternal {
280    uncontrolled: Option<SharedString>,
281    recording: bool,
282    pending: Option<ShortcutPending>,
283    nudge: Option<SharedString>,
284    focus_handle: FocusHandle,
285}
286
287impl RecorderInternal {
288    fn new(cx: &mut App) -> Self {
289        Self {
290            uncontrolled: None,
291            recording: false,
292            pending: None,
293            nudge: None,
294            focus_handle: cx.focus_handle(),
295        }
296    }
297}
298
299/// Arc `ShortcutRecorder` — a field that records a keyboard shortcut.
300#[derive(IntoElement)]
301pub struct ShortcutRecorder {
302    id: ElementId,
303    label: SharedString,
304    hide_label: bool,
305    value: Option<SharedString>,
306    default_value: Option<SharedString>,
307    reset_value: Option<SharedString>,
308    bindings: Vec<ShortcutBinding>,
309    warn_reserved: bool,
310    require_modifier: bool,
311    platform: ShortcutPlatform,
312    placeholder: SharedString,
313    description: Option<SharedString>,
314    disabled: bool,
315    width: Option<Pixels>,
316    on_value_change: Option<RecorderChangeHandler>,
317}
318
319impl ShortcutRecorder {
320    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
321        Self {
322            id: id.into(),
323            label: label.into(),
324            hide_label: false,
325            value: None,
326            default_value: None,
327            reset_value: None,
328            bindings: Vec::new(),
329            warn_reserved: true,
330            require_modifier: true,
331            platform: ShortcutPlatform::Other,
332            placeholder: "Record shortcut".into(),
333            description: None,
334            disabled: false,
335            width: None,
336            on_value_change: None,
337        }
338    }
339
340    pub fn hide_label(mut self, hide: bool) -> Self {
341        self.hide_label = hide;
342        self
343    }
344
345    pub fn value(mut self, value: Option<SharedString>) -> Self {
346        self.value = value;
347        self
348    }
349
350    pub fn default_value(mut self, value: Option<SharedString>) -> Self {
351        self.default_value = value;
352        self
353    }
354
355    /// What the reset button restores. Defaults to `default_value`.
356    pub fn reset_value(mut self, value: Option<SharedString>) -> Self {
357        self.reset_value = value;
358        self
359    }
360
361    /// Shortcuts already in use. Recording one of them asks before taking it.
362    pub fn bindings(mut self, bindings: Vec<ShortcutBinding>) -> Self {
363        self.bindings = bindings;
364        self
365    }
366
367    /// Also warn about combinations the browser or system keeps. On by default.
368    pub fn warn_reserved(mut self, warn: bool) -> Self {
369        self.warn_reserved = warn;
370        self
371    }
372
373    /// Require ⌘, Ctrl, or ⌥ (function keys are always allowed). On by default.
374    pub fn require_modifier(mut self, require: bool) -> Self {
375        self.require_modifier = require;
376        self
377    }
378
379    pub fn platform(mut self, platform: ShortcutPlatform) -> Self {
380        self.platform = platform;
381        self
382    }
383
384    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
385        self.placeholder = placeholder.into();
386        self
387    }
388
389    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
390        self.description = Some(description.into());
391        self
392    }
393
394    pub fn disabled(mut self, disabled: bool) -> Self {
395        self.disabled = disabled;
396        self
397    }
398
399    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
400        self.width = Some(width.into());
401        self
402    }
403
404    pub fn on_value_change(
405        mut self,
406        handler: impl Fn(&Option<SharedString>, &mut Window, &mut App) + 'static,
407    ) -> Self {
408        self.on_value_change = Some(Rc::new(handler));
409        self
410    }
411}
412
413impl RenderOnce for ShortcutRecorder {
414    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
415        let theme = cx.arc_theme().clone();
416        let colors = theme.colors;
417        let reduced = arc_motion::is_reduced_motion(cx);
418
419        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-recorder-state".into());
420        let internal = window.use_keyed_state(state_id, cx, |_, cx| RecorderInternal::new(cx));
421
422        // Controlled value sync.
423        let current = match self.value.clone() {
424            Some(ext) => {
425                let for_state = Some(ext.clone());
426                internal.update(cx, |s, _| s.uncontrolled = for_state);
427                Some(ext)
428            }
429            None => internal.read(cx).uncontrolled.clone(),
430        };
431        let restore_to = self.reset_value.clone().or(self.default_value.clone());
432        let snap = internal.read(cx).clone();
433
434        let recording = snap.recording && !self.disabled;
435        let pending = snap.pending.clone();
436        let nudge = snap.nudge.clone();
437
438        let is_ctrl_value = self.value.is_some();
439        let platform_here = self.platform;
440        let warn_here = self.warn_reserved;
441        let require_here = self.require_modifier;
442        let bindings_here = self.bindings.clone();
443        let on_change_here = self.on_value_change.clone();
444
445        let conflict_for =
446            move |shortcut: &str, current: &Option<SharedString>| -> Option<ShortcutPending> {
447                let normal = normalize_shortcut(shortcut, platform_here);
448                if let Some(cur) = current
449                    && normalize_shortcut(cur, platform_here) == normal
450                {
451                    return None;
452                }
453                let taken = bindings_here
454                    .iter()
455                    .find(|binding| normalize_shortcut(&binding.shortcut, platform_here) == normal);
456                if let Some(taken) = taken {
457                    return Some(ShortcutPending {
458                        shortcut: SharedString::from(shortcut),
459                        conflict: taken.clone(),
460                        reserved: false,
461                    });
462                }
463                let reserved = if warn_here {
464                    shortcut_reserved_bindings().into_iter().find(|binding| {
465                        normalize_shortcut(&binding.shortcut, platform_here) == normal
466                    })
467                } else {
468                    None
469                };
470                reserved.map(|binding| ShortcutPending {
471                    shortcut: SharedString::from(shortcut),
472                    conflict: binding,
473                    reserved: true,
474                })
475            };
476
477        let commit_internal = internal.clone();
478        let commit = move |next: Option<SharedString>, window: &mut Window, cx: &mut App| {
479            commit_internal.update(cx, |s, _| {
480                s.pending = None;
481                s.nudge = None;
482                s.recording = false;
483            });
484            if !is_ctrl_value {
485                commit_internal.update(cx, |s, _| s.uncontrolled = next.clone());
486            }
487            if let Some(handler) = &on_change_here {
488                handler(&next, window, cx);
489            }
490            window.refresh();
491        };
492
493        let shown = pending
494            .as_ref()
495            .map(|p| p.shortcut.clone())
496            .or_else(|| current.clone());
497        let tokens: Vec<ShortcutToken> = shown
498            .as_ref()
499            .map(|s| shortcut_tokens(s, self.platform))
500            .unwrap_or_default();
501        let can_reset = !recording && (pending.is_some() || current != restore_to);
502        let can_clear = !recording && current.is_some() && pending.is_none();
503
504        // ── Key caps ──────────────────────────────────────────────────────────────────────────
505        let chip_els: Vec<AnyElement> = tokens
506            .iter()
507            .map(|token| {
508                div()
509                    .id(ElementId::NamedChild(
510                        self.id.clone().into(),
511                        SharedString::from(format!("chip-{}", token.id)),
512                    ))
513                    .test_support()
514                    .px(px(6.0))
515                    .h(px(24.0))
516                    .flex()
517                    .items_center()
518                    .justify_center()
519                    .rounded(px(6.0))
520                    .border_1()
521                    .border_color(if pending.is_some() {
522                        colors.warning
523                    } else {
524                        colors.border
525                    })
526                    .bg(if recording {
527                        colors.surface_muted
528                    } else {
529                        colors.surface
530                    })
531                    .text_size(Typography::TEXT_XS)
532                    .font_medium()
533                    .text_color(colors.foreground)
534                    .child(token.label.clone())
535                    .into_any_element()
536            })
537            .collect();
538
539        let recorder_btn = BaseButton::new(ElementId::NamedChild(
540            self.id.clone().into(),
541            "recorder".into(),
542        ))
543        .accessibility_label(if recording {
544            SharedString::from("Recording")
545        } else {
546            shown
547                .as_ref()
548                .map(|s| spoken_of(s))
549                .unwrap_or_else(|| self.placeholder.clone())
550        })
551        .disabled(self.disabled)
552        .on_click({
553            let st = internal.clone();
554            let disabled_flag = self.disabled;
555            move |_, window, cx| {
556                if disabled_flag {
557                    return;
558                }
559                let focus = st.read(cx).focus_handle.clone();
560                window.focus(&focus, cx);
561                let was = st.read(cx).recording;
562                st.update(cx, |s, _| {
563                    s.recording = !was;
564                    s.pending = None;
565                    s.nudge = None;
566                });
567                window.refresh();
568            }
569        })
570        .w_full()
571        .h(px(36.0))
572        .px(px(10.0))
573        .flex()
574        .flex_row()
575        .items_center()
576        .gap(px(4.0))
577        .rounded(px(10.0))
578        .border_1()
579        .border_color(colors.border)
580        .bg(if recording {
581            colors.surface_muted
582        } else {
583            colors.surface
584        })
585        .when(self.disabled, |this| this.opacity(0.5))
586        .when(!self.disabled, |this| this.cursor_pointer())
587        .child(
588            div()
589                .flex()
590                .flex_row()
591                .items_center()
592                .gap(px(4.0))
593                .flex_1()
594                .min_w_0()
595                .children(chip_els)
596                .when(tokens.is_empty(), |this| {
597                    this.child(
598                        div()
599                            .text_size(Typography::TEXT_SM)
600                            .text_color(colors.text_muted)
601                            .child(if recording {
602                                SharedString::from("Press keys")
603                            } else {
604                                SharedString::from(self.placeholder.to_string())
605                            }),
606                    )
607                }),
608        );
609
610        // ── Reset / Clear actions ─────────────────────────────────────────────────────────────
611        let mut actions: Vec<AnyElement> = Vec::new();
612        if can_reset {
613            let commit_reset = commit.clone();
614            let restore = restore_to.clone();
615            actions.push(
616                BaseButton::new(ElementId::NamedChild(
617                    self.id.clone().into(),
618                    "reset-button".into(),
619                ))
620                .accessibility_label(SharedString::from(format!(
621                    "Reset to {}",
622                    restore
623                        .as_ref()
624                        .map(|r| format_shortcut(r, self.platform).0)
625                        .unwrap_or_else(|| "none".to_string())
626                )))
627                .on_click(move |_, window, cx| {
628                    commit_reset(restore.clone(), window, cx);
629                })
630                .size(px(24.0))
631                .rounded(px(6.0))
632                .cursor_pointer()
633                .text_color(colors.text_muted)
634                .hover(move |s| s.bg(colors.surface_muted))
635                .child(
636                    div()
637                        .text_size(Typography::TEXT_XS)
638                        .child(SharedString::from("↺")),
639                )
640                .into_any_element(),
641            );
642        }
643        if can_clear {
644            let commit_clear = commit.clone();
645            actions.push(
646                BaseButton::new(ElementId::NamedChild(
647                    self.id.clone().into(),
648                    "clear-button".into(),
649                ))
650                .accessibility_label("Clear shortcut")
651                .on_click(move |_, window, cx| {
652                    commit_clear(None, window, cx);
653                })
654                .size(px(24.0))
655                .rounded(px(6.0))
656                .cursor_pointer()
657                .text_color(colors.text_muted)
658                .hover(move |s| s.bg(colors.surface_muted))
659                .child(
660                    div()
661                        .text_size(Typography::TEXT_XS)
662                        .child(SharedString::from("×")),
663                )
664                .into_any_element(),
665            );
666        }
667
668        // ── Pending conflict message with Use anyway / Cancel ────────────────────────────────
669        let pending_msg = pending.clone();
670        let _use_anyway_st = internal.clone();
671        let use_anyway_commit = commit.clone();
672        let cancel_st = internal.clone();
673        let root_id = self.id.clone();
674        let focus_row = snap.focus_handle.clone();
675
676        div()
677            .id(root_id)
678            .when_some(self.width, |this, w| this.w(w))
679            .when(self.width.is_none(), |this| this.w_full())
680            .flex()
681            .flex_col()
682            .gap(px(4.0))
683            .when(!self.hide_label, |this| {
684                this.child(
685                    div()
686                        .text_size(Typography::TEXT_SM)
687                        .font_medium()
688                        .text_color(colors.foreground)
689                        .child(self.label.clone()),
690                )
691            })
692            .child(
693                div()
694                    .id(ElementId::NamedChild(
695                        self.id.clone().into(),
696                        "control".into(),
697                    ))
698                    .track_focus(&focus_row.clone())
699                    .on_key_down({
700                        let st = internal.clone();
701                        let disabled_flag = self.disabled;
702                        let conflict_fn = conflict_for.clone();
703                        let commit_fn = commit.clone();
704                        move |event: &KeyDownEvent, window, cx| {
705                            if disabled_flag {
706                                return;
707                            }
708                            let keystroke = &event.keystroke;
709                            let ctrl = keystroke.modifiers.control;
710                            let alt = keystroke.modifiers.alt;
711                            let shift = keystroke.modifiers.shift;
712                            let is_recording = st.read(cx).recording;
713                            if !is_recording {
714                                if keystroke.key == "backspace" && current.is_some() {
715                                    commit_fn(None, window, cx);
716                                }
717                                return;
718                            }
719                            if keystroke.key == "tab" && !shift && !ctrl && !alt {
720                                st.update(cx, |s, _| {
721                                    s.recording = false;
722                                    s.pending = None;
723                                    s.nudge = None;
724                                });
725                                window.refresh();
726                                return;
727                            }
728                            let bare = !ctrl && !alt && !shift;
729                            if bare && keystroke.key == "escape" {
730                                st.update(cx, |s, _| {
731                                    s.recording = false;
732                                    s.pending = None;
733                                    s.nudge = None;
734                                });
735                                window.refresh();
736                                return;
737                            }
738                            if bare && keystroke.key == "backspace" {
739                                commit_fn(None, window, cx);
740                                return;
741                            }
742                            let Some(shortcut_str) = shortcut_from_event(
743                                &keystroke.key,
744                                ctrl,
745                                alt,
746                                shift,
747                                self.platform,
748                            ) else {
749                                return;
750                            };
751                            let (mods, key_name) = split_shortcut(&shortcut_str);
752                            let strong = mods
753                                .iter()
754                                .any(|m| m == "mod" || m == "ctrl" || m == "alt" || m == "meta");
755                            if require_here && !strong && !key_name.starts_with('f') {
756                                st.update(cx, |s, _| {
757                                    s.nudge = Some("Include Ctrl or Alt".into());
758                                });
759                                window.refresh();
760                                return;
761                            }
762                            if let Some(pending) = conflict_fn(&shortcut_str, &current) {
763                                st.update(cx, |s, _| {
764                                    s.pending = Some(pending);
765                                });
766                                window.refresh();
767                                return;
768                            }
769                            commit_fn(Some(SharedString::from(shortcut_str)), window, cx);
770                        }
771                    })
772                    .flex()
773                    .flex_row()
774                    .items_center()
775                    .gap(px(4.0))
776                    .child(recorder_btn)
777                    .children(actions),
778            )
779            .when_some(pending_msg, |this, pending: ShortcutPending| {
780                this.child(
781                    div()
782                        .id(ElementId::NamedChild(
783                            self.id.clone().into(),
784                            "message".into(),
785                        ))
786                        .test_support()
787                        .flex()
788                        .flex_row()
789                        .items_center()
790                        .gap(px(6.0))
791                        .text_size(Typography::TEXT_XS)
792                        .text_color(colors.warning)
793                        .child(SharedString::from(format!(
794                            "{} {}",
795                            if pending.reserved {
796                                "Reserved for"
797                            } else {
798                                "Already used by"
799                            },
800                            pending.conflict.label
801                        )))
802                        .child(
803                            BaseButton::new(ElementId::NamedChild(
804                                self.id.clone().into(),
805                                "use-anyway".into(),
806                            ))
807                            .accessibility_label("Use anyway")
808                            .on_click(move |_, window, cx| {
809                                use_anyway_commit(Some(pending.shortcut.clone()), window, cx);
810                            })
811                            .text_size(Typography::TEXT_XS)
812                            .font_medium()
813                            .text_color(colors.warning)
814                            .cursor_pointer()
815                            .child(SharedString::from("Use anyway")),
816                        )
817                        .child(
818                            BaseButton::new(ElementId::NamedChild(
819                                self.id.clone().into(),
820                                "cancel-pending".into(),
821                            ))
822                            .accessibility_label("Cancel")
823                            .on_click(move |_, window, cx| {
824                                cancel_st.update(cx, |s, _| s.pending = None);
825                                window.refresh();
826                            })
827                            .text_size(Typography::TEXT_XS)
828                            .text_color(colors.text_muted)
829                            .cursor_pointer()
830                            .child(SharedString::from("Cancel")),
831                        ),
832                )
833            })
834            .when_some(
835                nudge.filter(|_| !recording).or(if recording {
836                    Some(SharedString::from("Esc to cancel, Backspace to clear"))
837                } else {
838                    None
839                }),
840                |this, hint| {
841                    this.child(
842                        div()
843                            .text_size(Typography::TEXT_XS)
844                            .text_color(colors.text_muted)
845                            .child(hint),
846                    )
847                },
848            )
849            .when_some(
850                self.description
851                    .clone()
852                    .filter(|_| !recording && pending.is_none()),
853                |this, desc| {
854                    this.child(
855                        div()
856                            .text_size(Typography::TEXT_XS)
857                            .text_color(colors.text_muted)
858                            .child(desc),
859                    )
860                },
861            )
862            .when(reduced, |this| this)
863    }
864}
865
866#[cfg(test)]
867mod tests {
868    use std::cell::RefCell;
869
870    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
871    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
872
873    use super::*;
874
875    #[test]
876    fn shortcut_split_normalize_and_tokens_match_upstream() {
877        // Normalize on "other" platform: ctrl -> mod.
878        assert_eq!(
879            normalize_shortcut("ctrl+shift+k", ShortcutPlatform::Other),
880            "mod+shift+k"
881        );
882        // Mac: meta -> mod.
883        assert_eq!(
884            normalize_shortcut("meta+shift+k", ShortcutPlatform::Mac),
885            "mod+shift+k"
886        );
887        // Modifier order is fixed.
888        assert_eq!(
889            normalize_shortcut("shift+alt+k", ShortcutPlatform::Other),
890            "alt+shift+k"
891        );
892        // Tokens render caps in platform order.
893        let tokens = shortcut_tokens("mod+shift+k", ShortcutPlatform::Other);
894        let labels: Vec<String> = tokens.iter().map(|t| t.label.to_string()).collect();
895        assert_eq!(labels, vec!["Ctrl", "Shift", "K"]);
896        let mac_caps = shortcut_tokens("mod+k", ShortcutPlatform::Mac);
897        let mac_labels: Vec<String> = mac_caps.iter().map(|t| t.label.to_string()).collect();
898        assert_eq!(mac_labels, vec!["⌘", "K"]);
899    }
900
901    #[test]
902    fn shortcut_from_event_reads_chords_and_rejects_bare_modifiers() {
903        assert_eq!(
904            shortcut_from_event("k", true, false, true, ShortcutPlatform::Other),
905            Some("mod+shift+k".to_string())
906        );
907        assert_eq!(
908            shortcut_from_event("shift", false, false, true, ShortcutPlatform::Other),
909            None
910        );
911        // Function keys are always allowed bare.
912        assert_eq!(
913            shortcut_from_event("f4", false, false, false, ShortcutPlatform::Other),
914            Some("f4".to_string())
915        );
916        // formatShortcut reads "⌘⇧K" on a Mac and "Ctrl+Shift+K" elsewhere.
917        assert_eq!(
918            format_shortcut("mod+shift+k", ShortcutPlatform::Mac).0,
919            "⇧⌘K"
920        );
921        assert_eq!(
922            format_shortcut("mod+shift+k", ShortcutPlatform::Other).0,
923            "Ctrl+Shift+K"
924        );
925    }
926
927    struct RecorderHost {
928        events: Rc<RefCell<Vec<Option<SharedString>>>>,
929        disabled: bool,
930    }
931
932    impl Render for RecorderHost {
933        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
934            let events = self.events.clone();
935            div().w(px(420.0)).p(px(16.0)).child(
936                ShortcutRecorder::new("recorder-test", "Shortcut")
937                    .disabled(self.disabled)
938                    .require_modifier(true)
939                    .on_value_change(cx.listener({
940                        let events = events.clone();
941                        move |_this, value: &Option<SharedString>, _, _cx| {
942                            events.borrow_mut().push(value.clone());
943                        }
944                    })),
945            )
946        }
947    }
948
949    fn recorder_element(name: &str) -> ElementId {
950        ElementId::NamedChild(ElementId::Name("recorder-test".into()).into(), name.into())
951    }
952
953    #[gpui_kit::test]
954    fn recorder_records_clears_and_warns_on_reserved(cx: &mut TestAppContext) {
955        cx.update(|cx| {
956            gpui_kit::init(cx);
957            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
958        });
959
960        let host = RecorderHost {
961            events: Rc::new(RefCell::new(Vec::new())),
962            disabled: false,
963        };
964        let events = host.events.clone();
965        let (view, cx) = cx.add_window_view(|_, _| host);
966
967        cx.update(|window, cx| {
968            window.render_frame(cx);
969            // Click to record, then press Ctrl+Shift+K.
970            window.click(recorder_element("recorder"), cx);
971            window.render_frame(cx);
972            window.press("ctrl-shift-k", cx);
973            window.render_frame(cx);
974        });
975        assert_eq!(
976            events
977                .borrow()
978                .last()
979                .map(|v| v.clone().unwrap().to_string()),
980            Some("mod+shift+k".to_string())
981        );
982
983        // Reserved combos ask before taking: Ctrl+W opens the pending message.
984        cx.update(|window, cx| {
985            window.click(recorder_element("recorder"), cx);
986            window.render_frame(cx);
987            window.press("ctrl-w", cx);
988            window.render_frame(cx);
989            assert!(window.try_find(recorder_element("message")).is_some());
990            // "Use anyway" takes it.
991            window.click(recorder_element("use-anyway"), cx);
992            window.render_frame(cx);
993        });
994        assert_eq!(
995            events
996                .borrow()
997                .last()
998                .map(|v| v.clone().unwrap().to_string()),
999            Some("mod+w".to_string())
1000        );
1001
1002        // Escape cancels recording without changing anything.
1003        cx.update(|window, cx| {
1004            window.click(recorder_element("recorder"), cx);
1005            window.render_frame(cx);
1006            window.press("escape", cx);
1007            window.render_frame(cx);
1008        });
1009        assert_eq!(
1010            events
1011                .borrow()
1012                .last()
1013                .map(|v| v.clone().unwrap().to_string()),
1014            Some("mod+w".to_string())
1015        );
1016
1017        // The clear button empties the value.
1018        cx.update(|window, cx| {
1019            window.click(recorder_element("clear-button"), cx);
1020            window.render_frame(cx);
1021        });
1022        assert_eq!(events.borrow().last(), Some(&None));
1023
1024        // Disabled swallows the record click.
1025        view.update(cx, |host, cx| {
1026            host.disabled = true;
1027            cx.notify();
1028        });
1029        cx.update(|window, cx| {
1030            window.render_frame(cx);
1031            window.click(recorder_element("recorder"), cx);
1032            window.render_frame(cx);
1033            window.press("ctrl-k", cx);
1034            window.render_frame(cx);
1035        });
1036        assert_eq!(events.borrow().last(), Some(&None));
1037    }
1038
1039    #[gpui_kit::test]
1040    fn recorder_reduced_motion_still_records(cx: &mut TestAppContext) {
1041        cx.update(|cx| {
1042            gpui_kit::init(cx);
1043            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1044            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1045        });
1046
1047        let host = RecorderHost {
1048            events: Rc::new(RefCell::new(Vec::new())),
1049            disabled: false,
1050        };
1051        let events = host.events.clone();
1052        let (_view, cx) = cx.add_window_view(|_, _| host);
1053
1054        cx.update(|window, cx| {
1055            window.render_frame(cx);
1056            window.click(recorder_element("recorder"), cx);
1057            window.render_frame(cx);
1058            window.press("ctrl-alt-p", cx);
1059            window.render_frame(cx);
1060        });
1061        assert_eq!(
1062            events
1063                .borrow()
1064                .last()
1065                .map(|v| v.clone().unwrap().to_string()),
1066            Some("mod+alt+p".to_string())
1067        );
1068    }
1069}