quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! `FolderPickerController` — engine-level folder/workspace directory picker.
//!
//! Owns all state for an interactive directory-browsing modal:
//! filesystem walking, fuzzy filtering, scroll, and selection. Renders
//! via the existing [`Palette`] primitive (no new
//! `Backend` trait method needed) and accepts backend-neutral
//! [`UiEvent`]s.
//!
//! # Relation to vimcode
//!
//! Extracted verbatim from vimcode's TUI-local `FolderPickerState`
//! (`src/tui_main/mod.rs`, ~285 lines). After the quadraui PR lands,
//! vimcode removes the TUI-local code and rewires both TUI and GTK
//! `OpenFolderDialog` through this controller.
//!
//! # Adoption status
//!
//! The vimcode migration above hasn't landed as of #825's audit — no
//! confirmed external adopter yet. Kept public rather than demoted:
//! full TUI + GTK demo coverage already exists
//! (`examples/tui_folder_picker.rs`, `examples/gtk_folder_picker.rs`,
//! `examples/common/folder_picker_app.rs`) plus a `TuiDriver` end-to-end
//! test in `tests/tui_example_driver.rs`, and the extraction above is a
//! concrete, named migration target, not a speculative one.
//!
//! # Usage pattern
//!
//! ```rust,ignore
//! // Instantiate when the user triggers "Open Folder":
//! let mut picker = FolderPickerController::new(
//!     std::env::current_dir().unwrap(),
//!     vec![],       // no extra file names to surface
//!     false,        // don't show hidden dirs
//! );
//!
//! // In AppLogic::render:
//! let rect = /* palette popup bounds */;
//! picker.render(rect, backend);
//!
//! // In AppLogic::handle:
//! let visible_rows = /* rect.height as usize - PALETTE_CHROME_ROWS */;
//! match picker.handle(&event, visible_rows) {
//!     FolderPickerEvent::Confirmed { path } => { /* open workspace */ },
//!     FolderPickerEvent::Cancelled             => { /* dismiss modal */ },
//!     FolderPickerEvent::Consumed              => { /* redraw */ },
//!     FolderPickerEvent::Ignored               => {},
//! }
//! ```
//!
//! # Scroll accounting
//!
//! `handle()` requires `visible_rows` — the number of list rows visible
//! inside the palette chrome (title row + query row + optional scrollbar
//! row). Consumers typically compute this as
//! `rect.height as usize - PALETTE_CHROME_ROWS` where
//! [`PALETTE_CHROME_ROWS`] = 4.

use std::cmp::Reverse;
use std::path::{Path, PathBuf};

use crate::{
    Backend, Icon, Key, Modifiers, NamedKey, Palette, PaletteItem, Rect, StyledText, UiEvent,
    WidgetId,
};

/// Overhead rows consumed by the `Palette` chrome (title + query + borders).
///
/// Subtract from the popup height to get `visible_rows`:
///
/// ```rust
/// # use quadraui::compose::folder_picker::PALETTE_CHROME_ROWS;
/// let popup_height = 20usize;
/// let visible_rows = popup_height.saturating_sub(PALETTE_CHROME_ROWS);
/// # let _ = visible_rows;
/// ```
pub const PALETTE_CHROME_ROWS: usize = 4;

/// Default recursion depth for [`FolderPickerController::new`].
///
/// Override per-instance with [`FolderPickerController::with_max_depth`].
pub const DEFAULT_MAX_DEPTH: usize = 5;

/// Default heavy build/dependency directory names that are skipped during
/// the filesystem walk.
///
/// Override per-instance with [`FolderPickerController::with_ignore_dirs`].
pub const DEFAULT_IGNORE_DIRS: &[&str] = &["target", "node_modules", "__pycache__"];

/// What happened after [`FolderPickerController::handle`] processed an event.
#[derive(Debug, Clone, PartialEq)]
pub enum FolderPickerEvent {
    /// The user confirmed a selection. The resolved absolute path is returned.
    ///
    /// The consumer should close the picker and act on the path (e.g.
    /// open it as a workspace folder). If the user selected `..` the
    /// controller navigates up internally and emits [`Consumed`] instead.
    ///
    /// [`Consumed`]: FolderPickerEvent::Consumed
    Confirmed { path: PathBuf },
    /// The user dismissed the picker (Escape).
    Cancelled,
    /// Event consumed — internal state changed, caller should redraw.
    Consumed,
    /// Event not relevant to this controller.
    Ignored,
}

