Skip to main content

fc_ui/capabilities/controls/
hotkey_input.rs

1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, *};
3use std::rc::Rc;
4
5#[derive(Clone)]
6pub struct HotkeyValue {
7    pub key: String,
8    pub modifiers: Modifiers,
9}
10
11impl HotkeyValue {
12    pub fn new(key: impl Into<String>, modifiers: Modifiers) -> Self {
13        Self {
14            key: key.into(),
15            modifiers,
16        }
17    }
18
19    pub fn from_keystroke(keystroke: &Keystroke) -> Option<Self> {
20        let key = keystroke.key.as_str();
21        if Self::is_modifier_only(key) {
22            return None;
23        }
24        Some(Self {
25            key: key.to_string(),
26            modifiers: keystroke.modifiers,
27        })
28    }
29
30    fn is_modifier_only(key: &str) -> bool {
31        matches!(
32            key.to_lowercase().as_str(),
33            "shift" | "control" | "alt" | "meta" | "cmd" | "command" | "ctrl" | "option"
34        )
35    }
36
37    #[cfg(target_os = "macos")]
38    pub fn format_display(&self) -> String {
39        let mut result = String::new();
40        if self.modifiers.control {
41            result.push('⌃');
42        }
43        if self.modifiers.alt {
44            result.push('⌥');
45        }
46        if self.modifiers.shift {
47            result.push('⇧');
48        }
49        if self.modifiers.platform {
50            result.push('⌘');
51        }
52        result.push_str(&self.format_key());
53        result
54    }
55
56    #[cfg(not(target_os = "macos"))]
57    pub fn format_display(&self) -> String {
58        let mut parts = Vec::new();
59        if self.modifiers.control {
60            parts.push("Ctrl".to_string());
61        }
62        if self.modifiers.alt {
63            parts.push("Alt".to_string());
64        }
65        if self.modifiers.shift {
66            parts.push("Shift".to_string());
67        }
68        if self.modifiers.platform {
69            parts.push("Win".to_string());
70        }
71        parts.push(self.format_key());
72        parts.join("+")
73    }
74
75    fn format_key(&self) -> String {
76        match self.key.as_str() {
77            "space" => "Space".to_string(),
78            "enter" => "Enter".to_string(),
79            "escape" => "Esc".to_string(),
80            "tab" => "Tab".to_string(),
81            "backspace" => "Backspace".to_string(),
82            "delete" => "Del".to_string(),
83            "up" => "Up".to_string(),
84            "down" => "Down".to_string(),
85            "left" => "Left".to_string(),
86            "right" => "Right".to_string(),
87            "home" => "Home".to_string(),
88            "end" => "End".to_string(),
89            "pageup" => "PgUp".to_string(),
90            "pagedown" => "PgDn".to_string(),
91            k if k.starts_with('f') && k.len() <= 3 => k.to_uppercase(),
92            k => k.to_uppercase(),
93        }
94    }
95}
96
97pub struct HotkeyInputState {
98    hotkey: Option<HotkeyValue>,
99    recording: bool,
100    focus_handle: FocusHandle,
101}
102
103impl HotkeyInputState {
104    pub fn new(cx: &mut Context<Self>) -> Self {
105        Self {
106            hotkey: None,
107            recording: false,
108            focus_handle: cx.focus_handle(),
109        }
110    }
111
112    pub fn with_hotkey(cx: &mut Context<Self>, hotkey: HotkeyValue) -> Self {
113        Self {
114            hotkey: Some(hotkey),
115            recording: false,
116            focus_handle: cx.focus_handle(),
117        }
118    }
119
120    pub fn hotkey(&self) -> Option<&HotkeyValue> {
121        self.hotkey.as_ref()
122    }
123
124    pub fn set_hotkey(&mut self, hotkey: Option<HotkeyValue>, cx: &mut Context<Self>) {
125        self.hotkey = hotkey;
126        self.recording = false;
127        cx.notify();
128    }
129
130    pub fn is_recording(&self) -> bool {
131        self.recording
132    }
133
134    pub fn start_recording(&mut self, cx: &mut Context<Self>) {
135        self.recording = true;
136        cx.notify();
137    }
138
139    pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
140        self.recording = false;
141        cx.notify();
142    }
143
144    pub fn clear(&mut self, cx: &mut Context<Self>) {
145        self.hotkey = None;
146        self.recording = false;
147        cx.notify();
148    }
149
150    pub fn capture_keystroke(&mut self, keystroke: &Keystroke, cx: &mut Context<Self>) -> bool {
151        if !self.recording {
152            return false;
153        }
154
155        if keystroke.key.as_str() == "escape" {
156            self.stop_recording(cx);
157            return true;
158        }
159
160        if let Some(hotkey) = HotkeyValue::from_keystroke(keystroke) {
161            self.hotkey = Some(hotkey);
162            self.recording = false;
163            cx.notify();
164            return true;
165        }
166
167        false
168    }
169}
170
171impl Focusable for HotkeyInputState {
172    fn focus_handle(&self, _: &App) -> FocusHandle {
173        self.focus_handle.clone()
174    }
175}
176
177impl Render for HotkeyInputState {
178    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
179        div()
180    }
181}
182
183/// Size variants for [`HotkeyInput`].
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
185pub enum HotkeyInputSize {
186    /// Compact 32px chip for dense settings rows and toolbars.
187    Sm,
188    /// Standard 40px input matching `Input`'s medium size.
189    #[default]
190    Md,
191}
192
193#[derive(IntoElement)]
194pub struct HotkeyInput {
195    state: Entity<HotkeyInputState>,
196    placeholder: SharedString,
197    recording_text: SharedString,
198    size: HotkeyInputSize,
199    clearable: bool,
200    disabled: bool,
201    on_change: Option<Rc<dyn Fn(Option<&HotkeyValue>, &mut Window, &mut App)>>,
202    style: StyleRefinement,
203}
204
205impl HotkeyInput {
206    pub fn new(state: Entity<HotkeyInputState>) -> Self {
207        Self {
208            state,
209            placeholder: "Click to record".into(),
210            recording_text: "Press a key...".into(),
211            size: HotkeyInputSize::default(),
212            clearable: true,
213            disabled: false,
214            on_change: None,
215            style: StyleRefinement::default(),
216        }
217    }
218
219    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
220        self.placeholder = placeholder.into();
221        self
222    }
223
224    /// Set the text shown while recording a hotkey.
225    pub fn recording_text(mut self, text: impl Into<SharedString>) -> Self {
226        self.recording_text = text.into();
227        self
228    }
229
230    /// Set the input size.
231    pub fn size(mut self, size: HotkeyInputSize) -> Self {
232        self.size = size;
233        self
234    }
235
236    /// Set whether the clear button is shown when a hotkey is recorded
237    /// (default `true`).
238    pub fn clearable(mut self, clearable: bool) -> Self {
239        self.clearable = clearable;
240        self
241    }
242
243    pub fn disabled(mut self, disabled: bool) -> Self {
244        self.disabled = disabled;
245        self
246    }
247
248    pub fn on_change(
249        mut self,
250        handler: impl Fn(Option<&HotkeyValue>, &mut Window, &mut App) + 'static,
251    ) -> Self {
252        self.on_change = Some(Rc::new(handler));
253        self
254    }
255}
256
257impl Styled for HotkeyInput {
258    fn style(&mut self) -> &mut StyleRefinement {
259        &mut self.style
260    }
261}
262
263impl RenderOnce for HotkeyInput {
264    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
265        let theme = use_theme(cx);
266        let user_style = self.style;
267
268        let state_data = self.state.read(cx);
269        let hotkey = state_data.hotkey.clone();
270        let mut recording = state_data.recording;
271        let focus_handle = state_data.focus_handle(cx);
272        let is_focused = focus_handle.is_focused(window);
273
274        if recording && !is_focused {
275            self.state.update(cx, |state, cx| state.stop_recording(cx));
276            recording = false;
277        }
278
279        let display_text: SharedString = if recording {
280            self.recording_text.clone()
281        } else if let Some(ref hk) = hotkey {
282            hk.format_display().into()
283        } else {
284            self.placeholder.clone()
285        };
286
287        let has_value = hotkey.is_some();
288        let show_clear = self.clearable && has_value && !self.disabled && !recording;
289
290        let (height, padding_x, text_size) = match self.size {
291            HotkeyInputSize::Sm => (px(32.0), px(8.0), px(13.0)),
292            HotkeyInputSize::Md => (px(40.0), px(12.0), px(14.0)),
293        };
294
295        let state_for_click = self.state.clone();
296        let state_for_keydown = self.state.clone();
297        let state_for_clear = self.state.clone();
298
299        let on_change_for_keydown = self.on_change.clone();
300        let on_change_for_clear = self.on_change.clone();
301
302        let border_color = if recording {
303            theme.tokens.primary
304        } else if is_focused {
305            theme.tokens.ring
306        } else {
307            theme.tokens.input
308        };
309
310        let focus_ring = theme.tokens.focus_ring_light();
311        let recording_ring = BoxShadow {
312            offset: point(px(0.0), px(0.0)),
313            blur_radius: px(0.0),
314            spread_radius: px(3.0),
315            inset: false,
316            color: theme.tokens.primary.opacity(0.3),
317        };
318
319        let text_color = if hotkey.is_some() && !recording {
320            theme.tokens.foreground
321        } else {
322            theme.tokens.muted_foreground
323        };
324
325        let clear_button = if show_clear {
326            Some(
327                div()
328                    .id("hotkey-clear")
329                    .ml(px(8.0))
330                    .px(px(6.0))
331                    .py(px(4.0))
332                    .rounded(px(4.0))
333                    .text_color(theme.tokens.muted_foreground)
334                    .hover(|s| s.bg(theme.tokens.muted).text_color(theme.tokens.foreground))
335                    .on_click(move |_, window, cx| {
336                        state_for_clear.update(cx, |state, cx| {
337                            state.clear(cx);
338                        });
339                        if let Some(ref handler) = on_change_for_clear {
340                            handler(None, window, cx);
341                        }
342                        cx.stop_propagation();
343                    })
344                    .child("×"),
345            )
346        } else {
347            None
348        };
349
350        div()
351            .map(|this| {
352                let mut d = this;
353                d.style().refine(&user_style);
354                d
355            })
356            .child(
357                div()
358                    .id(("hotkey-input", self.state.entity_id()))
359                    .track_focus(&focus_handle.tab_index(0).tab_stop(true))
360                    .h(height)
361                    .px(padding_x)
362                    .flex()
363                    .items_center()
364                    .justify_between()
365                    .bg(theme.tokens.background)
366                    .border_1()
367                    .border_color(border_color)
368                    .rounded(theme.tokens.radius_md)
369                    .font_family(theme.tokens.font_mono.clone())
370                    .text_size(text_size)
371                    .when(self.disabled, |d| d.opacity(0.5).cursor_not_allowed())
372                    .when(!self.disabled, |d| d.cursor_pointer())
373                    .when(is_focused && !recording, |d| {
374                        d.shadow(smallvec::smallvec![focus_ring])
375                    })
376                    .when(recording, |d| {
377                        d.shadow(smallvec::smallvec![recording_ring])
378                            .border_color(theme.tokens.primary)
379                    })
380                    .when(!self.disabled, |d| {
381                        d.on_click(move |_, window, cx| {
382                            state_for_click.update(cx, |state, cx| {
383                                if !state.recording {
384                                    state.start_recording(cx);
385                                }
386                            });
387                            window.refresh();
388                        })
389                    })
390                    .when(!self.disabled, |d| {
391                        d.on_key_down(move |event, window, cx| {
392                            let (captured, hotkey) = state_for_keydown.update(cx, |state, cx| {
393                                let captured = state.capture_keystroke(&event.keystroke, cx);
394                                (captured, state.hotkey.clone())
395                            });
396                            if captured {
397                                if let Some(ref handler) = on_change_for_keydown {
398                                    handler(hotkey.as_ref(), window, cx);
399                                }
400                                cx.stop_propagation();
401                            }
402                        })
403                    })
404                    .child(
405                        div()
406                            .flex_1()
407                            .text_color(text_color)
408                            .when(recording, |d| d.opacity(0.7))
409                            .child(display_text),
410                    )
411                    .children(clear_button),
412            )
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use crate::capabilities::foundation::theme::{install_theme, Theme};
420
421    #[gpui::test]
422    fn builders_configure_size_clear_and_recording_text() {
423        let mut app = TestApp::new();
424        app.update(|cx| install_theme(cx, Theme::light()));
425        let state = app.update(|cx| cx.new(HotkeyInputState::new));
426
427        let input = HotkeyInput::new(state)
428            .size(HotkeyInputSize::Sm)
429            .clearable(false)
430            .recording_text("Waiting for keys…");
431
432        assert_eq!(input.size, HotkeyInputSize::Sm);
433        assert!(!input.clearable);
434        assert_eq!(input.recording_text, "Waiting for keys…");
435    }
436}