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(crate::ui_kit::Button::new("Up"));
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 = crate::ui_kit::checkbox(ui, &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 = crate::ui_kit::text_input(&mut self.query).placeholder("Filter files").width(filter_width).show(ui).framed();
260                out.hits.push((format!("{}:filter", options.hit_prefix), filter.rect));
261            });
262        } else { self.show_nav_bar(ui, store, &location, options, &mut out); }
263        if !self.error.is_empty() {
264            ui.colored_label(ui.visuals().error_fg_color, &self.error);
265        }
266        ui.add_space(2.0);
267        ui.separator();
268
269        // The explorer FILLS the region its host gave it — a modal's resizable
270        // body ([`dialog_body`]), a window's content — rather than carrying a
271        // resize handle of its own around the file table: the footer pins to the
272        // bottom (under anything the host already pinned there) and the browse
273        // area takes every pixel between it and the nav bar, so the file list is
274        // the only thing that scrolls.
275        bottom_panel(ui, "brep-file-explorer-footer", options.hit_prefix, |ui| {
276            self.show_footer(ui, options, &mut out)
277        });
278        if compact {
279            self.show_list(ui, &entries, options, &mut out);
280        } else { ui.horizontal_top(|ui| {
281            if !places.is_empty() {
282                ui.vertical(|ui| {
283                    self.show_sidebar(ui, store, &places, &pins, &location, options, &mut out);
284                });
285                ui.separator();
286            }
287            ui.vertical(|ui| {
288                self.show_list(ui, &entries, options, &mut out);
289            });
290        }); }
291
292        self.handle_keys(ui, options, &mut out);
293        // A folder activated this frame (double click, Enter, footer confirm)
294        // is entered only now, after the listing drew from the old location.
295        if let Some(dir) = self.enter_dir.take() {
296            self.nav(store, || store.browser_enter(&dir));
297            ui.ctx().request_repaint();
298        }
299        out.selected = self.selected.clone();
300        // The footer (and any host footer: a name field, a confirm button) was
301        // drawn BEFORE the row that just changed the highlight, so it is showing
302        // last frame's selection. Ask for one more frame rather than leaving a
303        // confirm button greyed out until the pointer happens to move again.
304        if out.picked.is_some() || (self.selected.clone(), self.selected_dir.clone()) != selected_before {
305            ui.ctx().request_repaint();
306        }
307        out
308    }
309
310    // --- navigation with history ---------------------------------------------
311
312    /// Run a navigation action and, when it actually changes location, record the
313    /// previous location on the back stack (clearing the forward stack) and drop
314    /// the file highlight. Shared by up / breadcrumb / place / enter-directory.
315    fn nav<F: FnOnce() -> Result<(), String>>(&mut self, store: &dyn ModelStore, action: F) {
316        let before = store.browser_location();
317        match action() {
318            Ok(()) => {
319                let after = store.browser_location();
320                if after != before {
321                    self.history.push(before);
322                    self.forward.clear();
323                }
324                self.error.clear();
325                self.selected = None;
326                self.selected_dir = None;
327            }
328            Err(error) => self.error = error,
329        }
330    }
331
332    /// Step back to the previous location, remembering the current one for
333    /// forward. A failed navigate restores the stack unchanged.
334    fn back(&mut self, store: &dyn ModelStore) {
335        if let Some(prev) = self.history.pop() {
336            let current = store.browser_location();
337            if store.browser_navigate(&prev).is_ok() {
338                self.forward.push(current);
339                self.selected = None;
340                self.selected_dir = None;
341                self.error.clear();
342            } else {
343                self.history.push(prev);
344            }
345        }
346    }
347
348    fn forward_go(&mut self, store: &dyn ModelStore) {
349        if let Some(next) = self.forward.pop() {
350            let current = store.browser_location();
351            if store.browser_navigate(&next).is_ok() {
352                self.history.push(current);
353                self.selected = None;
354                self.selected_dir = None;
355                self.error.clear();
356            } else {
357                self.forward.push(next);
358            }
359        }
360    }
361
362    // --- top navigation bar: back/forward/up + breadcrumb + new folder --------
363
364    fn show_nav_bar(
365        &mut self,
366        ui: &mut egui::Ui,
367        store: &dyn ModelStore,
368        location: &str,
369        options: FileExplorerOptions<'_>,
370        out: &mut FileExplorerOutput,
371    ) {
372        ui.horizontal(|ui| {
373            let back = ui.add(crate::ui_kit::Button::ghost("\u{25C0}").size(crate::ui_kit::Size::Sm).enabled(!self.history.is_empty()));
374            out.hits.push((format!("{}:back", options.hit_prefix), back.rect));
375            if back.clicked() {
376                self.back(store);
377            }
378            let fwd = {
379            let b = crate::icon_text::icon_button(ui, "\u{25B6}").small()
380                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO));
381            ui.add_enabled(!self.forward.is_empty(), b)
382        };
383            out.hits.push((format!("{}:forward", options.hit_prefix), fwd.rect));
384            if fwd.clicked() {
385                self.forward_go(store);
386            }
387            let up = ui.add(crate::ui_kit::Button::ghost("\u{2191}").size(crate::ui_kit::Size::Sm));
388            out.hits.push((format!("{}:up", options.hit_prefix), up.rect));
389            if up.clicked() {
390                self.nav(store, || store.browser_up());
391            }
392            ui.separator();
393            self.show_breadcrumb(ui, store, location, options, out);
394        });
395        ui.horizontal(|ui| {
396            let create = ui.add(crate::ui_kit::Button::new("+ Folder").size(crate::ui_kit::Size::Sm));
397            out.hits
398                .push((format!("{}:new-folder", options.hit_prefix), create.rect));
399            let field = crate::ui_kit::text_input(&mut self.new_folder).placeholder("New folder").width(140.0).show(ui).framed();
400            out.hits
401                .push((format!("{}:new-folder-name", options.hit_prefix), field.rect));
402            let submit = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
403            if (create.clicked() || submit) && !self.new_folder.trim().is_empty() {
404                match store.browser_create_dir(self.new_folder.trim()) {
405                    Ok(()) => {
406                        self.new_folder.clear();
407                        self.error.clear();
408                    }
409                    Err(error) => self.error = error,
410                }
411            }
412        });
413    }
414
415    /// Either a clickable breadcrumb (each ancestor navigates) with a pencil
416    /// toggle, or — while editing — a path field that navigates on Enter.
417    fn show_breadcrumb(
418        &mut self,
419        ui: &mut egui::Ui,
420        store: &dyn ModelStore,
421        location: &str,
422        options: FileExplorerOptions<'_>,
423        out: &mut FileExplorerOutput,
424    ) {
425        if self.editing_path.is_some() {
426            let mut buf = self.editing_path.take().unwrap();
427            let resp = crate::ui_kit::text_input(&mut buf).placeholder("type a path, Enter to go").width(300.0).show(ui).framed();
428            out.hits
429                .push((format!("{}:path-edit", options.hit_prefix), resp.rect));
430            if self.path_focus {
431                resp.request_focus();
432                self.path_focus = false;
433            }
434            let go = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
435            if go {
436                self.nav(store, || store.browser_navigate(&buf));
437            } else if !resp.lost_focus() {
438                self.editing_path = Some(buf); // still editing
439            }
440            // lost focus without Enter → cancel (editing_path stays None)
441            return;
442        }
443        // The pencil comes FIRST, outside the crumbs' scroll area: at the end of
444        // a long path it sat past the dialog's right edge (x = 1910 in a
445        // 1400-wide window), where no one could press it.
446        let edit = ui.add(crate::icon_text::icon_button(ui, "\u{270E}").small()
447            .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO))); // ✎
448        out.hits
449            .push((format!("{}:path-edit-toggle", options.hit_prefix), edit.rect));
450        if edit.on_hover_text("Type a path").clicked() {
451            self.editing_path = Some(location.to_string());
452            self.path_focus = true;
453        }
454        let avail = ui.available_width();
455        egui::ScrollArea::horizontal()
456            .id_salt(format!("{}-crumbs", options.hit_prefix))
457            .max_width(avail)
458            // Fill the row width (so a long path scrolls horizontally) but shrink
459            // to ONE row's height — `false` here would balloon vertically to the
460            // modal's huge available height and push the dialog off-screen.
461            .auto_shrink([false, true])
462            // The folder you are IN is the crumb that matters: a long path shows
463            // its tail, and scrolls back to its root.
464            .stick_to_right(true)
465            .show(ui, |ui| {
466                ui.horizontal(|ui| {
467                    for (i, (label, path)) in breadcrumb_segments(location).into_iter().enumerate() {
468                        if i > 0 {
469                            ui.weak("\u{203A}"); // ›
470                        }
471                        let seg = ui.add(crate::ui_kit::Button::ghost(&label).size(crate::ui_kit::Size::Sm));
472                        out.hits
473                            .push((format!("{}:crumb:{i}", options.hit_prefix), seg.rect));
474                        if seg.clicked() {
475                            self.nav(store, || store.browser_navigate(&path));
476                        }
477                    }
478                });
479            });
480    }
481
482    // --- left sidebar: places + pinned folders --------------------------------
483
484    #[allow(clippy::too_many_arguments)]
485    fn show_sidebar(
486        &mut self,
487        ui: &mut egui::Ui,
488        store: &dyn ModelStore,
489        places: &[BrowserPlace],
490        pins: &[String],
491        location: &str,
492        options: FileExplorerOptions<'_>,
493        out: &mut FileExplorerOutput,
494    ) {
495        ui.set_min_width(132.0);
496        ui.set_max_width(152.0);
497        egui::ScrollArea::vertical()
498            .id_salt(format!("{}-sidebar", options.hit_prefix))
499            .auto_shrink([false, false])
500            .show(ui, |ui| {
501                ui.weak("Places");
502                for place in places {
503                    let caption = format!("{} {}", place_glyph(place.kind), place.label);
504                    let resp = ui.scope(|ui| { crate::theme::data_rows(ui); ui.add(sidebar_row(ui, &caption)) }).inner;
505                    out.hits
506                        .push((format!("{}:place:{}", options.hit_prefix, place.label), resp.rect));
507                    if resp.clicked() {
508                        let loc = place.location.clone();
509                        self.nav(store, || store.browser_navigate(&loc));
510                        self.after_touch_place(ui);
511                    }
512                }
513                if !pins.is_empty() {
514                    ui.add_space(6.0);
515                    ui.weak("Pinned");
516                    for pin in pins {
517                        ui.horizontal(|ui| {
518                            let label = pin.rsplit(['/', '\\']).find(|s| !s.is_empty()).unwrap_or(pin);
519                            let caption = format!("{PIN_GLYPH} {label}");
520                            let resp = ui.scope(|ui| { crate::theme::data_rows(ui); ui.add(sidebar_row(ui, &caption)) }).inner;
521                            out.hits
522                                .push((format!("{}:pin:{label}", options.hit_prefix), resp.rect));
523                            if resp.clicked() {
524                                let loc = pin.clone();
525                                self.nav(store, || store.browser_navigate(&loc));
526                                self.after_touch_place(ui);
527                            }
528                            let x = {
529                                let b = crate::icon_text::icon_button(ui, "\u{2715}").small();
530                                ui.add(b)
531                            };
532                            out.hits
533                                .push((format!("{}:unpin:{label}", options.hit_prefix), x.rect));
534                            if x.clicked() {
535                                Self::set_pin(store, pin, false);
536                            }
537                        });
538                    }
539                }
540                ui.add_space(6.0);
541                let pinned_now = pins.iter().any(|p| p == location);
542                let label = if pinned_now { "\u{2715} Unpin folder" } else { "Pin folder" };
543                let btn = ui.add(crate::icon_text::icon_button(ui, label).small());
544                out.hits
545                    .push((format!("{}:pin-current", options.hit_prefix), btn.rect));
546                if btn.clicked() {
547                    Self::set_pin(store, location, !pinned_now);
548                }
549            });
550    }
551
552    /// A finger tapped a place or a pin: on a phone the sidebar is the Places
553    /// MENU, which a navigation must close (it stayed open over the folder it
554    /// had just opened), and the tap's double-tap twin must not land on the
555    /// list row behind it.
556    fn after_touch_place(&mut self, ui: &egui::Ui) {
557        if crate::viewport::touch::enabled(ui.ctx()) {
558            self.touch_nav_at = Some(ui.input(|i| i.time));
559            if crate::viewport::touch::compact(ui.ctx()) {
560                ui.close();
561            }
562        }
563    }
564
565    /// Read the pinned-locations list (a JSON array under the reserved key).
566    fn read_pins(store: &dyn ModelStore) -> Vec<String> {
567        store
568            .read(PINNED_KEY)
569            .and_then(|raw| serde_json::from_str::<Vec<String>>(&raw).ok())
570            .unwrap_or_default()
571    }
572
573    /// Add or remove `location` from the pinned list, persisting the result.
574    fn set_pin(store: &dyn ModelStore, location: &str, want: bool) {
575        let mut pins = Self::read_pins(store);
576        let has = pins.iter().any(|p| p == location);
577        if want && !has {
578            pins.push(location.to_string());
579        } else if !want && has {
580            pins.retain(|p| p != location);
581        } else {
582            return;
583        }
584        let _ = store.write(
585            PINNED_KEY,
586            &serde_json::to_string(&pins).unwrap_or_else(|_| "[]".into()),
587        );
588    }
589
590    // --- central file list ----------------------------------------------------
591
592    fn show_list(
593        &mut self,
594        ui: &mut egui::Ui,
595        entries: &[BrowserEntry],
596        options: FileExplorerOptions<'_>,
597        out: &mut FileExplorerOutput,
598    ) {
599        // Header row: hidden toggle (left) + filter (right).
600        if !crate::viewport::touch::compact(ui.ctx()) { ui.horizontal(|ui| {
601            let hidden = crate::ui_kit::checkbox(ui, &mut self.show_hidden, "Hidden");
602            out.hits
603                .push((format!("{}:hidden-toggle", options.hit_prefix), hidden.rect));
604            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
605                let search = crate::ui_kit::text_input(&mut self.query).placeholder("Filter files").width(150.0).show(ui).framed();
606                out.hits
607                    .push((format!("{}:filter", options.hit_prefix), search.rect));
608            });
609        }); }
610
611        let query = self.query.trim().to_ascii_lowercase();
612        // Each name lowercased ONCE, for the filter and the sort: lowercasing
613        // both names in every comparison was ~130,000 allocations a frame for
614        // a 5,000-part PLM folder, while the dialog sat open.
615        let mut named: Vec<(String, &BrowserEntry)> = entries
616            .iter()
617            .filter_map(|entry| {
618                // Dotfiles hide unless toggled on; the filter box applies to files.
619                let hidden = entry.name.starts_with('.');
620                let lower = entry.name.to_ascii_lowercase();
621                ((self.show_hidden || !hidden) && (entry.is_dir || query.is_empty() || lower.contains(&query))).then_some((lower, entry))
622            })
623            .collect();
624        // Directories always first; within each group, by the active column.
625        let (key, desc) = (self.sort_key, self.sort_desc);
626        named.sort_by(|(a_name, a), (b_name, b)| {
627            b.is_dir.cmp(&a.is_dir).then_with(|| {
628                let by_name = || a_name.cmp(b_name);
629                let ord = match key {
630                    SortKey::Name => by_name(),
631                    SortKey::Kind => entry_kind(a).cmp(&entry_kind(b)).then_with(by_name),
632                    SortKey::Size => a.size.unwrap_or(0).cmp(&b.size.unwrap_or(0)).then_with(by_name),
633                    SortKey::Date => cmp_opt(a.modified, b.modified).then_with(by_name),
634                };
635                if desc { ord.reverse() } else { ord }
636            })
637        });
638        let visible: Vec<&BrowserEntry> = named.into_iter().map(|(_, entry)| entry).collect();
639        self.nav_rows = visible
640            .iter()
641            .map(|entry| (entry.identity.clone(), entry.is_dir))
642            .collect();
643
644        if visible.is_empty() {
645            ui.separator();
646            ui.weak(options.empty_label);
647            return;
648        }
649
650        if crate::viewport::touch::compact(ui.ctx()) {
651            let sort = ui.menu_button("Sort", |ui| {
652                for (label, key) in [("Name", SortKey::Name), ("Type", SortKey::Kind), ("Size", SortKey::Size), ("Date", SortKey::Date)] {
653                    if ui.selectable_label(self.sort_key == key, label).clicked() {
654                        if self.sort_key == key { self.sort_desc = !self.sort_desc; }
655                        else { self.sort_key = key; self.sort_desc = false; }
656                        ui.close();
657                    }
658                }
659            });
660            out.hits.push((format!("{}:sort-menu", options.hit_prefix), sort.response.rect));
661            let row_h = crate::viewport::touch::target_size(ui.ctx(), egui::vec2(0.0, egui::TextStyle::Body.resolve(ui.style()).size + 6.0)).y;
662            egui::ScrollArea::vertical().id_salt(format!("{}-compact-list", options.hit_prefix)).show(ui, |ui| {
663                for entry in visible {
664                    ui.horizontal(|ui| {
665                        crate::theme::data_rows(ui);
666                        let icon = if entry.is_dir { "\u{1F5C0}" } else { options.row_icon };
667                        let highlight = self.row_highlight(entry, options.current);
668                        let deletable = options.allow_delete && !entry.is_dir;
669                        let width = (ui.available_width() - if deletable { 44.0 + ui.spacing().item_spacing.x } else { 0.0 }).max(44.0);
670                        let text = format!("{icon} {}", entry.name);
671                        let r = ui.add_sized([width, row_h], crate::icon_text::icon_button(ui, &text).selected(highlight).truncate());
672                        out.hits.push((format!("{}:{}", options.hit_prefix, entry.name), r.rect));
673                        self.row_clicked(&r, entry, out);
674                        if deletable {
675                            let delete = ui.add(crate::icon_text::icon_button(ui, "\u{2715}").small()
676                                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
677                            out.hits.push((format!("del:{}", entry.name), delete.rect));
678                            if delete.clicked() { out.remove = Some(entry.identity.clone()); }
679                        }
680                    });
681                }
682            });
683            return;
684        }
685
686        // The PRIMARY layout: a sortable Name / Type / Size / Date table whose
687        // body scrolls inside the height the host left us. Header cells toggle
688        // the sort.
689        let row_h = egui::TextStyle::Body.resolve(ui.style()).size + 6.0;
690        let mut clicked_sort: Option<SortKey> = None;
691        // The WHOLE ROW is the click target: every cell senses clicks and the
692        // row's union response selects / activates. Only the delete button is
693        // interactive on top of it, so it keeps its own click. Labels must not
694        // be text-selectable here, or a selectable label would take the click
695        // (egui's default `selectable_labels` senses click-and-drag).
696        ui.scope(|ui| {
697        ui.style_mut().interaction.selectable_labels = false;
698        TableBuilder::new(ui)
699            .id_salt(format!("{}-table", options.hit_prefix))
700            .striped(true)
701            .sense(egui::Sense::click())
702            .cell_layout(egui::Layout::left_to_right(egui::Align::Center))
703            .column(Column::remainder().at_least(150.0).clip(true)) // Name
704            .column(Column::auto().at_least(72.0)) // Type
705            .column(Column::auto().at_least(66.0)) // Size
706            .column(Column::auto().at_least(120.0)) // Date
707            .column(Column::auto().at_least(20.0)) // delete
708            .header(row_h, |mut header| {
709                for (label, col) in [
710                    ("Name", SortKey::Name),
711                    ("Type", SortKey::Kind),
712                    ("Size", SortKey::Size),
713                    ("Date", SortKey::Date),
714                ] {
715                    header.col(|ui| {
716                        let arrow = if key == col {
717                            if desc {
718                                " \u{25BE}"
719                            } else {
720                                " \u{25B4}"
721                            }
722                        } else {
723                            ""
724                        };
725                        let btn =
726                            ui.add(crate::ui_kit::Button::ghost(&format!("{label}{arrow}")));
727                        out.hits.push((
728                            format!("{}:sort:{}", options.hit_prefix, sort_slug(col)),
729                            btn.rect,
730                        ));
731                        if btn.clicked() {
732                            clicked_sort = Some(col);
733                        }
734                    });
735                }
736                header.col(|_ui| {});
737            })
738            .body(|body| {
739                body.rows(row_h, visible.len(), |mut row| {
740                    let entry = visible[row.index()];
741                    let icon = if entry.is_dir {
742                        "\u{1F5C0}"
743                    } else {
744                        options.row_icon
745                    };
746                    row.set_selected(self.row_highlight(entry, options.current));
747                    let prefix = options.hit_prefix;
748                    let (name_rect, _) = row.col(|ui| {
749                        crate::ui_kit::surface::icon_name_cell(ui, &format!("{icon} {}", entry.name));
750                    });
751                    out.hits.push((format!("{prefix}:{}", entry.name), name_rect));
752                    let cells = [
753                        ("type", entry_kind(entry)),
754                        ("size", fmt_size(entry.size)),
755                        ("date", fmt_date(entry.modified)),
756                    ];
757                    for (slug, text) in cells {
758                        let (rect, _) = row.col(|ui| {
759                            ui.add(egui::Label::new(crate::theme::data(text).weak()).selectable(false));
760                        });
761                        out.hits.push((format!("{prefix}:cell:{slug}:{}", entry.name), rect));
762                    }
763                    // The row's click is read BEFORE the delete cell joins the
764                    // union: a click on the delete button is the button's alone.
765                    let clicked_row = row.response();
766                    row.col(|ui| {
767                        if options.allow_delete && !entry.is_dir {
768                            let del = {
769                                let b = crate::icon_text::icon_button(ui, "\u{2715}").small();
770                                ui.add(b)
771                            };
772                            out.hits.push((format!("del:{}", entry.name), del.rect));
773                            if del.clicked() {
774                                out.remove = Some(entry.identity.clone());
775                            }
776                        }
777                    });
778                    self.row_clicked(&clicked_row, entry, out);
779                });
780            });
781        });
782        if let Some(col) = clicked_sort {
783            if self.sort_key == col {
784                self.sort_desc = !self.sort_desc;
785            } else {
786                self.sort_key = col;
787                self.sort_desc = false;
788            }
789        }
790    }
791
792    /// Whether `entry`'s row shows highlighted: the selected file or folder;
793    /// before the user picks a row, the caller's `current` document.
794    fn row_highlight(&self, entry: &BrowserEntry, current: Option<&str>) -> bool {
795        let id = entry.identity.as_str();
796        if entry.is_dir {
797            self.selected_dir.as_deref() == Some(id)
798        } else {
799            match &self.selected {
800                Some(sel) => sel == id,
801                None => self.selected_dir.is_none() && current == Some(id),
802            }
803        }
804    }
805
806    /// A row's click: a double click activates (opens a file, enters a
807    /// folder), a single click only selects. The double-click test comes
808    /// first because its second press also reports `clicked()`.
809    ///
810    /// Under a finger (on a phone, tapping the home folder did not open it)
811    /// a double TAP rarely reads as a double click (time and
812    /// travel limits), so one tap on a folder enters it, and one tap on a file
813    /// selects it for the footer's Open; a double tap opens a file only once it
814    /// is the selected one. Row taps within a double tap's span of a tap that
815    /// changed the folder are ignored ([`Self::touch_nav_at`]).
816    fn row_clicked(&mut self, response: &egui::Response, entry: &BrowserEntry, out: &mut FileExplorerOutput) {
817        if crate::viewport::touch::enabled(&response.ctx) {
818            if !response.clicked() {
819                return;
820            }
821            let now = response.ctx.input(|i| i.time);
822            if double_tap_twin(&response.ctx, self.touch_nav_at, self.last_press_at) {
823                return;
824            }
825            if entry.is_dir {
826                self.activate(&entry.identity, true, out);
827                self.touch_nav_at = Some(now);
828            } else if response.double_clicked() && self.selected.as_deref() == Some(entry.identity.as_str()) {
829                self.activate(&entry.identity, false, out);
830            } else {
831                self.select(&entry.identity, false);
832                out.picked = Some(entry.identity.clone());
833            }
834            return;
835        }
836        if response.double_clicked() {
837            self.activate(&entry.identity, entry.is_dir, out);
838        } else if response.clicked() {
839            self.select(&entry.identity, entry.is_dir);
840            if !entry.is_dir {
841                out.picked = Some(entry.identity.clone());
842            }
843        }
844    }
845
846    /// Keyboard navigation over the visible rows: ↑/↓ move the selection
847    /// (folders and files alike), Enter activates it (opens the file, enters
848    /// the folder). Active only when the caller offers a confirm action and no
849    /// text field (filter / name / path) holds focus, so typing is never
850    /// hijacked. Not in hosts without one (Save As, step-parts): their name
851    /// field submits on Enter as it loses focus, the same frame this would see
852    /// the key, and an explorer Enter there would overwrite the typed name or
853    /// walk into a folder before the save.
854    fn handle_keys(
855        &mut self,
856        ui: &egui::Ui,
857        options: FileExplorerOptions<'_>,
858        out: &mut FileExplorerOutput,
859    ) {
860        if options.confirm_label.is_none() || ui.ctx().egui_wants_keyboard_input() {
861            return;
862        }
863        if self.nav_rows.is_empty() {
864            return;
865        }
866        let (down, up, enter) = ui.input(|i| {
867            (
868                i.key_pressed(egui::Key::ArrowDown),
869                i.key_pressed(egui::Key::ArrowUp),
870                i.key_pressed(egui::Key::Enter),
871            )
872        });
873        if down || up {
874            let held = self.selected.as_deref().or(self.selected_dir.as_deref());
875            let current = held.and_then(|s| self.nav_rows.iter().position(|(id, _)| id == s));
876            let next = match current {
877                Some(i) if down => (i + 1).min(self.nav_rows.len() - 1),
878                Some(i) => i.saturating_sub(1),
879                None => 0,
880            };
881            let (id, is_dir) = self.nav_rows[next].clone();
882            self.select(&id, is_dir);
883            if !is_dir {
884                out.picked = Some(id);
885            }
886        } else if enter {
887            if let Some(dir) = self.selected_dir.clone() {
888                self.enter_dir = Some(dir);
889            } else if let Some(sel) = &self.selected {
890                out.activated = Some(sel.clone());
891            }
892        }
893    }
894
895    fn show_footer(
896        &mut self,
897        ui: &mut egui::Ui,
898        options: FileExplorerOptions<'_>,
899        out: &mut FileExplorerOutput,
900    ) {
901        ui.separator();
902        ui.horizontal(|ui| {
903            if let Some(label) = options.confirm_label {
904                let any = self.selected.is_some() || self.selected_dir.is_some();
905                // The confirm is the dialog's primary action (under a finger it is
906                // also how a tapped file opens: a tap only selects it).
907                let confirm = ui.add(crate::ui_kit::Button::primary(label).enabled(any));
908                out.hits
909                    .push((format!("{}:confirm", options.hit_prefix), confirm.rect));
910                if confirm.clicked() {
911                    // With a folder selected the confirm button walks into it.
912                    if let Some(dir) = self.selected_dir.clone() {
913                        self.enter_dir = Some(dir);
914                    } else {
915                        out.activated = self.selected.clone();
916                    }
917                }
918            }
919            if options.allow_import {
920                let import = {
921                let label = format!("\u{2B06} {}", options.import_label);
922                let b = crate::icon_text::icon_button(ui, &label);
923                ui.add(b)
924            };
925                out.hits.push((options.import_hit.into(), import.rect));
926                out.import = import.clicked();
927            }
928            if options.show_cancel {
929                let cancel = ui.add(crate::ui_kit::Button::new("Cancel"));
930                out.hits.push(("cancel".into(), cancel.rect));
931                out.cancel = cancel.clicked();
932            }
933            // Selection preview (bare file name), right-aligned.
934            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
935                if let Some(sel) = self.selected.as_ref().or(self.selected_dir.as_ref()) {
936                    let name = sel.rsplit(['/', '\\']).next().unwrap_or(sel);
937                    // Truncated: the preview is the LAST thing on the footer row,
938                    // so a long file name laid out at its natural width runs left
939                    // across the Import / Cancel buttons it is meant to sit beside.
940                    ui.add(
941                        egui::Label::new(egui::RichText::new(name).weak()).truncate(),
942                    );
943                }
944            });
945        });
946    }
947
948}
949
950/// Wrap a file dialog's WHOLE body — heading, browser, footer and all — in the
951/// shared resizable frame. The drag grip therefore lands at the dialog WINDOW's
952/// bottom-right corner instead of around the file table, and dragging it grows
953/// the dialog itself in both axes, capped to the viewport so it can never grow
954/// off-screen. One shared id means resizing any file dialog resizes them all.
955///
956/// Only for MODAL hosts: an [`egui::Window`] already carries its own corner
957/// grip, and a second frame inside it would put back exactly the handle this
958/// removes.
959pub fn dialog_body<R>(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
960    let screen = ui.ctx().content_rect().size();
961    let compact = crate::viewport::touch::compact(ui.ctx());
962    let max = if compact { (screen - egui::Vec2::splat(24.0)).max(egui::Vec2::splat(80.0)) }
963        else { egui::vec2((screen.x - 40.0).max(320.0), (screen.y - 80.0).max(240.0)) };
964    egui::Resize::default()
965        .id_salt(if compact { "brep-file-dialog-size-mobile" } else { "brep-file-dialog-size" })
966        // The modal frame already draws the dialog's border; the resize region
967        // fills it exactly, so its own stroke would only double it up.
968        .with_stroke(false)
969        .min_size(egui::vec2(460.0_f32.min(max.x), 300.0_f32.min(max.y)))
970        .max_size(max)
971        .default_size(egui::vec2(620.0_f32.min(max.x), 520.0_f32.min(max.y)))
972        .show(ui, add_contents)
973}
974
975/// Pin a dialog's own trailing widgets — a status line, a name field, the
976/// action buttons — to the BOTTOM of the dialog. Call it BEFORE
977/// [`FileExplorer::show_store`]: the explorer then fills the gap that is left,
978/// which is what keeps the buttons still while the file list scrolls. `salt`
979/// distinguishes one dialog's footer from another's (two can be on screen at
980/// once), and the widgets inside are drawn top-down in the order written.
981pub fn dialog_footer<R>(
982    ui: &mut egui::Ui,
983    salt: &str,
984    add_contents: impl FnOnce(&mut egui::Ui) -> R,
985) -> R {
986    bottom_panel(ui, "brep-file-dialog-footer", salt, add_contents)
987}
988
989/// The one bottom-pinned strip both footers use: no frame and no separator line
990/// of its own, so it reads as part of the dialog rather than as a panel, and it
991/// takes exactly the height its contents need.
992fn bottom_panel<R>(
993    ui: &mut egui::Ui,
994    base: &str,
995    salt: &str,
996    add_contents: impl FnOnce(&mut egui::Ui) -> R,
997) -> R {
998    egui::containers::panel::Panel::bottom(egui::Id::new((base, salt)))
999        .frame(egui::Frame::NONE)
1000        .show_separator_line(false)
1001        .show(ui, add_contents)
1002        .inner
1003}
1004
1005/// Order two optional timestamps, sorting `None` (unknown, e.g. web) last.
1006fn cmp_opt(a: Option<f64>, b: Option<f64>) -> Ordering {
1007    match (a, b) {
1008        (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(Ordering::Equal),
1009        (Some(_), None) => Ordering::Less,
1010        (None, Some(_)) => Ordering::Greater,
1011        (None, None) => Ordering::Equal,
1012    }
1013}
1014
1015/// The Type column text for an entry (Folder / BREP model / extension / File).
1016fn entry_kind(entry: &BrowserEntry) -> String {
1017    if entry.is_dir {
1018        return "Folder".into();
1019    }
1020    let lower = entry.name.to_ascii_lowercase();
1021    if lower.ends_with(".nbrep") {
1022        return "BREP model".into();
1023    }
1024    match entry.name.rsplit_once('.') {
1025        Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() => ext.to_uppercase(),
1026        _ => "File".into(),
1027    }
1028}
1029
1030/// Stable slug for a sort column's hit key.
1031fn sort_slug(key: SortKey) -> &'static str {
1032    match key {
1033        SortKey::Name => "name",
1034        SortKey::Kind => "type",
1035        SortKey::Size => "size",
1036        SortKey::Date => "date",
1037    }
1038}
1039
1040/// Human-readable byte size, or an em-dash when the backend cannot report it.
1041fn fmt_size(size: Option<u64>) -> String {
1042    match size {
1043        None => "\u{2014}".into(),
1044        Some(bytes) => {
1045            let b = bytes as f64;
1046            if bytes < 1024 {
1047                format!("{bytes} B")
1048            } else if b < 1024.0 * 1024.0 {
1049                format!("{:.1} KB", b / 1024.0)
1050            } else if b < 1024.0 * 1024.0 * 1024.0 {
1051                format!("{:.1} MB", b / (1024.0 * 1024.0))
1052            } else {
1053                format!("{:.1} GB", b / (1024.0 * 1024.0 * 1024.0))
1054            }
1055        }
1056    }
1057}
1058
1059/// `YYYY-MM-DD HH:MM` (UTC) from whole Unix seconds, or an em-dash when unknown.
1060fn fmt_date(modified: Option<f64>) -> String {
1061    let Some(secs) = modified else {
1062        return "\u{2014}".into();
1063    };
1064    let days = (secs / 86_400.0).floor() as i64;
1065    let (y, m, d) = civil_from_days(days);
1066    let sod = ((secs as i64) % 86_400 + 86_400) % 86_400;
1067    format!("{y:04}-{m:02}-{d:02} {:02}:{:02}", sod / 3600, (sod % 3600) / 60)
1068}
1069
1070/// Gregorian `(year, month, day)` from a day count since the Unix epoch
1071/// (Howard Hinnant's `civil_from_days`) — pure integer arithmetic, so it is
1072/// wasm-safe and never touches `SystemTime`.
1073use brep_render::sheets::frame::civil_from_days;
1074
1075/// Split a POSIX-ish location into `(label, navigable-path)` breadcrumb segments,
1076/// starting at the root. e.g. `/home/me/models` →
1077/// `[("/", "/"), ("home", "/home"), ("me", "/home/me"), ("models", "/home/me/models")]`.
1078fn breadcrumb_segments(location: &str) -> Vec<(String, String)> {
1079    let mut out = vec![("/".to_string(), "/".to_string())];
1080    let mut acc = String::new();
1081    for comp in location.split('/').filter(|s| !s.is_empty()) {
1082        acc.push('/');
1083        acc.push_str(comp);
1084        out.push((comp.to_string(), acc.clone()));
1085    }
1086    out
1087}
1088
1089/// Whether the tap being reported is the second half of a double tap whose
1090/// first tap changed the folder at `nav_at`: it was pressed (`pressed_at`)
1091/// after that change and within egui's double-click delay of it, exactly what
1092/// egui would have counted as a double click. A later, deliberate tap is a tap.
1093pub(crate) fn double_tap_twin(ctx: &egui::Context, nav_at: Option<f64>, pressed_at: Option<f64>) -> bool {
1094    let delay = ctx.options(|o| o.input_options.max_double_click_delay);
1095    match (nav_at, pressed_at) {
1096        (Some(nav), Some(press)) => press >= nav && press - nav <= delay,
1097        _ => false,
1098    }
1099}
1100
1101/// The glyph a pinned folder's row draws: the Open command's folder artwork.
1102const PIN_GLYPH: &str = "\u{E011}";
1103
1104/// The glyph a sidebar place draws for its category — catalogued artwork
1105/// (`icons.rs`), drawn by [`sidebar_row`]. The plain characters these used to
1106/// be were partly missing from the UI font (🗀 and 📌 drew as empty boxes), and
1107/// Root drew "/" beside its label "/" (lane U audit item 12).
1108fn place_glyph(kind: PlaceKind) -> &'static str {
1109    match kind {
1110        PlaceKind::Home => "\u{2302}",      // ⌂ — the OS fallback font draws it (native)
1111        PlaceKind::Documents => "\u{1F5CE}", // 🗎 catalogued
1112        PlaceKind::Downloads => "\u{2B07}",  // ⬇ catalogued
1113        PlaceKind::Models | PlaceKind::Root => PIN_GLYPH,
1114    }
1115}
1116
1117/// A Places / Pinned row: the leading catalogued glyph as artwork, framed only
1118/// on hover — what `selectable_label(false, …)` drew, with the icon.
1119/// It is a list row: its callers add it under `theme::data_rows`.
1120fn sidebar_row<'a>(ui: &egui::Ui, caption: &'a str) -> egui::Button<'a> {
1121    crate::icon_text::icon_button(ui, caption).frame_when_inactive(false)
1122}
1123