cellix 0.5.2

The AI companion IDE inside your agent: a Claude Code mod, Codex plugin and Gemini CLI extension
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
use std::path::PathBuf;

use cellix_input::{Command, Format};
use cellix_render::{Bounds, Font, Grid, Icon, Measure, Rect, Rgb, Style};

use crate::theme::Theme;

const WIDTH: u16 = 64;
/// Text in the search field, as a percentage of the interface font.
const INTERFACE_SIZE_PERCENT: u8 = 100;
const ROWS: u16 = 12;
/// Space from the panel's edge to the icon and the text of the list, which line up.
const TEXT_INSET: f32 = 1.4;
/// How far a floating panel reaches past its rows, so nothing sits on its edge.
const PANEL_PADDING: f32 = 0.3;
/// Rows above the list: the search field, and a row holding the line under it.
const HEADER_ROWS: u16 = 2;
/// Where that line falls, as far below the field's text as the panel's edge is above it.
const HEADER_LINE: f32 = 1.3;
/// Air between what's typed and the status at the field's right end, in cells.
const STATUS_GAP: f32 = 1.5;
/// Space between the caret and the hint in an empty field.
const HINT_GAP: f32 = 0.45;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Item {
    File(PathBuf, String),
    Command(&'static str, Command),
    /// A branch to switch to, and when it last moved.
    Branch(String, String),
    NewBranch,
    /// A blank row with a line through it, between groups.
    Gap,
    /// A key to cite, and where it comes from.
    Citation(String, String),
    /// A picture, how it's shown, and whether it takes the place of the one at the caret.
    Image(PathBuf, String, bool),
    /// A folder to open as a workspace, as it's written, and a word about it.
    Folder(PathBuf, String, &'static str),
}

impl Item {
    fn label(&self) -> &str {
        match self {
            Self::File(_, label) | Self::Image(_, label, _) | Self::Folder(_, label, _) => label,
            Self::Command(label, _) => label,
            Self::Branch(name, _) | Self::Citation(name, _) => name,
            Self::NewBranch => "New branch…",
            Self::Gap => "",
        }
    }

    /// What sits at the right of the row.
    fn keys(&self) -> Option<&str> {
        match self {
            Self::File(..) | Self::Image(..) | Self::NewBranch | Self::Gap => None,
            Self::Command(_, command) => keys_of(*command),
            Self::Branch(_, when) | Self::Citation(_, when) => Some(when),
            Self::Folder(_, _, note) => (!note.is_empty()).then_some(note),
        }
    }
}

/// A command's usual keys, shown beside it.
pub fn keys_of(command: Command) -> Option<&'static str> {
    Some(match command {
        Command::Save => "Ctrl+S",
        Command::Cut => "Ctrl+X",
        Command::Copy => "Ctrl+C",
        Command::Paste => "Ctrl+V",
        Command::CommandPalette => "Ctrl+Shift+P",
        Command::Undo => "Ctrl+Z",
        Command::Redo => "Ctrl+Y",
        Command::SelectAll => "Ctrl+A",
        Command::CloseTab => "Ctrl+W",
        Command::FindInFile => "Ctrl+F",
        Command::GoBack => "Ctrl+-",
        Command::QuickFix => "Ctrl+.",
        Command::GoForward => "Ctrl+Shift+-",
        Command::ReplaceInFile => "Ctrl+R",
        Command::FindInProject => "Ctrl+Shift+F",
        Command::OpenDiff => "Ctrl+G",
        Command::ToggleSidebar => "Ctrl+B",
        Command::ToggleComment => "Ctrl+/",
        Command::GoToLine => "Ctrl+L",
        Command::GoToDefinition => "F12",
        Command::GoToReferences => "Shift+F12",
        Command::FormatDocument => "Alt+Shift+F",
        Command::RenameSymbol => "F2",
        Command::AddComment => "Alt+C",
        Command::SplitPane => "Ctrl+\\",
        Command::Quit => "Ctrl+Q",
        _ => return None,
    })
}

pub const COMMANDS: [(&str, Command); 88] = [
    ("Save", Command::Save),
    ("Undo", Command::Undo),
    ("Redo", Command::Redo),
    ("Select All", Command::SelectAll),
    ("Close Tab", Command::CloseTab),
    ("Next Tab", Command::NextTab),
    ("Previous Tab", Command::PreviousTab),
    ("Split Pane", Command::SplitPane),
    ("Focus Next Pane", Command::FocusNextPane),
    ("Toggle Sidebar", Command::ToggleSidebar),
    ("Find in Project", Command::FindInProject),
    ("Review Changes", Command::OpenDiff),
    ("Add Comment", Command::AddComment),
    ("Blame Line", Command::BlameLine),
    ("Replace in Project", Command::ReplaceInProject),
    ("Toggle Markdown Source", Command::MarkdownPreview),
    ("Open in Browser", Command::OpenInBrowser),
    ("Focus Agent Pane", Command::FocusAgent),
    ("Build PDF", Command::BuildPdf),
    ("Export to PDF", Command::ExportPdf),
    ("Compare Plan Versions", Command::ComparePlanVersions),
    ("Show Line in PDF", Command::ShowInPdf),
    ("Toggle Maximized Side Pane", Command::MaximizePane),
    ("Toggle Maximized Editor", Command::MaximizeEditor),
    ("Find in File", Command::FindInFile),
    ("Go Back", Command::GoBack),
    ("Next Change", Command::NextChange),
    ("Previous Change", Command::PreviousChange),
    ("Show Hover", Command::ShowHover),
    ("Quick Fix…", Command::QuickFix),
    ("Go Forward", Command::GoForward),
    ("Replace in File", Command::ReplaceInFile),
    ("Toggle Comment", Command::ToggleComment),
    ("Duplicate Line", Command::DuplicateLine),
    ("Move Line Up", Command::MoveLineUp),
    ("Go to Line", Command::GoToLine),
    ("Format: Bold", Command::Format(Format::Bold)),
    ("Format: Italic", Command::Format(Format::Italic)),
    ("Format: Inline Code", Command::Format(Format::Code)),
    ("Format: Heading", Command::Format(Format::Heading)),
    ("Format: Bulleted List", Command::Format(Format::Bullet)),
    ("Format: Task List", Command::Format(Format::Task)),
    ("Format: Quote", Command::Format(Format::Quote)),
    ("Send Comments to Agent", Command::SendToAgent),
    ("Send Selection to Agent", Command::MentionSelection),
    ("Accept Proposed Change", Command::AcceptProposal),
    ("Reject Proposed Change", Command::RejectProposal),
    ("Approve Plan", Command::ApprovePlan),
    ("Send Plan Back", Command::SendBackPlan),
    ("Show Agents", Command::ShowAgents),
    ("Close Side Pane", Command::CloseDock),
    ("Show Outline", Command::ShowOutline),
    ("Show Source Control", Command::ShowSourceControl),
    ("Toggle Terminal", Command::ToggleTerminal),
    ("New Terminal", Command::NewTerminal),
    ("Show Comments", Command::ShowComments),
    ("Show Browser", Command::ShowBrowser),
    ("List Agents", Command::ListAgents),
    ("Run Cell", Command::RunCell),
    ("Run All Cells", Command::RunAllCells),
    ("Clear All Outputs", Command::ClearOutputs),
    ("Interrupt Kernel", Command::InterruptKernel),
    ("Restart Kernel", Command::RestartKernel),
    ("Getting Started", Command::ShowGuide),
    ("New Document", Command::NewDocument),
    ("Toggle Track Changes", Command::ToggleTracking),
    ("Toggle Spell Check", Command::ToggleSpelling),
    ("Accept Change", Command::AcceptChange),
    ("Reject Change", Command::RejectChange),
    ("Accept All Changes", Command::AcceptAllChanges),
    ("Reject All Changes", Command::RejectAllChanges),
    ("Review Previous Agent Turn", Command::ReviewPreviousTurn),
    ("Undo Agent Turn", Command::UndoTurn),
    ("Commit Staged Changes", Command::Commit),
    ("Open Claude Code", Command::OpenClaude),
    ("Open Codex", Command::OpenCodex),
    ("Open Folder as a Workspace", Command::OpenWorkspace),
    ("Next Workspace", Command::NextWorkspace),
    ("Previous Workspace", Command::PreviousWorkspace),
    ("Open Settings", Command::OpenSettings),
    ("Switch Branch", Command::SwitchBranch),
    ("Open Gemini CLI", Command::OpenGemini),
    ("Go to Definition", Command::GoToDefinition),
    ("Go to References", Command::GoToReferences),
    ("Format Document", Command::FormatDocument),
    ("Complete", Command::Complete),
    ("Rename Symbol", Command::RenameSymbol),
    ("Quit", Command::Quit),
];

/// Quick open and the command palette: a filtered list with a text box.
pub struct Palette {
    pub query: String,
    /// What the empty field says.
    hint: &'static str,
    items: Vec<Item>,
    matches: Vec<usize>,
    /// Each match's score, beside it, while something is typed.
    scores: Vec<i32>,
    /// What the matches were found for: a longer query only needs to look among them.
    matched: String,
    pub selected: usize,
    /// What's still happening, as "8,310 files…", shown at the right of the field.
    pub status: Option<String>,
    /// Set when the palette finds a folder, which lists again as a path is typed.
    pub folders: Option<crate::folders::Picker>,
}

/// Scores `text` against `query`, whose characters must appear in order. Runs of
/// consecutive matches and matches in the file name score higher.
pub fn fuzzy_score(query: &str, text: &str) -> Option<i32> {
    let name_start = text.rfind('/').map_or(0, |i| i + 1);
    let mut score = 0;
    // Where the last match ended, to see a run.
    let mut last = None;
    // Nothing is allocated: Quick Open scores every file in a big tree on each key.
    let mut rest = text.char_indices();
    for q in query.chars().flat_map(char::to_lowercase) {
        let (found, c) = rest.by_ref().find(|(_, c)| same_letter(*c, q))?;
        score += 1;
        if last == Some(found) {
            score += 4;
        }
        if found >= name_start {
            score += 2;
        }
        last = Some(found + c.len_utf8());
    }
    Some(score - text.len() as i32 / 16)
}

/// Whether `c` is `lower`, whatever its case.
fn same_letter(c: char, lower: char) -> bool {
    c == lower || (!c.is_ascii() || c.is_ascii_uppercase()) && c.to_lowercase().eq([lower])
}

impl Palette {
    pub fn new(items: Vec<Item>) -> Self {
        let mut palette = Self {
            query: String::new(),
            hint: "Type to search",
            items,
            matches: Vec::new(),
            scores: Vec::new(),
            matched: String::new(),
            selected: 0,
            status: None,
            folders: None,
        };
        palette.filter();
        palette
    }

    /// Adds items that arrived after the palette opened, as files do from a walk of a big
    /// tree. What's typed applies to them too, and the picked row stays picked.
    pub fn extend(&mut self, items: Vec<Item>) {
        let picked = self.matches.get(self.selected).copied();
        let from = self.items.len();
        self.items.extend(items);
        if self.query.is_empty() {
            self.matches.extend(from..self.items.len());
            return;
        }
        let mut scored: Vec<(i32, usize)> = self
            .scores
            .iter()
            .copied()
            .zip(self.matches.iter().copied())
            .collect();
        for i in from..self.items.len() {
            if let Some(score) = fuzzy_score(&self.query, self.items[i].label()) {
                scored.push((score, i));
            }
        }
        scored.sort_by_key(|(score, i)| (-score, *i));
        (self.scores, self.matches) = scored.into_iter().unzip();
        if let Some(picked) = picked {
            self.selected = self.matches.iter().position(|&i| i == picked).unwrap_or(0);
        }
    }

    /// How many items it holds.
    #[cfg(test)]
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// A palette whose empty field asks for something other than a search.
    pub fn asking(items: Vec<Item>, hint: &'static str) -> Self {
        Self {
            hint,
            ..Self::new(items)
        }
    }

    /// Lists folders again for what's typed, when it's a path into another folder, and
    /// filters by it either way.
    pub fn refresh(&mut self) {
        let fresh = self
            .folders
            .as_mut()
            .and_then(|picker| picker.items_for(&self.query));
        if let Some(items) = fresh {
            self.items = items;
            self.matched.clear();
        }
        self.filter();
    }

    pub fn filter(&mut self) {
        // Nothing typed means no ranking: the list keeps the order it came in.
        if self.query.is_empty() {
            self.matches = (0..self.items.len()).collect();
            self.scores.clear();
            self.matched.clear();
            self.selected = 0;
            return;
        }
        // A letter added at the end can only narrow what matched, so only that is looked at
        // again: in a tree of half a million files, each key stays quick.
        let narrowing = !self.matched.is_empty() && self.query.starts_with(&self.matched);
        let candidates: Vec<usize> = if narrowing {
            std::mem::take(&mut self.matches)
        } else {
            (0..self.items.len()).collect()
        };
        let mut scored: Vec<(i32, usize)> = candidates
            .into_iter()
            .filter(|&i| self.items[i] != Item::Gap)
            .filter_map(|i| Some((fuzzy_score(&self.query, self.items[i].label())?, i)))
            .collect();
        scored.sort_by_key(|(score, i)| (-score, *i));
        (self.scores, self.matches) = scored.into_iter().unzip();
        self.matched = self.query.clone();
        self.selected = 0;
    }

    pub fn move_by(&mut self, delta: isize) {
        let last = self.matches.len().saturating_sub(1) as isize;
        self.selected = (self.selected as isize + delta).clamp(0, last) as usize;
        if self.current() == Some(&Item::Gap) {
            self.selected = (self.selected as isize + delta).clamp(0, last) as usize;
        }
    }

    pub fn current(&self) -> Option<&Item> {
        self.items.get(*self.matches.get(self.selected)?)
    }

    pub fn area(screen: Rect) -> Rect {
        let width = WIDTH.min(screen.w);
        Rect::new(
            screen.x + (screen.w - width) / 2,
            // Below the breadcrumbs, so its edge doesn't run through them.
            3,
            width,
            ROWS + HEADER_ROWS,
        )
    }

    pub fn row_at(&self, screen: Rect, y: u16) -> Option<usize> {
        let row = y.checked_sub(Self::area(screen).y + HEADER_ROWS)? as usize;
        (row < self.matches.len().min(ROWS as usize)).then_some(row)
    }

    pub fn draw(
        &self,
        grid: &mut Grid,
        hover: Option<(u16, u16)>,
        measure: &dyn Measure,
        theme: &Theme,
    ) {
        let area = Self::area(grid.area());
        let rows = self.matches.len().min(ROWS as usize) as u16;
        let area = Rect::new(area.x, area.y, area.w, rows + HEADER_ROWS);
        raised(grid, area, theme);
        let base = Style {
            fg: theme.text.fg,
            bg: theme.popup,
            ..theme.bar
        };
        let dim = Style {
            fg: theme.popup_dim,
            ..base
        };
        grid.glyph(
            area.x as f32 + TEXT_INSET,
            area.y,
            Icon::Search,
            theme.popup_dim,
            "⌕",
            base,
        );
        // Clear of the icon. The hint waits a little past the caret, so they don't touch.
        let x = area.x as f32 + TEXT_INSET + 2.3;
        let cell = area.x + 4;
        let font = Font {
            size: INTERFACE_SIZE_PERCENT,
            ..Font::default()
        };
        let caret = x - 0.1 + measure.width(&self.query, font);
        // The status keeps clear of what's typed, and gives way to it when both don't fit:
        // the query is what the person is working on.
        let status_right = area.right().saturating_sub(2);
        let status = self.status.as_deref().map(|text| {
            let width = measure.width(
                text,
                Font {
                    size: 85,
                    ..Font::default()
                },
            );
            (text, status_right as f32 - width)
        });
        let status = status.filter(|(_, left)| caret + STATUS_GAP <= *left);
        let end = status.map_or(area.right(), |(_, left)| (left - STATUS_GAP / 2.0) as u16);
        if self.query.is_empty() {
            grid.label_at(x + HINT_GAP, cell, area.y, self.hint, dim, end, 100);
        } else {
            grid.label_at(x, cell, area.y, &self.query, base, end, 100);
        }
        if let Some((text, _)) = status {
            grid.label_right(status_right, area.y, text, dim, 85);
        }
        grid.set_caret(caret, area.y, 0.56);
        let line_y = area.y as f32 + HEADER_LINE;
        let edge = Bounds::cells(area.x as f32, line_y, area.w as f32, 0.0);
        grid.hairline(edge, theme.popup_border);
        for (row, index) in self.matches.iter().take(ROWS as usize).enumerate() {
            let y = area.y + HEADER_ROWS + row as u16;
            let line = Rect::new(area.x, y, area.w, 1);
            if self.items[*index] == Item::Gap {
                let across = area.w as f32 - TEXT_INSET * 2.0;
                let rule = Bounds::cells(area.x as f32 + TEXT_INSET, y as f32 + 0.5, across, 0.0);
                grid.hairline(rule, theme.popup_border);
                continue;
            }
            let hovered = hover.is_some_and(|h| line.contains(h.0, h.1));
            if row == self.selected || hovered {
                let fill = if row == self.selected {
                    theme.pick
                } else {
                    theme.popup_hover
                };
                grid.panel(Bounds::inset(line, 0.5, 0.055), 18, Some(fill), None);
            }
            let text = self.items[*index].label();
            let end = area.right().saturating_sub(16);
            let inset = area.x as f32 + TEXT_INSET;
            // A long path keeps its end, which names the folder, and loses its middle.
            let shown = match &self.items[*index] {
                Item::Folder(..) => middle_out(text, f32::from(end) - inset, measure),
                _ => text.to_string(),
            };
            grid.label_at(inset, area.x + 2, y, &shown, base, end, 100);
            if let Some(keys) = self.items[*index].keys() {
                // The picked row's wash is lighter, so its keys need to be too.
                let fg = if row == self.selected {
                    theme.text.fg
                } else {
                    theme.popup_dim
                };
                let quiet = Style { fg, ..base };
                grid.label_right(area.right().saturating_sub(2), y, keys, quiet, 85);
            }
        }
    }
}

/// `text` with characters taken from its middle until it fits `room` cells.
fn middle_out(text: &str, room: f32, measure: &dyn Measure) -> String {
    let font = Font {
        size: INTERFACE_SIZE_PERCENT,
        ..Font::default()
    };
    if measure.width(text, font) <= room {
        return text.to_string();
    }
    let chars: Vec<char> = text.chars().collect();
    let mut keep = chars.len();
    while keep > 2 {
        keep -= 1;
        let head = keep / 3;
        let tail = keep - head;
        let tried: String = chars[..head]
            .iter()
            .chain(std::iter::once(&'…'))
            .chain(&chars[chars.len() - tail..])
            .collect();
        if measure.width(&tried, font) <= room {
            return tried;
        }
    }
    "…".to_string()
}

/// What a text box shows.
pub struct Input<'a> {
    pub text: &'a str,
    pub hint: &'a str,
    pub focused: bool,
    /// The colour behind the box's rounded corners.
    pub behind: Rgb,
}

