gpui-component 0.11.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
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
use std::rc::Rc;

use gpui_base::LogicalStyledExt as _;

use crate::{
    ActiveTheme, Icon, IconName, InteractiveElementExt as _, Sizable as _, StyledExt, h_flex,
};
#[cfg(target_os = "linux")]
use gpui::Subscription;
use gpui::{
    AnyElement, App, Background, ClickEvent, Context, Decorations, Hsla, InteractiveElement,
    IntoElement, MouseButton, ParentElement, Pixels, Render, RenderOnce, Rgba,
    StatefulInteractiveElement as _, StyleRefinement, Styled, TitlebarOptions, Window,
    WindowButton, WindowButtonLayout, WindowControlArea, WindowOptions, div, linear_color_stop,
    linear_gradient, prelude::FluentBuilder as _, px, rems,
};
use gpui_base::TestSupportExt as _;
use smallvec::SmallVec;

pub const TITLE_BAR_HEIGHT: Pixels = px(34.);
#[cfg(target_os = "macos")]
const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);
#[cfg(not(target_os = "macos"))]
const TITLE_BAR_LEFT_PADDING: Pixels = px(12.);

fn default_title_bar_background(title_bar: Hsla, background: Hsla) -> Background {
    let title_bar_rgb = title_bar.to_rgb();
    let background_rgb = background.to_rgb();
    let mixed = Hsla::from(Rgba {
        r: title_bar_rgb.r * 0.55 + background_rgb.r * 0.45,
        g: title_bar_rgb.g * 0.55 + background_rgb.g * 0.45,
        b: title_bar_rgb.b * 0.55 + background_rgb.b * 0.45,
        a: title_bar_rgb.a * 0.55 + background_rgb.a * 0.45,
    });

    linear_gradient(
        180.,
        linear_color_stop(mixed, 0.),
        linear_color_stop(title_bar, 1.),
    )
}

/// TitleBar used to customize the appearance of the title bar.
///
/// We can put some elements inside the title bar.
#[derive(IntoElement)]
pub struct TitleBar {
    style: StyleRefinement,
    children: SmallVec<[AnyElement; 1]>,
    on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
}

impl TitleBar {
    /// Create a new TitleBar.
    pub fn new() -> Self {
        Self {
            style: StyleRefinement::default(),
            children: SmallVec::new(),
            on_close_window: None,
        }
    }

    /// Returns the default title bar options for compatible with the [`crate::TitleBar`].
    pub fn title_bar_options() -> TitlebarOptions {
        TitlebarOptions {
            title: None,
            appears_transparent: true,
            traffic_light_position: Some(gpui::point(px(9.0), px(9.0))),
        }
    }

    /// Returns the default window options for compatible with the [`crate::TitleBar`].
    ///
    /// Use this as the base of the [`WindowOptions`] of any window that renders a
    /// [`crate::TitleBar`], so the title bar owns dragging and double clicking itself:
    ///
    /// ```no_run
    /// # mod gpui_kit { pub use gpui::*; pub extern crate gpui_component as component; }
    /// # use gpui_kit::WindowOptions;
    /// # use gpui_kit::component::TitleBar;
    /// let options = WindowOptions {
    ///     window_min_size: None,
    ///     ..TitleBar::window_options()
    /// };
    /// ```
    pub fn window_options() -> WindowOptions {
        WindowOptions {
            titlebar: Some(Self::title_bar_options()),
            // The title bar draws itself and moves the window via `start_window_move`,
            // so AppKit must not treat it as a system window-move region. Otherwise macOS
            // handles title bar double clicks on its own (in addition to `on_double_click`
            // below) and delays title bar clicks while disambiguating double clicks.
            app_owns_titlebar_drag: true,
            ..Default::default()
        }
    }

    /// Add custom for close window event, default is None, then click X button will call `window.remove_window()`.
    /// Linux only, this will do nothing on other platforms.
    pub fn on_close_window(
        mut self,
        f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        if cfg!(target_os = "linux") {
            self.on_close_window = Some(Rc::new(Box::new(f)));
        }
        self
    }
}

