Skip to main content

kitchen_views/
container.rs

1//! One container for every workspace's views (lumen's planes, tables and plots; dsp-kitchen's
2//! traces and rasters): a dock whose views are tabs dragged into splits, the "Add view or
3//! container" dialog (after Rerun's: arrange every view, or add one), and the buttons in a view's
4//! tab. A workspace only lists its view kinds ([`ViewOption`]) with their flags: whether each can
5//! be added now (and why not), which one a view shows.
6
7use std::rc::Rc;
8
9use gpui_kit::assets::IconName;
10use gpui_kit::base::Placement;
11use gpui_kit::base::dock::{DockArea, DockLayout, DockPlacement, InsertTarget, PanelId};
12use gpui_kit::component::button::{Button, ButtonVariants as _};
13use gpui_kit::component::dock::{DockSkin, Panel, panel_handle};
14use gpui_kit::component::{Disableable as _, Icon, Selectable as _, Sizable as _, h_flex, v_flex};
15use gpui_kit::prelude::FluentBuilder as _;
16use gpui_kit::{
17    App, AppContext as _, Context, Entity, EntityId, EventEmitter, FocusHandle, FontWeight, InteractiveElement as _,
18    IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _,
19    Styled as _, Window, div, px,
20};
21
22use kitchen_ui::theme::{self, color};
23use serde::{Deserialize, Serialize};
24
25/// How the views are laid out together.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum Arrangement {
29    /// Every view as a tab of one group.
30    Tabs,
31    /// Every view side by side.
32    Horizontal,
33    /// Every view stacked.
34    Vertical,
35    /// Every view in a grid (as square as the count allows).
36    Grid,
37}
38
39impl Arrangement {
40    /// Every arrangement, in the dialog's order.
41    pub const ALL: [Arrangement; 4] =
42        [Arrangement::Tabs, Arrangement::Horizontal, Arrangement::Vertical, Arrangement::Grid];
43
44    /// Its name ("Side by side").
45    pub fn title(self) -> &'static str {
46        match self {
47            Arrangement::Tabs => "Tabs",
48            Arrangement::Horizontal => "Side by side",
49            Arrangement::Vertical => "Stacked",
50            Arrangement::Grid => "Grid",
51        }
52    }
53}
54
55/// A kind of view a container offers.
56#[derive(Clone, Debug, PartialEq)]
57pub struct ViewOption {
58    /// Its name ("Plane", "Table").
59    pub title: String,
60    /// Its icon (the tab button, the dialog's tile).
61    pub icon: IconName,
62    /// What it shows (the dialog's line, the tab button's tooltip).
63    pub hint: String,
64    /// Whether it can be added now; when not, `hint` says why.
65    pub enabled: bool,
66}
67
68impl ViewOption {
69    /// A kind of view titled `title` showing what `hint` says.
70    pub fn new(title: impl Into<String>, icon: IconName, hint: impl Into<String>) -> Self {
71        Self { title: title.into(), icon, hint: hint.into(), enabled: true }
72    }
73
74    /// Not available now, for `why`.
75    pub fn unavailable(mut self, why: impl Into<String>) -> Self {
76        self.enabled = false;
77        self.hint = why.into();
78        self
79    }
80}
81
82/// A dock for views, with the look every workspace shares (no dock toggle buttons).
83pub fn new_dock(id: &'static str, window: &mut Window, cx: &mut App) -> Entity<DockArea> {
84    // The skin hides the toggles once the dock exists (it updates the dock)
85    let mut skin = None;
86    let dock = cx.new(|cx| {
87        let s = DockSkin::new(cx);
88        skin = Some(s.clone());
89        DockArea::new(id, Some(2), window, cx).with_renderer(s)
90    });
91    if let Some(skin) = skin {
92        skin.set_toggle_button_visible(false, cx);
93    }
94    dock
95}
96
97/// Adds `panel` to the dock's centre, split off `beside` (another view's entity) at `placement`
98/// when it is there.
99pub fn add_beside<P: Panel>(
100    dock: &Entity<DockArea>,
101    panel: Entity<P>,
102    beside: Option<(EntityId, Placement)>,
103    window: &mut Window,
104    cx: &mut App,
105) {
106    let id = PanelId::from(panel.entity_id());
107    dock.update(cx, |d, cx| {
108        let target =
109            beside.and_then(|(e, at)| Some((d.layout(DockPlacement::Center)?.find_panel_node(PanelId::from(e))?, at)));
110        d.add_panel_view(panel_handle(panel), DockPlacement::Center, None, window, cx);
111        if let Some((node, placement)) = target {
112            d.move_panel(id, InsertTarget::Split { node, placement, size: None }, window, cx);
113        }
114    });
115}
116
117/// Lays out `panels` in `dock`'s centre as `how`.
118pub fn arrange<P: Panel>(
119    dock: &Entity<DockArea>,
120    panels: &[Entity<P>],
121    how: Arrangement,
122    window: &mut Window,
123    cx: &mut App,
124) {
125    let layout = arranged(panels, how, cx);
126    dock.update(cx, |d, cx| d.set_center(layout, window, cx));
127}
128
129/// The views laid out as `how`, in order.
130pub fn arranged<P: Panel>(panels: &[Entity<P>], how: Arrangement, cx: &App) -> DockLayout {
131    let group = |p: &Entity<P>, cx: &App| DockLayout::tabs().panel_view(panel_handle(p.clone()), cx);
132    match how {
133        Arrangement::Tabs => panels.iter().fold(DockLayout::tabs(), |l, p| l.panel_view(panel_handle(p.clone()), cx)),
134        Arrangement::Horizontal => panels.iter().fold(DockLayout::h_split(), |l, p| l.child(group(p, cx), None)),
135        Arrangement::Vertical => panels.iter().fold(DockLayout::v_split(), |l, p| l.child(group(p, cx), None)),
136        Arrangement::Grid => {
137            let cols = (panels.len() as f64).sqrt().ceil().max(1.0) as usize;
138            panels.chunks(cols).fold(DockLayout::v_split(), |l, row| {
139                l.child(row.iter().fold(DockLayout::h_split(), |r, p| r.child(group(p, cx), None)), None)
140            })
141        }
142    }
143}
144
145type Pick = Rc<dyn Fn(usize, &mut Window, &mut App)>;
146
147/// The buttons in a view's tab: one per kind it can show (`current` selected; a click shows that
148/// kind in this view), then "+" (add a view, or arrange them). Ids: `{key}-kind-{i}`,
149/// `{key}-add`. gpui-kit's small size (about 24 px: designparser `touch-target`).
150pub fn tab_buttons(
151    key: &str,
152    options: &[ViewOption],
153    current: Option<usize>,
154    show: impl Fn(usize, &mut Window, &mut App) + 'static,
155    add: impl Fn(&mut Window, &mut App) + 'static,
156) -> Vec<Button> {
157    let show: Pick = Rc::new(show);
158    let mut out: Vec<Button> = options
159        .iter()
160        .enumerate()
161        .map(|(i, o)| {
162            let show = show.clone();
163            Button::new(SharedString::from(format!("{key}-kind-{i}")))
164                .ghost()
165                .small()
166                .icon(Icon::new(o.icon))
167                .tooltip(format!("{}: {}", o.title, o.hint))
168                .selected(current == Some(i))
169                .disabled(!o.enabled && current != Some(i))
170                .on_click(move |_, window, cx| show(i, window, cx))
171        })
172        .collect();
173    out.push(
174        Button::new(SharedString::from(format!("{key}-add")))
175            .ghost()
176            .small()
177            .icon(Icon::new(IconName::Plus))
178            .tooltip("Add a view, or arrange the views")
179            .on_click(move |_, window, cx| add(window, cx)),
180    );
181    out
182}
183
184/// What the dialog asks for.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum DialogEvent {
187    /// Arrange every view so.
188    Arrange(Arrangement),
189    /// Add the view of option `i`.
190    Add(usize),
191    /// Close it.
192    Close,
193}
194
195/// "Add view or container": the arrangements, then the workspace's views; ↑ ↓ move between the
196/// rows that can run, Enter runs one, Esc or a click outside closes.
197pub struct AddViewDialog {
198    options: Vec<ViewOption>,
199    /// Arranging needs views to arrange.
200    can_arrange: bool,
201    cursor: usize,
202    focus: FocusHandle,
203}
204
205impl EventEmitter<DialogEvent> for AddViewDialog {}
206
207/// The arrangements the dialog offers: icon and line.
208const ARRANGEMENTS: [(Arrangement, IconName, &str); 4] = [
209    (Arrangement::Tabs, IconName::AppWindow, "Every view as a tab of one group"),
210    (Arrangement::Horizontal, IconName::Columns2, "Every view side by side"),
211    (Arrangement::Vertical, IconName::Rows2, "Every view stacked"),
212    (Arrangement::Grid, IconName::Grid2x2, "Every view in a grid"),
213];
214
215impl AddViewDialog {
216    /// The dialog offering `options` (and the arrangements, when `can_arrange`); focuses it.
217    pub fn new(options: Vec<ViewOption>, can_arrange: bool, window: &mut Window, cx: &mut Context<Self>) -> Self {
218        let focus = cx.focus_handle();
219        window.focus(&focus, cx);
220        let mut d = Self { options, can_arrange, cursor: 0, focus };
221        d.cursor = d.enabled().first().copied().unwrap_or(0);
222        d
223    }
224
225    /// The rows that can run (arrangements first, then the views).
226    fn enabled(&self) -> Vec<usize> {
227        let arr = (0..ARRANGEMENTS.len()).filter(|_| self.can_arrange);
228        arr.chain(self.options.iter().enumerate().filter(|(_, o)| o.enabled).map(|(i, _)| ARRANGEMENTS.len() + i))
229            .collect()
230    }
231
232    /// Runs row `row` (arrangements first, then the views), as a click does.
233    pub fn run(&mut self, row: usize, cx: &mut Context<Self>) {
234        cx.emit(if row < ARRANGEMENTS.len() {
235            DialogEvent::Arrange(ARRANGEMENTS[row].0)
236        } else {
237            DialogEvent::Add(row - ARRANGEMENTS.len())
238        });
239    }
240
241    fn on_key(&mut self, e: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
242        let enabled = self.enabled();
243        let at = enabled.iter().position(|&i| i == self.cursor);
244        match e.keystroke.key.as_str() {
245            "escape" => cx.emit(DialogEvent::Close),
246            "down" | "up" if !enabled.is_empty() => {
247                let n = enabled.len();
248                let next = match (at, e.keystroke.key.as_str()) {
249                    (Some(i), "down") => (i + 1) % n,
250                    (Some(i), _) => (i + n - 1) % n,
251                    (None, "down") => 0,
252                    (None, _) => n - 1,
253                };
254                self.cursor = enabled[next];
255                cx.notify();
256            }
257            "enter" => {
258                if enabled.contains(&self.cursor) {
259                    self.run(self.cursor, cx);
260                }
261            }
262            _ => return,
263        }
264        cx.stop_propagation();
265    }
266}
267
268impl Render for AddViewDialog {
269    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
270        let me = cx.entity().downgrade();
271        let cursor = self.cursor;
272        let row = |ix: usize, icon: IconName, title: String, text: String, enabled: bool| {
273            let me = me.clone();
274            h_flex()
275                .id(SharedString::from(format!("add-view-row-{ix}")))
276                .min_h(px(48.))
277                .px(px(theme::SM))
278                .gap(px(theme::MD))
279                .rounded(px(theme::RADIUS))
280                .when(enabled && ix == cursor, |d| d.bg(color::control()))
281                .when(enabled, |d| {
282                    d.cursor_pointer().hover(|d| d.bg(color::control())).on_click(move |_, _, cx| {
283                        let _ = me.update(cx, |d, cx| d.run(ix, cx));
284                    })
285                })
286                .when(!enabled, |d| d.opacity(0.5))
287                .child(
288                    div()
289                        .flex_none()
290                        .size(px(32.))
291                        .rounded(px(theme::RADIUS))
292                        .border_1()
293                        .border_color(color::hover())
294                        .flex()
295                        .items_center()
296                        .justify_center()
297                        .child(Icon::new(icon)),
298                )
299                .child(
300                    v_flex()
301                        .min_w_0()
302                        .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(title))
303                        .child(div().text_xs().text_color(color::text_muted()).truncate().child(text)),
304                )
305        };
306        let heading = |text: &'static str, hint: &'static str| {
307            v_flex()
308                .px(px(theme::SM))
309                .pt(px(theme::MD))
310                .pb(px(theme::XS))
311                .child(div().text_xs().font_weight(FontWeight::SEMIBOLD).child(text))
312                .child(div().text_xs().text_color(color::text_muted()).child(hint))
313        };
314        let close = me.clone();
315        let n = ARRANGEMENTS.len();
316        let card = v_flex()
317            .id("add-view-dialog")
318            .occlude()
319            .w(px(460.))
320            .max_h(px(620.))
321            .overflow_y_scroll()
322            .p(px(theme::SM))
323            .rounded(px(theme::RADIUS_LG))
324            .border_1()
325            .border_color(color::border())
326            .bg(color::raised())
327            .shadow_lg()
328            .track_focus(&self.focus)
329            .on_key_down(cx.listener(Self::on_key))
330            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
331            .child(
332                h_flex()
333                    .px(px(theme::SM))
334                    .py(px(theme::XS))
335                    .justify_between()
336                    .child(
337                        h_flex()
338                            .gap(px(theme::SM))
339                            .items_baseline()
340                            .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child("Add view or container"))
341                            .child(div().text_xs().text_color(color::text_muted()).child("↑ ↓ Enter · Esc")),
342                    )
343                    .child(
344                        Button::new("add-view-close")
345                            .ghost()
346                            .small()
347                            .icon(Icon::new(IconName::X))
348                            .tooltip("Close")
349                            .on_click(move |_, _, cx| {
350                                let _ = close.update(cx, |_, cx| cx.emit(DialogEvent::Close));
351                            }),
352                    ),
353            )
354            .child(heading("Containers", "Arrange the views"))
355            .children(ARRANGEMENTS.iter().enumerate().map(|(i, (how, icon, text))| {
356                row(i, *icon, how.title().to_string(), text.to_string(), self.can_arrange)
357            }))
358            .child(div().mx(px(theme::SM)).my(px(theme::SM)).h(px(1.)).bg(color::border()))
359            .child(heading("Views", "Added beside the focused view"))
360            .children(
361                self.options
362                    .iter()
363                    .enumerate()
364                    .map(|(i, o)| row(n + i, o.icon, o.title.clone(), o.hint.clone(), o.enabled)),
365            );
366        let back = me.clone();
367        // The backdrop over the views closes it
368        div()
369            .id("add-view-backdrop")
370            .absolute()
371            .inset_0()
372            .bg(gpui_kit::black().opacity(0.35))
373            .flex()
374            .items_start()
375            .justify_center()
376            .pt(px(48.))
377            .on_mouse_down(MouseButton::Left, move |_, _, cx| {
378                let _ = back.update(cx, |_, cx| cx.emit(DialogEvent::Close));
379            })
380            .child(card)
381    }
382}