inkferro-core 0.1.0

Layout, text measurement, ANSI render, and frame-diff engine for inkferro — a Rust-backed, byte-for-byte drop-in for the ink terminal UI library.
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
//! Port of [`parse-keypress.ts`](../../../ink/src/parse-keypress.ts) and the
//! kitty-protocol decoding from `kitty-keyboard.ts`.
//!
//! Pure function: a single terminal key sequence (the raw bytes of one
//! [`Segment::Key`](super::segmenter::Segment) emitted by the segmenter) is
//! decoded into a [`Key`] mirroring ink's `Key` object fields, including the
//! kitty-protocol fields (`super`, `hyper`, `caps_lock`, `num_lock`,
//! `event_type`, `is_kitty_protocol`, `text`, `is_printable`).
//!
//! The kitty CSI-u and kitty-enhanced special-key parsers are tried **first**,
//! exactly as upstream `parseKeypress` does; on no match the legacy
//! enquirer-derived keypress table is consulted.
//!
//! # Byte vs string note
//!
//! Upstream operates on a UTF-16 JS string. This port takes `&[u8]`. The
//! high-bit single-byte transform (`s[0] > 127 && s[1] === undefined`) is
//! ported on the raw bytes; everything else decodes the bytes to a `&str`
//! once (lossily, matching `TextDecoder`) and matches on Rust `char`s, so the
//! length/range branches (`s.length === 1`, `s <= '\x1a'`, `'0'..='9'`) behave
//! as the char operations they are upstream.

use super::kitty::KITTY_MODIFIERS;

/// Press / repeat / release, mirroring ink's `eventType`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventType {
    Press,
    Repeat,
    Release,
}

/// A decoded key event, mirroring ink's `Key` object (including kitty fields).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Key {
    /// Resolved key name (e.g. `"up"`, `"a"`, `"return"`, `"number"`). Empty
    /// when the sequence is unmapped.
    pub name: String,
    pub ctrl: bool,
    pub meta: bool,
    pub shift: bool,
    /// The original sequence (decoded to text). Mirrors `key.sequence`.
    pub sequence: String,
    /// The raw sequence. `None` mirrors upstream's `raw: undefined` cases.
    pub raw: Option<String>,
    /// Reassembled escape code for legacy fn-key sequences (`key.code`).
    pub code: Option<String>,
    pub super_key: bool,
    pub hyper: bool,
    pub caps_lock: bool,
    pub num_lock: bool,
    /// Only set by the kitty protocol parser.
    pub event_type: Option<EventType>,
    /// `true` only for kitty-protocol keypresses.
    pub is_kitty_protocol: bool,
    /// Associated text input (kitty `text-as-codepoints`, or the default
    /// character for printable kitty keys).
    pub text: Option<String>,
    /// Whether this key represents printable text input. Only set by the kitty
    /// protocol parser (`None` for legacy keys).
    pub is_printable: Option<bool>,
}

impl Key {
    /// An all-default key carrying only the given `sequence`/`raw`, matching the
    /// legacy `ParsedKey` initial object.
    fn legacy(sequence: String) -> Self {
        Key {
            name: String::new(),
            ctrl: false,
            meta: false,
            shift: false,
            raw: Some(sequence.clone()),
            sequence,
            code: None,
            super_key: false,
            hyper: false,
            caps_lock: false,
            num_lock: false,
            event_type: None,
            is_kitty_protocol: false,
            text: None,
            is_printable: None,
        }
    }
}

// --- key-name tables (1:1 with parse-keypress.ts `keyName`) ---

