Skip to main content

kitchen_shell/
picker_view.rs

1//! The file picker's popup ([`FilePickerView`]), over the frame when File → Open… runs. It draws
2//! [`crate::picker::Picker`]:
3//!
4//! - **Left**: the places (home, Desktop, Documents, Downloads, the computer) and the app's
5//!   recent files.
6//! - **Top**: up one folder, then the breadcrumb (each folder a button).
7//! - **List**: folders first, then what the app opens, with kind, size and date; the rest only
8//!   with "Show all files", greyed. A click selects, a double click enters a folder or opens.
9//! - **Footer**: what the app opens, "Show all files", Cancel and Open.
10//!
11//! Keys: ↑ ↓ move, Enter opens or enters, Backspace goes up, Esc cancels. On a narrow window the
12//! places fold away (they are one Home button in the top row).
13
14use std::path::PathBuf;
15
16use gpui_kit::TestSupportExt as _;
17use gpui_kit::assets::IconName;
18use gpui_kit::component::button::{Button, ButtonVariants as _};
19use gpui_kit::component::checkbox::Checkbox;
20use gpui_kit::component::{Disableable as _, Icon, Selectable as _, Sizable as _, h_flex, v_flex};
21use gpui_kit::prelude::FluentBuilder as _;
22use gpui_kit::{
23    ClickEvent, Context, EventEmitter, FocusHandle, FontWeight, InteractiveElement as _, IntoElement, KeyDownEvent,
24    ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px,
25};
26use kitchen_ui::icons::standard;
27use kitchen_ui::theme::{self, color};
28use kitchen_ui::widgets::icon_button;
29
30use crate::picker::{EntryKind, Picker, Place, human_size, places};
31
32/// What the picker asks of its owner.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum PickerEvent {
35    /// Close it and open this.
36    Open(PathBuf),
37    /// Close it, opening nothing.
38    Cancel,
39}
40
41/// Below this width (px of the popup) the places column folds away.
42const PLACES_MIN_W: f32 = 560.;
43/// Height of a row of the list (px).
44const ROW_H: f32 = 28.;
45
46/// The file picker's popup.
47pub struct FilePickerView {
48    picker: Picker,
49    places: Vec<Place>,
50    title: SharedString,
51    focus: FocusHandle,
52}
53
54impl EventEmitter<PickerEvent> for FilePickerView {}
55
56impl FilePickerView {
57    /// The popup over `picker`, focused.
58    pub fn new(picker: Picker, window: &mut Window, cx: &mut Context<Self>) -> Self {
59        let focus = cx.focus_handle();
60        window.focus(&focus, cx);
61        Self { picker, places: places(), title: "Open".into(), focus }
62    }
63
64    /// Sets the heading ("Open", "Open a recording").
65    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
66        self.title = title.into();
67        self
68    }
69
70    /// The model (for tests).
71    pub fn picker(&self) -> &Picker {
72        &self.picker
73    }
74
75    /// The model, to change it (for tests).
76    pub fn picker_mut(&mut self) -> &mut Picker {
77        &mut self.picker
78    }
79
80    fn go(&mut self, dir: PathBuf, cx: &mut Context<Self>) {
81        let _ = self.picker.enter(&dir);
82        cx.notify();
83    }
84
85    fn activate(&mut self, i: usize, cx: &mut Context<Self>) {
86        if let Some(path) = self.picker.activate(i) {
87            cx.emit(PickerEvent::Open(path));
88        }
89        cx.notify();
90    }
91
92    fn open_selected(&mut self, cx: &mut Context<Self>) {
93        if let Some(i) = self.picker.selected() {
94            self.activate(i, cx);
95        }
96    }
97
98    fn on_key(&mut self, e: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
99        let n = self.picker.entries().len();
100        match e.keystroke.key.as_str() {
101            "escape" => cx.emit(PickerEvent::Cancel),
102            "enter" => self.open_selected(cx),
103            "backspace" => {
104                self.picker.up();
105            }
106            "down" if n > 0 => self.picker.select(Some(self.picker.selected().map_or(0, |i| (i + 1).min(n - 1)))),
107            "up" if n > 0 => self.picker.select(Some(self.picker.selected().map_or(0, |i| i.saturating_sub(1)))),
108            _ => return,
109        }
110        cx.stop_propagation();
111        cx.notify();
112    }
113
114    fn places_column(&self, cx: &mut Context<Self>) -> impl IntoElement {
115        let place = |id: String, name: String, icon: IconName, path: PathBuf, here: bool, cx: &mut Context<Self>| {
116            h_flex()
117                .id(SharedString::from(id))
118                .role(Role::Button)
119                .aria_label(SharedString::from(name.clone()))
120                .h(px(ROW_H))
121                .px(px(theme::SM))
122                .gap(px(theme::SM))
123                .items_center()
124                .rounded(px(theme::RADIUS))
125                .text_sm()
126                .cursor_pointer()
127                .hover(|d| d.bg(color::hover()))
128                .when(here, |d| d.bg(color::selection()).border_l_2().border_color(color::selection_edge()))
129                .child(Icon::new(icon).small().text_color(color::text_muted()))
130                .child(div().min_w_0().truncate().child(name))
131                .on_click(cx.listener(move |this, _, _, cx| this.go(path.clone(), cx)))
132                .test_support()
133        };
134        let mut col =
135            v_flex().w(px(180.)).flex_none().gap(px(2.)).p(px(theme::SM)).border_r_1().border_color(color::border());
136        col = col.child(section_label("Places"));
137        for (i, p) in self.places.iter().enumerate() {
138            let here = p.path == self.picker.dir();
139            col = col.child(place(format!("picker-place-{i}"), p.name.clone(), p.icon, p.path.clone(), here, cx));
140        }
141        let recent = self.picker.recent();
142        if !recent.is_empty() {
143            col = col.child(div().h(px(theme::SM))).child(section_label("Recent"));
144            for (i, path) in recent.into_iter().take(6).enumerate() {
145                let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
146                let me = cx.entity().downgrade();
147                let open = path.clone();
148                col = col.child(
149                    h_flex()
150                        .id(SharedString::from(format!("picker-recent-{i}")))
151                        .role(Role::Button)
152                        .aria_label(SharedString::from(format!("Open {name}")))
153                        .h(px(ROW_H))
154                        .px(px(theme::SM))
155                        .gap(px(theme::SM))
156                        .items_center()
157                        .rounded(px(theme::RADIUS))
158                        .text_sm()
159                        .cursor_pointer()
160                        .hover(|d| d.bg(color::hover()))
161                        .child(Icon::new(standard::RECENT).small().text_color(color::text_muted()))
162                        .child(div().min_w_0().truncate().child(name))
163                        .on_click(move |_, _, cx| {
164                            let open = open.clone();
165                            let _ = me.update(cx, |_, cx| cx.emit(PickerEvent::Open(open)));
166                        })
167                        .test_support(),
168                );
169            }
170        }
171        col
172    }
173
174    fn top_row(&self, wide: bool, cx: &mut Context<Self>) -> impl IntoElement {
175        let crumbs = self.picker.crumbs();
176        let last = crumbs.len().saturating_sub(1);
177        // Narrow: the last three folders, the rest behind "…"
178        let skip = if wide { 0 } else { crumbs.len().saturating_sub(3) };
179        let mut row = h_flex().id("picker-crumbs").flex_1().min_w_0().gap(px(2.)).items_center().overflow_x_scroll();
180        if skip > 0 {
181            row = row.child(div().text_sm().text_color(color::text_muted()).child("…"));
182        }
183        for (i, (name, path)) in crumbs.into_iter().enumerate().skip(skip) {
184            if i > skip || skip > 0 {
185                row = row.child(Icon::new(IconName::ChevronRight).xsmall().text_color(color::text_muted()));
186            }
187            row = row.child(
188                Button::new(SharedString::from(format!("picker-crumb-{i}")))
189                    .ghost()
190                    .small()
191                    .label(name)
192                    .selected(i == last)
193                    .on_click(cx.listener(move |this, _, _, cx| this.go(path.clone(), cx))),
194            );
195        }
196        h_flex()
197            .gap(px(theme::XS))
198            .px(px(theme::SM))
199            .py(px(theme::XS))
200            .items_center()
201            .border_b_1()
202            .border_color(color::border())
203            .child(icon_button("picker-up", standard::UP, "Up one folder (Backspace)").on_click(cx.listener(
204                |this, _, _, cx| {
205                    this.picker.up();
206                    cx.notify();
207                },
208            )))
209            .when(!wide, |d| {
210                let home = self.places.first().map(|p| p.path.clone());
211                d.children(home.map(|h| {
212                    icon_button("picker-home", standard::HOME, "Home")
213                        .on_click(cx.listener(move |this, _, _, cx| this.go(h.clone(), cx)))
214                }))
215            })
216            .child(row)
217    }
218
219    fn list(&self, wide: bool, cx: &mut Context<Self>) -> impl IntoElement {
220        let mut list = v_flex()
221            .id("picker-list")
222            .role(Role::ListBox)
223            .aria_label("Files")
224            .flex_1()
225            .min_h_0()
226            .overflow_y_scroll()
227            .p(px(theme::XS))
228            .gap(px(1.));
229        if let Some(e) = self.picker.error() {
230            list = list.child(
231                div()
232                    .p(px(theme::SM))
233                    .text_sm()
234                    .text_color(color::danger())
235                    .child(format!("Cannot open that folder. {e}")),
236            );
237        }
238        if self.picker.entries().is_empty() {
239            let line = if self.picker.show_all() {
240                "This folder is empty."
241            } else {
242                "Nothing here the app opens. Turn on \"Show all files\" to see everything."
243            };
244            list = list.child(div().p(px(theme::MD)).text_sm().text_color(color::text_muted()).child(line));
245        }
246        let selected = self.picker.selected();
247        for (i, e) in self.picker.entries().iter().enumerate() {
248            let (icon, kind, dim) = match e.kind {
249                EntryKind::Folder => (IconName::Folder, "Folder".to_string(), false),
250                EntryKind::Opens(k) => match self.picker.kinds().get(k) {
251                    Some(k) => (k.icon, k.name.clone(), false),
252                    None => (IconName::File, "File".to_string(), false),
253                },
254                EntryKind::Other => (IconName::File, String::new(), true),
255            };
256            let date = e
257                .modified
258                .and_then(|m| jiff::Timestamp::try_from(m).ok())
259                .map(|t| t.to_zoned_datetime(jiff::tz::TimeZone::system()).strftime("%Y-%m-%d %H:%M").to_string());
260            let text = if dim { color::text_disabled() } else { color::text() };
261            list = list.child(
262                h_flex()
263                    .id(SharedString::from(format!("picker-entry-{i}")))
264                    .role(Role::ListBoxOption)
265                    .aria_label(SharedString::from(e.name.clone()))
266                    .h(px(ROW_H))
267                    .px(px(theme::SM))
268                    .gap(px(theme::SM))
269                    .items_center()
270                    .rounded(px(theme::RADIUS))
271                    .text_sm()
272                    .text_color(text)
273                    .cursor_pointer()
274                    .hover(|d| d.bg(color::hover()))
275                    .when(selected == Some(i), |d| {
276                        d.bg(color::selection()).border_l_2().border_color(color::selection_edge())
277                    })
278                    .child(Icon::new(icon).small().text_color(if dim {
279                        color::text_disabled()
280                    } else {
281                        color::text_muted()
282                    }))
283                    .child(div().flex_1().min_w_0().truncate().child(e.name.clone()))
284                    .when(wide, |d| {
285                        d.child(
286                            div()
287                                .w(px(120.))
288                                .flex_none()
289                                .truncate()
290                                .text_xs()
291                                .text_color(color::text_muted())
292                                .child(kind),
293                        )
294                    })
295                    .child(
296                        div()
297                            .w(px(72.))
298                            .flex_none()
299                            .text_right()
300                            .text_xs()
301                            .font_family(kitchen_ui::theme::fonts::MONO)
302                            .text_color(color::text_muted())
303                            .child(e.size.map(human_size).unwrap_or_default()),
304                    )
305                    .when(wide, |d| {
306                        d.child(
307                            div()
308                                .w(px(128.))
309                                .flex_none()
310                                .text_right()
311                                .text_xs()
312                                .font_family(kitchen_ui::theme::fonts::MONO)
313                                .text_color(color::text_muted())
314                                .child(date.unwrap_or_default()),
315                        )
316                    })
317                    .on_click(cx.listener(move |this, ev: &ClickEvent, _, cx| {
318                        this.picker.select(Some(i));
319                        if ev.click_count() >= 2 {
320                            this.activate(i, cx);
321                        }
322                        cx.notify();
323                    }))
324                    .test_support(),
325            );
326        }
327        list
328    }
329
330    fn footer(&self, cx: &mut Context<Self>) -> impl IntoElement {
331        let can_open = self.picker.openable().is_some()
332            || self.picker.selected_entry().is_some_and(|e| e.kind == EntryKind::Folder);
333        let label =
334            if self.picker.selected_entry().is_some_and(|e| e.kind == EntryKind::Folder) { "Go into" } else { "Open" };
335        h_flex()
336            .flex_wrap()
337            .gap(px(theme::SM))
338            .px(px(theme::MD))
339            .py(px(theme::SM))
340            .items_center()
341            .border_t_1()
342            .border_color(color::border())
343            .child(
344                div()
345                    .flex_1()
346                    .min_w(px(160.))
347                    .text_xs()
348                    .text_color(color::text_muted())
349                    .child(self.picker.opens_line()),
350            )
351            .child(Checkbox::new("picker-show-all").label("Show all files").checked(self.picker.show_all()).on_click(
352                cx.listener(|this, on: &bool, _, cx| {
353                    this.picker.set_show_all(*on);
354                    cx.notify();
355                }),
356            ))
357            .child(
358                Button::new("picker-cancel")
359                    .label("Cancel")
360                    .small()
361                    .on_click(cx.listener(|_, _, _, cx| cx.emit(PickerEvent::Cancel))),
362            )
363            .child(
364                Button::new("picker-open")
365                    .primary()
366                    .small()
367                    .label(label)
368                    .disabled(!can_open)
369                    .on_click(cx.listener(|this, _, _, cx| this.open_selected(cx))),
370            )
371    }
372}
373
374fn section_label(text: &'static str) -> impl IntoElement {
375    div()
376        .px(px(theme::SM))
377        .pb(px(2.))
378        .text_xs()
379        .font_weight(FontWeight::SEMIBOLD)
380        .text_color(color::text_muted())
381        .child(text)
382}
383
384impl Render for FilePickerView {
385    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
386        let width = window.viewport_size().width.as_f32();
387        let popup_w = (width - 2. * theme::LG).min(880.);
388        let wide = popup_w >= PLACES_MIN_W;
389        let back = cx.entity().downgrade();
390        div()
391            .id("picker-backdrop")
392            .absolute()
393            .top_0()
394            .left_0()
395            .size_full()
396            .flex()
397            .items_start()
398            .justify_center()
399            .pt(px(if wide { 56. } else { theme::LG }))
400            .px(px(theme::LG))
401            .bg(gpui_kit::black().opacity(0.35))
402            .on_click(move |_, _, cx| {
403                let _ = back.update(cx, |_, cx| cx.emit(PickerEvent::Cancel));
404            })
405            .child(
406                v_flex()
407                    .id("picker")
408                    .track_focus(&self.focus)
409                    .occlude()
410                    .w(px(popup_w))
411                    .h(gpui_kit::relative(if wide { 0.75 } else { 0.9 }))
412                    .rounded(px(theme::RADIUS_LG))
413                    .border_1()
414                    .border_color(color::border())
415                    .bg(color::raised())
416                    .text_color(color::text())
417                    .shadow_lg()
418                    .overflow_hidden()
419                    .capture_key_down(cx.listener(Self::on_key))
420                    .on_click(|_, _, cx| cx.stop_propagation())
421                    .child(
422                        h_flex()
423                            .px(px(theme::MD))
424                            .py(px(theme::SM))
425                            .gap(px(theme::SM))
426                            .items_center()
427                            .border_b_1()
428                            .border_color(color::border())
429                            .child(Icon::new(standard::OPEN).small().text_color(color::accent_mark()))
430                            .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(self.title.clone()))
431                            .child(div().flex_1())
432                            .child(
433                                div()
434                                    .text_xs()
435                                    .text_color(color::text_muted())
436                                    .when(wide, |d| d.child("↑ ↓ Enter · Backspace up · Esc")),
437                            )
438                            .child(
439                                icon_button("picker-close", IconName::Close, "Close (Esc)")
440                                    .on_click(cx.listener(|_, _, _, cx| cx.emit(PickerEvent::Cancel))),
441                            ),
442                    )
443                    .child(h_flex().flex_1().min_h_0().when(wide, |d| d.child(self.places_column(cx))).child(
444                        v_flex().flex_1().min_w_0().min_h_0().child(self.top_row(wide, cx)).child(self.list(wide, cx)),
445                    ))
446                    .child(self.footer(cx)),
447            )
448    }
449}