iced-code-editor 0.7.1

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
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
//! 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,
    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, REPLACE_SHORTCUT,
    SAVE_SHORTCUT, SELECT_NEXT_OCCURRENCE_SHORTCUT, SharedAction,
    TOGGLE_COMMENT_SHORTCUT, TOGGLE_VIM_MODE_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),
}

/// Identity of a palette command, stable across relabelling and filtering.
///
/// Used to remember which commands were run recently. A built-in is keyed by
/// its message's discriminant rather than by its label, so switching language
/// does not lose the history; a host command is keyed by the identifier it
/// registered, which is already documented as stable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PaletteCommandKey {
    /// A built-in action, keyed by the variant of the message it sends.
    Builtin(std::mem::Discriminant<Message>),
    /// A host-registered action, keyed by its 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,
    /// Current state of a toggle command, `None` for every other command.
    pub(crate) status: Option<bool>,
    /// Whether this row belongs to the recently-used block at the top.
    ///
    /// Set by [`promote_recent`] rather than by the builders, since it depends
    /// on the history and not on the command itself.
    pub(crate) is_recent: bool,
    /// 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::builtin_owned(label, shortcut.to_string(), message)
    }

    /// Builds a row whose shortcut hint is not a `'static` string.
    ///
    /// The shared actions carry theirs through [`SharedAction::shortcut`],
    /// which is `&'static str` but reaches here as an owned `String` after
    /// going through the same mapping the context menu uses.
    fn builtin_owned(
        label: String,
        shortcut: String,
        message: Message,
    ) -> Self {
        Self {
            label,
            shortcut,
            status: None,
            is_recent: false,
            action: PaletteAction::Builtin(Box::new(message)),
        }
    }

    /// Marks this row as a toggle currently in state `status`.
    fn with_status(mut self, status: bool) -> Self {
        self.status = Some(status);
        self
    }

    /// Returns the identity used to remember this command in the history.
    pub(crate) fn key(&self) -> PaletteCommandKey {
        match &self.action {
            PaletteAction::Builtin(message) => {
                PaletteCommandKey::Builtin(std::mem::discriminant(&**message))
            }
            PaletteAction::Custom(id) => PaletteCommandKey::Custom(id.clone()),
        }
    }
}

/// 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,
    /// Commands run from the palette, most recent first, capped at
    /// [`MAX_RECENT_COMMANDS`].
    pub(crate) recent: Vec<PaletteCommandKey>,
}

/// Number of recently-run commands kept at the top of the list.
pub(crate) const MAX_RECENT_COMMANDS: usize = 3;

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,
            recent: Vec::new(),
        }
    }
}

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;
    }

    /// Records `key` as the command that was just run.
    ///
    /// Any earlier occurrence is removed first, so running a command already
    /// in the history moves it back to the front instead of listing it twice.
    pub(crate) fn record_recent(&mut self, key: PaletteCommandKey) {
        self.recent.retain(|known| known != &key);
        self.recent.insert(0, key);
        self.recent.truncate(MAX_RECENT_COMMANDS);
    }

    /// 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(),
            status: item.status,
            is_recent: false,
            action: PaletteAction::Custom(item.id.clone()),
        })
        .collect()
}

/// Moves the rows in `recent` to the front, in history order, and flags them.
///
/// Filtering runs first, so a recent command the query excludes is simply not
/// there to promote; the block shrinks rather than showing a row the user
/// filtered out. The commands left behind keep their registration order, which
/// is what makes the rest of the list stable while the top three churn.
///
/// # Arguments
///
/// * `entries` - The filtered rows, in display order
/// * `recent` - Command keys, most recent first
///
/// # Returns
///
/// The rows reordered, with `is_recent` set on the promoted ones
fn promote_recent(
    entries: Vec<PaletteEntry>,
    recent: &[PaletteCommandKey],
) -> Vec<PaletteEntry> {
    let mut remaining = entries;
    let mut promoted = Vec::with_capacity(recent.len());

    for key in recent {
        if let Some(index) =
            remaining.iter().position(|entry| &entry.key() == key)
        {
            let mut entry = remaining.remove(index);
            entry.is_recent = true;
            promoted.push(entry);
        }
    }

    promoted.extend(remaining);
    promoted
}

