iced-code-editor 0.4.2

A custom code editor widget for the Iced GUI framework with syntax highlighting, line numbers, and scrolling support.
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
//! State and command registry for the command palette.
//!
//! The palette is a keyboard-driven launcher for editor actions: `Ctrl+Shift+P`
//! opens a filtered list of every command available right now, typing narrows
//! it, and `Enter` runs the highlighted one. It exists so an action is
//! reachable without knowing its shortcut — the shortcut is shown beside each
//! row, so the palette also teaches them.
//!
//! The registry is extensible: a host application registers its own commands
//! with [`CodeEditor::set_custom_command_palette_entries`] and receives
//! [`Message::CommandPaletteAction`] carrying the entry's `id` when one is run.

pub(crate) mod dialog;
mod update;

use iced::widget::Id;

use super::actions::{
    ADD_CURSOR_ABOVE_SHORTCUT, ADD_CURSOR_BELOW_SHORTCUT, ActionContext,
    COPY_SHORTCUT, CUT_SHORTCUT, DUPLICATE_LINE_DOWN_SHORTCUT,
    DUPLICATE_LINE_UP_SHORTCUT, FIND_SHORTCUT, FOLD_ALL_SHORTCUT,
    FOLD_AT_CURSOR_SHORTCUT, GOTO_LINE_SHORTCUT, MOVE_LINE_DOWN_SHORTCUT,
    MOVE_LINE_UP_SHORTCUT, PASTE_SHORTCUT, REDO_SHORTCUT, REPLACE_SHORTCUT,
    SAVE_SHORTCUT, SELECT_ALL_SHORTCUT, SELECT_NEXT_OCCURRENCE_SHORTCUT,
    TOGGLE_COMMENT_SHORTCUT, TOGGLE_VIM_MODE_SHORTCUT, UNDO_SHORTCUT,
    UNFOLD_ALL_SHORTCUT,
};
use super::context_menu::ContextMenuItem;
use crate::canvas_editor::{CodeEditor, Message};
use crate::i18n::Translations;

/// What running a palette row does.
#[derive(Debug, Clone)]
pub(crate) enum PaletteAction {
    /// A built-in editor action, applied by re-entering [`CodeEditor::update`].
    Builtin(Box<Message>),
    /// A host-registered action, forwarded as [`Message::CommandPaletteAction`]
    /// carrying the entry's stable identifier.
    Custom(String),
}

/// One row of the palette: what is displayed, and what running it does.
#[derive(Debug, Clone)]
pub(crate) struct PaletteEntry {
    /// Text shown for the command.
    pub(crate) label: String,
    /// Keyboard shortcut hint shown to the right, empty when unbound.
    pub(crate) shortcut: String,
    /// The action performed when the row is run.
    pub(crate) action: PaletteAction,
}

impl PaletteEntry {
    /// Builds a row running a built-in editor message.
    fn builtin(
        label: String,
        shortcut: &'static str,
        message: Message,
    ) -> Self {
        Self {
            label,
            shortcut: shortcut.to_string(),
            action: PaletteAction::Builtin(Box::new(message)),
        }
    }
}

/// State owned by the command palette.
#[derive(Debug, Clone)]
pub(crate) struct CommandPaletteState {
    /// Current filter text typed by the user.
    pub(crate) query: String,
    /// Whether the palette is visible.
    pub(crate) is_open: bool,
    /// Index of the highlighted row within the filtered list.
    pub(crate) selected: usize,
    /// Stable input ID used for focus and selection operations.
    pub(crate) input_id: Id,
    /// Stable ID of the result list, used to scroll the highlighted row
    /// into view while navigating with the keyboard.
    pub(crate) scrollable_id: Id,
    /// Index of the row currently scrolled to the top of the list.
    ///
    /// Tracked rather than derived from [`Self::selected`] so the list only
    /// moves when the highlight would otherwise leave the window — see
    /// [`window_origin`].
    pub(crate) first_visible_row: usize,
}

