Playground: capture Ctrl+W as delete-previous-word

Prevent the browser from closing the tab when Ctrl+W is pressed
while the terminal is focused. Instead, handle it as the standard
terminal "delete previous word" action.
This commit is contained in:
Sylvestre Ledru
2026-04-04 12:52:31 +02:00
parent b39e3382e8
commit b82f7b65fb
+19
View File
@@ -809,6 +809,17 @@ async function handleInput(data) {
continue;
}
if (code === 23) { // Ctrl+W — delete previous word
const before = inputBuffer.slice(0, cursorPos);
const after = inputBuffer.slice(cursorPos);
// Skip trailing spaces, then delete back to the previous space
const trimmed = before.replace(/\S+\s*$/, "");
cursorPos = trimmed.length;
inputBuffer = trimmed + after;
redrawInput();
continue;
}
if (code === 21) { // Ctrl+U
inputBuffer = "";
cursorPos = 0;
@@ -866,6 +877,14 @@ async function initPlayground(containerId) {
terminal.open(container);
fitAddon.fit();
// Prevent browser from closing the tab on Ctrl+W when the terminal is focused;
// xterm.js will receive it as code 23 and we handle it as "delete previous word".
container.addEventListener("keydown", (ev) => {
if (ev.ctrlKey && ev.key === "w") {
ev.preventDefault();
}
}, true);
window.addEventListener("resize", () => fitAddon.fit());
terminal.writeln("\x1b[1;38;5;166m _ _ _ _ _ _ _\x1b[0m");