72 lines
2.0 KiB
JavaScript
72 lines
2.0 KiB
JavaScript
export function setupInput(buffer, cursor, onChange) {
|
|
document.addEventListener("keydown", (e) => {
|
|
if (e.key === "ArrowUp") {
|
|
e.preventDefault();
|
|
if (cursor.line > 0) cursor.line--;
|
|
cursor.col = Math.min(cursor.col, buffer[cursor.line].length);
|
|
onChange();
|
|
return;
|
|
}
|
|
if (e.key === "ArrowDown") {
|
|
e.preventDefault();
|
|
if (cursor.line < buffer.length - 1) cursor.line++;
|
|
cursor.col = Math.min(cursor.col, buffer[cursor.line].length);
|
|
onChange();
|
|
return;
|
|
}
|
|
if (e.key === "ArrowLeft") {
|
|
e.preventDefault();
|
|
if (cursor.col > 0) cursor.col--;
|
|
else if (cursor.line > 0) {
|
|
cursor.line--;
|
|
cursor.col = buffer[cursor.line].length;
|
|
}
|
|
onChange();
|
|
return;
|
|
}
|
|
if (e.key === "ArrowRight") {
|
|
e.preventDefault();
|
|
if (cursor.col < buffer[cursor.line].length) cursor.col++;
|
|
else if (cursor.line < buffer.length - 1) {
|
|
cursor.line++;
|
|
cursor.col = 0;
|
|
}
|
|
onChange();
|
|
return;
|
|
}
|
|
if (e.key === "Backspace") {
|
|
e.preventDefault();
|
|
if (cursor.col > 0) {
|
|
const line = buffer[cursor.line];
|
|
buffer[cursor.line] = line.slice(0, cursor.col - 1) + line.slice(cursor.col);
|
|
cursor.col--;
|
|
} else if (cursor.line > 0) {
|
|
cursor.col = buffer[cursor.line - 1].length;
|
|
buffer[cursor.line - 1] += buffer[cursor.line];
|
|
buffer.splice(cursor.line, 1);
|
|
cursor.line--;
|
|
}
|
|
onChange();
|
|
return;
|
|
}
|
|
if (e.key === "Enter") {
|
|
e.preventDefault();
|
|
const line = buffer[cursor.line];
|
|
const rest = line.slice(cursor.col);
|
|
buffer[cursor.line] = line.slice(0, cursor.col);
|
|
buffer.splice(cursor.line + 1, 0, rest);
|
|
cursor.line++;
|
|
cursor.col = 0;
|
|
onChange();
|
|
return;
|
|
}
|
|
if (e.key.length === 1) {
|
|
e.preventDefault();
|
|
const line = buffer[cursor.line];
|
|
buffer[cursor.line] = line.slice(0, cursor.col) + e.key + line.slice(cursor.col);
|
|
cursor.col++;
|
|
onChange();
|
|
}
|
|
});
|
|
}
|