impl Default for CommandPaletteState {
    fn default() -> Self {
        Self {
            query: String::new(),
            is_open: false,
            selected: 0,
            input_id: Id::unique(),
            scrollable_id: Id::unique(),
            first_visible_row: 0,
        }
    }
}

impl CommandPaletteState {
    /// Creates a closed palette state.
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Opens the palette with an empty query and the first row highlighted.
    ///
    /// The query is always reset: a palette that reopened on the previous
    /// search would hide most commands behind a filter the user did not
    /// type this time.
    pub(crate) fn open(&mut self) {
        self.query.clear();
        self.select_first_row();
        self.is_open = true;
    }

    /// Highlights the first row and scrolls the list back to the top.
    ///
    /// The two always move together: a highlight on row 0 under a list still
    /// scrolled to row 12 shows a window with nothing highlighted in it.
    pub(crate) fn select_first_row(&mut self) {
        self.selected = 0;
        self.first_visible_row = 0;
    }

    /// Closes the palette, leaving its query for the next [`Self::open`] to
    /// clear.
    pub(crate) fn close(&mut self) {
        self.is_open = false;
    }

    /// Moves the highlight by `delta` rows over a list of `len` entries,
    /// wrapping around at both ends, and scrolls the list only as far as
    /// keeping the new highlight visible requires.
    ///
    /// Wrapping matches the LSP completion menu, and makes the last command
    /// reachable with a single `Up` from the top.
    pub(crate) fn navigate(&mut self, delta: i32, len: usize) {
        if len == 0 {
            self.select_first_row();
            return;
        }
        let wrap = i32::try_from(len).unwrap_or(i32::MAX);
        let current = i32::try_from(self.selected).unwrap_or(0);
        let next = (current + delta).rem_euclid(wrap);
        self.selected = usize::try_from(next).unwrap_or(0);
        self.first_visible_row =
            window_origin(self.selected, self.first_visible_row, len);
    }
}

/// Returns the row the list should be scrolled to so that `selected` is
/// visible, moving as little as possible.
///
/// The window shows [`dialog::MAX_VISIBLE_ROWS`] rows starting at `origin`.
/// A highlight already inside that window leaves it where it is — scrolling on
/// every keystroke would make the list slide under the reader for no reason.
/// A highlight above the window becomes the new top row; one below it becomes
/// the new bottom row, which is what wrapping from the first row to the last
/// produces.
///
/// # Arguments
///
/// * `selected` - Index of the highlighted row
/// * `origin` - Row currently scrolled to the top of the list
/// * `len` - Number of rows in the list
///
/// # Returns
///
/// The row to scroll to the top, never far enough to leave a gap below the
/// last row
fn window_origin(selected: usize, origin: usize, len: usize) -> usize {
    // Scrolling past this would show empty space under the final row.
    let last_origin = len.saturating_sub(dialog::MAX_VISIBLE_ROWS);
    let origin = origin.min(last_origin);

    if selected < origin {
        selected
    } else if selected >= origin + dialog::MAX_VISIBLE_ROWS {
        (selected + 1 - dialog::MAX_VISIBLE_ROWS).min(last_origin)
    } else {
        origin
    }
}

/// Returns whether `label` matches `query`.
///
/// The match is a case-insensitive subsequence test, not a substring test:
/// the query's characters must appear in `label` in order but need not be
/// adjacent, so `tc` finds "Toggle Line Comment" and `fldall` finds "Fold
/// All". An empty query matches everything.
fn matches_query(label: &str, query: &str) -> bool {
    let mut remaining = query.chars().flat_map(char::to_lowercase).peekable();
    for candidate in label.chars().flat_map(char::to_lowercase) {
        match remaining.peek() {
            Some(wanted) if *wanted == candidate => {
                remaining.next();
            }
            Some(_) => {}
            None => return true,
        }
    }
    remaining.peek().is_none()
}