// The Windows control buttons have a fixed width of 35px.
//
// We don't need implementation the click event for the control buttons.
// If user clicked in the bounds, the window event will be triggered.
#[derive(IntoElement, Clone)]
enum ControlIcon {
    Minimize,
    Restore,
    Maximize,
    Close {
        on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
    },
}

fn window_button_layout(_cx: &App) -> WindowButtonLayout {
    #[cfg(target_os = "linux")]
    {
        _cx.button_layout()
            .unwrap_or_else(WindowButtonLayout::linux_default)
    }

    #[cfg(not(target_os = "linux"))]
    {
        WindowButtonLayout {
            left: [None; gpui::MAX_BUTTONS_PER_SIDE],
            right: [
                Some(WindowButton::Minimize),
                Some(WindowButton::Maximize),
                Some(WindowButton::Close),
            ],
        }
    }
}

fn supported_buttons(
    buttons: [Option<WindowButton>; gpui::MAX_BUTTONS_PER_SIDE],
    supported: gpui::WindowControls,
) -> SmallVec<[WindowButton; gpui::MAX_BUTTONS_PER_SIDE]> {
    buttons
        .into_iter()
        .flatten()
        .filter(|button| match button {
            WindowButton::Minimize => supported.minimize,
            WindowButton::Maximize => supported.maximize,
            WindowButton::Close => true,
        })
        .collect()
}

impl ControlIcon {
    fn minimize() -> Self {
        Self::Minimize
    }

    fn restore() -> Self {
        Self::Restore
    }

    fn maximize() -> Self {
        Self::Maximize
    }

    fn close(on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>) -> Self {
        Self::Close { on_close_window }
    }

    fn id(&self) -> &'static str {
        match self {
            Self::Minimize => "minimize",
            Self::Restore => "restore",
            Self::Maximize => "maximize",
            Self::Close { .. } => "close",
        }
    }

    fn icon(&self) -> IconName {
        match self {
            Self::Minimize => IconName::WindowMinimize,
            Self::Restore => IconName::WindowRestore,
            Self::Maximize => IconName::WindowMaximize,
            Self::Close { .. } => IconName::WindowClose,
        }
    }

    fn window_control_area(&self) -> WindowControlArea {
        match self {
            Self::Minimize => WindowControlArea::Min,
            Self::Restore | Self::Maximize => WindowControlArea::Max,
            Self::Close { .. } => WindowControlArea::Close,
        }
    }

    fn is_close(&self) -> bool {
        matches!(self, Self::Close { .. })
    }

    #[inline]
    fn hover_fg(&self, cx: &App) -> Hsla {
        if self.is_close() {
            cx.theme().danger_foreground
        } else {
            cx.theme().secondary_foreground
        }
    }

    #[inline]
    fn hover_bg(&self, cx: &App) -> Hsla {
        if self.is_close() {
            cx.theme().danger
        } else {
            cx.theme().secondary_hover
        }
    }

    #[inline]
    fn active_bg(&self, cx: &mut App) -> Hsla {
        if self.is_close() {
            cx.theme().danger_active
        } else {
            cx.theme().secondary_active
        }
    }
}

impl RenderOnce for ControlIcon {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let is_linux = cfg!(target_os = "linux");
        let is_windows = cfg!(target_os = "windows");
        let hover_fg = self.hover_fg(cx);
        let hover_bg = self.hover_bg(cx);
        let active_bg = self.active_bg(cx);
        let icon = self.clone();
        let on_close_window = match &self {
            ControlIcon::Close { on_close_window } => on_close_window.clone(),
            _ => None,
        };