/// Returns the legacy `keyName[code]` mapping, or `None` if unmapped.
fn key_name(code: &str) -> Option<&'static str> {
    Some(match code {
        // xterm/gnome ESC O letter
        "OP" => "f1",
        "OQ" => "f2",
        "OR" => "f3",
        "OS" => "f4",
        // vt220-style ESC [ letter
        "[P" => "f1",
        "[Q" => "f2",
        "[R" => "f3",
        "[S" => "f4",
        // xterm/rxvt ESC [ number ~
        "[11~" => "f1",
        "[12~" => "f2",
        "[13~" => "f3",
        "[14~" => "f4",
        // from Cygwin and used in libuv
        "[[A" => "f1",
        "[[B" => "f2",
        "[[C" => "f3",
        "[[D" => "f4",
        "[[E" => "f5",
        // common
        "[15~" => "f5",
        "[17~" => "f6",
        "[18~" => "f7",
        "[19~" => "f8",
        "[20~" => "f9",
        "[21~" => "f10",
        "[23~" => "f11",
        "[24~" => "f12",
        // xterm ESC [ letter
        "[A" => "up",
        "[B" => "down",
        "[C" => "right",
        "[D" => "left",
        "[E" => "clear",
        "[F" => "end",
        "[H" => "home",
        // xterm/gnome ESC O letter
        "OA" => "up",
        "OB" => "down",
        "OC" => "right",
        "OD" => "left",
        "OE" => "clear",
        "OF" => "end",
        "OH" => "home",
        // xterm/rxvt ESC [ number ~
        "[1~" => "home",
        "[2~" => "insert",
        "[3~" => "delete",
        "[4~" => "end",
        "[5~" => "pageup",
        "[6~" => "pagedown",
        // putty
        "[[5~" => "pageup",
        "[[6~" => "pagedown",
        // rxvt
        "[7~" => "home",
        "[8~" => "end",
        // rxvt keys with modifiers
        "[a" => "up",
        "[b" => "down",
        "[c" => "right",
        "[d" => "left",
        "[e" => "clear",

        "[2$" => "insert",
        "[3$" => "delete",
        "[5$" => "pageup",
        "[6$" => "pagedown",
        "[7$" => "home",
        "[8$" => "end",

        "Oa" => "up",
        "Ob" => "down",
        "Oc" => "right",
        "Od" => "left",
        "Oe" => "clear",

        "[2^" => "insert",
        "[3^" => "delete",
        "[5^" => "pageup",
        "[6^" => "pagedown",
        "[7^" => "home",
        "[8^" => "end",
        // misc.
        "[Z" => "tab",
        _ => return None,
    })
}

fn is_shift_key(code: &str) -> bool {
    matches!(
        code,
        "[a" | "[b" | "[c" | "[d" | "[e" | "[2$" | "[3$" | "[5$" | "[6$" | "[7$" | "[8$" | "[Z"
    )
}

fn is_ctrl_key(code: &str) -> bool {
    matches!(
        code,
        "Oa" | "Ob" | "Oc" | "Od" | "Oe" | "[2^" | "[3^" | "[5^" | "[6^" | "[7^" | "[8^"
    )
}

// --- kitty special-key tables ---

fn kitty_special_letter_key(terminator: char) -> Option<&'static str> {
    Some(match terminator {
        'A' => "up",
        'B' => "down",
        'C' => "right",
        'D' => "left",
        'E' => "clear",
        'F' => "end",
        'H' => "home",
        'P' => "f1",
        'Q' => "f2",
        'R' => "f3",
        'S' => "f4",
        _ => return None,
    })
}

fn kitty_special_number_key(number: u32) -> Option<&'static str> {
    Some(match number {
        2 => "insert",
        3 => "delete",
        5 => "pageup",
        6 => "pagedown",
        7 => "home",
        8 => "end",
        11 => "f1",
        12 => "f2",
        13 => "f3",
        14 => "f4",
        15 => "f5",
        17 => "f6",
        18 => "f7",
        19 => "f8",
        20 => "f9",
        21 => "f10",
        23 => "f11",
        24 => "f12",
        _ => return None,
    })
}

