xonecas.io
64875
Mc

mini-coder / files

mini-coder / src / tui / editor.ts

9.6 KB
1import { displayWidth, expandTabs, wrapLine, type Key } from "./term.ts";
2
3const TAB = 4;
4const DEFAULT_WIDTH = 80;
5
6function codePoints(line: string): string[] {
7  return Array.from(line);
8}
9
10function isSpace(ch: string): boolean {
11  return /\s/u.test(ch);
12}
13
14/** First code point index of the word before `col`; shared by all word motion. */
15function wordStart(cps: string[], col: number): number {
16  let i = col;
17  while (i > 0 && isSpace(cps[i - 1])) i--;
18  while (i > 0 && !isSpace(cps[i - 1])) i--;
19  return i;
20}
21
22/** Code point index one past the word at or after `col`. */
23function wordEnd(cps: string[], col: number): number {
24  let i = col;
25  while (i < cps.length && isSpace(cps[i])) i++;
26  while (i < cps.length && !isSpace(cps[i])) i++;
27  return i;
28}
29
30interface EditorRender {
31  rows: string[];
32  cursorRow: number;
33  cursorCol: number;
34}
35
36export class Editor {
37  private lines: string[] = [""];
38  private row = 0;
39  private col = 0;
40  private scroll = 0;
41  private width = DEFAULT_WIDTH;
42  private masked = false;
43
44  text(): string {
45    return this.lines.join("\n");
46  }
47
48  /** Renders each character as `*` without changing the underlying text. */
49  setMasked(masked: boolean): void {
50    this.masked = masked;
51  }
52
53  private display(line: string): string {
54    return this.masked ? "*".repeat(codePoints(line).length) : line;
55  }
56
57  clear(): void {
58    this.lines = [""];
59    this.row = 0;
60    this.col = 0;
61    this.scroll = 0;
62  }
63
64  setText(text: string): void {
65    this.lines = text.split("\n");
66    this.row = this.lines.length - 1;
67    this.col = codePoints(this.lines[this.row]).length;
68    this.scroll = 0;
69  }
70
71  handle(key: Key): "submit" | "changed" | "none" {
72    switch (key.type) {
73      case "submit":
74        return "submit";
75      case "newline":
76        this.insert("\n");
77        return "changed";
78      case "text":
79        this.insert(key.text);
80        return "changed";
81      case "backspace":
82        this.backspace();
83        return "changed";
84      case "delete":
85        this.deleteForward();
86        return "changed";
87      case "wordBack":
88        this.wordBack();
89        return "changed";
90      case "left":
91        this.left();
92        return "changed";
93      case "right":
94        this.right();
95        return "changed";
96      case "wordLeft":
97        this.wordLeft();
98        return "changed";
99      case "wordRight":
100        this.wordRight();
101        return "changed";
102      case "up":
103        this.up();
104        return "changed";
105      case "down":
106        this.down();
107        return "changed";
108      case "home":
109        this.col = 0;
110        return "changed";
111      case "end":
112        this.col = codePoints(this.lines[this.row]).length;
113        return "changed";
114      case "docStart":
115        this.row = 0;
116        this.col = 0;
117        return "changed";
118      case "docEnd":
119        this.row = this.lines.length - 1;
120        this.col = codePoints(this.lines[this.row]).length;
121        return "changed";
122      default:
123        return "none";
124    }
125  }
126
127  /** Clipped to `maxRows`, scrolled only as far as the caret requires. */
128  render(width: number, maxRows: number): EditorRender {
129    this.width = Math.max(1, width);
130    const rows: string[] = [];
131    let cursorRow = 0;
132    let cursorCol = 0;
133    for (let line = 0; line < this.lines.length; line++) {
134      const chunks = wrapLine(expandTabs(this.display(this.lines[line]), TAB), this.width);
135      if (line === this.row) {
136        const caret = this.caret();
137        cursorRow = rows.length + caret.row;
138        cursorCol = caret.col;
139      }
140      rows.push(...chunks);
141    }
142    const view = Math.max(1, maxRows);
143    if (cursorRow < this.scroll) this.scroll = cursorRow;
144    else if (cursorRow >= this.scroll + view) this.scroll = cursorRow - view + 1;
145    this.scroll = Math.min(Math.max(this.scroll, 0), Math.max(0, rows.length - view));
146    return {
147      rows: rows.slice(this.scroll, this.scroll + view),
148      cursorRow: cursorRow - this.scroll,
149      cursorCol,
150    };
151  }
152
153  /** The caret's display row within its logical line, and its cell column. */
154  private caret(): { row: number; col: number } {
155    const line = this.display(this.lines[this.row]);
156    const chunks = wrapLine(expandTabs(line, TAB), this.width);
157    const cell = this.cells(line)[this.col];
158    const row = Math.floor(cell / this.width);
159    if (row >= chunks.length) return { row: chunks.length - 1, col: displayWidth(chunks[chunks.length - 1]) };
160    return { row, col: cell - row * this.width };
161  }
162
163  /** Display column of every code point boundary in `line`, tabs expanded. */
164  private cells(line: string): number[] {
165    const out = [0];
166    let col = 0;
167    for (const ch of codePoints(line)) {
168      col += ch === "\t" ? TAB - (col % TAB) : displayWidth(ch);
169      out.push(col);
170    }
171    return out;
172  }
173
174  /** The caret column nearest `cell`, never past the end of the line. */
175  private colAtCell(line: string, cell: number): number {
176    const cells = this.cells(line);
177    let i = cells.length - 1;
178    while (i > 0 && cells[i] > cell) i--;
179    return i;
180  }
181
182  private insert(text: string): void {
183    const parts = text.split("\n");
184    const current = codePoints(this.lines[this.row]);
185    const before = current.slice(0, this.col).join("");
186    const after = current.slice(this.col).join("");
187    if (parts.length === 1) {
188      this.lines[this.row] = before + parts[0] + after;
189      this.col += codePoints(parts[0]).length;
190      return;
191    }
192    const head = before + parts[0];
193    const tail = parts[parts.length - 1] + after;
194    this.lines.splice(this.row, 1, head, ...parts.slice(1, -1), tail);
195    this.row += parts.length - 1;
196    this.col = codePoints(parts[parts.length - 1]).length;
197  }
198
199  private backspace(): void {
200    if (this.col > 0) {
201      const current = codePoints(this.lines[this.row]);
202      this.lines[this.row] = current.slice(0, this.col - 1).join("") + current.slice(this.col).join("");
203      this.col--;
204      return;
205    }
206    if (this.row > 0) {
207      const previous = codePoints(this.lines[this.row - 1]).length;
208      this.lines[this.row - 1] += this.lines[this.row];
209      this.lines.splice(this.row, 1);
210      this.row--;
211      this.col = previous;
212    }
213  }
214
215  private deleteForward(): void {
216    const current = codePoints(this.lines[this.row]);
217    if (this.col < current.length) {
218      this.lines[this.row] = current.slice(0, this.col).join("") + current.slice(this.col + 1).join("");
219      return;
220    }
221    if (this.row < this.lines.length - 1) {
222      this.lines[this.row] += this.lines[this.row + 1];
223      this.lines.splice(this.row + 1, 1);
224    }
225  }
226
227  private left(): void {
228    if (this.col > 0) this.col--;
229    else if (this.row > 0) {
230      this.row--;
231      this.col = codePoints(this.lines[this.row]).length;
232    }
233  }
234
235  private right(): void {
236    if (this.col < codePoints(this.lines[this.row]).length) this.col++;
237    else if (this.row < this.lines.length - 1) {
238      this.row++;
239      this.col = 0;
240    }
241  }
242
243  /** One display row, so the caret crosses the wrapped rows of a long line. */
244  private up(): void {
245    const line = this.lines[this.row];
246    const caret = this.caret();
247    if (caret.row > 0) {
248      this.col = this.colAtCell(line, this.cells(line)[this.col] - this.width);
249      return;
250    }
251    if (this.row === 0) return;
252    this.row--;
253    const previous = this.lines[this.row];
254    const lastRow = wrapLine(expandTabs(previous, TAB), this.width).length - 1;
255    this.col = this.colAtCell(previous, lastRow * this.width + caret.col);
256  }
257
258  private down(): void {
259    const line = this.lines[this.row];
260    const caret = this.caret();
261    if (caret.row < wrapLine(expandTabs(line, TAB), this.width).length - 1) {
262      this.col = this.colAtCell(line, this.cells(line)[this.col] + this.width);
263      return;
264    }
265    if (this.row === this.lines.length - 1) return;
266    this.row++;
267    this.col = this.colAtCell(this.lines[this.row], caret.col);
268  }
269
270  private wordLeft(): void {
271    const cps = codePoints(this.lines[this.row]);
272    const start = wordStart(cps, this.col);
273    if (start !== this.col) {
274      this.col = start;
275      return;
276    }
277    if (this.row === 0) return;
278    this.row--;
279    const previous = codePoints(this.lines[this.row]);
280    this.col = wordStart(previous, previous.length);
281  }
282
283  private wordRight(): void {
284    const cps = codePoints(this.lines[this.row]);
285    const end = wordEnd(cps, this.col);
286    if (end !== this.col) {
287      this.col = end;
288      return;
289    }
290    if (this.row === this.lines.length - 1) return;
291    this.row++;
292    this.col = wordEnd(codePoints(this.lines[this.row]), 0);
293  }
294
295  private wordBack(): void {
296    const current = codePoints(this.lines[this.row]);
297    const start = wordStart(current, this.col);
298    this.lines[this.row] = current.slice(0, start).join("") + current.slice(this.col).join("");
299    this.col = start;
300  }
301
302  /**
303   * Applies `step` to the word ending at the caret, replacing it; false when
304   * there is no word before the caret. Whitespace is `isSpace` (Unicode `\s`),
305   * so a path word may carry `/`, `~`, `.`, `$` — no path-specific separator
306   * set. No completion-undo: bash's TAB-_ restore is out; the user backspaces
307   * or re-types instead, with Esc and the editor's own keys as recovery.
308   */
309  completeWord(step: (word: string) => string | null): boolean {
310    const current = codePoints(this.lines[this.row]);
311    const start = wordStart(current, this.col);
312    if (start === this.col || isSpace(current[this.col - 1])) return false;
313    const word = current.slice(start, this.col).join("");
314    const completed = step(word);
315    if (completed === null) return false;
316    this.lines[this.row] = current.slice(0, start).join("") + completed + current.slice(this.col).join("");
317    this.col = start + codePoints(completed).length;
318    return true;
319  }
320}