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
//! Declarative cross-platform keybindings.
//!
//! Apps declare `Accelerator`s and register them with the active
//! [`Backend`][crate::Backend]. The backend watches native key events, matches
//! them to the registered accelerators, and emits
//! [`UiEvent::Accelerator`][crate::UiEvent::Accelerator] when one fires.
//! Apps dispatch on [`AcceleratorId`] without parsing key strings themselves.
//!
//! ## Platform idiom parity
//!
//! Universal bindings ([`KeyBinding::Save`], [`KeyBinding::Copy`], etc.)
//! render as `⌘S` on macOS and `Ctrl+S` elsewhere — the app doesn't care.
//! App-specific bindings use [`KeyBinding::Literal`], which accepts both
//! vim-style (`<C-S-t>`) and plus-style (`Ctrl+Shift+T`) input.
//!
//! See `quadraui/docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §3 for the full rationale.

use serde::{Deserialize, Serialize};

use crate::event::{Key, NamedKey};
use crate::types::{Modifiers, WidgetId};

/// Stable identifier for a registered accelerator. Apps match on this in the
/// [`UiEvent::Accelerator`][crate::UiEvent::Accelerator] arm of their
/// dispatcher.
///
/// Conventionally namespaced (`"editor.save"`, `"plugin:my-ext:send"`) so
/// plugin accelerators don't collide with app accelerators.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AcceleratorId(pub String);

impl AcceleratorId {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<&str> for AcceleratorId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

impl From<String> for AcceleratorId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

/// When an [`Accelerator`] should fire relative to app state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AcceleratorScope {
    /// Fires regardless of what's focused. E.g. "Ctrl+P" for the palette.
    Global,
    /// Fires only when the given widget (or its descendants) have focus.
    /// Used for widget-local shortcuts like Esc inside a picker.
    Widget(WidgetId),
    /// Fires only when the given mode is active. For vim-like apps: `"n"`
    /// = Normal mode, `"i"` = Insert, `"v"` = Visual. Apps define the
    /// mode strings.
    Mode(String),
}

/// The key combination to bind.
///
/// Universal variants render platform-appropriately (e.g. `⌘S` on macOS);
/// [`KeyBinding::Literal`] is for app-specific bindings that don't have a
/// universal name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyBinding {
    // ── Universal accelerators (render platform-appropriately) ─────────
    Save,
    Open,
    New,
    Close,
    Copy,
    Cut,
    Paste,
    /// Consumed by [`crate::primitives::text_input::EditOp::from_key_binding`]
    Undo,
    /// See [`Self::Undo`].
    Redo,
    /// Also consumed by
    /// [`crate::primitives::text_input::EditOp::from_key_binding`] — see
    /// [`Self::Undo`].
    SelectAll,
    Find,
    Replace,
    Quit,

    /// App-specific binding. Parser accepts **both** vim-style
    /// (`<C-S-t>`) and plus-style (`Ctrl+Shift+T`) input; first character
    /// determines which parser runs. See
    /// [`parse_key_binding`] for the grammar.
    Literal(String),
}

/// A declared accelerator: its stable ID, the keys that trigger it, the
/// scope in which it's active, and an optional display label for menus.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Accelerator {
    pub id: AcceleratorId,
    pub binding: KeyBinding,
    pub scope: AcceleratorScope,
    /// Human-readable label for menus, tooltips, help. `None` means the
    /// backend derives one from the binding (e.g. "Ctrl+Shift+T").
    pub label: Option<String>,
}

// ─── Parsing ────────────────────────────────────────────────────────────────

/// Parsed form of a [`KeyBinding::Literal`] string. Backends match native
/// key events against this struct.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ParsedBinding {
    pub modifiers: Modifiers,
    /// Lowercased character for letters; uppercase named key (`Enter`,
    /// `F1`, `Escape`) for non-printables.
    pub key: String,
}