/// Map of special codepoints to key names in the kitty protocol.
/// (1:1 with `kittyCodepointNames`.)
fn kitty_codepoint_name(cp: u32) -> Option<&'static str> {
    Some(match cp {
        27 => "escape",
        // 13 (return) and 32 (space) are handled before this lookup.
        9 => "tab",
        127 => "backspace",
        8 => "backspace",
        57358 => "capslock",
        57359 => "scrolllock",
        57360 => "numlock",
        57361 => "printscreen",
        57362 => "pause",
        57363 => "menu",
        57376 => "f13",
        57377 => "f14",
        57378 => "f15",
        57379 => "f16",
        57380 => "f17",
        57381 => "f18",
        57382 => "f19",
        57383 => "f20",
        57384 => "f21",
        57385 => "f22",
        57386 => "f23",
        57387 => "f24",
        57388 => "f25",
        57389 => "f26",
        57390 => "f27",
        57391 => "f28",
        57392 => "f29",
        57393 => "f30",
        57394 => "f31",
        57395 => "f32",
        57396 => "f33",
        57397 => "f34",
        57398 => "f35",
        57399 => "kp0",
        57400 => "kp1",
        57401 => "kp2",
        57402 => "kp3",
        57403 => "kp4",
        57404 => "kp5",
        57405 => "kp6",
        57406 => "kp7",
        57407 => "kp8",
        57408 => "kp9",
        57409 => "kpdecimal",
        57410 => "kpdivide",
        57411 => "kpmultiply",
        57412 => "kpsubtract",
        57413 => "kpadd",
        57414 => "kpenter",
        57415 => "kpequal",
        57416 => "kpseparator",
        57417 => "kpleft",
        57418 => "kpright",
        57419 => "kpup",
        57420 => "kpdown",
        57421 => "kppageup",
        57422 => "kppagedown",
        57423 => "kphome",
        57424 => "kpend",
        57425 => "kpinsert",
        57426 => "kpdelete",
        57427 => "kpbegin",
        57428 => "mediaplay",
        57429 => "mediapause",
        57430 => "mediaplaypause",
        57431 => "mediareverse",
        57432 => "mediastop",
        57433 => "mediafastforward",
        57434 => "mediarewind",
        57435 => "mediatracknext",
        57436 => "mediatrackprevious",
        57437 => "mediarecord",
        57438 => "lowervolume",
        57439 => "raisevolume",
        57440 => "mutevolume",
        57441 => "leftshift",
        57442 => "leftcontrol",
        57443 => "leftalt",
        57444 => "leftsuper",
        57445 => "lefthyper",
        57446 => "leftmeta",
        57447 => "rightshift",
        57448 => "rightcontrol",
        57449 => "rightalt",
        57450 => "rightsuper",
        57451 => "righthyper",
        57452 => "rightmeta",
        57453 => "isoLevel3Shift",
        57454 => "isoLevel5Shift",
        _ => return None,
    })
}

/// Valid Unicode codepoint range, excluding surrogates.
fn is_valid_codepoint(cp: u32) -> bool {
    cp <= 0x10_ffff && !(0xd8_00..=0xdf_ff).contains(&cp)
}

/// `safeFromCodePoint`: the character for a codepoint, or `'?'` when invalid.
fn safe_from_codepoint(cp: u32) -> String {
    match char::from_u32(cp) {
        Some(c) if is_valid_codepoint(cp) => c.to_string(),
        _ => "?".to_string(),
    }
}

fn resolve_event_type(value: u32) -> EventType {
    match value {
        3 => EventType::Release,
        2 => EventType::Repeat,
        _ => EventType::Press,
    }
}

/// Modifier flags decoded from a kitty modifier value (already `value - 1`).
struct KittyModifiers {
    ctrl: bool,
    shift: bool,
    meta: bool,
    super_key: bool,
    hyper: bool,
    caps_lock: bool,
    num_lock: bool,
}

