gpui-component 0.10.0

GPUI Component: the styled component library of GPUI Kit, with 60+ desktop UI components for GPUI.
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
use crate::theme::ActiveTheme;
use gpui::{
    AnyElement, App, Entity, FocusHandle, Focusable, InteractiveElement as _,
    StatefulInteractiveElement as _, Window, div, px,
};
use gpui::{
    IntoElement, ParentElement, RenderOnce, SharedString, StyleRefinement, Styled, TextAlign,
    prelude::FluentBuilder as _,
};

use crate::{Disableable, Icon, IconName, Sizable, Size, StyleSized as _, StyledExt as _};

use super::{Input, InputState, input::input_style};
use crate::ThemeStyled as _;
use gpui_base::NumberInput as BaseNumberInput;
pub use gpui_base::{NumberInputEvent, NumberStep, StepAction};
use rust_i18n::t;

/// A number input element with increment and decrement buttons.
#[derive(IntoElement)]
pub struct NumberInput {
    state: Entity<InputState>,
    placeholder: SharedString,
    size: Size,
    prefix: Option<AnyElement>,
    suffix: Option<AnyElement>,
    appearance: bool,
    focus_ring_enabled: bool,
    disabled: bool,
    accessibility_label: Option<SharedString>,
    stepper: bool,
    style: StyleRefinement,
}

impl NumberInput {
    /// Create a new [`NumberInput`] element bind to the [`InputState`].
    pub fn new(state: &Entity<InputState>) -> Self {
        Self {
            state: state.clone(),
            size: Size::default(),
            placeholder: SharedString::default(),
            prefix: None,
            suffix: None,
            appearance: true,
            focus_ring_enabled: true,
            disabled: false,
            accessibility_label: None,
            stepper: true,
            style: StyleRefinement::default(),
        }
    }

    /// Set the placeholder text of the number input.
    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Set the prefix element of the number input.
    pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
        self.prefix = Some(prefix.into_any_element());
        self
    }

    /// Set the suffix element of the number input.
    pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
        self.suffix = Some(suffix.into_any_element());
        self
    }

    /// Set the appearance of the number input, if false will no border and background.
    pub fn appearance(mut self, appearance: bool) -> Self {
        self.appearance = appearance;
        self
    }

    /// Set the name a screen reader announces.
    ///
    /// A number input has no visible text of its own to be named by, so set
    /// this whenever it is shown without one, for example next to a separate
    /// label. This does not change what is displayed.
    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
        self.accessibility_label = Some(label.into());
        self
    }

    /// Set whether the increment and decrement buttons are rendered.
    ///
    /// The buttons are rendered by default. Up and Down keys continue to step the
    /// value when the buttons are omitted.
    pub fn stepper(mut self, stepper: bool) -> Self {
        self.stepper = stepper;
        self
    }
}

