gpui-component 0.6.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
//! The gpui-component appearance for the dock area: the outer frame, the
//! split frames, and one dock's chrome.

use std::{ops::Deref as _, rc::Rc, sync::Arc};

use gpui::{
    AnyElement, App, AppContext as _, Axis, Context, Div, Element, Empty, InteractiveElement as _,
    IntoElement, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Render, Stateful, Style,
    Styled as _, Window, div, prelude::FluentBuilder as _,
};
use gpui_base::dock::{
    DockAreaRenderer, DockContext, DockEvent, DockPlacement, NodeId, PanelState, PanelView,
    TabGroupRenderer, TilesRenderer,
};

use crate::{
    ActiveTheme as _, Side,
    dock::{
        DockSkin, SkinShared, invalid_panel::InvalidPanel, panel_handle, tab_panel::TabGroupSkin,
        tiles::TilesSkin,
    },
    resize_handle,
};

/// The payload a dock's resize handle drags. It draws nothing: the handle
/// itself is the affordance.
#[derive(Clone)]
struct ResizePanel;

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

impl DockAreaRenderer for DockSkin {
    // The row, the fill and the clip are base's now -- applied around whatever
    // these return -- so a skin that has no appearance to add returns a bare
    // frame and still gets a dock area the right shape.
    fn frame(&self, _: &mut Window, _: &mut App) -> Stateful<Div> {
        div().id("dock-area")
    }

    fn center_frame(&self, _: &mut Window, _: &mut App) -> Stateful<Div> {
        div().id("dock-area-center")
    }

    fn split_frame(&self, node: NodeId, _: Axis, _: &mut Window, cx: &mut App) -> Stateful<Div> {
        // The size is base's; the background is this skin's, and is the only
        // reason this hook is implemented at all.
        div()
            .id(("dock-split-frame", node.as_u64()))
            .bg(cx.theme().tokens.tab_bar)
    }

    fn render_dock(
        &self,
        dock: &DockContext,
        content: AnyElement,
        window: &mut Window,
        cx: &mut App,
    ) -> AnyElement {
        // No box here any more. A dock's extent is structural, so
        // `DockArea::render_dock` applies it around whatever this returns --
        // which also means a renderer that draws no chrome still gets a dock
        // the right shape. This adds the edge you drag and nothing else.
        div()
            .flex()
            .size_full()
            .relative()
            .child(content)
            .child(self.render_resize_handle(dock, window, cx))
            .child(DockResizeTracker {
                dock: dock.clone(),
                shared: self.shared().clone(),
            })
            .into_any_element()
    }

    /// The "unknown panel" message the old `InvalidPanel` drew.
    ///
    /// It answers `dump` with the state it was handed, so a layout written by
    /// a build that knows the panel survives a load and save here.
    fn build_placeholder(
        &self,
        state: &PanelState,
        _: &mut Window,
        cx: &mut App,
    ) -> Option<Arc<dyn PanelView>> {
        let state = state.clone();
        Some(panel_handle(cx.new(|cx| {
            InvalidPanel::new(state.panel_name.clone(), state, cx)
        })))
    }

    fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
        Rc::new(TabGroupSkin::new(self.shared().clone()))
    }

    fn tiles_renderer(&self) -> Rc<dyn TilesRenderer> {
        Rc::new(TilesSkin::new(self.shared().clone()))
    }
}

impl DockSkin {
    fn render_resize_handle(
        &self,
        dock: &DockContext,
        _: &mut Window,
        _: &mut App,
    ) -> impl IntoElement {
        let placement = dock.placement();
        let shared = self.shared().clone();

        // One id per placement: the docks all render under the same stateful
        // ancestor, so a shared literal would collapse the handles into one
        // GlobalElementId and GPUI would silently share their element state —
        // a press on the left handle then starts the right handle's drag.
        let id = match placement {
            DockPlacement::Left => "resize-handle-left",
            DockPlacement::Right => "resize-handle-right",
            DockPlacement::Bottom => "resize-handle-bottom",
            DockPlacement::Center => "resize-handle-center",
        };

        resize_handle(id, placement.axis())
            .when(placement.is_left(), |this| this.placement(Side::Left))
            .on_drag(ResizePanel, move |info, _, _, cx| {
                cx.stop_propagation();
                shared.resizing_dock().set(Some(placement));
                cx.new(|_| info.deref().clone())
            })
    }
}

/// Turns the window's mouse stream into dock resizing.
///
/// A resize is driven by pointer moves that land anywhere in the window, not
/// only on the handle, so it cannot be expressed as a listener on the handle
/// itself. This element paints nothing and exists for its `paint` hook, which
/// is the only place a window-level mouse listener can be registered — which
/// is why it stays in the skin rather than moving into base: it is a
/// paint-order concern of this appearance.
struct DockResizeTracker {
    dock: DockContext,
    shared: Rc<SkinShared>,
}