/// Builds the palette rows for the host-registered commands.
///
/// Disabled entries are dropped rather than dimmed: unlike a context menu,
/// whose fixed shape helps muscle memory, the palette is a search result
/// list, so every row it shows should be runnable.
fn custom_entries(entries: &[ContextMenuItem]) -> Vec<PaletteEntry> {
    entries
        .iter()
        .filter(|item| item.enabled)
        .map(|item| PaletteEntry {
            label: item.label.clone(),
            shortcut: item.shortcut.clone().unwrap_or_default(),
            action: PaletteAction::Custom(item.id.clone()),
        })
        .collect()
}

/// Builds the palette rows for the built-in editor commands that are
/// available in `context`.
fn default_entries(
    context: ActionContext,
    translations: &Translations,
) -> Vec<PaletteEntry> {
    let mut entries = vec![
        PaletteEntry::builtin(
            translations.command_palette_save(),
            SAVE_SHORTCUT,
            Message::WriteRequested,
        ),
        PaletteEntry::builtin(
            translations.command_palette_toggle_comment(),
            TOGGLE_COMMENT_SHORTCUT,
            Message::ToggleComment,
        ),
        PaletteEntry::builtin(
            translations.command_palette_move_line_up(),
            MOVE_LINE_UP_SHORTCUT,
            Message::MoveLineUp,
        ),
        PaletteEntry::builtin(
            translations.command_palette_move_line_down(),
            MOVE_LINE_DOWN_SHORTCUT,
            Message::MoveLineDown,
        ),
        PaletteEntry::builtin(
            translations.command_palette_duplicate_line_up(),
            DUPLICATE_LINE_UP_SHORTCUT,
            Message::DuplicateLineUp,
        ),
        PaletteEntry::builtin(
            translations.command_palette_duplicate_line_down(),
            DUPLICATE_LINE_DOWN_SHORTCUT,
            Message::DuplicateLineDown,
        ),
        PaletteEntry::builtin(
            translations.command_palette_goto_line(),
            GOTO_LINE_SHORTCUT,
            Message::OpenGotoLine,
        ),
        PaletteEntry::builtin(
            translations.command_palette_add_cursor_above(),
            ADD_CURSOR_ABOVE_SHORTCUT,
            Message::AddCursorAbove,
        ),
        PaletteEntry::builtin(
            translations.command_palette_add_cursor_below(),
            ADD_CURSOR_BELOW_SHORTCUT,
            Message::AddCursorBelow,
        ),
        PaletteEntry::builtin(
            translations.command_palette_select_next_occurrence(),
            SELECT_NEXT_OCCURRENCE_SHORTCUT,
            Message::SelectNextOccurrence,
        ),
        PaletteEntry::builtin(
            translations.command_palette_toggle_vim_mode(),
            TOGGLE_VIM_MODE_SHORTCUT,
            Message::ToggleVimMode,
        ),
        // An empty payload is not an empty paste: it asks
        // `CodeEditor::handle_paste_msg` to read the clipboard and send a
        // second `Paste` carrying what it found. The context menu spells its
        // Paste entry the same way.
        PaletteEntry::builtin(
            translations.context_menu_paste(),
            PASTE_SHORTCUT,
            Message::Paste(String::new()),
        ),
    ];

    if context.can_undo {
        entries.push(PaletteEntry::builtin(
            translations.context_menu_undo(),
            UNDO_SHORTCUT,
            Message::Undo,
        ));
    }
    if context.can_redo {
        entries.push(PaletteEntry::builtin(
            translations.context_menu_redo(),
            REDO_SHORTCUT,
            Message::Redo,
        ));
    }
    if context.has_selection {
        entries.push(PaletteEntry::builtin(
            translations.context_menu_cut(),
            CUT_SHORTCUT,
            Message::Cut,
        ));
        entries.push(PaletteEntry::builtin(
            translations.context_menu_copy(),
            COPY_SHORTCUT,
            Message::Copy,
        ));
    }
    if context.has_content {
        entries.push(PaletteEntry::builtin(
            translations.context_menu_select_all(),
            SELECT_ALL_SHORTCUT,
            Message::SelectAll,
        ));
    }
    if context.search_replace_enabled {
        entries.push(PaletteEntry::builtin(
            translations.command_palette_find(),
            FIND_SHORTCUT,
            Message::OpenSearch,
        ));
        entries.push(PaletteEntry::builtin(
            translations.command_palette_replace(),
            REPLACE_SHORTCUT,
            Message::OpenSearchReplace,
        ));
    }
    if context.folding_enabled {
        entries.push(PaletteEntry::builtin(
            translations.command_palette_fold_at_cursor(),
            FOLD_AT_CURSOR_SHORTCUT,
            Message::ToggleFoldAtCursor,
        ));
        entries.push(PaletteEntry::builtin(
            translations.command_palette_fold_all(),
            FOLD_ALL_SHORTCUT,
            Message::FoldAll,
        ));
        entries.push(PaletteEntry::builtin(
            translations.command_palette_unfold_all(),
            UNFOLD_ALL_SHORTCUT,
            Message::UnfoldAll,
        ));
    }
    if context.reveal_in_file_manager_enabled {
        entries.push(PaletteEntry::builtin(
            translations.context_menu_reveal_in_file_manager(),
            "",
            Message::RevealInFileManager,
        ));
    }

    entries
}