/// A one-line text box. Text, placeholder and caret share one origin, and the caret comes
/// from measuring the text, so it can't drift out of the box or onto the words.
pub fn input(grid: &mut Grid, line: Rect, field: &Input, measure: &dyn Measure, theme: &Theme) {
    /// Space between the box's edge and its text.
    const PADDING: f32 = 0.8;
    let style = Style {
        fg: theme.text.fg,
        bg: theme.input,
        ..theme.sidebar
    };
    grid.fill(line, style);
    let border = if field.focused {
        theme.focus
    } else {
        theme.popup_border
    };
    grid.field(line, field.behind, theme.input, border);
    let (x, y) = (line.x as f32 + PADDING, line.y);
    let first = line.x + 1;
    if field.text.is_empty() {
        let dim = Style {
            fg: theme.gutter.fg,
            ..style
        };
        grid.label_at(x, first, y, field.hint, dim, line.right(), 95);
    } else {
        grid.label_at(x, first, y, field.text, style, line.right(), 95);
    }
    if field.focused {
        let font = Font {
            size: 95,
            ..Font::default()
        };
        // Just clear of the first letter, when there's only a placeholder.
        let end = x + measure.width(field.text, font) - 0.1;
        let last = line.right() as f32 - PADDING;
        grid.set_caret(end.min(last), y, 0.56);
    }
}