impl IntoElement for DockResizeTracker {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl Element for DockResizeTracker {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<gpui::ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _: Option<&gpui::GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
        (window.request_layout(Style::default(), None, cx), ())
    }

    fn prepaint(
        &mut self,
        _: Option<&gpui::GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        _: gpui::Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        _: &mut Window,
        _: &mut App,
    ) -> Self::PrepaintState {
    }

    fn paint(
        &mut self,
        _: Option<&gpui::GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        _: gpui::Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        _: &mut Self::PrepaintState,
        window: &mut Window,
        _: &mut App,
    ) {
        let placement = self.dock.placement();

        window.on_mouse_event({
            let dock = self.dock.clone();
            let shared = self.shared.clone();
            move |event: &MouseMoveEvent, phase, window, cx| {
                if !phase.bubble() || shared.resizing_dock().get() != Some(placement) {
                    return;
                }
                // Dragging a closed dock's handle reopens it, as the old dock
                // did. The live state is read rather than the render-time
                // snapshot in `dock`, which would still say closed for the
                // rest of the frame and toggle it shut again on the next move.
                let open = shared
                    .area()
                    .upgrade()
                    .is_some_and(|area| area.read(cx).is_dock_open(placement));
                if !open {
                    dock.toggle(window, cx);
                }
                dock.resize_to(event.position, window, cx);
            }
        });

        window.on_mouse_event({
            let shared = self.shared.clone();
            move |_: &MouseUpEvent, phase, _, cx| {
                if !phase.bubble() || shared.resizing_dock().get() != Some(placement) {
                    return;
                }
                shared.resizing_dock().set(None);
                // The size lives on the dock, not in the layout tree, so
                // nothing else tells a subscriber to persist it.
                _ = shared
                    .area()
                    .update(cx, |_, cx| cx.emit(DockEvent::LayoutChanged));
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use std::rc::Rc;

    use gpui::{
        App, Entity, IntoElement as _, Modifiers, MouseButton, TestAppContext, VisualTestContext,
        Window, point, px, size,
    };

    use std::cell::Cell;

    use gpui_base::dock::DockAreaRenderer;

    use crate::dock::{
        DockArea, DockLayout, DockPlacement, DockSkin,
        test_support::{MeasuredProbe, SizedProbe},
    };

    /// A renderer that draws no chrome at all: every hook at its trait default.
    ///
    /// This is the position every renderer that is not `DockSkin` starts from,
    /// including the one gpui-shell installs so a script can draw the chrome
    /// itself, and the shape of what it gets is base's promise.
    struct ChromelessDockSkin;

    impl DockAreaRenderer for ChromelessDockSkin {
        fn tab_group_renderer(&self) -> Rc<dyn gpui_base::dock::TabGroupRenderer> {
            Rc::new(ChromelessTabs)
        }

        fn tiles_renderer(&self) -> Rc<dyn gpui_base::dock::TilesRenderer> {
            Rc::new(ChromelessTiles)
        }
    }

    struct ChromelessTabs;
    impl gpui_base::dock::TabGroupRenderer for ChromelessTabs {
        // The one hook with no default, because a group with no tab bar has no
        // way to choose between its panels. Drawn as nothing, so the height it
        // leaves the content is the whole group.
        fn render_tab_bar(
            &self,
            _: &gpui_base::dock::TabGroupContext,
            _: &mut Window,
            _: &mut App,
        ) -> gpui::AnyElement {
            gpui::Empty.into_any_element()
        }
    }

    struct ChromelessTiles;
    impl gpui_base::dock::TilesRenderer for ChromelessTiles {
        fn render_drag_bar(
            &self,
            _: &gpui_base::dock::TileContext,
            _: &mut Window,
            _: &mut App,
        ) -> gpui::AnyElement {
            gpui::Empty.into_any_element()
        }
    }

    /// A dock's box is base's, not its renderer's.
    ///
    /// This is the regression. The extent lived in `DockSkin::render_dock`, so
    /// it was reachable only through that one renderer, and `render_dock`'s
    /// trait default hands the content straight back. A dock that never states
    /// its extent is not a column beside the centre: it takes whatever the row
    /// gives it and the panes inside shrink to their content. Nothing failed,
    /// and nothing said why.
    #[gpui::test]
    fn a_dock_is_its_own_width_under_a_renderer_that_draws_no_chrome(cx: &mut TestAppContext) {
        cx.update(|cx| crate::init(cx));
        let measured = Rc::new(Cell::new(gpui::Size::default()));
        let probe = measured.clone();
        let centre = Rc::new(Cell::new(gpui::Size::default()));
        let centre_probe = centre.clone();
        let (area, cx) = cx.add_window_view(|window, cx| {
            DockArea::new("test", None, window, cx).with_renderer(Rc::new(ChromelessDockSkin))
        });
        cx.simulate_resize(size(px(800.), px(600.)));
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::tabs().panel(SizedProbe::new(centre_probe, cx)),
                    window,
                    cx,
                );
                area.set_dock(
                    DockPlacement::Right,
                    DockLayout::tabs().panel(SizedProbe::new(probe, cx)),
                    window,
                    cx,
                );
                area.set_dock_size(DockPlacement::Right, px(200.), window, cx);
            });
        });
        cx.run_until_parked();
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                if !area.is_dock_open(DockPlacement::Right) {
                    area.toggle_dock(DockPlacement::Right, window, cx);
                }
            });
        });
        cx.run_until_parked();
        cx.update(|window, cx| window.draw(cx).clear(cx));

        let dock = measured.get().width;
        assert_eq!(
            dock,
            px(200.),
            "the right dock has to be its own width, not the area's: got {dock:?}"
        );
        // The other half of the same fault: a dock area that is not a row puts
        // the centre above the dock at the area's full width instead of beside
        // it at what the dock leaves.
        let middle = centre.get().width;
        assert_eq!(
            middle,
            px(600.),
            "the centre has to be what the docks leave: got {middle:?}"
        );
        // This renderer draws no tab bar, so a group that fills its slot leaves
        // its panel the whole 600. A tab group frame without a column and a
        // fill gives it nothing: the panel is positioned absolutely inside the
        // content region and contributes no height of its own, so the region
        // resolves to zero and the group is a strip of tabs.
        let tall = centre.get().height;
        assert_eq!(
            tall,
            px(600.),
            "a group has to fill its slot, or its panel gets no height: got {tall:?}"
        );
    }

    fn area_with_side_docks(cx: &mut TestAppContext) -> (Entity<DockArea>, &mut VisualTestContext) {
        cx.update(|cx| crate::init(cx));
        let (area, cx) = cx.add_window_view(|window, cx| {
            DockArea::new("test", None, window, cx).with_renderer(DockSkin::new(cx))
        });
        cx.simulate_resize(size(px(800.), px(600.)));
        cx.update(|window, cx| {
            area.update(cx, |area, cx| {
                area.set_center(
                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
                    window,
                    cx,
                );
                area.set_dock(
                    DockPlacement::Left,
                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
                    window,
                    cx,
                );
                area.set_dock(
                    DockPlacement::Right,
                    DockLayout::tabs().panel(MeasuredProbe::new(Rc::default(), cx)),
                    window,
                    cx,
                );
            });
        });
        cx.run_until_parked();
        (area, cx)
    }

    /// Every dock's handle once shared the literal element id
    /// `"resize-handle"`, so GPUI silently handed them one element state —
    /// including the pending-mouse-down that starts a drag. Pressing the left
    /// handle then let the right dock's drag listener (painted later, so
    /// dispatched first) claim the drag, and one pixel of movement threw the
    /// right dock to nearly the full area width.
    #[gpui::test]
    fn dragging_the_left_handle_resizes_only_the_left_dock(cx: &mut TestAppContext) {
        let (area, cx) = area_with_side_docks(cx);
        cx.update(|window, cx| window.draw(cx).clear(cx));

        // The left dock is 200px wide, so its handle sits at x ∈ [198, 199).
        cx.simulate_mouse_down(
            point(px(198.5), px(300.)),
            MouseButton::Left,
            Modifiers::none(),
        );
        // Past the drag threshold: the drag starts and claims a dock.
        cx.simulate_mouse_move(
            point(px(204.), px(300.)),
            MouseButton::Left,
            Modifiers::none(),
        );
        // The move the claimed dock resizes to.
        cx.simulate_mouse_move(
            point(px(240.), px(300.)),
            MouseButton::Left,
            Modifiers::none(),
        );
        cx.simulate_mouse_up(
            point(px(240.), px(300.)),
            MouseButton::Left,
            Modifiers::none(),
        );
        cx.run_until_parked();

        let (left, right) = cx.update(|_, cx| {
            let area = area.read(cx);
            (
                area.dock_size(DockPlacement::Left),
                area.dock_size(DockPlacement::Right),
            )
        });
        assert_eq!(
            right,
            Some(px(200.)),
            "the right dock must not move when the left handle is dragged"
        );
        assert_eq!(left, Some(px(240.)), "the left dock follows the pointer");
    }
}