fn parse_kitty_modifiers(modifiers: u32) -> KittyModifiers {
    KittyModifiers {
        ctrl: modifiers & KITTY_MODIFIERS.ctrl != 0,
        shift: modifiers & KITTY_MODIFIERS.shift != 0,
        meta: modifiers & (KITTY_MODIFIERS.meta | KITTY_MODIFIERS.alt) != 0,
        super_key: modifiers & KITTY_MODIFIERS.super_key != 0,
        hyper: modifiers & KITTY_MODIFIERS.hyper != 0,
        caps_lock: modifiers & KITTY_MODIFIERS.caps_lock != 0,
        num_lock: modifiers & KITTY_MODIFIERS.num_lock != 0,
    }
}

/// Parse a kitty CSI-u sequence: `CSI codepoint ; modifiers [: eventType] [;
/// text-as-codepoints] u`. Returns `None` if it does not match the pattern.
///
/// On a matched-but-rejected sequence (invalid primary codepoint), returns
/// `Some(Err(()))` so the caller can emit a safe empty kitty keypress instead
/// of falling through to legacy parsing (mirrors `kittyKeyRe.test(s)`).
#[allow(clippy::result_unit_err)]
fn parse_kitty_keypress(s: &str) -> Option<Result<Key, ()>> {
    // Pattern: ^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?(?:;([\d:]+))?)?u$
    let body = s.strip_prefix("\u{1b}[")?.strip_suffix('u')?;

    // Split on ';': [codepoint] [; modifiers(:eventType)] [; text]
    let mut groups = body.split(';');
    let codepoint_str = groups.next()?;
    let codepoint: u32 = parse_all_digits(codepoint_str)?;

    let (modifiers_raw, event_type_raw) = match groups.next() {
        Some(seg) => {
            // seg is `modifiers` or `modifiers:eventType`
            let mut parts = seg.split(':');
            let m = parse_all_digits(parts.next()?)?;
            let e = match parts.next() {
                Some(e_str) => Some(parse_all_digits(e_str)?),
                None => None,
            };
            if parts.next().is_some() {
                return None;
            }
            (Some(m), e)
        }
        None => (None, None),
    };

    let text_field = match groups.next() {
        Some(t) => {
            // text-as-codepoints: colon-separated digits ([\d:]+)
            if t.is_empty() || !t.chars().all(|c| c.is_ascii_digit() || c == ':') {
                return None;
            }
            Some(t)
        }
        None => None,
    };
    if groups.next().is_some() {
        return None;
    }

    let modifiers = modifiers_raw.map_or(0, |m| m.saturating_sub(1));
    let event_type = event_type_raw.unwrap_or(1);

    if !is_valid_codepoint(codepoint) {
        return Some(Err(()));
    }

    // Parse the text-as-codepoints field.
    let mut text: Option<String> = match text_field {
        Some(field) => {
            let mut out = String::new();
            for cp_str in field.split(':') {
                let cp = parse_all_digits(cp_str)?;
                out.push_str(&safe_from_codepoint(cp));
            }
            Some(out)
        }
        None => None,
    };

    // Determine key name from codepoint.
    let (name, is_printable) = if codepoint == 32 {
        ("space".to_string(), true)
    } else if codepoint == 13 {
        ("return".to_string(), true)
    } else if let Some(n) = kitty_codepoint_name(codepoint) {
        (n.to_string(), false)
    } else if (1..=26).contains(&codepoint) {
        // Ctrl+letter comes as codepoint 1-26 ('a' is 97).
        (
            char::from_u32(codepoint + 96)
                .map(String::from)
                .unwrap_or_default(),
            false,
        )
    } else {
        (safe_from_codepoint(codepoint).to_lowercase(), true)
    };

    // Default text to the character from the codepoint when not provided.
    if is_printable && text.is_none() {
        text = Some(safe_from_codepoint(codepoint));
    }

    let m = parse_kitty_modifiers(modifiers);
    Some(Ok(Key {
        name,
        ctrl: m.ctrl,
        meta: m.meta,
        shift: m.shift,
        super_key: m.super_key,
        hyper: m.hyper,
        caps_lock: m.caps_lock,
        num_lock: m.num_lock,
        event_type: Some(resolve_event_type(event_type)),
        sequence: s.to_string(),
        raw: Some(s.to_string()),
        code: None,
        is_kitty_protocol: true,
        is_printable: Some(is_printable),
        text,
    }))
}

