fc-ui 0.9.7

A comprehensive, professional UI component library for GPUI inspired by shadcn/ui. 85+ polished components for building beautiful desktop applications.
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
use crate::capabilities::foundation::theme::use_theme;
use gpui::{prelude::FluentBuilder as _, *};
use std::rc::Rc;

#[derive(Clone)]
pub struct HotkeyValue {
    pub key: String,
    pub modifiers: Modifiers,
}

impl HotkeyValue {
    pub fn new(key: impl Into<String>, modifiers: Modifiers) -> Self {
        Self {
            key: key.into(),
            modifiers,
        }
    }

    pub fn from_keystroke(keystroke: &Keystroke) -> Option<Self> {
        let key = keystroke.key.as_str();
        if Self::is_modifier_only(key) {
            return None;
        }
        Some(Self {
            key: key.to_string(),
            modifiers: keystroke.modifiers,
        })
    }

    fn is_modifier_only(key: &str) -> bool {
        matches!(
            key.to_lowercase().as_str(),
            "shift" | "control" | "alt" | "meta" | "cmd" | "command" | "ctrl" | "option"
        )
    }

    #[cfg(target_os = "macos")]
    pub fn format_display(&self) -> String {
        let mut result = String::new();
        if self.modifiers.control {
            result.push('⌃');
        }
        if self.modifiers.alt {
            result.push('⌥');
        }
        if self.modifiers.shift {
            result.push('⇧');
        }
        if self.modifiers.platform {
            result.push('⌘');
        }
        result.push_str(&self.format_key());
        result
    }

    #[cfg(not(target_os = "macos"))]
    pub fn format_display(&self) -> String {
        let mut parts = Vec::new();
        if self.modifiers.control {
            parts.push("Ctrl".to_string());
        }
        if self.modifiers.alt {
            parts.push("Alt".to_string());
        }
        if self.modifiers.shift {
            parts.push("Shift".to_string());
        }
        if self.modifiers.platform {
            parts.push("Win".to_string());
        }
        parts.push(self.format_key());
        parts.join("+")
    }

    fn format_key(&self) -> String {
        match self.key.as_str() {
            "space" => "Space".to_string(),
            "enter" => "Enter".to_string(),
            "escape" => "Esc".to_string(),
            "tab" => "Tab".to_string(),
            "backspace" => "Backspace".to_string(),
            "delete" => "Del".to_string(),
            "up" => "Up".to_string(),
            "down" => "Down".to_string(),
            "left" => "Left".to_string(),
            "right" => "Right".to_string(),
            "home" => "Home".to_string(),
            "end" => "End".to_string(),
            "pageup" => "PgUp".to_string(),
            "pagedown" => "PgDn".to_string(),
            k if k.starts_with('f') && k.len() <= 3 => k.to_uppercase(),
            k => k.to_uppercase(),
        }
    }
}

pub struct HotkeyInputState {
    hotkey: Option<HotkeyValue>,
    recording: bool,
    focus_handle: FocusHandle,
}

impl HotkeyInputState {
    pub fn new(cx: &mut Context<Self>) -> Self {
        Self {
            hotkey: None,
            recording: false,
            focus_handle: cx.focus_handle(),
        }
    }

    pub fn with_hotkey(cx: &mut Context<Self>, hotkey: HotkeyValue) -> Self {
        Self {
            hotkey: Some(hotkey),
            recording: false,
            focus_handle: cx.focus_handle(),
        }
    }

    pub fn hotkey(&self) -> Option<&HotkeyValue> {
        self.hotkey.as_ref()
    }

    pub fn set_hotkey(&mut self, hotkey: Option<HotkeyValue>, cx: &mut Context<Self>) {
        self.hotkey = hotkey;
        self.recording = false;
        cx.notify();
    }

    pub fn is_recording(&self) -> bool {
        self.recording
    }