/// Cross-backend compose controller for a directory-browsing picker modal.
///
/// Combines filesystem walking, fuzzy filtering, keyboard navigation, and
/// scroll tracking into a single reusable state machine. Rendering is
/// delegated to the existing [`Palette`] primitive via
/// [`Backend::draw_palette`].
///
/// See the [module-level documentation](self) for a usage example.
pub struct FolderPickerController {
    /// Widget ID used for the rendered `Palette`.
    id: WidgetId,
    /// Current browsing root. Changes on `navigate_to` / `navigate_up`.
    root: PathBuf,
    /// Live query string (typed characters build up incrementally).
    query: String,
    /// All candidate entries relative to `root` (unfiltered, stable).
    all_entries: Vec<PathBuf>,
    /// Currently filtered + ranked entries (subset of `all_entries`).
    filtered: Vec<PathBuf>,
    /// Index into `filtered` of the highlighted row.
    selected: usize,
    /// First visible row index (scroll offset into `filtered`).
    scroll_top: usize,
    /// Whether to surface hidden directories (names beginning with `.`).
    show_hidden: bool,
    /// Additional dotfile names to surface even when `show_hidden` is false.
    ///
    /// E.g. `[".vimcode-workspace"]` lets the consumer surface workspace
    /// marker files without exposing all hidden files. Defaults to empty.
    extra_file_names: Vec<String>,
    /// Ignore directories with these names (heavy build / dependency dirs).
    ///
    /// Defaults: [`DEFAULT_IGNORE_DIRS`]. Override with
    /// [`with_ignore_dirs`](Self::with_ignore_dirs).
    ignore_dirs: Vec<String>,
    /// Maximum recursion depth for the filesystem walk.
    ///
    /// Defaults to [`DEFAULT_MAX_DEPTH`]. Override with
    /// [`with_max_depth`](Self::with_max_depth).
    max_depth: usize,
}

impl FolderPickerController {
    /// Create a new picker rooted at `root`.
    ///
    /// # Arguments
    ///
    /// - `root` — initial browsing directory (typically `env::current_dir()`
    ///   or the engine's active workspace root).
    /// - `extra_file_names` — dotfile names to surface even when
    ///   `show_hidden` is false (e.g. `[".vimcode-workspace".to_string()]`).
    ///   Pass an empty `Vec` for the common case.
    /// - `show_hidden` — if true, all hidden directories are shown; if false,
    ///   only names in `extra_file_names` are surfaced from hidden entries.
    pub fn new(root: impl Into<PathBuf>, extra_file_names: Vec<String>, show_hidden: bool) -> Self {
        let root = root.into();
        let ignore_dirs: Vec<String> = DEFAULT_IGNORE_DIRS
            .iter()
            .map(|s| (*s).to_string())
            .collect();
        let max_depth = DEFAULT_MAX_DEPTH;
        let all_entries = collect_dir_entries(
            &root,
            show_hidden,
            &extra_file_names,
            &ignore_dirs,
            max_depth,
        );
        let filtered = all_entries.iter().take(50).cloned().collect();
        Self {
            id: WidgetId::new("folder_picker"),
            root,
            query: String::new(),
            all_entries,
            filtered,
            selected: 0,
            scroll_top: 0,
            show_hidden,
            extra_file_names,
            ignore_dirs,
            max_depth,
        }
    }