/// Parse a `KeyBinding::Literal` string. Accepts two formats:
///
/// - **Vim-style**: `<C-S-t>`, `<C-A-Left>`, `<F5>`. Starts with `<`.
///   Modifier letters: `C` = Ctrl, `S` = Shift, `A` = Alt, `D`/`M` =
///   Cmd/Super.
/// - **Plus-style**: `Ctrl+Shift+T`, `Cmd+S`, `Alt+F4`. Case-insensitive
///   modifiers.
///
/// Format is detected from the first character — `<` means vim-style,
/// anything else means plus-style. Single-character bindings without
/// separators (e.g. `"a"`, `"Escape"`) parse as plus-style with no
/// modifiers.
///
/// Returns `None` on unparseable input.
pub fn parse_key_binding(s: &str) -> Option<ParsedBinding> {
    let s = s.trim();
    if s.is_empty() {
        return None;
    }
    if s.starts_with('<') {
        parse_vim_style(s)
    } else {
        parse_plus_style(s)
    }
}

/// Vim-style: `<C-S-t>`, `<C-A-Left>`, `<F5>`, `<Escape>`.
fn parse_vim_style(s: &str) -> Option<ParsedBinding> {
    let inner = s.strip_prefix('<')?.strip_suffix('>')?;
    if inner.is_empty() {
        return None;
    }
    let parts: Vec<&str> = inner.split('-').collect();
    // Last part is the key; earlier parts are modifier letters.
    let (key_part, mod_parts) = parts.split_last()?;
    let mut modifiers = Modifiers::default();
    for m in mod_parts {
        match *m {
            "C" => modifiers.ctrl = true,
            "S" => modifiers.shift = true,
            "A" => modifiers.alt = true,
            "D" | "M" => modifiers.cmd = true,
            _ => return None,
        }
    }
    Some(ParsedBinding {
        modifiers,
        key: normalise_key_name(key_part),
    })
}

/// Plus-style: `Ctrl+Shift+T`, `Cmd+S`, `Alt+F4`, `Escape`.
fn parse_plus_style(s: &str) -> Option<ParsedBinding> {
    let parts: Vec<&str> = s.split('+').map(str::trim).collect();
    if parts.is_empty() || parts.iter().any(|p| p.is_empty()) {
        return None;
    }
    let mut modifiers = Modifiers::default();
    let mut key: Option<String> = None;
    for p in &parts {
        let lower = p.to_ascii_lowercase();
        match lower.as_str() {
            "ctrl" | "control" => modifiers.ctrl = true,
            "shift" => modifiers.shift = true,
            "alt" | "option" | "opt" => modifiers.alt = true,
            "cmd" | "command" | "super" | "win" | "meta" => modifiers.cmd = true,
            _ => {
                if key.is_some() {
                    // More than one non-modifier token → malformed.
                    return None;
                }
                key = Some(normalise_key_name(p));
            }
        }
    }
    Some(ParsedBinding {
        modifiers,
        key: key?,
    })
}

/// Normalise a key name to the canonical form used by backends.
///
/// - Single letters → lowercase (`T` → `t`).
/// - Named keys → TitleCase preserved (`Escape`, `F5`, `Left`).
fn normalise_key_name(s: &str) -> String {
    if s.chars().count() == 1 {
        s.to_ascii_lowercase()
    } else {
        s.to_string()
    }
}

// ─── Matching ───────────────────────────────────────────────────────────────