/// A floating panel with room above and below its rows. Paint reaches past the cells, so the
/// cell tier keeps its plain box.
pub fn raised(grid: &mut Grid, area: Rect, theme: &Theme) {
    let base = Style {
        fg: theme.text.fg,
        bg: theme.popup,
        ..theme.bar
    };
    grid.fill(area, base);
    let bounds = Bounds::inset(area, 0.0, -PANEL_PADDING);
    grid.popup(bounds, 28, theme.popup, theme.popup_border);
}

/// A floating panel. Its corner cells keep what's behind them, so rounded corners show the
/// page rather than a square of panel colour.
pub fn popup(grid: &mut Grid, area: Rect, theme: &Theme) {
    let base = Style {
        fg: theme.text.fg,
        bg: theme.popup,
        ..theme.bar
    };
    for y in area.y..area.bottom() {
        let edge = y == area.y || y + 1 == area.bottom();
        let (x, w) = if edge {
            (area.x + 1, area.w.saturating_sub(2))
        } else {
            (area.x, area.w)
        };
        grid.fill(Rect::new(x, y, w, 1), base);
    }
    let bounds = cellix_render::Bounds::inset(area, 0.0, 0.0);
    grid.popup(bounds, 28, theme.popup, theme.popup_border);
}

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

    /// The status at the field's right end gives way to a long query instead of covering it.
    #[test]
    fn a_long_query_keeps_clear_of_the_status() {
        let field = |query: &str| {
            let mut palette = Palette::new(Vec::new());
            palette.query = query.to_string();
            palette.status = Some("8,310 files…".to_string());
            let mut grid = Grid::new(100, 20, Style::default());
            palette.draw(
                &mut grid,
                None,
                &cellix_render::CellMeasure,
                &Theme::default(),
            );
            grid.row_text(Palette::area(grid.area()).y)
        };
        let short = field("needle");
        assert!(
            short.contains("needle") && short.contains("8,310 files…"),
            "{short}"
        );
        // Fits the field, but reaches where the status sits.
        let long = "src/a/long/path/that/someone/pasted/in/it/needle.rs";
        let row = field(long);
        assert!(row.contains(long), "the query stays whole: {row}");
        assert!(!row.contains("files…"), "and the status gives way: {row}");
    }

    #[test]
    fn subsequence_required() {
        assert!(fuzzy_score("xyz", "abc").is_none());
        assert!(fuzzy_score("abc", "a-b-c").is_some());
    }

    #[test]
    fn the_keyboard_steps_over_a_gap() {
        let items = vec![
            Item::Branch("main".to_string(), "current".to_string()),
            Item::Gap,
            Item::NewBranch,
        ];
        let mut palette = Palette::asking(items, "Switch branch");
        palette.move_by(1);
        assert_eq!(palette.current(), Some(&Item::NewBranch));
        palette.query = "new".to_string();
        palette.filter();
        assert_eq!(
            palette.current(),
            Some(&Item::NewBranch),
            "gaps don't match"
        );
    }

    #[test]
    fn file_name_beats_directory() {
        let by_name = fuzzy_score("app", "src/app.rs").unwrap();
        let by_dir = fuzzy_score("app", "app/src/main.rs").unwrap();
        assert!(by_name > by_dir);
    }
}