/// Assembles the full command list: host-registered entries first, then the
/// built-in ones when they are enabled.
fn build_entries(
    custom: &[ContextMenuItem],
    default_command_palette_enabled: bool,
    context: ActionContext,
    translations: &Translations,
) -> Vec<PaletteEntry> {
    let mut entries = custom_entries(custom);
    if default_command_palette_enabled {
        entries.extend(default_entries(context, translations));
    }
    entries
}

impl CodeEditor {
    /// Returns the palette rows matching the current query, in display order.
    pub(crate) fn command_palette_entries(&self) -> Vec<PaletteEntry> {
        build_entries(
            self.custom_command_palette_entries(),
            self.default_command_palette_enabled(),
            self.action_context(),
            &self.translations,
        )
        .into_iter()
        .filter(|entry| {
            matches_query(&entry.label, self.command_palette_state.query.trim())
        })
        .collect()
    }

    /// Opens the command palette programmatically.
    ///
    /// Use this to wire a menu item or toolbar button, alongside the built-in
    /// `Ctrl/Cmd+Shift+P` shortcut.
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that focuses the palette's input
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// let _task = editor.open_command_palette();
    /// ```
    pub fn open_command_palette(&mut self) -> iced::Task<Message> {
        self.update(&Message::OpenCommandPalette)
    }

    /// Closes the command palette without running anything.
    ///
    /// Safe to call when the palette is already closed.
    ///
    /// # Returns
    ///
    /// A `Task<Message>` returning focus to the editor canvas
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// let _task = editor.open_command_palette();
    /// let _task = editor.close_command_palette();
    /// ```
    pub fn close_command_palette(&mut self) -> iced::Task<Message> {
        self.update(&Message::CloseCommandPalette)
    }
}

#[cfg(test)]
mod tests {
    use std::cmp::Ordering;

    use super::dialog::MAX_VISIBLE_ROWS;
    use super::*;
    use crate::canvas_editor::compare_floats;
    use crate::{Language, Translations};

    fn labels(entries: &[PaletteEntry]) -> Vec<&str> {
        entries.iter().map(|entry| entry.label.as_str()).collect()
    }