/// Parse a [`KeyBinding`] (any variant) into a [`ParsedBinding`]. Returns
/// `None` for unparseable literals — those silently miss matching, same
/// as [`parse_key_binding`]'s contract. The universal arms map to the
/// canonical vim-style strings [`parse_key_binding`] itself accepts, so a
/// `KeyBinding::Save` and a `KeyBinding::Literal("<C-s>".into())` resolve
/// identically.
pub fn parse_binding(b: &KeyBinding) -> Option<ParsedBinding> {
    match b {
        KeyBinding::Literal(s) if s.is_empty() => None,
        KeyBinding::Literal(s) => parse_key_binding(s),
        KeyBinding::Save => parse_key_binding("<C-s>"),
        KeyBinding::Open => parse_key_binding("<C-o>"),
        KeyBinding::New => parse_key_binding("<C-n>"),
        KeyBinding::Close => parse_key_binding("<C-w>"),
        KeyBinding::Copy => parse_key_binding("<C-c>"),
        KeyBinding::Cut => parse_key_binding("<C-x>"),
        KeyBinding::Paste => parse_key_binding("<C-v>"),
        KeyBinding::Undo => parse_key_binding("<C-z>"),
        KeyBinding::Redo => parse_key_binding("<C-S-z>"),
        KeyBinding::SelectAll => parse_key_binding("<C-a>"),
        KeyBinding::Find => parse_key_binding("<C-f>"),
        KeyBinding::Replace => parse_key_binding("<C-h>"),
        KeyBinding::Quit => parse_key_binding("<C-q>"),
    }
}

/// Canonical key name for a native [`Key`], in the same form
/// [`ParsedBinding`]'s `key` field uses — lowercased single ASCII
/// characters, named keys in their `normalise_key_name` TitleCase.
/// Backends and resolvers match a native key press against a registered
/// binding by comparing this name (plus modifiers) against
/// `ParsedBinding::key`.
pub fn key_to_binding_name(key: &Key) -> String {
    match key {
        Key::Char(c) => {
            // Single ASCII letters parse as lowercase in
            // `parse_key_binding`; mirror that so `<C-S-T>` and
            // `Ctrl+Shift+t` both match here.
            if c.is_ascii() {
                c.to_ascii_lowercase().to_string()
            } else {
                c.to_string()
            }
        }
        Key::Named(named) => named_key_to_binding_name(*named).to_string(),
    }
}

/// Map a [`NamedKey`] to the canonical name [`parse_key_binding`]
/// produces. Letter case follows [`normalise_key_name`]: single letters
/// lowercase, named keys TitleCase-preserved.
fn named_key_to_binding_name(named: NamedKey) -> &'static str {
    use NamedKey::*;
    match named {
        Escape => "Escape",
        Tab => "Tab",
        BackTab => "BackTab",
        Enter => "Enter",
        Backspace => "Backspace",
        Delete => "Delete",
        Insert => "Insert",
        Home => "Home",
        End => "End",
        PageUp => "PageUp",
        PageDown => "PageDown",
        Up => "Up",
        Down => "Down",
        Left => "Left",
        Right => "Right",
        F(1) => "F1",
        F(2) => "F2",
        F(3) => "F3",
        F(4) => "F4",
        F(5) => "F5",
        F(6) => "F6",
        F(7) => "F7",
        F(8) => "F8",
        F(9) => "F9",
        F(10) => "F10",
        F(11) => "F11",
        F(12) => "F12",
        F(_) => "",
        CapsLock => "CapsLock",
        NumLock => "NumLock",
        ScrollLock => "ScrollLock",
        Menu => "Menu",
    }
}

// ─── Rendering ──────────────────────────────────────────────────────────────

/// Render an [`Accelerator`] for display in a menu, tooltip, or help overlay.
///
/// Always platform-appropriate: `⌘⇧T` on macOS, `Ctrl+Shift+T` on
/// Win/Linux/TUI — regardless of which input format the app used.
pub fn render_accelerator(acc: &Accelerator, platform: Platform) -> String {
    if let Some(ref label) = acc.label {
        return label.clone();
    }
    render_binding(&acc.binding, platform)
}