    pub fn start_recording(&mut self, cx: &mut Context<Self>) {
        self.recording = true;
        cx.notify();
    }

    pub fn stop_recording(&mut self, cx: &mut Context<Self>) {
        self.recording = false;
        cx.notify();
    }

    pub fn clear(&mut self, cx: &mut Context<Self>) {
        self.hotkey = None;
        self.recording = false;
        cx.notify();
    }

    pub fn capture_keystroke(&mut self, keystroke: &Keystroke, cx: &mut Context<Self>) -> bool {
        if !self.recording {
            return false;
        }

        if keystroke.key.as_str() == "escape" {
            self.stop_recording(cx);
            return true;
        }

        if let Some(hotkey) = HotkeyValue::from_keystroke(keystroke) {
            self.hotkey = Some(hotkey);
            self.recording = false;
            cx.notify();
            return true;
        }

        false
    }
}

impl Focusable for HotkeyInputState {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl Render for HotkeyInputState {
    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
        div()
    }
}

/// Size variants for [`HotkeyInput`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HotkeyInputSize {
    /// Compact 32px chip for dense settings rows and toolbars.
    Sm,
    /// Standard 40px input matching `Input`'s medium size.
    #[default]
    Md,
}

#[derive(IntoElement)]
pub struct HotkeyInput {
    state: Entity<HotkeyInputState>,
    placeholder: SharedString,
    recording_text: SharedString,
    size: HotkeyInputSize,
    clearable: bool,
    disabled: bool,
    on_change: Option<Rc<dyn Fn(Option<&HotkeyValue>, &mut Window, &mut App)>>,
    style: StyleRefinement,
}

impl HotkeyInput {
    pub fn new(state: Entity<HotkeyInputState>) -> Self {
        Self {
            state,
            placeholder: "Click to record".into(),
            recording_text: "Press a key...".into(),
            size: HotkeyInputSize::default(),
            clearable: true,
            disabled: false,
            on_change: None,
            style: StyleRefinement::default(),
        }
    }

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

    /// Set the text shown while recording a hotkey.
    pub fn recording_text(mut self, text: impl Into<SharedString>) -> Self {
        self.recording_text = text.into();
        self
    }

    /// Set the input size.
    pub fn size(mut self, size: HotkeyInputSize) -> Self {
        self.size = size;
        self
    }

    /// Set whether the clear button is shown when a hotkey is recorded
    /// (default `true`).
    pub fn clearable(mut self, clearable: bool) -> Self {
        self.clearable = clearable;
        self
    }

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

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

impl Styled for HotkeyInput {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for HotkeyInput {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = use_theme(cx);
        let user_style = self.style;

        let state_data = self.state.read(cx);
        let hotkey = state_data.hotkey.clone();
        let mut recording = state_data.recording;
        let focus_handle = state_data.focus_handle(cx);
        let is_focused = focus_handle.is_focused(window);

        if recording && !is_focused {
            self.state.update(cx, |state, cx| state.stop_recording(cx));
            recording = false;
        }

        let display_text: SharedString = if recording {
            self.recording_text.clone()
        } else if let Some(ref hk) = hotkey {
            hk.format_display().into()
        } else {
            self.placeholder.clone()
        };

        let has_value = hotkey.is_some();
        let show_clear = self.clearable && has_value && !self.disabled && !recording;

        let (height, padding_x, text_size) = match self.size {
            HotkeyInputSize::Sm => (px(32.0), px(8.0), px(13.0)),
            HotkeyInputSize::Md => (px(40.0), px(12.0), px(14.0)),
        };

        let state_for_click = self.state.clone();
        let state_for_keydown = self.state.clone();
        let state_for_clear = self.state.clone();

        let on_change_for_keydown = self.on_change.clone();
        let on_change_for_clear = self.on_change.clone();

        let border_color = if recording {
            theme.tokens.primary
        } else if is_focused {
            theme.tokens.ring
        } else {
            theme.tokens.input
        };

