i need history

This commit is contained in:
Chris Wanstrath 2025-09-20 20:13:04 -07:00
parent 55d81040c1
commit d4809f8af0
4 changed files with 64 additions and 1 deletions

54
src/js/history.ts Normal file
View File

@ -0,0 +1,54 @@
////
// Command input history storage and navigation.
import { cmdTextbox } from "./dom.js"
const history: string[] = ["one", "two", "three"]
let idx = -1
let savedInput = ""
export function initHistory() {
cmdTextbox.addEventListener("keydown", navigateHistory)
}
export function addToHistory(input: string) {
if (history.length === 0 || history[0] === input)
return
history.unshift(input)
resetHistory()
}
export function resetHistory() {
idx = -1
savedInput = ""
}
function navigateHistory(e: KeyboardEvent) {
if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p")) {
e.preventDefault()
if (idx >= history.length - 1) return
if (idx === -1)
savedInput = cmdTextbox.value
cmdTextbox.value = history[++idx] || ""
if (idx >= history.length) idx = history.length - 1
} else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n")) {
e.preventDefault()
console.log(idx, savedInput)
if (idx <= 0) {
cmdTextbox.value = savedInput
idx = -1
return
}
cmdTextbox.value = history[--idx] || ""
if (idx < -1) idx = -1
} else if (idx !== -1) {
resetHistory()
}
}

View File

@ -3,6 +3,7 @@
import { cmdTextbox, cmdLine } from "./dom.js"
import { runCommand } from "./shell.js"
import { resetHistory } from "./history.js"
export function initInput() {
cmdTextbox.addEventListener("keydown", inputHandler)
@ -12,7 +13,10 @@ function inputHandler(event: KeyboardEvent) {
const target = event.target as HTMLElement
if (target?.id !== cmdTextbox.id) return
if (event.key === "Tab") {
if (event.key === "Escape" || (event.ctrlKey && event.key === "c")) {
cmdTextbox.value = ""
resetHistory()
} else if (event.key === "Tab") {
event.preventDefault()
} else if (event.shiftKey && event.key === "Enter") {
cmdTextbox.rows += 1

View File

@ -1,12 +1,14 @@
import { initResize } from "./resize.js"
import { initInput } from "./input.js"
import { initFocus } from "./focus.js"
import { initHistory } from "./history.js"
import { startVramCounter } from "./vram.js"
import { startConnection } from "./websocket.js"
initFocus()
initResize()
initInput()
initHistory()
startConnection()
startVramCounter()

View File

@ -5,9 +5,12 @@ import { addInput, setStatus, addOutput } from "./scrollback.js"
import { send } from "./websocket.js"
import { randomID } from "../shared/utils.js"
import type { Message, CommandResult } from "../shared/types.js"
import { addToHistory } from "./history.js"
export function runCommand(input: string) {
const id = randomID()
addToHistory(input)
addInput(id, input)
send({ id, type: "input", data: input })