    #[test]
    fn test_matches_query_accepts_out_of_order_free_subsequences() {
        assert!(matches_query("Toggle Line Comment", "tc"));
        assert!(matches_query("Fold All", "fldall"));
        assert!(matches_query("Fold All", "FOLD"));
        assert!(matches_query("Go to Line", ""));
        assert!(!matches_query("Fold All", "unfold"));
        assert!(!matches_query("Fold All", "lof"));
    }

    #[test]
    fn test_matches_query_is_case_insensitive_beyond_ascii() {
        assert!(matches_query("Aller à la ligne", "À"));
        assert!(matches_query("Tout replier", "TOUT"));
    }

    #[test]
    fn test_custom_entries_drop_disabled_items() {
        let entries = custom_entries(&[
            ContextMenuItem::new("app.format", "Format Document"),
            ContextMenuItem::new("app.rename", "Rename Symbol")
                .with_enabled(false),
        ]);

        assert_eq!(labels(&entries), vec!["Format Document"]);
        assert!(matches!(
            &entries[0].action,
            PaletteAction::Custom(id) if id == "app.format"
        ));
    }

    #[test]
    fn test_custom_entries_precede_built_in_entries() {
        let entries = build_entries(
            &[ContextMenuItem::new("app.format", "Format Document")],
            true,
            ActionContext::default(),
            &Translations::default(),
        );

        assert_eq!(entries[0].label, "Format Document");
        assert!(entries.len() > 1);
    }

    #[test]
    fn test_built_in_entries_can_be_turned_off() {
        let entries = build_entries(
            &[ContextMenuItem::new("app.format", "Format Document")],
            false,
            ActionContext::default(),
            &Translations::default(),
        );

        assert_eq!(labels(&entries), vec!["Format Document"]);
    }

    #[test]
    fn test_unavailable_actions_are_omitted() {
        let entries =
            default_entries(ActionContext::default(), &Translations::default());

        assert!(!labels(&entries).contains(&"Undo"));
        assert!(!labels(&entries).contains(&"Cut"));
        assert!(!labels(&entries).contains(&"Fold All"));
    }

    #[test]
    fn test_available_actions_are_listed() {
        let entries = default_entries(
            ActionContext {
                can_undo: true,
                can_redo: true,
                has_selection: true,
                has_content: true,
                reveal_in_file_manager_enabled: false,
                search_replace_enabled: true,
                folding_enabled: true,
            },
            &Translations::default(),
        );
        let labels = labels(&entries);

        assert!(labels.contains(&"Undo"));
        assert!(labels.contains(&"Redo"));
        assert!(labels.contains(&"Cut"));
        assert!(labels.contains(&"Select All"));
        assert!(labels.contains(&"Fold All"));
        assert!(labels.contains(&"Find"));
    }

    #[test]
    fn test_built_in_entries_use_the_selected_language() {
        let translations = Translations::new(Language::French);
        let entries = default_entries(ActionContext::default(), &translations);

        assert!(labels(&entries).contains(&"Aller à la ligne"));
        assert!(labels(&entries).contains(&"Coller"));
    }

    #[test]
    fn test_navigate_wraps_at_both_ends() {
        let mut state = CommandPaletteState::new();

        state.navigate(1, 3);
        assert_eq!(state.selected, 1);
        state.navigate(-1, 3);
        assert_eq!(state.selected, 0);
        state.navigate(-1, 3);
        assert_eq!(state.selected, 2);
        state.navigate(1, 3);
        assert_eq!(state.selected, 0);
    }

    #[test]
    fn test_navigate_on_empty_list_stays_at_zero() {
        let mut state = CommandPaletteState::new();
        state.selected = 4;

        state.navigate(1, 0);

        assert_eq!(state.selected, 0);
    }

    #[test]
    fn test_open_resets_the_previous_query_and_selection() {
        let mut state = CommandPaletteState::new();
        state.query = "fold".to_string();
        state.selected = 3;
        state.first_visible_row = 3;

        state.open();

        assert!(state.is_open);
        assert!(state.query.is_empty());
        assert_eq!(state.selected, 0);
        assert_eq!(state.first_visible_row, 0);
    }