        let focus_ring = theme.tokens.focus_ring_light();
        let recording_ring = BoxShadow {
            offset: point(px(0.0), px(0.0)),
            blur_radius: px(0.0),
            spread_radius: px(3.0),
            inset: false,
            color: theme.tokens.primary.opacity(0.3),
        };

        let text_color = if hotkey.is_some() && !recording {
            theme.tokens.foreground
        } else {
            theme.tokens.muted_foreground
        };

        let clear_button = if show_clear {
            Some(
                div()
                    .id("hotkey-clear")
                    .ml(px(8.0))
                    .px(px(6.0))
                    .py(px(4.0))
                    .rounded(px(4.0))
                    .text_color(theme.tokens.muted_foreground)
                    .hover(|s| s.bg(theme.tokens.muted).text_color(theme.tokens.foreground))
                    .on_click(move |_, window, cx| {
                        state_for_clear.update(cx, |state, cx| {
                            state.clear(cx);
                        });
                        if let Some(ref handler) = on_change_for_clear {
                            handler(None, window, cx);
                        }
                        cx.stop_propagation();
                    })
                    .child("×"),
            )
        } else {
            None
        };

        div()
            .map(|this| {
                let mut d = this;
                d.style().refine(&user_style);
                d
            })
            .child(
                div()
                    .id(("hotkey-input", self.state.entity_id()))
                    .track_focus(&focus_handle.tab_index(0).tab_stop(true))
                    .h(height)
                    .px(padding_x)
                    .flex()
                    .items_center()
                    .justify_between()
                    .bg(theme.tokens.background)
                    .border_1()
                    .border_color(border_color)
                    .rounded(theme.tokens.radius_md)
                    .font_family(theme.tokens.font_mono.clone())
                    .text_size(text_size)
                    .when(self.disabled, |d| d.opacity(0.5).cursor_not_allowed())
                    .when(!self.disabled, |d| d.cursor_pointer())
                    .when(is_focused && !recording, |d| {
                        d.shadow(smallvec::smallvec![focus_ring])
                    })
                    .when(recording, |d| {
                        d.shadow(smallvec::smallvec![recording_ring])
                            .border_color(theme.tokens.primary)
                    })
                    .when(!self.disabled, |d| {
                        d.on_click(move |_, window, cx| {
                            state_for_click.update(cx, |state, cx| {
                                if !state.recording {
                                    state.start_recording(cx);
                                }
                            });
                            window.refresh();
                        })
                    })
                    .when(!self.disabled, |d| {
                        d.on_key_down(move |event, window, cx| {
                            let (captured, hotkey) = state_for_keydown.update(cx, |state, cx| {
                                let captured = state.capture_keystroke(&event.keystroke, cx);
                                (captured, state.hotkey.clone())
                            });
                            if captured {
                                if let Some(ref handler) = on_change_for_keydown {
                                    handler(hotkey.as_ref(), window, cx);
                                }
                                cx.stop_propagation();
                            }
                        })
                    })
                    .child(
                        div()
                            .flex_1()
                            .text_color(text_color)
                            .when(recording, |d| d.opacity(0.7))
                            .child(display_text),
                    )
                    .children(clear_button),
            )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capabilities::foundation::theme::{install_theme, Theme};

    #[gpui::test]
    fn builders_configure_size_clear_and_recording_text() {
        let mut app = TestApp::new();
        app.update(|cx| install_theme(cx, Theme::light()));
        let state = app.update(|cx| cx.new(HotkeyInputState::new));

        let input = HotkeyInput::new(state)
            .size(HotkeyInputSize::Sm)
            .clearable(false)
            .recording_text("Waiting for keys…");

        assert_eq!(input.size, HotkeyInputSize::Sm);
        assert!(!input.clearable);
        assert_eq!(input.recording_text, "Waiting for keys…");
    }
}