        div()
            .id(self.id())
            .test_support()
            .flex()
            .w(TITLE_BAR_HEIGHT)
            .h_full()
            .flex_shrink_0()
            .justify_center()
            .content_center()
            .items_center()
            .text_color(cx.theme().foreground)
            .hover(|style| style.bg(hover_bg).text_color(hover_fg))
            .active(|style| style.bg(active_bg).text_color(hover_fg))
            .when(is_windows, |this| {
                this.window_control_area(self.window_control_area())
            })
            .when(is_linux, |this| {
                this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
                    window.prevent_default();
                    cx.stop_propagation();
                })
                .on_click(move |_, window, cx| {
                    cx.stop_propagation();
                    match icon {
                        Self::Minimize => window.minimize_window(),
                        Self::Restore | Self::Maximize => window.zoom_window(),
                        Self::Close { .. } => {
                            if let Some(f) = on_close_window.clone() {
                                f(&ClickEvent::default(), window, cx);
                            } else {
                                window.remove_window();
                            }
                        }
                    }
                })
            })
            .child(Icon::new(self.icon()).small())
    }
}

#[derive(IntoElement)]
struct WindowControls {
    id: &'static str,
    buttons: [Option<WindowButton>; gpui::MAX_BUTTONS_PER_SIDE],
    on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
}

impl RenderOnce for WindowControls {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        if cfg!(target_os = "macos") || cfg!(target_family = "wasm") {
            return div().id(self.id).test_support();
        }

        // Under server-side decorations the window manager already renders
        // its own title bar, complete with min/max/close; drawing ours as
        // well stacks a duplicate set of controls on top of it (most
        // visibly two close buttons). gpui falls back to server-side
        // decorations on X11 sessions without a compositor, and a Wayland
        // compositor may grant server mode even when client mode was
        // requested. Skip ours unless this window is actually client-side
        // decorated, mirroring the `is_client_decorated` gating of the
        // title bar's window-menu overlay.
        #[cfg(target_os = "linux")]
        if !matches!(window.window_decorations(), Decorations::Client { .. }) {
            return div().id(self.id).test_support();
        }

        // The window manager declares which controls it can honor; a tiling
        // compositor may support neither minimize nor maximize.
        let supported = window.window_controls();

        // In RTL the controls sit on the start (left) edge, close outermost.
        h_flex()
            .flex_row_dir(cx)
            .id(self.id)
            .test_support()
            .items_center()
            .flex_shrink_0()
            .h_full()
            .children(
                supported_buttons(self.buttons, supported)
                    .into_iter()
                    .map(|button| match button {
                        WindowButton::Minimize => ControlIcon::minimize(),
                        WindowButton::Maximize if window.is_maximized() => ControlIcon::restore(),
                        WindowButton::Maximize => ControlIcon::maximize(),
                        WindowButton::Close => ControlIcon::close(self.on_close_window.clone()),
                    }),
            )
    }
}

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

impl ParentElement for TitleBar {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

struct TitleBarState {
    should_move: bool,
    #[cfg(target_os = "linux")]
    // Keep the title bar in sync with system button-layout changes.
    _button_layout_subscription: Subscription,
}

// TODO: Remove this when GPUI has released v0.2.3
impl Render for TitleBarState {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
    }
}

impl RenderOnce for TitleBar {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let is_client_decorated = matches!(window.window_decorations(), Decorations::Client { .. });
        let is_web = cfg!(target_family = "wasm");
        let is_linux = cfg!(target_os = "linux");
        let is_macos = cfg!(target_os = "macos");

        let state = window.use_state(cx, |_window, _state_cx| TitleBarState {
            should_move: false,
            #[cfg(target_os = "linux")]
            _button_layout_subscription: _state_cx
                .observe_button_layout_changed(_window, |_, _, cx| cx.notify()),
        });
        let radii = crate::window_corner_radii(window, cx);
        let button_layout = window_button_layout(cx);