    /// Override the `WidgetId` used by the rendered `Palette`.
    ///
    /// Use this when more than one folder picker may exist in the same
    /// app, so each one has a distinct ID. Defaults to
    /// `WidgetId::new("folder_picker")`.
    ///
    /// Returns `self` for builder-style chaining.
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = WidgetId::new(id.into());
        self
    }

    /// Override the list of directory names to skip during the filesystem walk.
    ///
    /// Defaults to [`DEFAULT_IGNORE_DIRS`]. Pass an empty `Vec` to walk
    /// every directory (use with care on large filesystems).
    ///
    /// Re-walks the current `root` so the new list takes effect immediately.
    /// Returns `self` for builder-style chaining.
    pub fn with_ignore_dirs(mut self, ignore_dirs: Vec<String>) -> Self {
        self.ignore_dirs = ignore_dirs;
        self.all_entries = collect_dir_entries(
            &self.root,
            self.show_hidden,
            &self.extra_file_names,
            &self.ignore_dirs,
            self.max_depth,
        );
        self.refilter();
        self
    }

    /// Override the maximum recursion depth for the filesystem walk.
    ///
    /// Defaults to [`DEFAULT_MAX_DEPTH`]. Higher values surface deeper
    /// directories at the cost of a slower initial walk.
    ///
    /// Re-walks the current `root` so the new depth takes effect immediately.
    /// Returns `self` for builder-style chaining.
    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
        self.max_depth = max_depth;
        self.all_entries = collect_dir_entries(
            &self.root,
            self.show_hidden,
            &self.extra_file_names,
            &self.ignore_dirs,
            self.max_depth,
        );
        self.refilter();
        self
    }

    // ── State accessors ───────────────────────────────────────────────

    /// Current browsing root.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Current query string.
    pub fn query(&self) -> &str {
        &self.query
    }

    /// Currently filtered entries (relative paths).
    pub fn filtered(&self) -> &[PathBuf] {
        &self.filtered
    }

    /// Index of the highlighted row in `filtered`.
    pub fn selected(&self) -> usize {
        self.selected
    }

    /// Scroll offset (first visible row index in `filtered`).
    pub fn scroll_top(&self) -> usize {
        self.scroll_top
    }

    /// The resolved absolute path for the currently selected entry, or `None`
    /// if the list is empty.
    ///
    /// The `..` entry resolves to the parent of `root`; all others resolve to
    /// `root.join(rel)`.
    pub fn selected_path(&self) -> Option<PathBuf> {
        let rel = self.filtered.get(self.selected)?;
        if rel.as_os_str() == ".." {
            self.root.parent().map(|p| p.to_path_buf())
        } else {
            Some(self.root.join(rel))
        }
    }

    // ── Navigation ────────────────────────────────────────────────────

    /// Navigate to `new_root`, clearing the query and reloading entries.
    pub fn navigate_to(&mut self, new_root: PathBuf) {
        self.root = new_root;
        self.query.clear();
        self.all_entries = collect_dir_entries(
            &self.root,
            self.show_hidden,
            &self.extra_file_names,
            &self.ignore_dirs,
            self.max_depth,
        );
        self.filtered = self.all_entries.iter().take(50).cloned().collect();
        self.selected = 0;
        self.scroll_top = 0;
    }

    /// Navigate to the parent directory (no-op at filesystem root).
    pub fn navigate_up(&mut self) {
        if let Some(parent) = self.root.parent() {
            self.navigate_to(parent.to_path_buf());
        }
    }

    // ── Query editing ─────────────────────────────────────────────────

    /// Append `c` to the query and refilter.
    pub fn push_char(&mut self, c: char) {
        self.query.push(c);
        self.refilter();
    }

    /// Remove the last character from the query and refilter.
    pub fn pop_char(&mut self) {
        self.query.pop();
        self.refilter();
    }

    /// Re-compute `filtered` from `all_entries` and the current `query`.
    pub fn refilter(&mut self) {
        self.filtered = filter_dir_entries(&self.all_entries, &self.query);
        self.selected = 0;
        self.scroll_top = 0;
    }

    // ── Selection movement ────────────────────────────────────────────

    /// Move the selection one row up (clamped at 0).
    pub fn move_up(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// Move the selection one row down (clamped at last row).
    pub fn move_down(&mut self) {
        if !self.filtered.is_empty() {
            self.selected = (self.selected + 1).min(self.filtered.len() - 1);
        }
    }

    /// Clamp `scroll_top` so `selected` is always visible within
    /// `visible_rows` rows.
    pub fn sync_scroll(&mut self, visible_rows: usize) {
        if visible_rows == 0 {
            return;
        }
        if self.selected < self.scroll_top {
            self.scroll_top = self.selected;
        }
        if self.selected >= self.scroll_top + visible_rows {
            self.scroll_top = self.selected + 1 - visible_rows;
        }
    }

    // ── Render ────────────────────────────────────────────────────────

    /// Paint the picker as a `Palette` inside `rect`.
    ///
    /// Call this from `AppLogic::render` whenever the picker is open.
    pub fn render(&self, rect: Rect, backend: &mut dyn Backend) {
        let palette = self.build_palette(rect);
        backend.draw_palette(rect, &palette);
    }

    // ── Handle ────────────────────────────────────────────────────────

    /// Drive the state machine with a backend-neutral `UiEvent`.
    ///
    /// `visible_rows` is the number of list rows that fit inside the
    /// palette chrome; compute it as
    /// `popup_height.saturating_sub(PALETTE_CHROME_ROWS)`.
    ///
    /// # Canonical typing source
    ///
    /// Query characters are sourced from `UiEvent::KeyPressed`'s
    /// `Key::Char(c)` arm only — never from `UiEvent::CharTyped`. Today
    /// neither the TUI nor GTK backend emits `CharTyped`, and a future
    /// backend (e.g. Win/macOS IME) might emit *both* for the same input;
    /// listening to only `KeyPressed` avoids the double-insert risk. If a
    /// future backend needs IME-composed input, route it through
    /// `KeyPressed` as well or call [`push_char`](Self::push_char) directly.
    pub fn handle(&mut self, event: &UiEvent, visible_rows: usize) -> FolderPickerEvent {
        let result = match event {
            UiEvent::KeyPressed { key, modifiers, .. } => self.handle_key(key, modifiers),
            _ => FolderPickerEvent::Ignored,
        };

        // Keep scroll in sync after any state change.
        if matches!(result, FolderPickerEvent::Consumed) {
            self.sync_scroll(visible_rows);
        }

        result
    }

    // ── Internal helpers ──────────────────────────────────────────────

    // Key dispatch.
    //
    // Trade-off (intentional, matches vimcode's existing behavior): the vim
    // shortcuts `-` (parent dir), `k` (up), and `j` (down) are matched
    // *before* the generic `Key::Char(c) => push_char` arm. That means the
    // query input can never begin with — or contain — those three
    // characters: a user typing "kubernetes" cannot start the query with
    // `k`, nor include `j`/`-` anywhere. This is documented for downstream
    // consumers; if any consumer needs typing-priority (e.g. searching
    // codebases with hyphenated names), they can build their own dispatch
    // by calling the state-mutation methods (`push_char`, `move_up`, …)
    // directly instead of routing through `handle()`.
    fn handle_key(&mut self, key: &Key, modifiers: &Modifiers) -> FolderPickerEvent {
        let ctrl = modifiers.ctrl;
        match key {
            Key::Named(NamedKey::Escape) => FolderPickerEvent::Cancelled,

            Key::Named(NamedKey::Enter) => {
                // ".." → navigate up; anything else → confirm selection.
                let is_dotdot = self
                    .filtered
                    .get(self.selected)
                    .map(|p| p.as_os_str() == "..")
                    .unwrap_or(false);
                if is_dotdot {
                    self.navigate_up();
                    FolderPickerEvent::Consumed
                } else if let Some(path) = self.selected_path() {
                    FolderPickerEvent::Confirmed { path }
                } else {
                    FolderPickerEvent::Consumed
                }
            }

            // '-' navigates up to parent (vim netrw convention).
            Key::Char('-') if !ctrl => {
                self.navigate_up();
                FolderPickerEvent::Consumed
            }

            Key::Named(NamedKey::Up) => {
                self.move_up();
                FolderPickerEvent::Consumed
            }
            // 'k' vim-style up (only if no modifier).
            Key::Char('k') if !ctrl => {
                self.move_up();
                FolderPickerEvent::Consumed
            }

            Key::Named(NamedKey::Down) => {
                self.move_down();
                FolderPickerEvent::Consumed
            }
            // 'j' vim-style down (only if no modifier).
            Key::Char('j') if !ctrl => {
                self.move_down();
                FolderPickerEvent::Consumed
            }

            Key::Named(NamedKey::Backspace) => {
                self.pop_char();
                FolderPickerEvent::Consumed
            }

            Key::Char(c) if !ctrl => {
                self.push_char(*c);
                FolderPickerEvent::Consumed
            }

            _ => FolderPickerEvent::Ignored,
        }
    }

    /// Build the `Palette` descriptor for the current state.
    fn build_palette(&self, rect: Rect) -> Palette {
        let r = self.root.to_string_lossy();
        // Truncate from the left if the root path is too long.
        // Reserve ~30 cells for palette chrome (borders + count chip + padding).
        let max = (rect.width as usize).saturating_sub(30).max(10);
        // `r.len()` is bytes; we must split on a UTF-8 char boundary so paths
        // containing non-ASCII (e.g. Japanese, accented Latin) don't panic.
        // Approach: walk char_indices() from the start, dropping the leftmost
        // chars until the remaining suffix fits within `max` bytes.
        let root_display = if r.len() > max {
            let s: &str = r.as_ref();
            let target_drop = s.len().saturating_sub(max);
            // Find the first char boundary >= target_drop bytes from the start.
            let mut split_at = s.len();
            for (idx, _) in s.char_indices() {
                if idx >= target_drop {
                    split_at = idx;
                    break;
                }
            }
            format!("…{}", &s[split_at..])
        } else {
            r.into_owned()
        };
        let title = format!("Open Folder {root_display}");

        let folder_icon = Icon::new("\u{1F4C1}", "\u{1F4C1}"); // 📁
        let file_icon = Icon::new("\u{2699}", "\u{2699}"); // ⚙

        let items: Vec<PaletteItem> = self
            .filtered
            .iter()
            .map(|entry| {
                // Entries that are files (not directories) get the file icon.
                // We detect them by checking if the full path is a file — or
                // by the heuristic that the entry name contains a dot and
                // appears in `extra_file_names`.
                let name = entry.file_name().and_then(|n| n.to_str()).unwrap_or("");
                let is_extra_file = self.extra_file_names.iter().any(|e| e == name);
                let icon = if is_extra_file {
                    Some(file_icon.clone())
                } else {
                    Some(folder_icon.clone())
                };
                PaletteItem {
                    text: StyledText::plain(entry.to_string_lossy().to_string()),
                    detail: None,
                    icon,
                    match_positions: Vec::new(),
                    depth: 0,
                    expandable: false,
                    expanded: false,
                }
            })
            .collect();

        Palette {
            id: self.id,
            title,
            query: self.query.clone(),
            query_cursor: self.query.len(),
            items,
            selected_idx: self.selected,
            scroll_offset: self.scroll_top,
            total_count: self.all_entries.len(),
            has_focus: true,
            show_query: true,
            create_label: None,
            preview: None,
            mode: crate::primitives::palette::PaletteMode::List,
        }
    }
}

