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