        div().flex_shrink_0().child(
            div()
                .id("title-bar")
                .flex_row_dir(cx)
                .when(is_linux, |this| this.flex_row())
                .items_center()
                .justify_between()
                .h(TITLE_BAR_HEIGHT)
                // macOS draws its traffic lights on the left whatever the
                // direction; elsewhere the padding is on the start edge.
                .map(|this| {
                    if is_macos || is_linux {
                        this.pl(TITLE_BAR_LEFT_PADDING)
                    } else {
                        this.ps(TITLE_BAR_LEFT_PADDING, cx)
                    }
                })
                .rounded_tl(radii.top_left)
                .rounded_tr(radii.top_right)
                .border_b_1()
                .border_color(cx.theme().title_bar_border)
                .bg(default_title_bar_background(
                    cx.theme().title_bar,
                    cx.theme().background,
                ))
                .refine_style(&self.style)
                .when(is_linux, |this| {
                    this.on_double_click(|_, window, _| window.zoom_window())
                })
                .when(is_macos, |this| {
                    this.on_double_click(|_, window, _| window.titlebar_double_click())
                })
                // After `on_double_click`, which is implemented for `Stateful` only.
                .test_support()
                .on_mouse_down_out(window.listener_for(&state, |state, _, _, _| {
                    state.should_move = false;
                }))
                .on_mouse_down(
                    MouseButton::Left,
                    // A control that took the press, such as a Button or a
                    // focusable Select, prevents the default; its click must
                    // not turn into a window move on the smallest motion.
                    window.listener_for(&state, |state, _, window, cx| {
                        state.should_move = !window.default_prevented();
                        // The bar moves the window; it never starts a text
                        // selection. On Windows the press arrives through the
                        // caption hit test and the move loop swallows the
                        // release, so a started selection would follow the
                        // pointer afterwards.
                        crate::GlobalState::suppress_text_selection(cx);
                    }),
                )
                .on_mouse_up(
                    MouseButton::Left,
                    window.listener_for(&state, |state, _, _, _| {
                        state.should_move = false;
                    }),
                )
                .on_mouse_move(window.listener_for(
                    &state,
                    |state, event: &gpui::MouseMoveEvent, window, cx| {
                        if event.pressed_button != Some(MouseButton::Left) {
                            state.should_move = false;
                            return;
                        }
                        if state.should_move {
                            state.should_move = false;
                            gpui_base::TextSelection::end(window, cx);
                            cx.stop_active_drag(window);
                            window.start_window_move();
                        }
                    },
                ))
                .when(is_linux, |this| {
                    this.child(WindowControls {
                        id: "window-controls-start",
                        buttons: button_layout.left,
                        on_close_window: self.on_close_window.clone(),
                    })
                })
                .child(
                    h_flex()
                        .id("bar")
                        .h_full()
                        .justify_between()
                        .flex_shrink_0()
                        .flex_1()
                        .when(!is_web, |this| {
                            this.window_control_area(WindowControlArea::Drag)
                                .when(window.is_fullscreen(), |this| this.ps(rems(0.75), cx))
                                .when(is_linux && is_client_decorated, |this| {
                                    this.child(
                                        div()
                                            .top_0()
                                            .left_0()
                                            .absolute()
                                            .size_full()
                                            .h_full()
                                            .on_mouse_down(
                                                MouseButton::Right,
                                                move |ev, window, _| {
                                                    window.show_window_menu(ev.position)
                                                },
                                            ),
                                    )
                                })
                        })
                        .children(self.children),
                )
                .child(WindowControls {
                    id: "window-controls",
                    buttons: button_layout.right,
                    on_close_window: self.on_close_window,
                }),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui::{
        AppContext as _, Modifiers, Rgba, TestAppContext, VisualTestContext, linear_color_stop,
        linear_gradient, point, px,
    };
    use std::cell::Cell;

    use crate::button::Button;

    #[test]
    fn linux_window_controls_follow_layout_order_and_capabilities() {
        let layout = WindowButtonLayout {
            left: [
                Some(WindowButton::Close),
                Some(WindowButton::Minimize),
                None,
            ],
            right: [
                Some(WindowButton::Maximize),
                Some(WindowButton::Close),
                None,
            ],
        };
        let supported = gpui::WindowControls {
            fullscreen: true,
            maximize: false,
            minimize: true,
            window_menu: true,
        };

        assert_eq!(
            supported_buttons(layout.left, supported).as_slice(),
            [WindowButton::Close, WindowButton::Minimize]
        );
        assert_eq!(
            supported_buttons(layout.right, supported).as_slice(),
            [WindowButton::Close]
        );
    }

    const BUTTON: &str = "title-bar-button";

    struct BarWithButton {
        clicks: Rc<Cell<usize>>,
    }

    impl Render for BarWithButton {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let clicks = self.clicks.clone();
            TitleBar::new().child(div().w(px(200.)).child("App")).child(
                Button::new("open")
                    .label("Open")
                    .debug_selector(|| BUTTON.to_string())
                    .on_click(move |_, _, _| clicks.set(clicks.get() + 1)),
            )
        }
    }

