1use std::path::PathBuf;
15
16use gpui_kit::assets::IconName;
17use gpui_kit::component::button::{Button, ButtonVariants as _};
18use gpui_kit::TestSupportExt 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, Role, FocusHandle, FontWeight, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _, Render, SharedString,
24 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#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum PickerEvent {
35 Open(PathBuf),
37 Cancel,
39}
40
41const PLACES_MIN_W: f32 = 560.;
43const ROW_H: f32 = 28.;
45
46pub 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 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 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
66 self.title = title.into();
67 self
68 }
69
70 pub fn picker(&self) -> &Picker {
72 &self.picker
73 }
74
75 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 = v_flex().w(px(180.)).flex_none().gap(px(2.)).p(px(theme::SM)).border_r_1().border_color(color::border());
135 col = col.child(section_label("Places"));
136 for (i, p) in self.places.iter().enumerate() {
137 let here = p.path == self.picker.dir();
138 col = col.child(place(format!("picker-place-{i}"), p.name.clone(), p.icon, p.path.clone(), here, cx));
139 }
140 let recent = self.picker.recent();
141 if !recent.is_empty() {
142 col = col.child(div().h(px(theme::SM))).child(section_label("Recent"));
143 for (i, path) in recent.into_iter().take(6).enumerate() {
144 let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
145 let me = cx.entity().downgrade();
146 let open = path.clone();
147 col = col.child(
148 h_flex()
149 .id(SharedString::from(format!("picker-recent-{i}")))
150 .role(Role::Button)
151 .aria_label(SharedString::from(format!("Open {name}")))
152 .h(px(ROW_H))
153 .px(px(theme::SM))
154 .gap(px(theme::SM))
155 .items_center()
156 .rounded(px(theme::RADIUS))
157 .text_sm()
158 .cursor_pointer()
159 .hover(|d| d.bg(color::hover()))
160 .child(Icon::new(standard::RECENT).small().text_color(color::text_muted()))
161 .child(div().min_w_0().truncate().child(name))
162 .on_click(move |_, _, cx| {
163 let open = open.clone();
164 let _ = me.update(cx, |_, cx| cx.emit(PickerEvent::Open(open)));
165 })
166 .test_support(),
167 );
168 }
169 }
170 col
171 }
172
173 fn top_row(&self, wide: bool, cx: &mut Context<Self>) -> impl IntoElement {
174 let crumbs = self.picker.crumbs();
175 let last = crumbs.len().saturating_sub(1);
176 let skip = if wide { 0 } else { crumbs.len().saturating_sub(3) };
178 let mut row = h_flex().id("picker-crumbs").flex_1().min_w_0().gap(px(2.)).items_center().overflow_x_scroll();
179 if skip > 0 {
180 row = row.child(div().text_sm().text_color(color::text_muted()).child("…"));
181 }
182 for (i, (name, path)) in crumbs.into_iter().enumerate().skip(skip) {
183 if i > skip || skip > 0 {
184 row = row.child(Icon::new(IconName::ChevronRight).xsmall().text_color(color::text_muted()));
185 }
186 row = row.child(
187 Button::new(SharedString::from(format!("picker-crumb-{i}")))
188 .ghost()
189 .small()
190 .label(name)
191 .selected(i == last)
192 .on_click(cx.listener(move |this, _, _, cx| this.go(path.clone(), cx))),
193 );
194 }
195 h_flex()
196 .gap(px(theme::XS))
197 .px(px(theme::SM))
198 .py(px(theme::XS))
199 .items_center()
200 .border_b_1()
201 .border_color(color::border())
202 .child(icon_button("picker-up", standard::UP, "Up one folder (Backspace)").on_click(cx.listener(|this, _, _, cx| {
203 this.picker.up();
204 cx.notify();
205 })))
206 .when(!wide, |d| {
207 let home = self.places.first().map(|p| p.path.clone());
208 d.children(home.map(|h| icon_button("picker-home", standard::HOME, "Home").on_click(cx.listener(move |this, _, _, cx| this.go(h.clone(), cx)))))
209 })
210 .child(row)
211 }
212
213 fn list(&self, wide: bool, cx: &mut Context<Self>) -> impl IntoElement {
214 let mut list = v_flex().id("picker-list").role(Role::ListBox).aria_label("Files").flex_1().min_h_0().overflow_y_scroll().p(px(theme::XS)).gap(px(1.));
215 if let Some(e) = self.picker.error() {
216 list = list.child(div().p(px(theme::SM)).text_sm().text_color(color::danger()).child(format!("Cannot open that folder. {e}")));
217 }
218 if self.picker.entries().is_empty() {
219 let line = if self.picker.show_all() { "This folder is empty." } else { "Nothing here the app opens. Turn on \"Show all files\" to see everything." };
220 list = list.child(div().p(px(theme::MD)).text_sm().text_color(color::text_muted()).child(line));
221 }
222 let selected = self.picker.selected();
223 for (i, e) in self.picker.entries().iter().enumerate() {
224 let (icon, kind, dim) = match e.kind {
225 EntryKind::Folder => (IconName::Folder, "Folder".to_string(), false),
226 EntryKind::Opens(k) => match self.picker.kinds().get(k) {
227 Some(k) => (k.icon, k.name.clone(), false),
228 None => (IconName::File, "File".to_string(), false),
229 },
230 EntryKind::Other => (IconName::File, String::new(), true),
231 };
232 let date = e.modified.and_then(|m| jiff::Timestamp::try_from(m).ok()).map(|t| t.to_zoned_datetime(jiff::tz::TimeZone::system()).strftime("%Y-%m-%d %H:%M").to_string());
233 let text = if dim { color::text_disabled() } else { color::text() };
234 list = list.child(
235 h_flex()
236 .id(SharedString::from(format!("picker-entry-{i}")))
237 .role(Role::ListBoxOption)
238 .aria_label(SharedString::from(e.name.clone()))
239 .h(px(ROW_H))
240 .px(px(theme::SM))
241 .gap(px(theme::SM))
242 .items_center()
243 .rounded(px(theme::RADIUS))
244 .text_sm()
245 .text_color(text)
246 .cursor_pointer()
247 .hover(|d| d.bg(color::hover()))
248 .when(selected == Some(i), |d| d.bg(color::selection()).border_l_2().border_color(color::selection_edge()))
249 .child(Icon::new(icon).small().text_color(if dim { color::text_disabled() } else { color::text_muted() }))
250 .child(div().flex_1().min_w_0().truncate().child(e.name.clone()))
251 .when(wide, |d| d.child(div().w(px(120.)).flex_none().truncate().text_xs().text_color(color::text_muted()).child(kind)))
252 .child(div().w(px(72.)).flex_none().text_right().text_xs().font_family(kitchen_ui::theme::fonts::MONO).text_color(color::text_muted()).child(e.size.map(human_size).unwrap_or_default()))
253 .when(wide, |d| d.child(div().w(px(128.)).flex_none().text_right().text_xs().font_family(kitchen_ui::theme::fonts::MONO).text_color(color::text_muted()).child(date.unwrap_or_default())))
254 .on_click(cx.listener(move |this, ev: &ClickEvent, _, cx| {
255 this.picker.select(Some(i));
256 if ev.click_count() >= 2 {
257 this.activate(i, cx);
258 }
259 cx.notify();
260 }))
261 .test_support(),
262 );
263 }
264 list
265 }
266
267 fn footer(&self, cx: &mut Context<Self>) -> impl IntoElement {
268 let can_open = self.picker.openable().is_some() || self.picker.selected_entry().is_some_and(|e| e.kind == EntryKind::Folder);
269 let label = if self.picker.selected_entry().is_some_and(|e| e.kind == EntryKind::Folder) { "Go into" } else { "Open" };
270 h_flex()
271 .flex_wrap()
272 .gap(px(theme::SM))
273 .px(px(theme::MD))
274 .py(px(theme::SM))
275 .items_center()
276 .border_t_1()
277 .border_color(color::border())
278 .child(div().flex_1().min_w(px(160.)).text_xs().text_color(color::text_muted()).child(self.picker.opens_line()))
279 .child(Checkbox::new("picker-show-all").label("Show all files").checked(self.picker.show_all()).on_click(cx.listener(|this, on: &bool, _, cx| {
280 this.picker.set_show_all(*on);
281 cx.notify();
282 })))
283 .child(Button::new("picker-cancel").label("Cancel").small().on_click(cx.listener(|_, _, _, cx| cx.emit(PickerEvent::Cancel))))
284 .child(Button::new("picker-open").primary().small().label(label).disabled(!can_open).on_click(cx.listener(|this, _, _, cx| this.open_selected(cx))))
285 }
286}
287
288fn section_label(text: &'static str) -> impl IntoElement {
289 div().px(px(theme::SM)).pb(px(2.)).text_xs().font_weight(FontWeight::SEMIBOLD).text_color(color::text_muted()).child(text)
290}
291
292impl Render for FilePickerView {
293 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
294 let width = window.viewport_size().width.as_f32();
295 let popup_w = (width - 2. * theme::LG).min(880.);
296 let wide = popup_w >= PLACES_MIN_W;
297 let back = cx.entity().downgrade();
298 div()
299 .id("picker-backdrop")
300 .absolute()
301 .top_0()
302 .left_0()
303 .size_full()
304 .flex()
305 .items_start()
306 .justify_center()
307 .pt(px(if wide { 56. } else { theme::LG }))
308 .px(px(theme::LG))
309 .bg(gpui_kit::black().opacity(0.35))
310 .on_click(move |_, _, cx| {
311 let _ = back.update(cx, |_, cx| cx.emit(PickerEvent::Cancel));
312 })
313 .child(
314 v_flex()
315 .id("picker")
316 .track_focus(&self.focus)
317 .occlude()
318 .w(px(popup_w))
319 .h(gpui_kit::relative(if wide { 0.75 } else { 0.9 }))
320 .rounded(px(theme::RADIUS_LG))
321 .border_1()
322 .border_color(color::border())
323 .bg(color::raised())
324 .text_color(color::text())
325 .shadow_lg()
326 .overflow_hidden()
327 .capture_key_down(cx.listener(Self::on_key))
328 .on_click(|_, _, cx| cx.stop_propagation())
329 .child(
330 h_flex()
331 .px(px(theme::MD))
332 .py(px(theme::SM))
333 .gap(px(theme::SM))
334 .items_center()
335 .border_b_1()
336 .border_color(color::border())
337 .child(Icon::new(standard::OPEN).small().text_color(color::accent_mark()))
338 .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(self.title.clone()))
339 .child(div().flex_1())
340 .child(div().text_xs().text_color(color::text_muted()).when(wide, |d| d.child("↑ ↓ Enter · Backspace up · Esc")))
341 .child(icon_button("picker-close", IconName::Close, "Close (Esc)").on_click(cx.listener(|_, _, _, cx| cx.emit(PickerEvent::Cancel)))),
342 )
343 .child(
344 h_flex()
345 .flex_1()
346 .min_h_0()
347 .when(wide, |d| d.child(self.places_column(cx)))
348 .child(v_flex().flex_1().min_w_0().min_h_0().child(self.top_row(wide, cx)).child(self.list(wide, cx))),
349 )
350 .child(self.footer(cx)),
351 )
352 }
353}