/// Render just the [`KeyBinding`] portion.
pub fn render_binding(b: &KeyBinding, platform: Platform) -> String {
    match b {
        KeyBinding::Save => platform.fmt_mod_letter("Ctrl", "S"),
        KeyBinding::Open => platform.fmt_mod_letter("Ctrl", "O"),
        KeyBinding::New => platform.fmt_mod_letter("Ctrl", "N"),
        KeyBinding::Close => platform.fmt_mod_letter("Ctrl", "W"),
        KeyBinding::Copy => platform.fmt_mod_letter("Ctrl", "C"),
        KeyBinding::Cut => platform.fmt_mod_letter("Ctrl", "X"),
        KeyBinding::Paste => platform.fmt_mod_letter("Ctrl", "V"),
        KeyBinding::Undo => platform.fmt_mod_letter("Ctrl", "Z"),
        KeyBinding::Redo => platform.fmt_mod_shift_letter("Ctrl", "Z"),
        KeyBinding::SelectAll => platform.fmt_mod_letter("Ctrl", "A"),
        KeyBinding::Find => platform.fmt_mod_letter("Ctrl", "F"),
        KeyBinding::Replace => platform.fmt_mod_letter("Ctrl", "H"),
        KeyBinding::Quit => platform.fmt_mod_letter("Ctrl", "Q"),
        KeyBinding::Literal(s) => render_literal(s, platform),
    }
}

fn render_literal(s: &str, platform: Platform) -> String {
    match parse_key_binding(s) {
        Some(p) => platform.fmt_parsed(&p),
        // Unparseable literal — show the raw string rather than hide it.
        None => s.to_string(),
    }
}

/// Platform identity for rendering. Backends return their own variant from
/// [`PlatformServices::platform_name`][crate::PlatformServices::platform_name].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Platform {
    Macos,
    Windows,
    Linux,
    Tui,
}

impl Platform {
    fn fmt_mod_letter(self, modifier: &str, letter: &str) -> String {
        match self {
            Platform::Macos => format!("{}{}", self.cmd_glyph(), letter),
            _ => format!("{}+{}", modifier, letter),
        }
    }

    fn fmt_mod_shift_letter(self, modifier: &str, letter: &str) -> String {
        match self {
            Platform::Macos => format!("{}⇧{}", self.cmd_glyph(), letter),
            _ => format!("{}+Shift+{}", modifier, letter),
        }
    }

    fn fmt_parsed(self, p: &ParsedBinding) -> String {
        match self {
            Platform::Macos => {
                let mut s = String::new();
                if p.modifiers.ctrl {
                    s.push('⌃');
                }
                if p.modifiers.alt {
                    s.push('⌥');
                }
                if p.modifiers.shift {
                    s.push('⇧');
                }
                if p.modifiers.cmd {
                    s.push('⌘');
                }
                s.push_str(&display_key(&p.key));
                s
            }
            _ => {
                let mut parts: Vec<&str> = Vec::new();
                if p.modifiers.ctrl {
                    parts.push("Ctrl");
                }
                if p.modifiers.alt {
                    parts.push("Alt");
                }
                if p.modifiers.shift {
                    parts.push("Shift");
                }
                if p.modifiers.cmd {
                    parts.push("Super");
                }
                let key_disp = display_key(&p.key);
                parts.push(&key_disp);
                parts.join("+")
            }
        }
    }

    fn cmd_glyph(self) -> &'static str {
        match self {
            Platform::Macos => "⌘",
            _ => "",
        }
    }
}