/// Parse a kitty-enhanced special key: `CSI number ; modifiers : eventType
/// {letter|~}`. Returns `None` if no match.
fn parse_kitty_special_key(s: &str) -> Option<Key> {
    // Pattern: ^\x1b\[(\d+);(\d+):(\d+)([A-Za-z~])$
    let body = s.strip_prefix("\u{1b}[")?;
    let terminator = body.chars().last()?;
    if !(terminator.is_ascii_alphabetic() || terminator == '~') {
        return None;
    }
    let body = &body[..body.len() - terminator.len_utf8()];

    let mut parts = body.split(';');
    let number: u32 = parse_all_digits(parts.next()?)?;
    let rest = parts.next()?;
    if parts.next().is_some() {
        return None;
    }
    let mut mod_event = rest.split(':');
    let modifiers_raw: u32 = parse_all_digits(mod_event.next()?)?;
    let event_type: u32 = parse_all_digits(mod_event.next()?)?;
    if mod_event.next().is_some() {
        return None;
    }

    let modifiers = modifiers_raw.saturating_sub(1);

    let name = if terminator == '~' {
        kitty_special_number_key(number)?
    } else {
        kitty_special_letter_key(terminator)?
    };

    let m = parse_kitty_modifiers(modifiers);
    Some(Key {
        name: name.to_string(),
        ctrl: m.ctrl,
        meta: m.meta,
        shift: m.shift,
        super_key: m.super_key,
        hyper: m.hyper,
        caps_lock: m.caps_lock,
        num_lock: m.num_lock,
        event_type: Some(resolve_event_type(event_type)),
        sequence: s.to_string(),
        raw: Some(s.to_string()),
        code: None,
        is_kitty_protocol: true,
        is_printable: Some(false),
        text: None,
    })
}

/// Parse a run of ASCII digits in full (the whole string must be digits),
/// mirroring `parseInt(x, 10)` on a `\d+` capture. Returns `None` on overflow
/// or non-digit content.
fn parse_all_digits(s: &str) -> Option<u32> {
    if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    s.parse::<u32>().ok()
}

/// Decode a single key sequence (the raw bytes of one segmented key) into a
/// [`Key`]. Faithful port of `parseKeypress`.
pub fn parse_keypress(bytes: &[u8]) -> Key {
    // High-bit single-byte transform: a lone byte > 127 becomes ESC + (byte-128).
    let decoded: String = if bytes.len() == 1 && bytes[0] > 127 {
        let mut s = String::from('\u{1b}');
        s.push_str(&String::from_utf8_lossy(&[bytes[0] - 128]));
        s
    } else {
        String::from_utf8_lossy(bytes).into_owned()
    };
    parse_keypress_str(&decoded)
}

