xonecas.io
70160
Ce

cel-tui / commit ed842d8

feat(core): add bracketed paste support

xonecas2026-04-10 ed842d841202cabaceb9f6ac6db5d1b2c443af8c parent d111105

4 files changed

packages/core/src/cel.ts+165−29
@@ -191,8 +191,19 @@ function findFocusedTIInTree(ln: LayoutNode): LayoutNode | null {
191191
192192 // --- Input handling ---
193193
194-// Regex for a single SGR mouse event (non-anchored, for scanning batched input)
195-const SGR_MOUSE_RE = /\x1b\[<(\d+);(\d+);(\d+)([Mm])/g;
194+const BRACKETED_PASTE_START = "\x1b[200~";
195+const BRACKETED_PASTE_END = "\x1b[201~";
196+
197+// Regex for a single SGR mouse event, anchored to the current parse position.
198+const SGR_MOUSE_RE = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])/;
199+
200+// Trailing keyboard data that ended with an incomplete CSI sequence.
201+let pendingKeyData = "";
202+
203+// Bracketed paste state across stdin chunks.
204+let inBracketedPaste = false;
205+let bracketedPasteData = "";
206+let bracketedPasteSuffix = "";
196207
197208 // Tracks accumulated scroll offsets during a batch of mouse events.
198209 // Controlled scroll reads scrollOffset from props, which doesn't update until
@@ -206,32 +217,61 @@ let batchScrollOffsets: Map<object, number> | null = null;
206217 let batchTextInputEdits: Map<TextInputProps, EditState> | null = null;
207218
208219 function handleInput(data: string): void {
209- SGR_MOUSE_RE.lastIndex = 0;
210220 batchTextInputEdits = new Map();
211221
212- let lastIndex = 0;
213-
214222 try {
215- let match = SGR_MOUSE_RE.exec(data);
216- while (match) {
217- if (match.index > lastIndex) {
218- handleKeyChunk(data.slice(lastIndex, match.index));
219- }
223+ let remaining = data;
224+
225+ if (inBracketedPaste) {
226+ remaining = consumeBracketedPasteData(remaining);
227+ if (remaining.length === 0) return;
228+ }
229+
230+ let chunk = pendingKeyData + remaining;
231+ pendingKeyData = "";
232+
233+ let keyChunkStart = 0;
234+ let index = 0;
235+
236+ while (index < chunk.length) {
237+ if (chunk.startsWith(BRACKETED_PASTE_START, index)) {
238+ handleKeyChunk(chunk.slice(keyChunkStart, index));
239+
240+ index += BRACKETED_PASTE_START.length;
241+ keyChunkStart = index;
242+ inBracketedPaste = true;
243+
244+ const afterPaste = consumeBracketedPasteData(chunk.slice(index));
245+ if (afterPaste.length === 0) return;
220246
221- if (batchScrollOffsets === null) {
222- batchScrollOffsets = new Map();
247+ chunk = afterPaste;
248+ index = 0;
249+ keyChunkStart = 0;
250+ continue;
223251 }
224252
225- const mouse = parseSgrMatch(match);
226- if (mouse) handleMouseEvent(mouse);
253+ const mouse = readSgrMouseEvent(chunk, index);
254+ if (mouse) {
255+ handleKeyChunk(chunk.slice(keyChunkStart, index));
227256
228- lastIndex = match.index + match[0].length;
229- match = SGR_MOUSE_RE.exec(data);
230- }
257+ if (batchScrollOffsets === null) {
258+ batchScrollOffsets = new Map();
259+ }
260+ if (mouse.event) handleMouseEvent(mouse.event);
261+
262+ index = mouse.nextIndex;
263+ keyChunkStart = index;
264+ continue;
265+ }
231266
232- if (lastIndex < data.length) {
233- handleKeyChunk(data.slice(lastIndex));
267+ index++;
234268 }
269+
270+ const { complete, pending } = splitIncompleteCsiSuffix(
271+ chunk.slice(keyChunkStart),
272+ );
273+ handleKeyChunk(complete);
274+ pendingKeyData = pending;
235275 } finally {
236276 batchScrollOffsets = null;
237277 batchTextInputEdits = null;
@@ -245,12 +285,84 @@ function handleKeyChunk(data: string): void {
245285 }
246286 }
247287
288+function consumeBracketedPasteData(data: string): string {
289+ const chunk = bracketedPasteSuffix + data;
290+ bracketedPasteSuffix = "";
291+
292+ const endIndex = chunk.indexOf(BRACKETED_PASTE_END);
293+ if (endIndex === -1) {
294+ const { complete, pending } = splitTrailingMarkerPrefix(
295+ chunk,
296+ BRACKETED_PASTE_END,
297+ );
298+ bracketedPasteData += complete;
299+ bracketedPasteSuffix = pending;
300+ return "";
301+ }
302+
303+ bracketedPasteData += chunk.slice(0, endIndex);
304+ const pastedText = bracketedPasteData;
305+
306+ inBracketedPaste = false;
307+ bracketedPasteData = "";
308+ bracketedPasteSuffix = "";
309+ handleBracketedPaste(pastedText);
310+
311+ return chunk.slice(endIndex + BRACKETED_PASTE_END.length);
312+}
313+
314+function splitTrailingMarkerPrefix(
315+ data: string,
316+ marker: string,
317+): { complete: string; pending: string } {
318+ const maxPrefixLength = Math.min(data.length, marker.length - 1);
319+ for (let length = maxPrefixLength; length > 0; length--) {
320+ if (data.endsWith(marker.slice(0, length))) {
321+ return {
322+ complete: data.slice(0, data.length - length),
323+ pending: data.slice(data.length - length),
324+ };
325+ }
326+ }
327+ return { complete: data, pending: "" };
328+}
329+
330+function splitIncompleteCsiSuffix(data: string): {
331+ complete: string;
332+ pending: string;
333+} {
334+ const csiStart = data.lastIndexOf("\x1b[");
335+ if (csiStart === -1) return { complete: data, pending: "" };
336+
337+ const suffix = data.slice(csiStart);
338+ for (let i = 2; i < suffix.length; i++) {
339+ const code = suffix.charCodeAt(i);
340+ if (code >= 0x40 && code <= 0x7e) {
341+ return { complete: data, pending: "" };
342+ }
343+ }
344+
345+ return { complete: data.slice(0, csiStart), pending: suffix };
346+}
347+
248348 interface MouseEvent {
249349 type: "click" | "scroll-up" | "scroll-down";
250350 x: number;
251351 y: number;
252352 }
253353
354+function readSgrMouseEvent(
355+ data: string,
356+ index: number,
357+): { event: MouseEvent | null; nextIndex: number } | null {
358+ const match = SGR_MOUSE_RE.exec(data.slice(index));
359+ if (!match) return null;
360+ return {
361+ event: parseSgrMatch(match),
362+ nextIndex: index + match[0].length,
363+ };
364+}
365+
254366 /**
255367 * Parse a single SGR mouse event from a RegExp match.
256368 * Returns a MouseEvent for scroll and click events, null for unhandled buttons.
@@ -610,6 +722,31 @@ function getTextInputEditState(props: TextInputProps): EditState {
610722 };
611723 }
612724
725+function commitTextInputEdit(
726+ props: TextInputProps,
727+ previousState: EditState,
728+ nextState: EditState,
729+): void {
730+ batchTextInputEdits?.set(props, nextState);
731+ setTextInputCursor(props, nextState.cursor);
732+ if (nextState.value !== previousState.value) {
733+ props.onChange(nextState.value);
734+ }
735+ cel.render();
736+}
737+
738+function handleBracketedPaste(text: string): void {
739+ if (text.length === 0) return;
740+
741+ const focusedInput = findFocusedTextInput();
742+ if (!focusedInput) return;
743+
744+ const props = focusedInput.node.props as TextInputProps;
745+ const editState = getTextInputEditState(props);
746+ const nextState = insertChar(editState, text);
747+ commitTextInputEdit(props, editState, nextState);
748+}
749+
613750 function handleKeyEvent(event: KeyInput): void {
614751 const { key, text } = event;
615752
@@ -750,12 +887,7 @@ function handleKeyEvent(event: KeyInput): void {
750887 }
751888
752889 if (newState && newState !== editState) {
753- batchTextInputEdits?.set(props, newState);
754- setTextInputCursor(props, newState.cursor);
755- if (newState.value !== editState.value) {
756- props.onChange(newState.value);
757- }
758- cel.render();
890+ commitTextInputEdit(props, editState, newState);
759891 return;
760892 }
761893 }
@@ -874,8 +1006,8 @@ export const cel = {
8741006 * Initialize the framework with a terminal implementation.
8751007 * Must be called before {@link cel.viewport}.
8761008 *
877- * Enables the Kitty keyboard protocol (level 1) via the terminal,
878- * enters raw mode, and starts mouse tracking.
1009+ * Enables the Kitty keyboard protocol (level 1) and bracketed paste mode via
1010+ * the terminal, enters raw mode, and starts mouse tracking.
8791011 *
8801012 * @param term - Terminal to render to (ProcessTerminal or MockTerminal).
8811013 * @param options - Optional configuration.
@@ -914,8 +1046,8 @@ export const cel = {
9141046 /**
9151047 * Stop the framework and restore terminal state.
9161048 *
917- * Pops the Kitty keyboard protocol mode, disables mouse tracking,
918- * and restores the terminal to its previous state.
1049+ * Pops the Kitty keyboard protocol mode, disables bracketed paste and mouse
1050+ * tracking, and restores the terminal to its previous state.
9191051 */
9201052 stop(): void {
9211053 terminal?.stop();
@@ -930,6 +1062,10 @@ export const cel = {
9301062 stampedNode = null;
9311063 uncontrolledScrollOffsets.clear();
9321064 stampedScrollNodes = [];
1065+ pendingKeyData = "";
1066+ inBracketedPaste = false;
1067+ bracketedPasteData = "";
1068+ bracketedPasteSuffix = "";
9331069 lastTerminalCursor = { visible: false };
9341070 activeTheme = defaultTheme;
9351071 },
packages/core/src/terminal.ts+11−6
@@ -12,8 +12,8 @@ export interface Terminal {
1212 /** Terminal height in rows. */
1313 get rows(): number;
1414 /**
15- * Enter raw mode, enable Kitty level 1 keyboard reporting, enable mouse
16- * tracking, and hide the cursor.
15+ * Enter raw mode, enable Kitty level 1 keyboard reporting, enable bracketed
16+ * paste mode, enable mouse tracking, and hide the cursor.
1717 *
1818 * The framework prefers Kitty semantics but its parser also accepts mixed
1919 * tmux/legacy keyboard encodings that may still arrive on stdin.
@@ -30,10 +30,11 @@ export interface Terminal {
3030 /**
3131 * Real terminal using process.stdin/stdout.
3232 *
33- * Enables Kitty keyboard protocol level 1, SGR mouse tracking, and raw mode.
34- * The runtime prefers Kitty semantics for full modifier fidelity, while the
35- * parser remains compatible with mixed tmux/legacy keyboard encodings that
36- * may still arrive on stdin. All modes are restored on stop/crash.
33+ * Enables Kitty keyboard protocol level 1, bracketed paste mode, SGR mouse
34+ * tracking, and raw mode. The runtime prefers Kitty semantics for full
35+ * modifier fidelity, while the parser remains compatible with mixed
36+ * tmux/legacy keyboard encodings that may still arrive on stdin. All modes are
37+ * restored on stop/crash.
3738 */
3839 export class ProcessTerminal implements Terminal {
3940 private wasRaw = false;
@@ -76,6 +77,8 @@ export class ProcessTerminal implements Terminal {
7677 this.write("\x1b[?1049h");
7778 // Enable Kitty keyboard protocol level 1 (disambiguate) with push flag
7879 this.write("\x1b[>1u");
80+ // Enable bracketed paste mode
81+ this.write("\x1b[?2004h");
7982 // Enable mouse tracking (normal mode) + SGR encoding
8083 this.write("\x1b[?1000h\x1b[?1006h");
8184 this.hideCursor();
@@ -110,6 +113,8 @@ export class ProcessTerminal implements Terminal {
110113
111114 // Disable mouse tracking + SGR encoding
112115 this.write("\x1b[?1006l\x1b[?1000l");
116+ // Disable bracketed paste mode
117+ this.write("\x1b[?2004l");
113118 // Pop Kitty keyboard protocol mode
114119 this.write("\x1b[<u");
115120 this.showCursor();
packages/core/src/text-input.test.ts+141−0
@@ -12,6 +12,12 @@ const CTRL_S = kittyEncode("ctrl+s");
1212 const LEFT = kittyEncode("left");
1313 const LEGACY_CTRL_R = "\x12";
1414 const LEGACY_ALT_X = "\x1bx";
15+const BRACKETED_PASTE_START = "\x1b[200~";
16+const BRACKETED_PASTE_END = "\x1b[201~";
17+
18+function bracketedPaste(text: string): string {
19+ return `${BRACKETED_PASTE_START}${text}${BRACKETED_PASTE_END}`;
20+}
1521
1622 describe("TextInput integration", () => {
1723 let term: MockTerminal;
@@ -99,6 +105,141 @@ describe("TextInput integration", () => {
99105 expect(value).toBe("hiab");
100106 });
101107
108+ test("bracketed paste in focused TextInput inserts full payload literally and skips onKeyPress", async () => {
109+ const term = setup(20, 3);
110+ let value = "hi";
111+ let onChangeCalls = 0;
112+ const keys: string[] = [];
113+
114+ cel.viewport(() =>
115+ VStack({}, [
116+ TextInput({
117+ value,
118+ focused: true,
119+ onChange: (v) => {
120+ value = v;
121+ onChangeCalls++;
122+ },
123+ onKeyPress: (key) => {
124+ keys.push(key);
125+ },
126+ }),
127+ ]),
128+ );
129+ await waitForRender();
130+
131+ term.sendInput(bracketedPaste("!\n\tok"));
132+ await waitForRender();
133+
134+ expect(value).toBe("hi!\n\tok");
135+ expect(onChangeCalls).toBe(1);
136+ expect(keys).toEqual([]);
137+ });
138+
139+ test("bracketed paste split across stdin chunks waits for end marker and fires one onChange", async () => {
140+ const term = setup(20, 3);
141+ let value = "";
142+ let onChangeCalls = 0;
143+
144+ cel.viewport(() =>
145+ VStack({}, [
146+ TextInput({
147+ value,
148+ focused: true,
149+ onChange: (v) => {
150+ value = v;
151+ onChangeCalls++;
152+ },
153+ }),
154+ ]),
155+ );
156+ await waitForRender();
157+
158+ term.sendInput(`${BRACKETED_PASTE_START}hel`);
159+ await waitForRender();
160+ expect(value).toBe("");
161+ expect(onChangeCalls).toBe(0);
162+
163+ term.sendInput("lo\nwo");
164+ await waitForRender();
165+ expect(value).toBe("");
166+ expect(onChangeCalls).toBe(0);
167+
168+ term.sendInput(`rld${BRACKETED_PASTE_END}`);
169+ await waitForRender();
170+
171+ expect(value).toBe("hello\nworld");
172+ expect(onChangeCalls).toBe(1);
173+ });
174+
175+ test("bracketed paste start marker can be split across stdin chunks", async () => {
176+ const term = setup(20, 3);
177+ let value = "";
178+ let onChangeCalls = 0;
179+
180+ cel.viewport(() =>
181+ VStack({}, [
182+ TextInput({
183+ value,
184+ focused: true,
185+ onChange: (v) => {
186+ value = v;
187+ onChangeCalls++;
188+ },
189+ }),
190+ ]),
191+ );
192+ await waitForRender();
193+
194+ term.sendInput("\x1b[20");
195+ await waitForRender();
196+ expect(value).toBe("");
197+ expect(onChangeCalls).toBe(0);
198+
199+ term.sendInput("0~hi");
200+ await waitForRender();
201+ expect(value).toBe("");
202+ expect(onChangeCalls).toBe(0);
203+
204+ term.sendInput(BRACKETED_PASTE_END);
205+ await waitForRender();
206+
207+ expect(value).toBe("hi");
208+ expect(onChangeCalls).toBe(1);
209+ });
210+
211+ test("bracketed paste with no focused TextInput is ignored and does not bubble as keys", async () => {
212+ const term = setup(20, 3);
213+ let value = "";
214+ const receivedKeys: string[] = [];
215+
216+ cel.viewport(() =>
217+ VStack(
218+ {
219+ onKeyPress: (key) => {
220+ receivedKeys.push(key);
221+ },
222+ },
223+ [
224+ TextInput({
225+ value,
226+ focused: false,
227+ onChange: (v) => {
228+ value = v;
229+ },
230+ }),
231+ ],
232+ ),
233+ );
234+ await waitForRender();
235+
236+ term.sendInput(bracketedPaste("abc\n\tdef"));
237+ await waitForRender();
238+
239+ expect(value).toBe("");
240+ expect(receivedKeys).toEqual([]);
241+ });
242+
102243 test("onKeyPress receives normalized keys while TextInput inserts original text", async () => {
103244 const term = setup(20, 3);
104245 let keyReceived = "";
spec.md+19−3
@@ -425,14 +425,14 @@ cel-tui enables the [Kitty keyboard protocol](https://sw.kovidgoyal.net/kitty/ke
425425
426426 **Lifecycle:**
427427
428-1. `cel.init()` enables Kitty keyboard protocol **level 1** (`CSI > 1 u`) and sets a push flag so the mode is restored on exit
428+1. `cel.init()` enables Kitty keyboard protocol **level 1** (`CSI > 1 u`) and bracketed paste mode (`CSI ? 2004 h`), and sets a push flag so the keyboard mode is restored on exit
429429 2. The input decoder accepts a mixed stream of:
430430 - Kitty `CSI unicode-codepoint ; modifiers u`
431431 - legacy CSI letter / tilde sequences for arrows, Home/End, Delete, PageUp/Down, and function keys
432432 - raw printable text
433433 - legacy ASCII control bytes for recoverable `ctrl+letter` shortcuts
434434 - recoverable ESC-prefixed Alt combinations
435-3. `cel.stop()` pops the keyboard mode (`CSI < u`), restoring the terminal's previous state
435+3. `cel.stop()` pops the keyboard mode (`CSI < u`) and disables bracketed paste mode (`CSI ? 2004 l`), restoring the terminal's previous state
436436
437437 **Stream model:** Terminals and multiplexers may batch multiple keyboard and mouse sequences into a single stdin chunk. The framework treats stdin as a stream and decodes all events in order.
438438
@@ -442,6 +442,22 @@ cel-tui enables the [Kitty keyboard protocol](https://sw.kovidgoyal.net/kitty/ke
442442
443443 **Unavoidable ambiguity:** Some legacy encodings are indistinguishable once a host has collapsed them. For example, `Ctrl+I` vs `Tab`, `Ctrl+M` vs `Enter`, and `Ctrl+[` vs `Escape` cannot be recovered if the terminal or multiplexer emits only the shared legacy byte. In those cases the framework uses the legacy key meaning (`tab`, `enter`, `escape`) and cannot infer the modifier combo.
444444
445+### Bracketed Paste Mode
446+
447+cel-tui enables bracketed paste mode so the terminal wraps pasted content with `CSI 200~` and `CSI 201~`. This lets the framework distinguish paste from typing and prevents pasted bytes from being mis-decoded as keyboard sequences.
448+
449+**Paste stream model:** The paste start marker, payload, and end marker may be split across multiple stdin chunks. The input layer must track paste state across chunks and wait for the closing marker before ending the paste.
450+
451+**Paste semantics:**
452+
453+- Inside a bracketed paste region, bytes are treated as literal pasted content until `CSI 201~` arrives. Kitty key decoding, legacy key parsing, and ESC-prefixed Alt handling do not run on the payload.
454+- Newlines, tabs, spaces, and repeated characters are preserved exactly as pasted.
455+- If a TextInput is focused, the full pasted payload is inserted at the cursor as a single batch edit. `onChange` fires once with the final value, then cursor-follow and scroll updates apply to the post-paste state.
456+- Bracketed paste is **not** a key event. `onKeyPress` handlers are not called for the paste markers or for the pasted text itself.
457+- If no TextInput is focused, pasted text is ignored by the framework.
458+
459+**Fallback:** If the terminal or multiplexer ignores bracketed paste mode and emits only raw text, the framework cannot distinguish paste from typing; that input falls back to the normal mixed-stream keyboard path.
460+
445461 > **Future enhancement:** Higher protocol levels enable key-release events (`level 2`), associated text reporting (`level 3`), and full key event types (`level 4`). These would enable held-key detection for game-like UIs, distinguishing physical key layout from logical input, and other advanced input patterns. The framework may adopt higher levels in the future.
446462
447463 ### Key Event Flow
@@ -617,7 +633,7 @@ Container sizing props (`width`, `height`, `flex`, `min*`, `max*`, `padding`), f
617633 | `onKeyPress` | `(key: string) => boolean \| void` | Key handler, fires before editing. Receives normalized semantic key strings. Return `false` to prevent the default editing action. |
618634 | `placeholder` | `TextNode` | Text node shown when value is empty (pass a `Text()` call) |
619635
620-Word-wrap is always on. Cursor position is framework-managed.
636+Word-wrap is always on. Cursor position is framework-managed. In bracketed paste mode, pasted text is inserted literally at the cursor as one batch edit: one `onChange`, no `onKeyPress`, newlines and tabs preserved.
621637
622638 #### Growing / Shrinking Pattern