    // ---- Scrolling the result list ----
    //
    // `window_origin` is the whole of the scroll arithmetic: the offset handed
    // to iced is `rows_to_pixels(first_visible_row)`, so a row index that is
    // right here is a pixel offset that is right there. `LONG` is longer than
    // one window, which is the only case where scrolling happens at all.

    /// A list comfortably longer than one window.
    const LONG: usize = MAX_VISIBLE_ROWS * 2 + 5;

    #[test]
    fn test_window_origin_does_not_move_for_a_row_already_visible() {
        // Every row of the first window, including its last, must leave the
        // list where it is — this is what the offset used to get wrong, by
        // scrolling the highlighted row up to the top on the very first Down.
        for selected in 0..MAX_VISIBLE_ROWS {
            assert_eq!(
                window_origin(selected, 0, LONG),
                0,
                "row {selected} is already visible in the first window"
            );
        }
    }

    #[test]
    fn test_window_origin_scrolls_by_one_row_when_the_highlight_moves_past_the_bottom()
     {
        assert_eq!(window_origin(MAX_VISIBLE_ROWS, 0, LONG), 1);
        assert_eq!(window_origin(MAX_VISIBLE_ROWS + 1, 1, LONG), 2);
    }

    #[test]
    fn test_window_origin_puts_a_row_above_the_window_at_the_top() {
        assert_eq!(window_origin(4, 7, LONG), 4);
    }

    #[test]
    fn test_window_origin_never_scrolls_past_the_last_full_window() {
        let last_origin = LONG - MAX_VISIBLE_ROWS;

        // Wrapping from the first row up to the last must show the final
        // window, not scroll the last row to the top and leave a gap below it.
        assert_eq!(window_origin(LONG - 1, 0, LONG), last_origin);
        // An origin left over from a longer list is clamped back in range.
        assert_eq!(window_origin(0, LONG, LONG), 0);
    }

    #[test]
    fn test_window_origin_stays_at_zero_for_a_list_that_fits() {
        for len in [0, 1, MAX_VISIBLE_ROWS] {
            for selected in 0..len {
                assert_eq!(
                    window_origin(selected, 0, len),
                    0,
                    "a list of {len} rows never scrolls"
                );
            }
        }
    }

    #[test]
    fn test_navigating_a_full_list_keeps_the_highlight_inside_the_window() {
        let mut state = CommandPaletteState::new();

        // One full lap down and back up: the highlight must never leave the
        // window, at any point, in either direction.
        for delta in [1, -1] {
            for _ in 0..=LONG {
                state.navigate(delta, LONG);
                let origin = state.first_visible_row;
                assert!(
                    (origin..origin + MAX_VISIBLE_ROWS)
                        .contains(&state.selected),
                    "row {} is outside the window at {origin}",
                    state.selected
                );
                assert!(
                    origin <= LONG - MAX_VISIBLE_ROWS,
                    "the window starts at {origin}, past the end of the list"
                );
            }
        }
    }

    #[test]
    fn test_row_offsets_account_for_the_gap_between_rows() {
        // A row's offset is its pitch, not its height: the two differ by the
        // one-pixel gap the list puts between rows, and a scroll computed
        // from the height alone drifts by one pixel per row.
        let two_rows = dialog::rows_to_pixels(2);
        let one_row = dialog::rows_to_pixels(1);

        assert_eq!(
            compare_floats(dialog::rows_to_pixels(0), 0.0),
            Ordering::Equal
        );
        assert_eq!(
            compare_floats(two_rows - one_row, one_row),
            Ordering::Equal,
            "rows must be evenly pitched"
        );
        assert!(
            one_row > 26.0,
            "the pitch must exceed the 26px row height by the row gap"
        );
    }
}