impl Disableable for NumberInput {
    fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl crate::FocusableExt for NumberInput {
    fn focus_ring(mut self, enabled: bool) -> Self {
        self.focus_ring_enabled = enabled;
        self
    }

    fn is_focus_ring_enabled(&self) -> bool {
        self.focus_ring_enabled
    }
}

impl Focusable for NumberInput {
    fn focus_handle(&self, cx: &App) -> FocusHandle {
        self.state.focus_handle(cx)
    }
}

impl Sizable for NumberInput {
    fn with_size(mut self, size: impl Into<Size>) -> Self {
        self.size = size.into();
        self
    }
}

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

impl RenderOnce for NumberInput {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let focused = self.state.read(cx).focus_handle(cx).is_focused(window) && !self.disabled;
        let (bg, _) = input_style(self.disabled, cx);
        let border_color = if self.disabled {
            cx.theme().input.opacity(0.5)
        } else {
            cx.theme().input
        };
        // Transparent like a ghost button, but tinted to the frame on hover.
        let button_foreground = cx.theme().secondary_foreground;
        let button_hover = cx.theme().input.opacity(0.4);
        let button_active = cx.theme().input.opacity(0.6);
        let button_size = self.size;
        // The buttons sit inside the 1px frame, so their corners are a pixel
        // tighter than the frame's, or they paint over its inner curve.
        let button_radius = if self.appearance {
            (cx.theme().radius - px(1.)).max(px(0.))
        } else {
            cx.theme().radius
        };
        let base_state = self.state.clone();
        let content = BaseNumberInput::new(&base_state)
            .disabled(self.disabled)
            .stepper(self.stepper)
            .when_some(self.accessibility_label, |this, label| {
                this.accessibility_label(label)
            })
            .size_full()
            .when(self.stepper, |this| {
                this.decrement_button(move |this| {
                    this.accessibility_label(t!("Input.Decrement"))
                        .flex()
                        .items_center()
                        .justify_center()
                        .text_color(button_foreground)
                        .hover(move |this| this.bg(button_hover))
                        .active(move |this| this.bg(button_active))
                        // The frame owns the control height, so the buttons fill it
                        // rather than setting their own and outgrowing the border.
                        .h_full()
                        .map(|this| match button_size {
                            Size::XSmall | Size::Small => this.min_w_6(),
                            Size::Medium | Size::Large => this.min_w_8(),
                            Size::Size(size) => this.min_w(size),
                        })
                        // Only the outer corners are rounded, to follow the frame.
                        .rounded_tl(button_radius)
                        .rounded_bl(button_radius)
                        .child(Icon::new(IconName::Minus).with_size(button_size))
                })
            })
            .input(
                Input::new(&self.state)
                    .appearance(false)
                    .with_size(button_size)
                    .h_full()
                    .disabled(self.disabled)
                    .gap_0()
                    .rounded_none()
                    .text_align(TextAlign::Center)
                    .when_some(self.prefix, |this, prefix| this.prefix(prefix))
                    .when_some(self.suffix, |this, suffix| this.suffix(suffix)),
            )
            .when(self.stepper, |this| {
                this.increment_button(move |this| {
                    this.accessibility_label(t!("Input.Increment"))
                        .flex()
                        .items_center()
                        .justify_center()
                        .text_color(button_foreground)
                        .hover(move |this| this.bg(button_hover))
                        .active(move |this| this.bg(button_active))
                        .h_full()
                        .map(|this| match button_size {
                            Size::XSmall | Size::Small => this.min_w_6(),
                            Size::Medium | Size::Large => this.min_w_8(),
                            Size::Size(size) => this.min_w(size),
                        })
                        .rounded_tr(button_radius)
                        .rounded_br(button_radius)
                        .child(Icon::new(IconName::Plus).with_size(button_size))
                })
            });

        // The visual frame wraps the complete spinbutton. BaseNumberInput routes
        // application children into its text slot, so putting the ring on that
        // element would incorrectly surround only the editable middle region.
        div()
            .flex_1()
            .input_h(self.size)
            .rounded(cx.theme().radius)
            .when(self.appearance, |this| {
                this.bg(bg)
                    .border_1()
                    .border_color(border_color)
                    .when(focused, |this| {
                        this.border_1().border_color(cx.theme().ring)
                    })
            })
            .refine_style(&self.style)
            .when(self.disabled, |this| this.opacity(0.5))
            .child(content)
            .when(
                focused && self.appearance && self.focus_ring_enabled,
                |this| this.focus_ring_style(window, cx),
            )
    }
}

#[cfg(test)]
mod tests {
    use super::StepAction;
    use gpui_base::step_value;

    // `test_number_step` lives in `state::tests` because `NumberStep::value`
    // now needs a `Context<InputState>` to invoke the `by_value` closure.

    #[test]
    fn test_step_value() {
        fn some(value: &str) -> Option<String> {
            Some(value.to_string())
        }

        // Step from empty value
        assert_eq!(
            step_value("", StepAction::Increment, 1., None, None),
            some("1")
        );
        assert_eq!(
            step_value("", StepAction::Decrement, 1., None, None),
            some("-1")
        );
        // Invalid intermediate values are treated as 0
        assert_eq!(
            step_value("-", StepAction::Increment, 1., None, None),
            some("1")
        );
        assert_eq!(
            step_value("1", StepAction::Increment, 1., None, None),
            some("2")
        );
        assert_eq!(
            step_value("-2", StepAction::Increment, 1., None, None),
            some("-1")
        );

        // Avoid float precision issue, e.g. 0.1 + 0.2 != 0.30000000000000004
        assert_eq!(
            step_value("0.1", StepAction::Increment, 0.2, None, None),
            some("0.3")
        );
        assert_eq!(
            step_value("0.3", StepAction::Decrement, 0.1, None, None),
            some("0.2")
        );
        // Keep the fraction digits of the current value
        assert_eq!(
            step_value("1.25", StepAction::Increment, 1., None, None),
            some("2.25")
        );

        // Step from empty value always steps into the range
        assert_eq!(
            step_value("", StepAction::Increment, 1., Some(10.), None),
            some("10")
        );
        assert_eq!(
            step_value("", StepAction::Decrement, 1., Some(10.), None),
            some("10")
        );
        // Clamp to min/max
        assert_eq!(
            step_value("99.5", StepAction::Increment, 1., None, Some(100.)),
            some("100.0")
        );
        assert_eq!(
            step_value("1000", StepAction::Decrement, 1., None, Some(100.)),
            some("100")
        );
        // Keep the fraction digits of the clamped bound
        assert_eq!(
            step_value("1", StepAction::Decrement, 1., Some(0.25), None),
            some("0.25")
        );

        // Stepping must move the value in the pressed direction:
        // no-op at the boundary
        assert_eq!(
            step_value("10", StepAction::Decrement, 1., Some(10.), None),
            None
        );
        assert_eq!(
            step_value("100", StepAction::Increment, 1., None, Some(100.)),
            None
        );
        // Decrement on a below-min value (or Increment on an above-max value)
        // does nothing, instead of moving the value in the opposite direction
        assert_eq!(
            step_value("5", StepAction::Decrement, 1., Some(10.), None),
            None
        );
        assert_eq!(
            step_value("1000", StepAction::Increment, 1., None, Some(100.)),
            None
        );
    }
}