fn display_key(k: &str) -> String {
    if k.chars().count() == 1 {
        k.to_ascii_uppercase()
    } else {
        k.to_string()
    }
}

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

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

    fn mods(ctrl: bool, shift: bool, alt: bool, cmd: bool) -> Modifiers {
        Modifiers {
            ctrl,
            shift,
            alt,
            cmd,
        }
    }

    #[test]
    fn parse_vim_style_basic() {
        let p = parse_key_binding("<C-S-t>").unwrap();
        assert_eq!(p.modifiers, mods(true, true, false, false));
        assert_eq!(p.key, "t");
    }

    #[test]
    fn parse_vim_style_named_key() {
        let p = parse_key_binding("<C-A-Left>").unwrap();
        assert_eq!(p.modifiers, mods(true, false, true, false));
        assert_eq!(p.key, "Left");
    }

    #[test]
    fn parse_vim_style_no_modifiers() {
        let p = parse_key_binding("<F5>").unwrap();
        assert_eq!(p.modifiers, Modifiers::default());
        assert_eq!(p.key, "F5");
    }

    #[test]
    fn parse_vim_style_cmd_via_d_modifier() {
        let p = parse_key_binding("<D-s>").unwrap();
        assert_eq!(p.modifiers, mods(false, false, false, true));
    }

    #[test]
    fn parse_vim_style_rejects_unknown_modifier() {
        assert!(parse_key_binding("<X-t>").is_none());
    }

    #[test]
    fn parse_vim_style_rejects_unclosed() {
        assert!(parse_key_binding("<C-t").is_none());
    }

    #[test]
    fn parse_plus_style_basic() {
        let p = parse_key_binding("Ctrl+Shift+T").unwrap();
        assert_eq!(p.modifiers, mods(true, true, false, false));
        assert_eq!(p.key, "t");
    }

    #[test]
    fn parse_plus_style_case_insensitive_modifiers() {
        let p = parse_key_binding("ctrl+SHIFT+t").unwrap();
        assert_eq!(p.modifiers, mods(true, true, false, false));
        assert_eq!(p.key, "t");
    }

    #[test]
    fn parse_plus_style_cmd_aliases() {
        for input in ["Cmd+S", "Command+S", "Super+S", "Win+S", "Meta+S"] {
            let p = parse_key_binding(input).unwrap_or_else(|| panic!("failed to parse {input}"));
            assert_eq!(p.modifiers, mods(false, false, false, true));
            assert_eq!(p.key, "s", "input was {input}");
        }
    }

    #[test]
    fn parse_plus_style_alt_aliases() {
        for input in ["Alt+F4", "Option+F4", "Opt+F4"] {
            let p = parse_key_binding(input).unwrap();
            assert_eq!(p.modifiers, mods(false, false, true, false));
            assert_eq!(p.key, "F4");
        }
    }

    #[test]
    fn parse_plus_style_bare_key() {
        let p = parse_key_binding("Escape").unwrap();
        assert_eq!(p.modifiers, Modifiers::default());
        assert_eq!(p.key, "Escape");

        let p = parse_key_binding("a").unwrap();
        assert_eq!(p.key, "a");
    }

    #[test]
    fn parse_plus_style_rejects_multiple_keys() {
        assert!(parse_key_binding("Ctrl+A+B").is_none());
    }

    #[test]
    fn parse_plus_style_rejects_empty_parts() {
        assert!(parse_key_binding("Ctrl++T").is_none());
        assert!(parse_key_binding("+T").is_none());
    }

    #[test]
    fn parse_empty_or_whitespace() {
        assert!(parse_key_binding("").is_none());
        assert!(parse_key_binding("   ").is_none());
    }

    #[test]
    fn parse_round_trip_vim_and_plus_agree() {
        let vim = parse_key_binding("<C-S-t>").unwrap();
        let plus = parse_key_binding("Ctrl+Shift+T").unwrap();
        assert_eq!(vim, plus);
    }

    #[test]
    fn render_save_macos_vs_other() {
        let acc = Accelerator {
            id: AcceleratorId::new("app.save"),
            binding: KeyBinding::Save,
            scope: AcceleratorScope::Global,
            label: None,
        };
        assert_eq!(render_accelerator(&acc, Platform::Macos), "⌘S");
        assert_eq!(render_accelerator(&acc, Platform::Windows), "Ctrl+S");
        assert_eq!(render_accelerator(&acc, Platform::Linux), "Ctrl+S");
        assert_eq!(render_accelerator(&acc, Platform::Tui), "Ctrl+S");
    }

    #[test]
    fn render_redo_uses_shift_on_every_platform() {
        let b = KeyBinding::Redo;
        assert_eq!(render_binding(&b, Platform::Macos), "⌘⇧Z");
        assert_eq!(render_binding(&b, Platform::Linux), "Ctrl+Shift+Z");
    }

    #[test]
    fn render_literal_parses_and_formats() {
        let b = KeyBinding::Literal("<C-S-t>".into());
        assert_eq!(render_binding(&b, Platform::Linux), "Ctrl+Shift+T");
        assert_eq!(render_binding(&b, Platform::Macos), "⌃⇧T");
    }

    #[test]
    fn render_literal_plus_style_round_trips() {
        let b = KeyBinding::Literal("Ctrl+Shift+T".into());
        assert_eq!(render_binding(&b, Platform::Linux), "Ctrl+Shift+T");
    }

    #[test]
    fn render_literal_unparseable_falls_back_to_raw() {
        let b = KeyBinding::Literal("gibberish".into());
        assert_eq!(render_binding(&b, Platform::Linux), "gibberish");
    }

    #[test]
    fn render_uses_explicit_label_when_set() {
        let acc = Accelerator {
            id: AcceleratorId::new("custom"),
            binding: KeyBinding::Literal("<C-S-t>".into()),
            scope: AcceleratorScope::Global,
            label: Some("Secret handshake".into()),
        };
        assert_eq!(
            render_accelerator(&acc, Platform::Linux),
            "Secret handshake"
        );
    }

    #[test]
    fn accelerator_serde_round_trip() {
        let acc = Accelerator {
            id: AcceleratorId::new("editor.save"),
            binding: KeyBinding::Save,
            scope: AcceleratorScope::Global,
            label: None,
        };
        let json = serde_json::to_string(&acc).unwrap();
        let back: Accelerator = serde_json::from_str(&json).unwrap();
        assert_eq!(acc, back);

        let acc = Accelerator {
            id: AcceleratorId::new("terminal.maximize"),
            binding: KeyBinding::Literal("<C-S-t>".into()),
            scope: AcceleratorScope::Mode("normal".into()),
            label: Some("Maximize terminal".into()),
        };
        let json = serde_json::to_string(&acc).unwrap();
        let back: Accelerator = serde_json::from_str(&json).unwrap();
        assert_eq!(acc, back);
    }

    // ── parse_binding / key_to_binding_name ─────────────────────────────

    #[test]
    fn parse_binding_universal_matches_literal_equivalent() {
        assert_eq!(parse_binding(&KeyBinding::Save), parse_key_binding("<C-s>"));
        assert_eq!(
            parse_binding(&KeyBinding::Redo),
            parse_key_binding("<C-S-z>")
        );
    }

    #[test]
    fn parse_binding_literal_delegates_to_parse_key_binding() {
        assert_eq!(
            parse_binding(&KeyBinding::Literal("Ctrl+P".into())),
            parse_key_binding("Ctrl+P")
        );
    }

    #[test]
    fn parse_binding_empty_literal_is_none() {
        assert!(parse_binding(&KeyBinding::Literal(String::new())).is_none());
    }

    #[test]
    fn key_to_binding_name_lowercases_ascii_char() {
        assert_eq!(key_to_binding_name(&Key::Char('P')), "p");
        assert_eq!(key_to_binding_name(&Key::Char('p')), "p");
    }

    #[test]
    fn key_to_binding_name_named_key_matches_parsed_binding() {
        assert_eq!(key_to_binding_name(&Key::Named(NamedKey::F(5))), "F5");
        let parsed = parse_key_binding("<F5>").unwrap();
        assert_eq!(key_to_binding_name(&Key::Named(NamedKey::F(5))), parsed.key);
    }
}