/// Internal: `parseKeypress` operating on an already-decoded string.
fn parse_keypress_str(s: &str) -> Key {
    // Try kitty keyboard protocol parsers first.
    match parse_kitty_keypress(s) {
        Some(Ok(key)) => return key,
        Some(Err(())) => {
            // Matched the kitty CSI-u pattern but was rejected: return a safe
            // empty kitty keypress instead of falling through to legacy parsing.
            return Key {
                name: String::new(),
                ctrl: false,
                meta: false,
                shift: false,
                sequence: s.to_string(),
                raw: Some(s.to_string()),
                code: None,
                super_key: false,
                hyper: false,
                caps_lock: false,
                num_lock: false,
                event_type: None,
                is_kitty_protocol: true,
                is_printable: Some(false),
                text: None,
            };
        }
        None => {}
    }

    if let Some(key) = parse_kitty_special_key(s) {
        return key;
    }

    let mut key = Key::legacy(s.to_string());

    // `key.sequence = key.sequence || s || key.name;` is a no-op here (sequence
    // is already `s`), preserved implicitly.

    let chars: Vec<char> = s.chars().collect();

    if s == "\r" || s == "\u{1b}\r" {
        // carriage return (or meta+return on macOS)
        key.raw = None;
        key.name = "return".to_string();
        key.meta = chars.len() == 2;
    } else if s == "\n" {
        // enter, should have been called linefeed
        key.name = "enter".to_string();
    } else if s == "\t" {
        key.name = "tab".to_string();
    } else if s == "\u{8}" || s == "\u{1b}\u{8}" {
        // backspace or ctrl+h
        key.name = "backspace".to_string();
        key.meta = chars.first() == Some(&'\u{1b}');
    } else if s == "\u{7f}" || s == "\u{1b}\u{7f}" {
        // backspace
        key.name = "backspace".to_string();
        key.meta = chars.first() == Some(&'\u{1b}');
    } else if s == "\u{1b}" || s == "\u{1b}\u{1b}" {
        // escape key
        key.name = "escape".to_string();
        key.meta = chars.len() == 2;
    } else if s == " " || s == "\u{1b} " {
        key.name = "space".to_string();
        key.meta = chars.len() == 2;
    } else if chars.len() == 1 && chars[0] <= '\u{1a}' {
        // ctrl+letter
        let c = chars[0] as u32;
        key.name = char::from_u32(c + ('a' as u32) - 1)
            .map(String::from)
            .unwrap_or_default();
        key.ctrl = true;
    } else if chars.len() == 1 && chars[0].is_ascii_digit() {
        // number
        key.name = "number".to_string();
    } else if chars.len() == 1 && chars[0].is_ascii_lowercase() {
        // lowercase letter
        key.name = chars[0].to_string();
    } else if chars.len() == 1 && chars[0].is_ascii_uppercase() {
        // shift+letter
        key.name = chars[0].to_ascii_lowercase().to_string();
        key.shift = true;
    } else if let Some((name, meta, shift)) = match_meta_key_code(s) {
        // meta+character key
        key.name = name;
        key.meta = meta;
        key.shift = shift;
    } else if let Some(parsed) = match_fn_key(&chars) {
        if chars.first() == Some(&'\u{1b}') && chars.get(1) == Some(&'\u{1b}') {
            key.meta = true;
        }
        let modifier = parsed.modifier;
        key.ctrl = modifier & 4 != 0;
        key.meta = key.meta || (modifier & 10 != 0);
        key.shift = modifier & 1 != 0;
        key.code = Some(parsed.code.clone());
        key.name = key_name(&parsed.code).unwrap_or("").to_string();
        key.shift = is_shift_key(&parsed.code) || key.shift;
        key.ctrl = is_ctrl_key(&parsed.code) || key.ctrl;
    }

    key
}

/// `metaKeyCodeRe`: `^(?:\x1b)([a-zA-Z0-9])$`. Returns `(name, meta, shift)`.
fn match_meta_key_code(s: &str) -> Option<(String, bool, bool)> {
    let inner = s.strip_prefix('\u{1b}')?;
    let mut it = inner.chars();
    let c = it.next()?;
    if it.next().is_some() {
        return None;
    }
    if !c.is_ascii_alphanumeric() {
        return None;
    }
    let name = c.to_ascii_lowercase().to_string();
    let shift = c.is_ascii_uppercase();
    Some((name, true, shift))
}

struct FnKeyMatch {
    code: String,
    /// Signed to reproduce ink's JS two's-complement semantics: a literal `0`
    /// modifier param (e.g. `ESC[1;0~`) yields `-1` here, so the `& {4,10,1}`
    /// masks below are all truthy — matching `parse-keypress.ts:531`. A `u32`
    /// would underflow-panic on the per-stdin-chunk hot path.
    modifier: i64,
}