// ── Filesystem helpers ────────────────────────────────────────────────────────

/// Walk `root` collecting relative paths of subdirectories (depth ≤ `max_depth`).
///
/// `..` is prepended (unless `root` is a filesystem root) and `.` is always
/// included so the consumer can open the current directory directly.
///
/// Skips:
/// - hidden names (starting with `.`) unless `show_hidden` is true or the
///   name appears in `extra_file_names`.
/// - directory names in `ignore_dirs` (e.g. `target`, `node_modules`).
fn collect_dir_entries(
    root: &Path,
    show_hidden: bool,
    extra_file_names: &[String],
    ignore_dirs: &[String],
    max_depth: usize,
) -> Vec<PathBuf> {
    let mut out = Vec::new();
    // Prepend ".." so the user can navigate up (omit at filesystem root).
    if root.parent().is_some() {
        out.push(PathBuf::from(".."));
    }
    out.push(PathBuf::from("."));
    walk_dir_entries_recursive(
        root,
        root,
        &mut out,
        0,
        show_hidden,
        extra_file_names,
        ignore_dirs,
        max_depth,
    );
    out
}

#[allow(clippy::too_many_arguments)]
fn walk_dir_entries_recursive(
    root: &Path,
    dir: &Path,
    out: &mut Vec<PathBuf>,
    depth: usize,
    show_hidden: bool,
    extra_file_names: &[String],
    ignore_dirs: &[String],
    max_depth: usize,
) {
    if depth > max_depth {
        return;
    }
    let mut entries: Vec<_> = match std::fs::read_dir(dir) {
        Ok(e) => e.flatten().collect(),
        Err(_) => return,
    };
    entries.sort_by_key(|e| e.file_name());
    for entry in entries {
        let path = entry.path();
        let name = match path.file_name().and_then(|n| n.to_str()) {
            Some(n) => n.to_owned(),
            None => continue,
        };
        // Hidden entries: skip unless show_hidden or name is in extra_file_names.
        if name.starts_with('.') && !show_hidden {
            if path.is_file() && extra_file_names.iter().any(|e| e == &name) {
                if let Ok(rel) = path.strip_prefix(root) {
                    out.push(rel.to_path_buf());
                }
            }
            continue;
        }
        // Skip heavy build/dep directories.
        if ignore_dirs.iter().any(|d| d == &name) {
            continue;
        }
        if path.is_dir() {
            if let Ok(rel) = path.strip_prefix(root) {
                out.push(rel.to_path_buf());
            }
            walk_dir_entries_recursive(
                root,
                &path,
                out,
                depth + 1,
                show_hidden,
                extra_file_names,
                ignore_dirs,
                max_depth,
            );
        }
    }
}

