scroll/src/common/editor.ts

352 lines
8.2 KiB
JavaScript

import Ansi, { KeyCommand } from './ansi.ts';
import Buffer from './buffer.ts';
import Document from './document.ts';
import { ITerminalSize, logToFile, Position, SCROLL_VERSION } from './mod.ts';
import Row from './row.ts';
import { ctrlKey, maxAdd, posSub, truncate } from './utils.ts';
class Editor {
/**
* The document being edited
* @private
*/
#document: Document;
/**
* The output buffer for the terminal
* @private
*/
#buffer: Buffer;
/**
* The size of the screen in rows/columns
* @private
*/
#screen: ITerminalSize;
/**
* The current location of the mouse cursor
* @private
*/
#cursor: Position;
/**
* The current scrolling offset
*/
#offset: Position;
/**
* The scrolling offset for the rendered row
* @private
*/
#renderX: number = 0;
/**
* The name of the currently open file
* @private
*/
#filename: string = '';
/**
* A message to display at the bottom of the screen
* @private
*/
#statusMessage: string = '';
/**
* Timeout for status messages
* @private
*/
#statusTimeout: number = 0;
constructor(terminalSize: ITerminalSize) {
this.#buffer = new Buffer();
// Subtract two rows from the terminal size
// for displaying the status bar
// and message bar
this.#screen = terminalSize;
this.#screen.rows -= 2;
this.#cursor = Position.default();
this.#offset = Position.default();
this.#document = Document.empty();
}
private get numRows(): number {
return this.#document.numRows;
}
private get currentRow(): Row | null {
return this.#document.row(this.#cursor.y);
}
public async open(filename: string): Promise<Editor> {
await this.#document.open(filename);
this.#filename = filename;
return this;
}
// --------------------------------------------------------------------------
// Command/input mapping
// --------------------------------------------------------------------------
/**
* Determine what to do based on input
* @param input - the decoded chunk of stdin
*/
public async processKeyPress(input: string): Promise<boolean> {
switch (input) {
case KeyCommand.Enter:
// TODO
break;
case ctrlKey('q'):
await this.clearScreen();
return false;
case ctrlKey('s'):
await this.#document.save();
this.setStatusMessage(`${this.#filename} was saved to disk.`);
break;
case KeyCommand.Home:
this.#cursor.x = 0;
break;
case KeyCommand.End:
if (this.currentRow !== null) {
this.#cursor.x = this.currentRow.size - 1;
}
break;
case KeyCommand.Delete:
this.#document.delete(this.#cursor);
break;
case KeyCommand.Backspace:
{
if (this.#cursor.x > 0 || this.#cursor.y > 0) {
this.moveCursor(KeyCommand.ArrowLeft);
this.#document.delete(this.#cursor);
}
}
break;
case KeyCommand.PageUp:
case KeyCommand.PageDown:
{
if (input === KeyCommand.PageUp) {
this.#cursor.y = this.#offset.y;
} else if (input === KeyCommand.PageDown) {
this.#cursor.y = maxAdd(
this.#offset.y,
this.#screen.rows - 1,
this.numRows,
);
}
let times = this.#screen.rows;
while (times--) {
this.moveCursor(
input === KeyCommand.PageUp
? KeyCommand.ArrowUp
: KeyCommand.ArrowDown,
);
}
}
break;
case KeyCommand.ArrowUp:
case KeyCommand.ArrowDown:
case KeyCommand.ArrowRight:
case KeyCommand.ArrowLeft:
this.moveCursor(input);
break;
case KeyCommand.Escape:
break;
default:
this.#document.insert(this.#cursor, input);
this.#cursor.x++;
}
return true;
}
private moveCursor(char: string): void {
switch (char) {
case KeyCommand.ArrowLeft:
if (this.#cursor.x > 0) {
this.#cursor.x--;
} else if (this.#cursor.y > 0) {
this.#cursor.y--;
this.#cursor.x = (this.currentRow !== null)
? this.currentRow.size - 1
: 0;
}
break;
case KeyCommand.ArrowRight:
if (
this.currentRow !== null && this.#cursor.x < this.currentRow.size - 1
) {
this.#cursor.x++;
} else if (
this.currentRow !== null &&
this.#cursor.x === this.currentRow.size - 1
) {
this.#cursor.y++;
this.#cursor.x = 0;
}
break;
case KeyCommand.ArrowUp:
if (this.#cursor.y > 0) {
this.#cursor.y--;
}
break;
case KeyCommand.ArrowDown:
if (this.#cursor.y < this.numRows) {
this.#cursor.y++;
}
break;
}
const rowLen = this.currentRow?.size ?? 0;
if (this.#cursor.x > rowLen) {
this.#cursor.x = rowLen;
}
}
private scroll(): void {
this.#renderX = 0;
if (this.currentRow !== null) {
this.#renderX = this.currentRow.cxToRx(this.#cursor.x);
}
if (this.#cursor.y < this.#offset.y) {
this.#offset.y = this.#cursor.y;
}
if (this.#cursor.y >= this.#offset.y + this.#screen.rows) {
this.#offset.y = this.#cursor.y - this.#screen.rows + 1;
}
if (this.#renderX < this.#offset.x) {
this.#offset.x = this.#renderX;
}
if (this.#renderX >= this.#offset.x + this.#screen.cols) {
this.#offset.x = this.#renderX - this.#screen.cols + 1;
}
}
// --------------------------------------------------------------------------
// Terminal Output / Drawing
// --------------------------------------------------------------------------
public setStatusMessage(msg: string): void {
// TODO: consider some sort of formatting for passed strings
this.#statusMessage = msg;
this.#statusTimeout = Date.now();
}
/**
* Clear the screen and write out the buffer
*/
public async refreshScreen(): Promise<void> {
this.scroll();
this.#buffer.append(Ansi.HideCursor);
this.#buffer.append(Ansi.ResetCursor);
this.drawRows();
this.drawStatusBar();
this.drawMessageBar();
this.#buffer.append(
Ansi.moveCursor(
this.#cursor.y - this.#offset.y,
this.#renderX - this.#offset.x,
),
);
this.#buffer.append(Ansi.ShowCursor);
await this.#buffer.flush();
}
private async clearScreen(): Promise<void> {
this.#buffer.append(Ansi.ClearScreen);
this.#buffer.append(Ansi.ResetCursor);
await this.#buffer.flush();
}
private drawRows(): void {
for (let y = 0; y < this.#screen.rows; y++) {
this.#buffer.append(Ansi.ClearLine);
const fileRow = y + this.#offset.y;
if (fileRow >= this.numRows) {
this.drawPlaceholderRow(fileRow);
} else {
this.drawFileRow(fileRow);
}
this.#buffer.appendLine();
}
}
private drawFileRow(y: number): void {
const row = this.#document.row(y);
if (row === null) {
logToFile(`Warning: trying to draw non-existent row '${y}'`);
return this.drawPlaceholderRow(y);
}
const len = Math.min(
posSub(row.rsize, this.#offset.x),
this.#screen.cols,
);
this.#buffer.append(row.rstring(this.#offset.x), len);
}
private drawPlaceholderRow(y: number): void {
if (y === Math.trunc(this.#screen.rows / 2) && this.#document.isEmpty()) {
const message = `Scroll editor -- version ${SCROLL_VERSION}`;
const messageLen = (message.length > this.#screen.cols)
? this.#screen.cols
: message.length;
let padding = Math.trunc((this.#screen.cols - messageLen) / 2);
if (padding > 0) {
this.#buffer.append('~');
padding -= 1;
this.#buffer.append(' '.repeat(padding));
}
this.#buffer.append(message, messageLen);
} else {
this.#buffer.append('~');
}
}
private drawStatusBar(): void {
this.#buffer.append(Ansi.InvertColor);
const name = (this.#filename !== '') ? this.#filename : '[No Name]';
const modified = (this.#document.dirty) ? '(modified)' : '';
const status = `${truncate(name, 20)} - ${this.numRows} lines ${modified}`;
const rStatus = `${this.#cursor.y + 1}/${this.numRows}`;
let len = Math.min(status.length, this.#screen.cols);
this.#buffer.append(status, len);
while (len < this.#screen.cols) {
if (this.#screen.cols - len === rStatus.length) {
this.#buffer.append(rStatus);
break;
} else {
this.#buffer.append(' ');
len++;
}
}
this.#buffer.appendLine(Ansi.ResetFormatting);
}
private drawMessageBar(): void {
this.#buffer.append(Ansi.ClearLine);
const msgLen = this.#statusMessage.length;
if (msgLen > 0 && (Date.now() - this.#statusTimeout < 5000)) {
this.#buffer.append(this.#statusMessage, this.#screen.cols);
}
}
}
export default Editor;