|
| 1 | +import type { ReactiveController, ReactiveControllerHost } from "lit"; |
| 2 | +import { appState } from "../state/app-state.js"; |
| 3 | + |
| 4 | +export interface HistoryResult { |
| 5 | + handled: boolean; |
| 6 | + text: string; |
| 7 | +} |
| 8 | + |
| 9 | +function isCursorOnFirstLine(ta: HTMLTextAreaElement): boolean { |
| 10 | + return !ta.value.substring(0, ta.selectionStart).includes("\n"); |
| 11 | +} |
| 12 | + |
| 13 | +function isCursorOnLastLine(ta: HTMLTextAreaElement): boolean { |
| 14 | + return !ta.value.substring(ta.selectionEnd).includes("\n"); |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Lit reactive controller that provides shell-like arrow-up / arrow-down |
| 19 | + * input history for a textarea. History entries come from the current |
| 20 | + * chat's user messages (via appState). |
| 21 | + */ |
| 22 | +export class InputHistory implements ReactiveController { |
| 23 | + private index = -1; |
| 24 | + private draft = ""; |
| 25 | + |
| 26 | + constructor(private host: ReactiveControllerHost) { |
| 27 | + host.addController(this); |
| 28 | + } |
| 29 | + |
| 30 | + hostConnected() {} |
| 31 | + hostDisconnected() { |
| 32 | + this.reset(); |
| 33 | + } |
| 34 | + |
| 35 | + private entries(): string[] { |
| 36 | + return appState.state.messages |
| 37 | + .filter((m) => m.role === "user") |
| 38 | + .map((m) => m.content) |
| 39 | + .reverse(); |
| 40 | + } |
| 41 | + |
| 42 | + handleKeyDown( |
| 43 | + e: KeyboardEvent, |
| 44 | + textarea: HTMLTextAreaElement, |
| 45 | + currentText: string, |
| 46 | + ): HistoryResult { |
| 47 | + const unchanged: HistoryResult = { handled: false, text: currentText }; |
| 48 | + |
| 49 | + if (e.key === "ArrowUp" && isCursorOnFirstLine(textarea)) { |
| 50 | + const hist = this.entries(); |
| 51 | + if (!hist.length) return unchanged; |
| 52 | + if (this.index === -1) this.draft = currentText; |
| 53 | + this.index = Math.min(this.index + 1, hist.length - 1); |
| 54 | + return { handled: true, text: hist[this.index] }; |
| 55 | + } |
| 56 | + |
| 57 | + if (e.key === "ArrowDown" && isCursorOnLastLine(textarea)) { |
| 58 | + if (this.index === -1) return unchanged; |
| 59 | + this.index -= 1; |
| 60 | + const text = this.index === -1 ? this.draft : this.entries()[this.index]; |
| 61 | + return { handled: true, text }; |
| 62 | + } |
| 63 | + |
| 64 | + return unchanged; |
| 65 | + } |
| 66 | + |
| 67 | + reset(): void { |
| 68 | + this.index = -1; |
| 69 | + this.draft = ""; |
| 70 | + } |
| 71 | +} |
0 commit comments