    fn open(cx: &mut TestAppContext) -> (VisualTestContext, Rc<Cell<usize>>) {
        cx.update(crate::init);
        let clicks = Rc::new(Cell::new(0));
        let view = cx.new(|_| BarWithButton {
            clicks: clicks.clone(),
        });
        let window = cx.update(|cx| {
            cx.open_window(Default::default(), |window, cx| {
                cx.new(|cx| crate::Root::new(view.clone(), window, cx))
            })
            .unwrap()
        });
        let mut cx = VisualTestContext::from_window(window.into(), cx);
        cx.update(|window, cx| window.draw(cx).clear(cx));
        (cx, clicks)
    }

    /// Press, move one pixel, release, as a hand often does.
    fn click_with_drift(cx: &mut VisualTestContext, at: gpui::Point<Pixels>) {
        let drift = point(at.x + px(1.), at.y);
        cx.simulate_mouse_down(at, MouseButton::Left, Modifiers::default());
        cx.simulate_mouse_move(drift, Some(MouseButton::Left), Modifiers::default());
        cx.simulate_mouse_up(drift, MouseButton::Left, Modifiers::default());
    }

    #[gpui::test]
    fn a_press_on_a_control_keeps_its_click(cx: &mut TestAppContext) {
        let (mut cx, clicks) = open(cx);
        let at = cx
            .debug_bounds(BUTTON)
            .expect("the button is drawn")
            .center();
        click_with_drift(&mut cx, at);
        assert_eq!(clicks.get(), 1);
    }

    #[gpui::test]
    fn a_press_on_the_bar_does_not_start_a_text_selection(cx: &mut TestAppContext) {
        let (mut cx, _) = open(cx);
        let button = cx.debug_bounds(BUTTON).expect("the button is drawn");
        let bar = point(button.left() - px(100.), button.center().y);
        cx.simulate_mouse_down(bar, MouseButton::Left, Modifiers::default());
        cx.update(|_, cx| assert!(crate::GlobalState::is_text_selection_suppressed(cx)));
    }

    /// The test platform's `start_window_move` is `unimplemented!()`, so a
    /// press on the bar itself still reaching it shows up as this panic.
    #[gpui::test]
    #[should_panic(expected = "not implemented")]
    fn a_press_on_the_bar_itself_still_moves_the_window(cx: &mut TestAppContext) {
        let (mut cx, _) = open(cx);
        let button = cx.debug_bounds(BUTTON).expect("the button is drawn");
        click_with_drift(&mut cx, point(button.left() - px(100.), button.center().y));
    }

    #[test]
    fn test_default_title_bar_background() {
        let title_bar = Hsla::black();
        let background = Hsla::white();

        assert_eq!(
            default_title_bar_background(title_bar, background),
            linear_gradient(
                180.,
                linear_color_stop(
                    Hsla::from(Rgba {
                        r: 0.45,
                        g: 0.45,
                        b: 0.45,
                        a: 1.,
                    }),
                    0.,
                ),
                linear_color_stop(title_bar, 1.),
            )
        );
    }
}