/// Filter `all` by `query` using subsequence matching with a relevance score.
///
/// Returns up to 50 entries, sorted by descending score.
/// If `query` is empty, the first 50 entries are returned unchanged.
fn filter_dir_entries(all: &[PathBuf], query: &str) -> Vec<PathBuf> {
    const CAP: usize = 50;
    if query.is_empty() {
        return all.iter().take(CAP).cloned().collect();
    }
    let q = query.to_lowercase();
    let mut scored: Vec<(i32, &PathBuf)> = all
        .iter()
        .filter_map(|p| {
            let display = p.to_string_lossy().to_lowercase();
            dir_fuzzy_score(&display, &q).map(|s| (s, p))
        })
        .collect();
    scored.sort_by_key(|&(s, _)| Reverse(s));
    scored
        .into_iter()
        .take(CAP)
        .map(|(_, p)| p.clone())
        .collect()
}

/// Subsequence fuzzy match returning a relevance score, or `None` if the
/// query is not a subsequence of `path`.
///
/// Higher scores mean the query characters appear closer together and/or
/// at word boundaries (`/`, `\`, `_`, `-`, `.`). Both forward and backward
/// slashes count so that Windows paths get the same boundary bonus as
/// POSIX paths.
///
/// Thin wrapper over [`crate::text_util::fuzzy_score`] — the match
/// positions it also returns aren't needed here (the folder picker doesn't
/// highlight per-character matches), so this drops them and keeps the
/// score-only signature the rest of this module already expects.
fn dir_fuzzy_score(path: &str, query: &str) -> Option<i32> {
    crate::text_util::fuzzy_score(path, query).map(|(score, _positions)| score)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    /// Number of child directories [`picker_root`] creates. Chosen so
    /// `filtered()` (which also carries `".."` and `"."`) holds well over
    /// ten entries, the largest selection index any test below drives.
    const PICKER_ROOT_CHILDREN: usize = 12;

    /// A throwaway browsing root holding [`PICKER_ROOT_CHILDREN`] empty
    /// child directories.
    ///
    /// Every controller test roots its picker here rather than at the
    /// ambient `env::temp_dir()`: `FolderPickerController::new` walks the
    /// root recursively to `DEFAULT_MAX_DEPTH`, so a shared system temp
    /// directory makes both the entry list and the walk's cost depend on
    /// whatever else happens to live there. The returned `TempDir` must
    /// stay bound for the lifetime of the picker — dropping it deletes
    /// the directory.
    fn picker_root() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("create picker tempdir");
        for i in 0..PICKER_ROOT_CHILDREN {
            std::fs::create_dir(dir.path().join(format!("child{i:02}"))).expect("create child dir");
        }
        dir
    }

    // ── dir_fuzzy_score ───────────────────────────────────────────────

    #[test]
    fn fuzzy_score_exact_match_scores_high() {
        let s = dir_fuzzy_score("src/main.rs", "src/main.rs");
        assert!(s.is_some());
        assert!(s.unwrap() > 0);
    }

    #[test]
    fn fuzzy_score_subsequence_matches() {
        // "sm" is a subsequence of "src/main"
        let s = dir_fuzzy_score("src/main", "sm");
        assert!(s.is_some());
    }

    #[test]
    fn fuzzy_score_non_subsequence_is_none() {
        let s = dir_fuzzy_score("src/main", "xyz");
        assert!(s.is_none());
    }

    #[test]
    fn fuzzy_score_boundary_bonus() {
        // "m" starting at a "/" boundary should score higher than mid-word.
        let at_boundary = dir_fuzzy_score("src/main", "m");
        let mid_word = dir_fuzzy_score("abcmain", "m");
        assert!(at_boundary.unwrap() > mid_word.unwrap());
    }

    #[test]
    fn fuzzy_score_empty_query_none() {
        // Empty query returns None — the caller (filter_dir_entries) handles
        // the empty-query fast path before calling dir_fuzzy_score.
        let s = dir_fuzzy_score("anything", "");
        // Empty query: qi starts at 0, qb.len() is 0, so qi == qb.len()
        // at the start → Some(100).  This is fine — filter_dir_entries
        // short-circuits before reaching here for empty queries.
        assert!(s.is_some());
    }

    // ── filter_dir_entries ────────────────────────────────────────────

    #[test]
    fn filter_returns_all_on_empty_query() {
        let paths: Vec<PathBuf> = (0..10).map(|i| PathBuf::from(format!("dir{i}"))).collect();
        let result = filter_dir_entries(&paths, "");
        assert_eq!(result.len(), 10);
    }

    #[test]
    fn filter_caps_at_50() {
        let paths: Vec<PathBuf> = (0..100).map(|i| PathBuf::from(format!("dir{i}"))).collect();
        let result = filter_dir_entries(&paths, "");
        assert_eq!(result.len(), 50);
    }

    #[test]
    fn filter_excludes_non_matching() {
        let paths = vec![
            PathBuf::from("src/main"),
            PathBuf::from("docs/readme"),
            PathBuf::from("tests/unit"),
        ];
        let result = filter_dir_entries(&paths, "src");
        assert_eq!(result.len(), 1);
        assert_eq!(result[0], PathBuf::from("src/main"));
    }

    #[test]
    fn filter_sorts_by_score() {
        // "sr" matches both "src/main" (boundary) and "usr/local" (mid-word).
        let paths = vec![PathBuf::from("usr/local"), PathBuf::from("src/main")];
        let result = filter_dir_entries(&paths, "sr");
        // "src/main" should rank higher (boundary bonus on 's').
        assert_eq!(result[0], PathBuf::from("src/main"));
    }

    // ── FolderPickerController state machine ──────────────────────────

    #[test]
    fn new_sets_dotdot_and_dot_entries() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let picker = FolderPickerController::new(tmp, vec![], false);
        // ".." and "." should always be the first two entries.
        assert!(picker.all_entries.contains(&PathBuf::from("..")));
        assert!(picker.all_entries.contains(&PathBuf::from(".")));
        // An isolated root makes the whole walk deterministic: "..", "."
        // and one entry per child directory, nothing else.
        assert_eq!(
            picker.filtered().len(),
            PICKER_ROOT_CHILDREN + 2,
            "isolated root must yield exactly \"..\", \".\" and one entry per child"
        );
    }

    #[test]
    fn push_and_pop_char_update_query() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        picker.push_char('s');
        picker.push_char('r');
        assert_eq!(picker.query(), "sr");
        picker.pop_char();
        assert_eq!(picker.query(), "s");
    }

    #[test]
    fn move_up_clamps_at_zero() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        assert_eq!(picker.selected(), 0);
        picker.move_up();
        assert_eq!(picker.selected(), 0);
    }

    #[test]
    fn move_down_advances_selection() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        assert!(picker.filtered().len() >= 2);
        picker.move_down();
        assert_eq!(picker.selected(), 1);
    }

    #[test]
    fn move_down_clamps_at_last() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        let last = picker.filtered().len().saturating_sub(1);
        for _ in 0..last + 5 {
            picker.move_down();
        }
        assert_eq!(picker.selected(), last);
    }

    #[test]
    fn sync_scroll_brings_selected_into_view() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        // Force a large selection index.
        assert!(picker.filtered().len() >= 10);
        picker.selected = 9;
        picker.sync_scroll(5);
        assert!(picker.scroll_top + 5 > picker.selected);
        assert!(picker.scroll_top <= picker.selected);
    }

    #[test]
    fn sync_scroll_scrolls_up_when_needed() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        assert!(picker.filtered().len() >= 5);
        picker.scroll_top = 5;
        picker.selected = 2; // above scroll_top
        picker.sync_scroll(3);
        assert_eq!(picker.scroll_top, 2);
    }

    #[test]
    fn escape_event_returns_cancelled() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        let ev = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Escape),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        assert_eq!(picker.handle(&ev, 10), FolderPickerEvent::Cancelled);
    }

    #[test]
    fn enter_on_dotdot_navigates_up() {
        // Use tempfile so parallel test runs don't race on a fixed name and
        // a crashed prior run can't leak a stale marker directory.
        let parent = tempfile::tempdir().expect("create parent tempdir");
        let sub = parent.path().join("nav_up_child");
        std::fs::create_dir_all(&sub).expect("create child dir");
        let mut picker = FolderPickerController::new(sub.clone(), vec![], false);
        // Select ".." (index 0, always prepended when parent exists).
        picker.selected = 0;
        assert_eq!(picker.filtered().first(), Some(&PathBuf::from("..")));
        let ev = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let result = picker.handle(&ev, 10);
        assert_eq!(result, FolderPickerEvent::Consumed);
        assert_eq!(picker.root(), parent.path());
    }

    #[test]
    fn enter_on_dot_returns_confirmed_with_root() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp.clone(), vec![], false);
        // "." is always at index 1 (after "..") when parent exists.
        let dot_idx = picker
            .filtered()
            .iter()
            .position(|p| p.as_os_str() == ".")
            .expect("'.' should always be in filtered");
        picker.selected = dot_idx;
        let ev = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let result = picker.handle(&ev, 10);
        assert_eq!(result, FolderPickerEvent::Confirmed { path: tmp });
    }

    #[test]
    fn up_down_key_moves_selection() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        assert!(picker.filtered().len() >= 2);
        let ev_down = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Down),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        picker.handle(&ev_down, 10);
        assert_eq!(picker.selected(), 1);

        let ev_up = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Up),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        picker.handle(&ev_up, 10);
        assert_eq!(picker.selected(), 0);
    }

    #[test]
    fn key_char_appends_to_query() {
        // Query characters arrive via `Key::Char` in `KeyPressed`, *not* via
        // `CharTyped`. The latter is intentionally ignored to avoid
        // double-insert when a future backend emits both for the same input.
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        let ev = UiEvent::KeyPressed {
            key: Key::Char('s'),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        picker.handle(&ev, 10);
        assert_eq!(picker.query(), "s");
    }

    #[test]
    fn char_typed_is_ignored() {
        // Documented contract: `CharTyped` is not the canonical typing
        // source; only `Key::Char` in `KeyPressed` mutates the query.
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        let ev = UiEvent::CharTyped('s');
        let result = picker.handle(&ev, 10);
        assert_eq!(result, FolderPickerEvent::Ignored);
        assert_eq!(picker.query(), "");
    }

    #[test]
    fn backspace_removes_last_char() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let mut picker = FolderPickerController::new(tmp, vec![], false);
        picker.push_char('s');
        picker.push_char('r');
        let ev = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Backspace),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        picker.handle(&ev, 10);
        assert_eq!(picker.query(), "s");
    }

    #[test]
    fn selected_path_resolves_dot_to_root() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let picker = FolderPickerController::new(tmp.clone(), vec![], false);
        let dot_idx = picker
            .filtered()
            .iter()
            .position(|p| p.as_os_str() == ".")
            .unwrap();
        let mut picker = picker;
        picker.selected = dot_idx;
        assert_eq!(picker.selected_path(), Some(tmp));
    }

    #[test]
    fn dash_key_navigates_up() {
        let parent = tempfile::tempdir().expect("create parent tempdir");
        let sub = parent.path().join("dash_nav_child");
        std::fs::create_dir_all(&sub).expect("create child dir");
        let mut picker = FolderPickerController::new(sub.clone(), vec![], false);
        let ev = UiEvent::KeyPressed {
            key: Key::Char('-'),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let result = picker.handle(&ev, 10);
        assert_eq!(result, FolderPickerEvent::Consumed);
        assert_eq!(picker.root(), parent.path());
    }

    #[test]
    fn build_palette_id_is_folder_picker() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let picker = FolderPickerController::new(tmp, vec![], false);
        let rect = Rect::new(0.0, 0.0, 80.0, 24.0);
        let palette = picker.build_palette(rect);
        assert_eq!(palette.id.as_str(), "folder_picker");
    }

    #[test]
    fn build_palette_title_contains_open_folder() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let picker = FolderPickerController::new(tmp, vec![], false);
        let rect = Rect::new(0.0, 0.0, 80.0, 24.0);
        let palette = picker.build_palette(rect);
        assert!(palette.title.starts_with("Open Folder"));
    }

    #[test]
    fn build_palette_items_match_filtered() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let picker = FolderPickerController::new(tmp, vec![], false);
        let rect = Rect::new(0.0, 0.0, 80.0, 24.0);
        let palette = picker.build_palette(rect);
        assert_eq!(palette.items.len(), picker.filtered().len());
    }

    #[test]
    fn extra_file_names_gets_file_icon() {
        // Isolate the marker file in a fresh tempdir so concurrent test
        // runs don't race and a crashed prior run can't leak state.
        let root = tempfile::tempdir().expect("create marker tempdir");
        let marker = root.path().join(".my-workspace");
        std::fs::write(&marker, b"").expect("write marker file");
        let picker = FolderPickerController::new(
            root.path().to_path_buf(),
            vec![".my-workspace".to_string()],
            false,
        );
        let rect = Rect::new(0.0, 0.0, 80.0, 24.0);
        let palette = picker.build_palette(rect);
        // The marker file should appear in items with the ⚙ icon.
        let has_marker = palette.items.iter().any(|item| {
            item.text
                .spans
                .first()
                .map(|s| s.text.contains(".my-workspace"))
                .unwrap_or(false)
        });
        assert!(has_marker, "marker file should appear in palette items");
    }

    #[test]
    fn build_palette_handles_non_ascii_root_path() {
        // `build_palette` must handle non-ASCII paths correctly: it must
        // validate UTF-8 char boundaries when slicing the root path to fit
        // the viewport width, rather than panicking on multi-byte characters.
        let long_japanese = PathBuf::from(format!("/a/{}", "ト".repeat(50)));
        let picker = FolderPickerController::new(long_japanese, vec![], false);
        // Narrow rect forces truncation: max = max(80-30, 10) = 50 bytes.
        let rect = Rect::new(0.0, 0.0, 80.0, 24.0);
        // Must not panic.
        let palette = picker.build_palette(rect);
        assert!(palette.title.starts_with("Open Folder "));
        // Sanity: ellipsis should be present and the suffix should still
        // be valid UTF-8 (implicit — `format!` would have panicked otherwise).
        assert!(palette.title.contains('…'));
    }

    #[test]
    fn build_palette_handles_accented_root_path() {
        // Regression: shorter multi-byte (Latin-1 / Latin-Extended) paths
        // should also be safe.
        let path = PathBuf::from(
            "/home/utilisateur/répertoire/sous-répertoire/encore-plus-profond/données",
        );
        let picker = FolderPickerController::new(path, vec![], false);
        let rect = Rect::new(0.0, 0.0, 60.0, 24.0);
        let palette = picker.build_palette(rect);
        assert!(palette.title.starts_with("Open Folder "));
    }

    // ── Windows-style path scoring ────────────────────────────────────

    #[test]
    fn fuzzy_score_treats_backslash_as_boundary() {
        // On Windows, paths use `\\` as the separator. Both
        // `src\\main.rs`-style and `src/main.rs`-style paths should get
        // the same boundary bonus when matching at a directory boundary.
        let posix = dir_fuzzy_score("src/main", "m");
        let windows = dir_fuzzy_score("src\\main", "m");
        // Both should rank higher than a mid-word match.
        let mid = dir_fuzzy_score("abcmain", "m");
        assert!(posix.unwrap() > mid.unwrap());
        assert!(windows.unwrap() > mid.unwrap());
        // And they should rank equally (same boundary bonus).
        assert_eq!(posix.unwrap(), windows.unwrap());
    }

    // ── Builder-method overrides ──────────────────────────────────────

    #[test]
    fn with_id_overrides_widget_id() {
        let dir = picker_root();
        let tmp = dir.path().to_path_buf();
        let picker = FolderPickerController::new(tmp, vec![], false).with_id("picker_b");
        let rect = Rect::new(0.0, 0.0, 80.0, 24.0);
        assert_eq!(picker.build_palette(rect).id.as_str(), "picker_b");
    }

    #[test]
    fn with_ignore_dirs_replaces_default_list() {
        let root = tempfile::tempdir().expect("tempdir");
        // Create `target` and `keep_me`; default list skips `target`.
        std::fs::create_dir_all(root.path().join("target")).unwrap();
        std::fs::create_dir_all(root.path().join("keep_me")).unwrap();
        // With an empty override list, `target` is no longer skipped.
        let picker = FolderPickerController::new(root.path().to_path_buf(), vec![], false)
            .with_ignore_dirs(vec![]);
        let has_target = picker
            .all_entries
            .iter()
            .any(|p| p == &PathBuf::from("target"));
        let has_keep = picker
            .all_entries
            .iter()
            .any(|p| p == &PathBuf::from("keep_me"));
        assert!(
            has_target,
            "target should be present after with_ignore_dirs(empty)"
        );
        assert!(has_keep);
    }

    #[test]
    fn with_max_depth_limits_recursion() {
        let root = tempfile::tempdir().expect("tempdir");
        // Build a nested chain: depth1/depth2/depth3
        let d3 = root.path().join("d1").join("d2").join("d3");
        std::fs::create_dir_all(&d3).unwrap();
        // depth=0 should only emit the top-level "d1".
        let picker =
            FolderPickerController::new(root.path().to_path_buf(), vec![], false).with_max_depth(0);
        let has_d1 = picker.all_entries.iter().any(|p| p.ends_with("d1"));
        let has_d2 = picker.all_entries.iter().any(|p| p.ends_with("d2"));
        assert!(has_d1);
        assert!(!has_d2, "depth=0 should not surface nested subdirs");
    }
}