/// Turns a shared action into a palette row.
///
/// The binding it renders — label, shortcut hint, message — comes from
/// [`SharedAction`], the same source the context menu reads.
fn shared_row(
    action: SharedAction,
    translations: &Translations,
) -> PaletteEntry {
    PaletteEntry::builtin_owned(
        action.label(translations),
        action.shortcut().to_string(),
        action.message(),
    )
}

/// 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,
        )
        .with_status(context.vim_enabled),
    ];

    // Paste keeps its place among the always-available commands: it is the
    // only shared action with no availability condition.
    entries.push(shared_row(SharedAction::Paste, translations));

    // The rest of what the context menu also offers. Labels, shortcuts and
    // messages come from `SharedAction`, so the two surfaces cannot disagree
    // on a binding; what belongs to the palette is *dropping* an unavailable
    // action instead of dimming it, since a search result list should only
    // offer rows that can be run.
    entries.extend(
        [
            SharedAction::Undo,
            SharedAction::Redo,
            SharedAction::Cut,
            SharedAction::Copy,
            SharedAction::SelectAll,
        ]
        .into_iter()
        .filter(|action| action.is_available(context))
        .map(|action| shared_row(action, translations)),
    );

    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,
        ));
    }

    // Reveal comes last: it acts on the file rather than on the text.
    if SharedAction::RevealInFileManager.is_available(context) {
        entries
            .push(shared_row(SharedAction::RevealInFileManager, translations));
    }

    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> {
        let entries: 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();

        promote_recent(entries, &self.command_palette_state.recent)
    }

    /// 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_entry_status_reaches_the_palette_row() {
        let entries = custom_entries(&[
            ContextMenuItem::new("app.format", "Format Document"),
            ContextMenuItem::new("app.fos", "Toggle Format On Save")
                .with_status(false),
        ]);

        assert_eq!(entries[0].status, None);
        assert_eq!(entries[1].status, Some(false));
    }

    #[test]
    fn test_toggle_vim_mode_reports_its_current_state() {
        let off =
            default_entries(ActionContext::default(), &Translations::default());
        let on = default_entries(
            ActionContext { vim_enabled: true, ..ActionContext::default() },
            &Translations::default(),
        );

        let status = |entries: &[PaletteEntry]| {
            entries
                .iter()
                .find(|entry| entry.label == "Toggle Vim Mode")
                .and_then(|entry| entry.status)
        };

        assert_eq!(status(&off), Some(false));
        assert_eq!(status(&on), Some(true));
    }

    #[test]
    fn test_recent_commands_move_to_the_front_in_history_order() {
        let entries =
            default_entries(ActionContext::default(), &Translations::default());
        let recent = vec![
            PaletteCommandKey::Builtin(std::mem::discriminant(
                &Message::ToggleVimMode,
            )),
            PaletteCommandKey::Builtin(std::mem::discriminant(
                &Message::MoveLineDown,
            )),
        ];

        let promoted = promote_recent(entries.clone(), &recent);

        assert_eq!(
            labels(&promoted)[..2],
            ["Toggle Vim Mode", "Move Line Down"]
        );
        assert!(promoted[0].is_recent);
        assert!(promoted[1].is_recent);
        assert!(!promoted[2].is_recent);
        // Promotion reorders, it never adds or drops a command.
        assert_eq!(promoted.len(), entries.len());
    }

    #[test]
    fn test_recent_commands_filtered_out_are_not_promoted() {
        let entries = vec![PaletteEntry::builtin(
            "Save".to_string(),
            SAVE_SHORTCUT,
            Message::WriteRequested,
        )];
        let recent = vec![PaletteCommandKey::Builtin(std::mem::discriminant(
            &Message::MoveLineUp,
        ))];

        let promoted = promote_recent(entries, &recent);

        assert!(!promoted[0].is_recent);
    }

    #[test]
    fn test_history_keeps_the_last_three_without_duplicates() {
        let mut state = CommandPaletteState::new();
        let key = |id: &str| PaletteCommandKey::Custom(id.to_string());

        for id in ["a", "b", "c", "d"] {
            state.record_recent(key(id));
        }
        assert_eq!(
            state.recent,
            vec![key("d"), key("c"), key("b")],
            "the oldest command falls off the end"
        );

        state.record_recent(key("b"));
        assert_eq!(
            state.recent,
            vec![key("b"), key("d"), key("c")],
            "re-running a known command moves it back to the front"
        );
    }

    #[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,
                vim_enabled: false,
            },
            &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"
        );
    }
}