6615
Yc
yoctoselect / files
yoctoselect / src / input.ts
1.8 KB
1export type InputEvent = 2 | { type: "char"; char: string } 3 | { type: "escape" } 4 | { type: "enter" } 5 | { type: "backspace" } 6 | { type: "up" } 7 | { type: "down" } 8 | { type: "home" } 9 | { type: "end" }; 10 11const CSI_SEQUENCES: Record<string, InputEvent> = { 12 A: { type: "up" }, 13 B: { type: "down" }, 14 H: { type: "home" }, 15 F: { type: "end" }, 16 "1~": { type: "home" }, 17 "4~": { type: "end" }, 18}; 19 20export function parseInput(data: string): InputEvent[] { 21 const events: InputEvent[] = []; 22 let i = 0; 23 24 while (i < data.length) { 25 const ch = data[i] as string; 26 27 if (ch === "\r" || ch === "\n") { 28 events.push({ type: "enter" }); 29 i++; 30 continue; 31 } 32 33 if (ch === "\x7f" || ch === "\x08") { 34 events.push({ type: "backspace" }); 35 i++; 36 continue; 37 } 38 39 if (ch === "\x1b") { 40 // Check for CSI sequence: ESC [ 41 if (data[i + 1] === "[") { 42 // Try 4-char sequences first (e.g. \x1b[1~ or \x1b[4~) 43 const fourChar = data.slice(i + 2, i + 4); 44 const event4 = CSI_SEQUENCES[fourChar]; 45 if (event4) { 46 events.push({ ...event4 }); 47 i += 4; 48 continue; 49 } 50 51 // Try 3-char sequences (e.g. \x1b[A) 52 const oneChar = data[i + 2]; 53 const event3 = oneChar ? CSI_SEQUENCES[oneChar] : undefined; 54 if (event3) { 55 events.push({ ...event3 }); 56 i += 3; 57 continue; 58 } 59 60 // Unknown CSI sequence — skip ESC [ and the next char 61 i += 3; 62 continue; 63 } 64 65 // Bare ESC (not followed by '[') 66 events.push({ type: "escape" }); 67 i++; 68 continue; 69 } 70 71 // Printable characters 72 if (ch >= " ") { 73 events.push({ type: "char", char: ch }); 74 } 75 // Control chars we don't handle are silently skipped 76 i++; 77 } 78 79 return events; 80}