#[cfg(all(test, feature = "test-support"))]
mod interaction_tests {
    use super::*;
    use gpui::{Context, Render, TestAppContext, VisualTestContext};
    use gpui_base::test_support::{ElementSnapshot, find};

    struct Probe {
        state: Entity<InputState>,
        show_stepper: bool,
    }

    impl Render for Probe {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().size_full().child(
                NumberInput::new(&self.state).when(!self.show_stepper, |this| this.stepper(false)),
            )
        }
    }

    fn draw(cx: &mut VisualTestContext) {
        cx.run_until_parked();
        cx.update(|window, cx| window.draw(cx).clear(cx));
    }

    fn button(cx: &mut VisualTestContext, id: &'static str) -> Option<ElementSnapshot> {
        cx.update(|window, _| find(window, &[], &id.into()))
    }

    #[gpui::test]
    fn disabling_stepper_omits_buttons_and_keeps_keyboard_stepping(cx: &mut TestAppContext) {
        use gpui::AppContext as _;

        cx.update(crate::init);
        let (probe, mut cx) = cx.add_window_view(|window, cx| Probe {
            state: cx.new(|cx| InputState::new(window, cx).default_value("3")),
            show_stepper: true,
        });
        let state = probe.read_with(cx, |probe, _| probe.state.clone());
        draw(&mut cx);

        for id in ["decrement", "increment"] {
            assert!(
                button(&mut cx, id).is_some(),
                "{id} should exist by default"
            );
        }

        probe.update(cx, |probe, cx| {
            probe.show_stepper = false;
            cx.notify();
        });
        draw(&mut cx);

        for id in ["decrement", "increment"] {
            assert!(
                button(&mut cx, id).is_none(),
                "{id} should not be constructed"
            );
        }

        cx.update(|window, cx| {
            state.update(cx, |state, cx| state.focus(window, cx));
        });
        cx.simulate_keystrokes("up");
        draw(&mut cx);
        assert_eq!(
            state.read_with(cx, |state, _| state.value().to_string()),
            "4"
        );
    }

    /// The frame does not track the editor's focus handle (#3873: two painted
    /// elements tracking one focused handle both claim accessibility focus
    /// and abort debug builds), so a step button press must still leave the
    /// editor focused, step once, and keep arrow keys stepping.
    #[gpui::test]
    fn step_button_keeps_editor_focused_and_arrows_step(cx: &mut TestAppContext) {
        use gpui::{AppContext as _, Modifiers, MouseButton};

        cx.update(crate::init);
        let (probe, mut cx) = cx.add_window_view(|window, cx| Probe {
            state: cx.new(|cx| InputState::new(window, cx).default_value("3")),
            show_stepper: true,
        });
        let state = probe.read_with(cx, |probe, _| probe.state.clone());
        cx.update(|window, cx| {
            state.update(cx, |state, cx| state.focus(window, cx));
        });
        draw(&mut cx);

        let center = button(&mut cx, "increment").unwrap().bounds().center();
        cx.simulate_mouse_move(center, None, Modifiers::default());
        cx.simulate_mouse_down(center, MouseButton::Left, Modifiers::default());
        cx.update(|window, cx| {
            assert!(
                state.read(cx).focus_handle(cx).is_focused(window),
                "pressing the step button moved focus off the editor"
            );
        });
        cx.simulate_mouse_up(center, MouseButton::Left, Modifiers::default());
        draw(&mut cx);
        cx.update(|window, cx| {
            assert!(state.read(cx).focus_handle(cx).is_focused(window));
            assert_eq!(state.read(cx).value(), "4");
        });

        cx.simulate_keystrokes("up up down");
        draw(&mut cx);
        assert_eq!(
            state.read_with(cx, |state, _| state.value().to_string()),
            "5"
        );
    }
}