/// `fnKeyRe`: `^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))`.
///
/// Reassembles the `code` (leading ESCs, the modifier bitflag, and any
/// meaningless `1;` stripped) and the resolved `modifier`, matching upstream.
fn match_fn_key(chars: &[char]) -> Option<FnKeyMatch> {
    let mut i = 0;
    // (?:\x1b+) — one or more ESC.
    if chars.get(i) != Some(&'\u{1b}') {
        return None;
    }
    while chars.get(i) == Some(&'\u{1b}') {
        i += 1;
    }

    // (O|N|\[|\[\[) — prefer the longest alternation match as JS regex does.
    let prefix: String;
    if chars.get(i) == Some(&'[') {
        if chars.get(i + 1) == Some(&'[') {
            prefix = "[[".to_string();
            i += 2;
        } else {
            prefix = "[".to_string();
            i += 1;
        }
    } else if chars.get(i) == Some(&'O') {
        prefix = "O".to_string();
        i += 1;
    } else if chars.get(i) == Some(&'N') {
        prefix = "N".to_string();
        i += 1;
    } else {
        return None;
    }

    // Branch A: (\d+)(?:;(\d+))?([~^$])
    // Branch B: (?:1;)?(\d+)?([a-zA-Z])
    let rest = &chars[i..];

    // Try branch A first (regex alternation order).
    if let Some(m) = match_fn_branch_a(&prefix, rest) {
        return Some(m);
    }
    match_fn_branch_b(&prefix, rest)
}

/// Branch A: `(\d+)(?:;(\d+))?([~^$])`.
fn match_fn_branch_a(prefix: &str, rest: &[char]) -> Option<FnKeyMatch> {
    let mut j = 0;
    // (\d+)
    let num_start = j;
    while rest.get(j).is_some_and(|c| c.is_ascii_digit()) {
        j += 1;
    }
    if j == num_start {
        return None;
    }
    let p2: String = rest[num_start..j].iter().collect();

    // (?:;(\d+))?
    let mut p3: Option<String> = None;
    if rest.get(j) == Some(&';') {
        let mut k = j + 1;
        let s = k;
        while rest.get(k).is_some_and(|c| c.is_ascii_digit()) {
            k += 1;
        }
        if k > s {
            p3 = Some(rest[s..k].iter().collect());
            j = k;
        }
        // If `;` not followed by digits, the optional group doesn't match;
        // leave j at the `;` so the terminator check below fails appropriately.
    }

    // ([~^$])
    let term = rest.get(j)?;
    if !matches!(term, '~' | '^' | '$') {
        return None;
    }

    let code = format!("{prefix}{p2}{term}");
    let modifier = i64::from(p3.as_deref().and_then(parse_all_digits).unwrap_or(1)) - 1;
    Some(FnKeyMatch { code, modifier })
}

/// Branch B: `(?:1;)?(\d+)?([a-zA-Z])`.
fn match_fn_branch_b(prefix: &str, rest: &[char]) -> Option<FnKeyMatch> {
    let mut j = 0;
    // (?:1;)? — optional literal "1;".
    if rest.get(j) == Some(&'1') && rest.get(j + 1) == Some(&';') {
        j += 2;
    }
    // (\d+)?
    let s = j;
    while rest.get(j).is_some_and(|c| c.is_ascii_digit()) {
        j += 1;
    }
    let p5: Option<String> = if j > s {
        Some(rest[s..j].iter().collect())
    } else {
        None
    };
    // ([a-zA-Z])
    let letter = rest.get(j)?;
    if !letter.is_ascii_alphabetic() {
        return None;
    }

    // `code` joins parts[1] (prefix) + parts[6] (letter) only; parts[5] (p5) is
    // the modifier and is intentionally excluded.
    let code = format!("{prefix}{letter}");
    let modifier = i64::from(p5.as_deref().and_then(parse_all_digits).unwrap_or(1)) - 1;
    Some(FnKeyMatch { code, modifier })
}

#[cfg(test)]
mod tests;