Skip to main content

brep_app/panels/
file_explorer.rs

1//! Reusable, embeddable file explorer for the application's persistent store.
2//! It owns only transient browsing state; callers decide what activating a file
3//! means (open a document, choose a Save-As name, or insert an ACOMP part).
4//!
5//! Interaction model (matches a conventional file dialog): a single click
6//! anywhere on a row (name, type, size, date or blank space) selects it — the
7//! whole row highlights on hover and when selected; a double-click, the Enter
8//! key, or the footer confirm button *activates* it. Activating a FILE hands it
9//! to the caller; activating a FOLDER walks into it, so a single click on a
10//! folder only selects it. A left sidebar offers quick
11//! places + pinned folders, and the top bar is a clickable breadcrumb with an
12//! editable path and back / forward history — all driven through the
13//! [`ModelStore`] seam so web and native share one UI.
14//!
15//! The explorer never sizes itself: it FILLS the region its host hands it. A
16//! modal host wraps its whole body in [`dialog_body`], which puts one resize
17//! grip at the dialog window's bottom-right corner; a window host ([`egui::Window`])
18//! already has that grip. Either way the host's own trailing widgets go in a
19//! [`dialog_footer`] BEFORE the explorer, so they pin to the bottom and the
20//! file list is the only part that scrolls.
21
22use crate::automation::hit_keys::HitKeyDoc;
23use crate::store::{BrowserEntry, BrowserPlace, ModelStore, PlaceKind, PINNED_KEY};
24use eframe::egui;
25use egui_extras::{Column, TableBuilder};
26use std::cmp::Ordering;
27
28#[derive(Clone, Copy)]
29pub struct FileExplorerOptions<'a> {
30    pub hit_prefix: &'a str,
31    pub empty_label: &'a str,
32    pub row_icon: &'a str,
33    pub current: Option<&'a str>,
34    pub allow_delete: bool,
35    pub allow_import: bool,
36    pub import_label: &'a str,
37    pub import_hit: &'a str,
38    pub show_cancel: bool,
39    /// Footer primary/confirm button label (`"Open"` / `"Import"` / `"Insert"`).
40    /// `None` when the caller supplies its own action button and uses the
41    /// explorer only for navigation + name selection (Save As, step-parts
42    /// destination) — then keyboard confirm is disabled too, leaving Enter to
43    /// the caller's name field.
44    pub confirm_label: Option<&'a str>,
45    pub extensions: &'a [&'a str],
46}
47
48impl<'a> FileExplorerOptions<'a> {
49    pub fn open(current: Option<&'a str>) -> Self {
50        Self {
51            hit_prefix: "open",
52            empty_label: "(no saved models)",
53            row_icon: "\u{1F5CE}",
54            current,
55            allow_delete: true,
56            allow_import: false,
57            import_label: "Upload\u{2026}",
58            import_hit: "upload",
59            show_cancel: true,
60            confirm_label: Some("Open"),
61            extensions: crate::store::MODEL_EXTENSIONS,
62        }
63    }
64}
65
66/// The hit keys the EXPLORER publishes, documented beside the publisher
67/// (`automation::hit_keys`) rather than in each host panel: the widget set is
68/// the explorer's, only the `hit_prefix` is the host's, so one registration per
69/// prefix covers every key the shell can draw. A file ROW is keyed by its own
70/// displayed name (`open:bracket.nbrep`), which is what lets a script open
71/// a document through the modal the way a user does.
72///
73/// Until a script opened the modal these keys had never been published under
74/// `hit_keys_check`: every native script reached its document through
75/// `session_start`'s `document` or `document_open`, both of which bypass the
76/// interface entirely.
77pub static HIT_KEYS: &[HitKeyDoc] = &[
78    HitKeyDoc { panel: "file", prefix: "open:", meaning: "the Open modal's explorer: open:<file or folder name> (a row's name cell; one click selects, a double click opens the file or enters the folder; under a finger one tap enters a folder and selects a file, which open:confirm opens), open:cell:<column>:<name> (the type, size or date cell of the same row, which selects it the same way), open:confirm, open:filter, open:back / forward / up, open:path-edit, open:path-edit-toggle, open:crumb:<i>, open:place:<label>, open:pin:<label>, open:unpin:<label>, open:pin-current, open:new-folder, open:new-folder-name, open:hidden-toggle, open:sort:<column>", command: Some("doc_load") },
79    HitKeyDoc { panel: "file", prefix: "import:", meaning: "the Import modal's explorer, same key set under the `import` prefix, plus import:upload", command: Some("doc_import") },
80    HitKeyDoc { panel: "file", prefix: "saveas:", meaning: "the Save As modal's destination explorer (saveas:file:<key>) and saveas:upload", command: Some("doc_json") },
81    HitKeyDoc { panel: "file", prefix: "insert:", meaning: "the Insert-component modal: insert:lib:<name> for a parts-library entry, insert:model:<key> for the store explorer, insert:upload", command: None },
82    HitKeyDoc { panel: "file", prefix: "del:", meaning: "delete the file on that explorer row (del:<file name>)", command: None },
83    HitKeyDoc { panel: "file", prefix: "upload", meaning: "the explorer's Upload… action where the platform has real-file interchange", command: None },
84    HitKeyDoc { panel: "stepparts", prefix: "steplib:dest:", meaning: "the parts-library destination explorer, the same key set under the `steplib:dest` prefix", command: None },
85];
86
87#[derive(Default)]
88pub struct FileExplorerOutput {
89    /// A file was CONFIRMED (double-click, Enter, or the footer confirm button):
90    /// the caller acts on it and closes the modal.
91    pub activated: Option<String>,
92    /// The file currently highlighted, persisting across frames until the
93    /// browser location changes. Mirrors the live selection for callers that
94    /// want it (and for the headed verifier). `None` when a directory or nothing
95    /// is selected.
96    pub selected: Option<String>,
97    /// A file row was single-clicked THIS frame — a one-shot event. Name-field
98    /// callers (Save As, step-parts) fill their field from it without clobbering
99    /// keystrokes the user makes afterwards.
100    pub picked: Option<String>,
101    pub remove: Option<String>,
102    pub import: bool,
103    pub cancel: bool,
104    pub hits: Vec<(String, egui::Rect)>,
105}
106
107/// Which column the file table is sorted by.
108#[derive(Clone, Copy, PartialEq, Eq, Default)]
109enum SortKey {
110    #[default]
111    Name,
112    Kind,
113    Size,
114    Date,
115}
116
117/// Embeddable browser state. The search text deliberately survives modal uses,
118/// making repeated Open / ACOMP operations retain the user's working filter.
119#[derive(Default)]
120pub struct FileExplorer {
121    query: String,
122    new_folder: String,
123    error: String,
124    /// The highlighted FILE identity. Persists across frames so the footer
125    /// confirm button and keyboard Enter have a stable target; cleared when the
126    /// browser location changes so a stale highlight never leaks into a
127    /// different directory. At most one of `selected` / `selected_dir` is set.
128    selected: Option<String>,
129    /// The highlighted FOLDER identity: one click on a folder row selects it,
130    /// and only a double click, Enter or the footer confirm walks into it (a
131    /// finger's one tap walks in: [`Self::row_clicked`]). Kept
132    /// apart from `selected` so no caller ever receives a folder as a file
133    /// choice (`selected()`, `picked`, `activated` are files only).
134    selected_dir: Option<String>,
135    /// A folder activated THIS frame. Entered at the end of
136    /// [`Self::show_store`], after every widget has drawn from this frame's
137    /// listing, so the footer and the table never disagree about the location.
138    enter_dir: Option<String>,
139    /// The location `selected` belongs to — a mismatch means we walked into
140    /// another directory and must drop the highlight.
141    selected_at: String,
142    /// Visited-location back / forward stacks for the nav buttons.
143    history: Vec<String>,
144    forward: Vec<String>,
145    /// `Some` while the breadcrumb is swapped for an editable path field.
146    editing_path: Option<String>,
147    /// Grab focus for the path field on the frame it appears.
148    path_focus: bool,
149    /// The visible rows (identity, is-folder) in display order — the
150    /// keyboard-nav target set, refreshed every frame by [`Self::show_list`].
151    nav_rows: Vec<(String, bool)>,
152    /// When (egui input time) a finger's tap last changed the folder. A row tap
153    /// PRESSED within egui's double-click delay after it is ignored: the second
154    /// tap of a double tap on a folder lands on whatever row the folder it
155    /// opened draws under the finger, and must not select or open that.
156    touch_nav_at: Option<f64>,
157    /// When the pointer was last pressed. egui forgets a press's start by the
158    /// release frame that reports the click, so it is kept here.
159    last_press_at: Option<f64>,
160    /// Which column the file table sorts by, and its direction (`false` = asc).
161    sort_key: SortKey,
162    sort_desc: bool,
163    /// Show dotfile / hidden entries in the list. Off by default; toggling it on
164    /// never affects navigation — a hidden path can always be entered directly.
165    show_hidden: bool,
166}
167
168impl FileExplorer {
169    pub fn new() -> Self {
170        Self::default()
171    }
172
173    /// The file identity currently highlighted (for the headed verifier and any
174    /// caller mirroring the selection). `None` when nothing / a directory holds
175    /// the highlight.
176    pub fn selected(&self) -> Option<&str> {
177        self.selected.as_deref()
178    }
179
180    /// Drop the file highlight. The host calls it when the explorer is shown for
181    /// another PURPOSE: one explorer serves Import, Insert component and Open in
182    /// the same folder, and a file highlighted for one of them is not a choice
183    /// made for the next. Without it a `.kicad_sym` picked in Import was still
184    /// Insert component's footer choice, and Insert sent it to the parts library.
185    pub fn clear_selection(&mut self) {
186        self.selected = None;
187        self.selected_dir = None;
188    }
189
190    /// The folder identity currently highlighted (for the verifier), `None`
191    /// when a file or nothing holds the highlight.
192    pub fn selected_folder(&self) -> Option<&str> {
193        self.selected_dir.as_deref()
194    }
195
196    /// Highlight a row: a file becomes the file selection, a folder the folder
197    /// selection, and either one drops the other.
198    fn select(&mut self, identity: &str, is_dir: bool) {
199        if is_dir {
200            self.selected = None;
201            self.selected_dir = Some(identity.to_string());
202        } else {
203            self.selected_dir = None;
204            self.selected = Some(identity.to_string());
205        }
206    }
207
208    /// Activate a row: a file is confirmed to the caller, a folder is entered
209    /// at the end of the frame.
210    fn activate(&mut self, identity: &str, is_dir: bool, out: &mut FileExplorerOutput) {
211        self.select(identity, is_dir);
212        if is_dir {
213            self.enter_dir = Some(identity.to_string());
214        } else {
215            out.activated = Some(identity.to_string());
216        }
217    }
218
219    /// Browse the model entries exposed by a platform [`ModelStore`].
220    pub fn show_store(
221        &mut self,
222        ui: &mut egui::Ui,
223        store: &dyn ModelStore,
224        options: FileExplorerOptions<'_>,
225    ) -> FileExplorerOutput {
226        let entries = store.browser_entries(options.extensions);
227        let location = store.browser_location();
228        if location != self.selected_at {
229            self.selected = None;
230            self.selected_dir = None;
231            self.selected_at = location.clone();
232        }
233        let places = store.browser_places();
234        let pins = Self::read_pins(store);
235        let mut out = FileExplorerOutput::default();
236
237        let selected_before = (self.selected.clone(), self.selected_dir.clone());
238        if let Some(now) = ui.input(|i| i.pointer.any_pressed().then_some(i.time)) {
239            self.last_press_at = Some(now);
240        }
241        let compact = crate::viewport::touch::compact(ui.ctx());
242        if compact {
243            ui.horizontal_wrapped(|ui| {
244                let places_menu = ui.menu_button("Places", |ui| {
245                    ui.set_height((ui.ctx().content_rect().height() - 100.0).clamp(80.0, 300.0));
246                    self.show_sidebar(ui, store, &places, &pins, &location, options, &mut out);
247                });
248                out.hits.push((format!("{}:places-menu", options.hit_prefix), places_menu.response.rect));
249                let up = ui.add(egui::Button::new("Up").min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
250                out.hits.push((format!("{}:up", options.hit_prefix), up.rect));
251                if up.clicked() { self.nav(store, || store.browser_up()); }
252                let folder = ui.menu_button("Folder", |ui| {
253                    self.show_nav_bar(ui, store, &location, options, &mut out);
254                    let hidden = ui.checkbox(&mut self.show_hidden, "Show hidden files");
255                    out.hits.push((format!("{}:hidden-toggle", options.hit_prefix), hidden.rect));
256                });
257                out.hits.push((format!("{}:folder-menu", options.hit_prefix), folder.response.rect));
258                let filter_width = ui.available_width().clamp(60.0, 150.0);
259                let filter = ui.add(egui::TextEdit::singleline(&mut self.query).margin(crate::viewport::touch::text_edit_margin(ui)).hint_text("Filter files")
260                    .desired_width(filter_width).min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
261                out.hits.push((format!("{}:filter", options.hit_prefix), filter.rect));
262            });
263        } else { self.show_nav_bar(ui, store, &location, options, &mut out); }
264        if !self.error.is_empty() {
265            ui.colored_label(ui.visuals().error_fg_color, &self.error);
266        }
267        ui.add_space(2.0);
268        ui.separator();
269
270        // The explorer FILLS the region its host gave it — a modal's resizable
271        // body ([`dialog_body`]), a window's content — rather than carrying a
272        // resize handle of its own around the file table: the footer pins to the
273        // bottom (under anything the host already pinned there) and the browse
274        // area takes every pixel between it and the nav bar, so the file list is
275        // the only thing that scrolls.
276        bottom_panel(ui, "brep-file-explorer-footer", options.hit_prefix, |ui| {
277            self.show_footer(ui, options, &mut out)
278        });
279        if compact {
280            self.show_list(ui, &entries, options, &mut out);
281        } else { ui.horizontal_top(|ui| {
282            if !places.is_empty() {
283                ui.vertical(|ui| {
284                    self.show_sidebar(ui, store, &places, &pins, &location, options, &mut out);
285                });
286                ui.separator();
287            }
288            ui.vertical(|ui| {
289                self.show_list(ui, &entries, options, &mut out);
290            });
291        }); }
292
293        self.handle_keys(ui, options, &mut out);
294        // A folder activated this frame (double click, Enter, footer confirm)
295        // is entered only now, after the listing drew from the old location.
296        if let Some(dir) = self.enter_dir.take() {
297            self.nav(store, || store.browser_enter(&dir));
298            ui.ctx().request_repaint();
299        }
300        out.selected = self.selected.clone();
301        // The footer (and any host footer: a name field, a confirm button) was
302        // drawn BEFORE the row that just changed the highlight, so it is showing
303        // last frame's selection. Ask for one more frame rather than leaving a
304        // confirm button greyed out until the pointer happens to move again.
305        if out.picked.is_some() || (self.selected.clone(), self.selected_dir.clone()) != selected_before {
306            ui.ctx().request_repaint();
307        }
308        out
309    }
310
311    // --- navigation with history ---------------------------------------------
312
313    /// Run a navigation action and, when it actually changes location, record the
314    /// previous location on the back stack (clearing the forward stack) and drop
315    /// the file highlight. Shared by up / breadcrumb / place / enter-directory.
316    fn nav<F: FnOnce() -> Result<(), String>>(&mut self, store: &dyn ModelStore, action: F) {
317        let before = store.browser_location();
318        match action() {
319            Ok(()) => {
320                let after = store.browser_location();
321                if after != before {
322                    self.history.push(before);
323                    self.forward.clear();
324                }
325                self.error.clear();
326                self.selected = None;
327                self.selected_dir = None;
328            }
329            Err(error) => self.error = error,
330        }
331    }
332
333    /// Step back to the previous location, remembering the current one for
334    /// forward. A failed navigate restores the stack unchanged.
335    fn back(&mut self, store: &dyn ModelStore) {
336        if let Some(prev) = self.history.pop() {
337            let current = store.browser_location();
338            if store.browser_navigate(&prev).is_ok() {
339                self.forward.push(current);
340                self.selected = None;
341                self.selected_dir = None;
342                self.error.clear();
343            } else {
344                self.history.push(prev);
345            }
346        }
347    }
348
349    fn forward_go(&mut self, store: &dyn ModelStore) {
350        if let Some(next) = self.forward.pop() {
351            let current = store.browser_location();
352            if store.browser_navigate(&next).is_ok() {
353                self.history.push(current);
354                self.selected = None;
355                self.selected_dir = None;
356                self.error.clear();
357            } else {
358                self.forward.push(next);
359            }
360        }
361    }
362
363    // --- top navigation bar: back/forward/up + breadcrumb + new folder --------
364
365    fn show_nav_bar(
366        &mut self,
367        ui: &mut egui::Ui,
368        store: &dyn ModelStore,
369        location: &str,
370        options: FileExplorerOptions<'_>,
371        out: &mut FileExplorerOutput,
372    ) {
373        ui.horizontal(|ui| {
374            let back = ui.add_enabled(!self.history.is_empty(), egui::Button::new("\u{25C0}").small()
375                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
376            out.hits.push((format!("{}:back", options.hit_prefix), back.rect));
377            if back.clicked() {
378                self.back(store);
379            }
380            let fwd = {
381            let b = crate::icon_text::icon_button(ui, "\u{25B6}").small()
382                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO));
383            ui.add_enabled(!self.forward.is_empty(), b)
384        };
385            out.hits.push((format!("{}:forward", options.hit_prefix), fwd.rect));
386            if fwd.clicked() {
387                self.forward_go(store);
388            }
389            let up = ui.add(egui::Button::new("\u{2191}").small()
390                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
391            out.hits.push((format!("{}:up", options.hit_prefix), up.rect));
392            if up.clicked() {
393                self.nav(store, || store.browser_up());
394            }
395            ui.separator();
396            self.show_breadcrumb(ui, store, location, options, out);
397        });
398        ui.horizontal(|ui| {
399            let create = ui.add(egui::Button::new("+ Folder").small()
400                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
401            out.hits
402                .push((format!("{}:new-folder", options.hit_prefix), create.rect));
403            let field = ui.add(
404                egui::TextEdit::singleline(&mut self.new_folder).margin(crate::viewport::touch::text_edit_margin(ui))
405                    .hint_text("New folder")
406                    .desired_width(140.0)
407                    .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)),
408            );
409            out.hits
410                .push((format!("{}:new-folder-name", options.hit_prefix), field.rect));
411            let submit = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
412            if (create.clicked() || submit) && !self.new_folder.trim().is_empty() {
413                match store.browser_create_dir(self.new_folder.trim()) {
414                    Ok(()) => {
415                        self.new_folder.clear();
416                        self.error.clear();
417                    }
418                    Err(error) => self.error = error,
419                }
420            }
421        });
422    }
423
424    /// Either a clickable breadcrumb (each ancestor navigates) with a pencil
425    /// toggle, or — while editing — a path field that navigates on Enter.
426    fn show_breadcrumb(
427        &mut self,
428        ui: &mut egui::Ui,
429        store: &dyn ModelStore,
430        location: &str,
431        options: FileExplorerOptions<'_>,
432        out: &mut FileExplorerOutput,
433    ) {
434        if self.editing_path.is_some() {
435            let mut buf = self.editing_path.take().unwrap();
436            let resp = ui.add(
437                egui::TextEdit::singleline(&mut buf).margin(crate::viewport::touch::text_edit_margin(ui))
438                    .hint_text("type a path, Enter to go")
439                    .desired_width(300.0),
440            );
441            out.hits
442                .push((format!("{}:path-edit", options.hit_prefix), resp.rect));
443            if self.path_focus {
444                resp.request_focus();
445                self.path_focus = false;
446            }
447            let go = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
448            if go {
449                self.nav(store, || store.browser_navigate(&buf));
450            } else if !resp.lost_focus() {
451                self.editing_path = Some(buf); // still editing
452            }
453            // lost focus without Enter → cancel (editing_path stays None)
454            return;
455        }
456        // The pencil comes FIRST, outside the crumbs' scroll area: at the end of
457        // a long path it sat past the dialog's right edge (x = 1910 in a
458        // 1400-wide window), where no one could press it.
459        let edit = ui.add(crate::icon_text::icon_button(ui, "\u{270E}").small()
460            .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO))); // ✎
461        out.hits
462            .push((format!("{}:path-edit-toggle", options.hit_prefix), edit.rect));
463        if edit.on_hover_text("Type a path").clicked() {
464            self.editing_path = Some(location.to_string());
465            self.path_focus = true;
466        }
467        let avail = ui.available_width();
468        egui::ScrollArea::horizontal()
469            .id_salt(format!("{}-crumbs", options.hit_prefix))
470            .max_width(avail)
471            // Fill the row width (so a long path scrolls horizontally) but shrink
472            // to ONE row's height — `false` here would balloon vertically to the
473            // modal's huge available height and push the dialog off-screen.
474            .auto_shrink([false, true])
475            // The folder you are IN is the crumb that matters: a long path shows
476            // its tail, and scrolls back to its root.
477            .stick_to_right(true)
478            .show(ui, |ui| {
479                ui.horizontal(|ui| {
480                    for (i, (label, path)) in breadcrumb_segments(location).into_iter().enumerate() {
481                        if i > 0 {
482                            ui.weak("\u{203A}"); // ›
483                        }
484                        let seg = ui.add(egui::Button::new(label).frame(false).small()
485                            .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
486                        out.hits
487                            .push((format!("{}:crumb:{i}", options.hit_prefix), seg.rect));
488                        if seg.clicked() {
489                            self.nav(store, || store.browser_navigate(&path));
490                        }
491                    }
492                });
493            });
494    }
495
496    // --- left sidebar: places + pinned folders --------------------------------
497
498    #[allow(clippy::too_many_arguments)]
499    fn show_sidebar(
500        &mut self,
501        ui: &mut egui::Ui,
502        store: &dyn ModelStore,
503        places: &[BrowserPlace],
504        pins: &[String],
505        location: &str,
506        options: FileExplorerOptions<'_>,
507        out: &mut FileExplorerOutput,
508    ) {
509        ui.set_min_width(132.0);
510        ui.set_max_width(152.0);
511        egui::ScrollArea::vertical()
512            .id_salt(format!("{}-sidebar", options.hit_prefix))
513            .auto_shrink([false, false])
514            .show(ui, |ui| {
515                ui.weak("Places");
516                for place in places {
517                    let caption = format!("{} {}", place_glyph(place.kind), place.label);
518                    let resp = ui.add(sidebar_row(ui, &caption));
519                    out.hits
520                        .push((format!("{}:place:{}", options.hit_prefix, place.label), resp.rect));
521                    if resp.clicked() {
522                        let loc = place.location.clone();
523                        self.nav(store, || store.browser_navigate(&loc));
524                        self.after_touch_place(ui);
525                    }
526                }
527                if !pins.is_empty() {
528                    ui.add_space(6.0);
529                    ui.weak("Pinned");
530                    for pin in pins {
531                        ui.horizontal(|ui| {
532                            let label = pin.rsplit(['/', '\\']).find(|s| !s.is_empty()).unwrap_or(pin);
533                            let caption = format!("{PIN_GLYPH} {label}");
534                            let resp = ui.add(sidebar_row(ui, &caption));
535                            out.hits
536                                .push((format!("{}:pin:{label}", options.hit_prefix), resp.rect));
537                            if resp.clicked() {
538                                let loc = pin.clone();
539                                self.nav(store, || store.browser_navigate(&loc));
540                                self.after_touch_place(ui);
541                            }
542                            let x = {
543                                let b = crate::icon_text::icon_button(ui, "\u{2715}").small();
544                                ui.add(b)
545                            };
546                            out.hits
547                                .push((format!("{}:unpin:{label}", options.hit_prefix), x.rect));
548                            if x.clicked() {
549                                Self::set_pin(store, pin, false);
550                            }
551                        });
552                    }
553                }
554                ui.add_space(6.0);
555                let pinned_now = pins.iter().any(|p| p == location);
556                let label = if pinned_now { "\u{2715} Unpin folder" } else { "Pin folder" };
557                let btn = ui.add(crate::icon_text::icon_button(ui, label).small());
558                out.hits
559                    .push((format!("{}:pin-current", options.hit_prefix), btn.rect));
560                if btn.clicked() {
561                    Self::set_pin(store, location, !pinned_now);
562                }
563            });
564    }
565
566    /// A finger tapped a place or a pin: on a phone the sidebar is the Places
567    /// MENU, which a navigation must close (it stayed open over the folder it
568    /// had just opened), and the tap's double-tap twin must not land on the
569    /// list row behind it.
570    fn after_touch_place(&mut self, ui: &egui::Ui) {
571        if crate::viewport::touch::enabled(ui.ctx()) {
572            self.touch_nav_at = Some(ui.input(|i| i.time));
573            if crate::viewport::touch::compact(ui.ctx()) {
574                ui.close();
575            }
576        }
577    }
578
579    /// Read the pinned-locations list (a JSON array under the reserved key).
580    fn read_pins(store: &dyn ModelStore) -> Vec<String> {
581        store
582            .read(PINNED_KEY)
583            .and_then(|raw| serde_json::from_str::<Vec<String>>(&raw).ok())
584            .unwrap_or_default()
585    }
586
587    /// Add or remove `location` from the pinned list, persisting the result.
588    fn set_pin(store: &dyn ModelStore, location: &str, want: bool) {
589        let mut pins = Self::read_pins(store);
590        let has = pins.iter().any(|p| p == location);
591        if want && !has {
592            pins.push(location.to_string());
593        } else if !want && has {
594            pins.retain(|p| p != location);
595        } else {
596            return;
597        }
598        let _ = store.write(
599            PINNED_KEY,
600            &serde_json::to_string(&pins).unwrap_or_else(|_| "[]".into()),
601        );
602    }
603
604    // --- central file list ----------------------------------------------------
605
606    fn show_list(
607        &mut self,
608        ui: &mut egui::Ui,
609        entries: &[BrowserEntry],
610        options: FileExplorerOptions<'_>,
611        out: &mut FileExplorerOutput,
612    ) {
613        // Header row: hidden toggle (left) + filter (right).
614        if !crate::viewport::touch::compact(ui.ctx()) { ui.horizontal(|ui| {
615            let hidden = ui.checkbox(&mut self.show_hidden, "Hidden");
616            out.hits
617                .push((format!("{}:hidden-toggle", options.hit_prefix), hidden.rect));
618            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
619                let search = ui.add(
620                    egui::TextEdit::singleline(&mut self.query).margin(crate::viewport::touch::text_edit_margin(ui))
621                        .hint_text("Filter files")
622                        .desired_width(150.0),
623                );
624                out.hits
625                    .push((format!("{}:filter", options.hit_prefix), search.rect));
626            });
627        }); }
628
629        let query = self.query.trim().to_ascii_lowercase();
630        // Each name lowercased ONCE, for the filter and the sort: lowercasing
631        // both names in every comparison was ~130,000 allocations a frame for
632        // a 5,000-part PLM folder, while the dialog sat open.
633        let mut named: Vec<(String, &BrowserEntry)> = entries
634            .iter()
635            .filter_map(|entry| {
636                // Dotfiles hide unless toggled on; the filter box applies to files.
637                let hidden = entry.name.starts_with('.');
638                let lower = entry.name.to_ascii_lowercase();
639                ((self.show_hidden || !hidden) && (entry.is_dir || query.is_empty() || lower.contains(&query))).then_some((lower, entry))
640            })
641            .collect();
642        // Directories always first; within each group, by the active column.
643        let (key, desc) = (self.sort_key, self.sort_desc);
644        named.sort_by(|(a_name, a), (b_name, b)| {
645            b.is_dir.cmp(&a.is_dir).then_with(|| {
646                let by_name = || a_name.cmp(b_name);
647                let ord = match key {
648                    SortKey::Name => by_name(),
649                    SortKey::Kind => entry_kind(a).cmp(&entry_kind(b)).then_with(by_name),
650                    SortKey::Size => a.size.unwrap_or(0).cmp(&b.size.unwrap_or(0)).then_with(by_name),
651                    SortKey::Date => cmp_opt(a.modified, b.modified).then_with(by_name),
652                };
653                if desc { ord.reverse() } else { ord }
654            })
655        });
656        let visible: Vec<&BrowserEntry> = named.into_iter().map(|(_, entry)| entry).collect();
657        self.nav_rows = visible
658            .iter()
659            .map(|entry| (entry.identity.clone(), entry.is_dir))
660            .collect();
661
662        if visible.is_empty() {
663            ui.separator();
664            ui.weak(options.empty_label);
665            return;
666        }
667
668        if crate::viewport::touch::compact(ui.ctx()) {
669            let sort = ui.menu_button("Sort", |ui| {
670                for (label, key) in [("Name", SortKey::Name), ("Type", SortKey::Kind), ("Size", SortKey::Size), ("Date", SortKey::Date)] {
671                    if ui.selectable_label(self.sort_key == key, label).clicked() {
672                        if self.sort_key == key { self.sort_desc = !self.sort_desc; }
673                        else { self.sort_key = key; self.sort_desc = false; }
674                        ui.close();
675                    }
676                }
677            });
678            out.hits.push((format!("{}:sort-menu", options.hit_prefix), sort.response.rect));
679            let row_h = crate::viewport::touch::target_size(ui.ctx(), egui::vec2(0.0, egui::TextStyle::Body.resolve(ui.style()).size + 6.0)).y;
680            egui::ScrollArea::vertical().id_salt(format!("{}-compact-list", options.hit_prefix)).show(ui, |ui| {
681                for entry in visible {
682                    ui.horizontal(|ui| {
683                        let icon = if entry.is_dir { "\u{1F5C0}" } else { options.row_icon };
684                        let highlight = self.row_highlight(entry, options.current);
685                        let deletable = options.allow_delete && !entry.is_dir;
686                        let width = (ui.available_width() - if deletable { 44.0 + ui.spacing().item_spacing.x } else { 0.0 }).max(44.0);
687                        let text = format!("{icon} {}", entry.name);
688                        let r = ui.add_sized([width, row_h], crate::icon_text::icon_button(ui, &text).selected(highlight).truncate());
689                        out.hits.push((format!("{}:{}", options.hit_prefix, entry.name), r.rect));
690                        self.row_clicked(&r, entry, out);
691                        if deletable {
692                            let delete = ui.add(crate::icon_text::icon_button(ui, "\u{2715}").small()
693                                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
694                            out.hits.push((format!("del:{}", entry.name), delete.rect));
695                            if delete.clicked() { out.remove = Some(entry.identity.clone()); }
696                        }
697                    });
698                }
699            });
700            return;
701        }
702
703        // The PRIMARY layout: a sortable Name / Type / Size / Date table whose
704        // body scrolls inside the height the host left us. Header cells toggle
705        // the sort.
706        let row_h = egui::TextStyle::Body.resolve(ui.style()).size + 6.0;
707        let mut clicked_sort: Option<SortKey> = None;
708        // The WHOLE ROW is the click target: every cell senses clicks and the
709        // row's union response selects / activates. Only the delete button is
710        // interactive on top of it, so it keeps its own click. Labels must not
711        // be text-selectable here, or a selectable label would take the click
712        // (egui's default `selectable_labels` senses click-and-drag).
713        ui.scope(|ui| {
714        ui.style_mut().interaction.selectable_labels = false;
715        TableBuilder::new(ui)
716            .id_salt(format!("{}-table", options.hit_prefix))
717            .striped(true)
718            .sense(egui::Sense::click())
719            .cell_layout(egui::Layout::left_to_right(egui::Align::Center))
720            .column(Column::remainder().at_least(150.0).clip(true)) // Name
721            .column(Column::auto().at_least(72.0)) // Type
722            .column(Column::auto().at_least(66.0)) // Size
723            .column(Column::auto().at_least(120.0)) // Date
724            .column(Column::auto().at_least(20.0)) // delete
725            .header(row_h, |mut header| {
726                for (label, col) in [
727                    ("Name", SortKey::Name),
728                    ("Type", SortKey::Kind),
729                    ("Size", SortKey::Size),
730                    ("Date", SortKey::Date),
731                ] {
732                    header.col(|ui| {
733                        let arrow = if key == col {
734                            if desc {
735                                " \u{25BE}"
736                            } else {
737                                " \u{25B4}"
738                            }
739                        } else {
740                            ""
741                        };
742                        let btn =
743                            ui.add(egui::Button::new(format!("{label}{arrow}")).frame(false));
744                        out.hits.push((
745                            format!("{}:sort:{}", options.hit_prefix, sort_slug(col)),
746                            btn.rect,
747                        ));
748                        if btn.clicked() {
749                            clicked_sort = Some(col);
750                        }
751                    });
752                }
753                header.col(|_ui| {});
754            })
755            .body(|body| {
756                body.rows(row_h, visible.len(), |mut row| {
757                    let entry = visible[row.index()];
758                    let icon = if entry.is_dir {
759                        "\u{1F5C0}"
760                    } else {
761                        options.row_icon
762                    };
763                    row.set_selected(self.row_highlight(entry, options.current));
764                    let prefix = options.hit_prefix;
765                    let (name_rect, _) = row.col(|ui| {
766                        crate::icon_text::IconText::new(format!("{icon} {}", entry.name))
767                            .selectable(false)
768                            .truncate()
769                            .show(ui);
770                    });
771                    out.hits.push((format!("{prefix}:{}", entry.name), name_rect));
772                    let cells = [
773                        ("type", entry_kind(entry)),
774                        ("size", fmt_size(entry.size)),
775                        ("date", fmt_date(entry.modified)),
776                    ];
777                    for (slug, text) in cells {
778                        let (rect, _) = row.col(|ui| {
779                            ui.add(egui::Label::new(egui::RichText::new(text).weak()).selectable(false));
780                        });
781                        out.hits.push((format!("{prefix}:cell:{slug}:{}", entry.name), rect));
782                    }
783                    // The row's click is read BEFORE the delete cell joins the
784                    // union: a click on the delete button is the button's alone.
785                    let clicked_row = row.response();
786                    row.col(|ui| {
787                        if options.allow_delete && !entry.is_dir {
788                            let del = {
789                                let b = crate::icon_text::icon_button(ui, "\u{2715}").small();
790                                ui.add(b)
791                            };
792                            out.hits.push((format!("del:{}", entry.name), del.rect));
793                            if del.clicked() {
794                                out.remove = Some(entry.identity.clone());
795                            }
796                        }
797                    });
798                    self.row_clicked(&clicked_row, entry, out);
799                });
800            });
801        });
802        if let Some(col) = clicked_sort {
803            if self.sort_key == col {
804                self.sort_desc = !self.sort_desc;
805            } else {
806                self.sort_key = col;
807                self.sort_desc = false;
808            }
809        }
810    }
811
812    /// Whether `entry`'s row shows highlighted: the selected file or folder;
813    /// before the user picks a row, the caller's `current` document.
814    fn row_highlight(&self, entry: &BrowserEntry, current: Option<&str>) -> bool {
815        let id = entry.identity.as_str();
816        if entry.is_dir {
817            self.selected_dir.as_deref() == Some(id)
818        } else {
819            match &self.selected {
820                Some(sel) => sel == id,
821                None => self.selected_dir.is_none() && current == Some(id),
822            }
823        }
824    }
825
826    /// A row's click: a double click activates (opens a file, enters a
827    /// folder), a single click only selects. The double-click test comes
828    /// first because its second press also reports `clicked()`.
829    ///
830    /// Under a finger (on a phone, tapping the home folder did not open it)
831    /// a double TAP rarely reads as a double click (time and
832    /// travel limits), so one tap on a folder enters it, and one tap on a file
833    /// selects it for the footer's Open; a double tap opens a file only once it
834    /// is the selected one. Row taps within a double tap's span of a tap that
835    /// changed the folder are ignored ([`Self::touch_nav_at`]).
836    fn row_clicked(&mut self, response: &egui::Response, entry: &BrowserEntry, out: &mut FileExplorerOutput) {
837        if crate::viewport::touch::enabled(&response.ctx) {
838            if !response.clicked() {
839                return;
840            }
841            let now = response.ctx.input(|i| i.time);
842            if double_tap_twin(&response.ctx, self.touch_nav_at, self.last_press_at) {
843                return;
844            }
845            if entry.is_dir {
846                self.activate(&entry.identity, true, out);
847                self.touch_nav_at = Some(now);
848            } else if response.double_clicked() && self.selected.as_deref() == Some(entry.identity.as_str()) {
849                self.activate(&entry.identity, false, out);
850            } else {
851                self.select(&entry.identity, false);
852                out.picked = Some(entry.identity.clone());
853            }
854            return;
855        }
856        if response.double_clicked() {
857            self.activate(&entry.identity, entry.is_dir, out);
858        } else if response.clicked() {
859            self.select(&entry.identity, entry.is_dir);
860            if !entry.is_dir {
861                out.picked = Some(entry.identity.clone());
862            }
863        }
864    }
865
866    /// Keyboard navigation over the visible rows: ↑/↓ move the selection
867    /// (folders and files alike), Enter activates it (opens the file, enters
868    /// the folder). Active only when the caller offers a confirm action and no
869    /// text field (filter / name / path) holds focus, so typing is never
870    /// hijacked. Not in hosts without one (Save As, step-parts): their name
871    /// field submits on Enter as it loses focus, the same frame this would see
872    /// the key, and an explorer Enter there would overwrite the typed name or
873    /// walk into a folder before the save.
874    fn handle_keys(
875        &mut self,
876        ui: &egui::Ui,
877        options: FileExplorerOptions<'_>,
878        out: &mut FileExplorerOutput,
879    ) {
880        if options.confirm_label.is_none() || ui.ctx().egui_wants_keyboard_input() {
881            return;
882        }
883        if self.nav_rows.is_empty() {
884            return;
885        }
886        let (down, up, enter) = ui.input(|i| {
887            (
888                i.key_pressed(egui::Key::ArrowDown),
889                i.key_pressed(egui::Key::ArrowUp),
890                i.key_pressed(egui::Key::Enter),
891            )
892        });
893        if down || up {
894            let held = self.selected.as_deref().or(self.selected_dir.as_deref());
895            let current = held.and_then(|s| self.nav_rows.iter().position(|(id, _)| id == s));
896            let next = match current {
897                Some(i) if down => (i + 1).min(self.nav_rows.len() - 1),
898                Some(i) => i.saturating_sub(1),
899                None => 0,
900            };
901            let (id, is_dir) = self.nav_rows[next].clone();
902            self.select(&id, is_dir);
903            if !is_dir {
904                out.picked = Some(id);
905            }
906        } else if enter {
907            if let Some(dir) = self.selected_dir.clone() {
908                self.enter_dir = Some(dir);
909            } else if let Some(sel) = &self.selected {
910                out.activated = Some(sel.clone());
911            }
912        }
913    }
914
915    fn show_footer(
916        &mut self,
917        ui: &mut egui::Ui,
918        options: FileExplorerOptions<'_>,
919        out: &mut FileExplorerOutput,
920    ) {
921        ui.separator();
922        ui.horizontal(|ui| {
923            if let Some(label) = options.confirm_label {
924                let any = self.selected.is_some() || self.selected_dir.is_some();
925                // Under a finger the confirm is how a tapped file opens (a tap
926                // only selects it), so it is drawn as the primary action.
927                let touch = crate::viewport::touch::enabled(ui.ctx());
928                let button = if touch && any {
929                    egui::Button::new(egui::RichText::new(label).strong().color(ui.visuals().selection.stroke.color))
930                        .fill(ui.visuals().selection.bg_fill)
931                } else {
932                    egui::Button::new(label)
933                };
934                let confirm = ui.add_enabled(any, button.min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
935                out.hits
936                    .push((format!("{}:confirm", options.hit_prefix), confirm.rect));
937                if confirm.clicked() {
938                    // With a folder selected the confirm button walks into it.
939                    if let Some(dir) = self.selected_dir.clone() {
940                        self.enter_dir = Some(dir);
941                    } else {
942                        out.activated = self.selected.clone();
943                    }
944                }
945            }
946            if options.allow_import {
947                let import = {
948                let label = format!("\u{2B06} {}", options.import_label);
949                let b = crate::icon_text::icon_button(ui, &label);
950                ui.add(b)
951            };
952                out.hits.push((options.import_hit.into(), import.rect));
953                out.import = import.clicked();
954            }
955            if options.show_cancel {
956                let cancel = ui.button("Cancel");
957                out.hits.push(("cancel".into(), cancel.rect));
958                out.cancel = cancel.clicked();
959            }
960            // Selection preview (bare file name), right-aligned.
961            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
962                if let Some(sel) = self.selected.as_ref().or(self.selected_dir.as_ref()) {
963                    let name = sel.rsplit(['/', '\\']).next().unwrap_or(sel);
964                    // Truncated: the preview is the LAST thing on the footer row,
965                    // so a long file name laid out at its natural width runs left
966                    // across the Import / Cancel buttons it is meant to sit beside.
967                    ui.add(
968                        egui::Label::new(egui::RichText::new(name).weak()).truncate(),
969                    );
970                }
971            });
972        });
973    }
974
975}
976
977/// Wrap a file dialog's WHOLE body — heading, browser, footer and all — in the
978/// shared resizable frame. The drag grip therefore lands at the dialog WINDOW's
979/// bottom-right corner instead of around the file table, and dragging it grows
980/// the dialog itself in both axes, capped to the viewport so it can never grow
981/// off-screen. One shared id means resizing any file dialog resizes them all.
982///
983/// Only for MODAL hosts: an [`egui::Window`] already carries its own corner
984/// grip, and a second frame inside it would put back exactly the handle this
985/// removes.
986pub fn dialog_body<R>(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
987    let screen = ui.ctx().content_rect().size();
988    let compact = crate::viewport::touch::compact(ui.ctx());
989    let max = if compact { (screen - egui::Vec2::splat(24.0)).max(egui::Vec2::splat(80.0)) }
990        else { egui::vec2((screen.x - 40.0).max(320.0), (screen.y - 80.0).max(240.0)) };
991    egui::Resize::default()
992        .id_salt(if compact { "brep-file-dialog-size-mobile" } else { "brep-file-dialog-size" })
993        // The modal frame already draws the dialog's border; the resize region
994        // fills it exactly, so its own stroke would only double it up.
995        .with_stroke(false)
996        .min_size(egui::vec2(460.0_f32.min(max.x), 300.0_f32.min(max.y)))
997        .max_size(max)
998        .default_size(egui::vec2(620.0_f32.min(max.x), 520.0_f32.min(max.y)))
999        .show(ui, add_contents)
1000}
1001
1002/// Pin a dialog's own trailing widgets — a status line, a name field, the
1003/// action buttons — to the BOTTOM of the dialog. Call it BEFORE
1004/// [`FileExplorer::show_store`]: the explorer then fills the gap that is left,
1005/// which is what keeps the buttons still while the file list scrolls. `salt`
1006/// distinguishes one dialog's footer from another's (two can be on screen at
1007/// once), and the widgets inside are drawn top-down in the order written.
1008pub fn dialog_footer<R>(
1009    ui: &mut egui::Ui,
1010    salt: &str,
1011    add_contents: impl FnOnce(&mut egui::Ui) -> R,
1012) -> R {
1013    bottom_panel(ui, "brep-file-dialog-footer", salt, add_contents)
1014}
1015
1016/// The one bottom-pinned strip both footers use: no frame and no separator line
1017/// of its own, so it reads as part of the dialog rather than as a panel, and it
1018/// takes exactly the height its contents need.
1019fn bottom_panel<R>(
1020    ui: &mut egui::Ui,
1021    base: &str,
1022    salt: &str,
1023    add_contents: impl FnOnce(&mut egui::Ui) -> R,
1024) -> R {
1025    egui::containers::panel::Panel::bottom(egui::Id::new((base, salt)))
1026        .frame(egui::Frame::NONE)
1027        .show_separator_line(false)
1028        .show(ui, add_contents)
1029        .inner
1030}
1031
1032/// Order two optional timestamps, sorting `None` (unknown, e.g. web) last.
1033fn cmp_opt(a: Option<f64>, b: Option<f64>) -> Ordering {
1034    match (a, b) {
1035        (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(Ordering::Equal),
1036        (Some(_), None) => Ordering::Less,
1037        (None, Some(_)) => Ordering::Greater,
1038        (None, None) => Ordering::Equal,
1039    }
1040}
1041
1042/// The Type column text for an entry (Folder / BREP model / extension / File).
1043fn entry_kind(entry: &BrowserEntry) -> String {
1044    if entry.is_dir {
1045        return "Folder".into();
1046    }
1047    let lower = entry.name.to_ascii_lowercase();
1048    if lower.ends_with(".nbrep") {
1049        return "BREP model".into();
1050    }
1051    match entry.name.rsplit_once('.') {
1052        Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() => ext.to_uppercase(),
1053        _ => "File".into(),
1054    }
1055}
1056
1057/// Stable slug for a sort column's hit key.
1058fn sort_slug(key: SortKey) -> &'static str {
1059    match key {
1060        SortKey::Name => "name",
1061        SortKey::Kind => "type",
1062        SortKey::Size => "size",
1063        SortKey::Date => "date",
1064    }
1065}
1066
1067/// Human-readable byte size, or an em-dash when the backend cannot report it.
1068fn fmt_size(size: Option<u64>) -> String {
1069    match size {
1070        None => "\u{2014}".into(),
1071        Some(bytes) => {
1072            let b = bytes as f64;
1073            if bytes < 1024 {
1074                format!("{bytes} B")
1075            } else if b < 1024.0 * 1024.0 {
1076                format!("{:.1} KB", b / 1024.0)
1077            } else if b < 1024.0 * 1024.0 * 1024.0 {
1078                format!("{:.1} MB", b / (1024.0 * 1024.0))
1079            } else {
1080                format!("{:.1} GB", b / (1024.0 * 1024.0 * 1024.0))
1081            }
1082        }
1083    }
1084}
1085
1086/// `YYYY-MM-DD HH:MM` (UTC) from whole Unix seconds, or an em-dash when unknown.
1087fn fmt_date(modified: Option<f64>) -> String {
1088    let Some(secs) = modified else {
1089        return "\u{2014}".into();
1090    };
1091    let days = (secs / 86_400.0).floor() as i64;
1092    let (y, m, d) = civil_from_days(days);
1093    let sod = ((secs as i64) % 86_400 + 86_400) % 86_400;
1094    format!("{y:04}-{m:02}-{d:02} {:02}:{:02}", sod / 3600, (sod % 3600) / 60)
1095}
1096
1097/// Gregorian `(year, month, day)` from a day count since the Unix epoch
1098/// (Howard Hinnant's `civil_from_days`) — pure integer arithmetic, so it is
1099/// wasm-safe and never touches `SystemTime`.
1100use brep_render::sheets::frame::civil_from_days;
1101
1102/// Split a POSIX-ish location into `(label, navigable-path)` breadcrumb segments,
1103/// starting at the root. e.g. `/home/me/models` →
1104/// `[("/", "/"), ("home", "/home"), ("me", "/home/me"), ("models", "/home/me/models")]`.
1105fn breadcrumb_segments(location: &str) -> Vec<(String, String)> {
1106    let mut out = vec![("/".to_string(), "/".to_string())];
1107    let mut acc = String::new();
1108    for comp in location.split('/').filter(|s| !s.is_empty()) {
1109        acc.push('/');
1110        acc.push_str(comp);
1111        out.push((comp.to_string(), acc.clone()));
1112    }
1113    out
1114}
1115
1116/// Whether the tap being reported is the second half of a double tap whose
1117/// first tap changed the folder at `nav_at`: it was pressed (`pressed_at`)
1118/// after that change and within egui's double-click delay of it, exactly what
1119/// egui would have counted as a double click. A later, deliberate tap is a tap.
1120pub(crate) fn double_tap_twin(ctx: &egui::Context, nav_at: Option<f64>, pressed_at: Option<f64>) -> bool {
1121    let delay = ctx.options(|o| o.input_options.max_double_click_delay);
1122    match (nav_at, pressed_at) {
1123        (Some(nav), Some(press)) => press >= nav && press - nav <= delay,
1124        _ => false,
1125    }
1126}
1127
1128/// The glyph a pinned folder's row draws: the Open command's folder artwork.
1129const PIN_GLYPH: &str = "\u{E011}";
1130
1131/// The glyph a sidebar place draws for its category — catalogued artwork
1132/// (`icons.rs`), drawn by [`sidebar_row`]. The plain characters these used to
1133/// be were partly missing from the UI font (🗀 and 📌 drew as empty boxes), and
1134/// Root drew "/" beside its label "/" (lane U audit item 12).
1135fn place_glyph(kind: PlaceKind) -> &'static str {
1136    match kind {
1137        PlaceKind::Home => "\u{2302}",      // ⌂ — the font draws it
1138        PlaceKind::Documents => "\u{1F5CE}", // 🗎 catalogued
1139        PlaceKind::Downloads => "\u{2B07}",  // ⬇ catalogued
1140        PlaceKind::Models | PlaceKind::Root => PIN_GLYPH,
1141    }
1142}
1143
1144/// A Places / Pinned row: the leading catalogued glyph as artwork, framed only
1145/// on hover — what `selectable_label(false, …)` drew, with the icon.
1146fn sidebar_row<'a>(ui: &egui::Ui, caption: &'a str) -> egui::Button<'a> {
1147    crate::icon_text::icon_button(ui, caption).frame_when_inactive(false)
1148}
1149