scroll/src/common/document.ts

64 lines
1.0 KiB
JavaScript

import { chars } from './utils.ts';
import { getRuntime } from './runtime.ts';
export class Row {
chars: string[] = [];
constructor(s: string = '') {
this.chars = chars(s);
}
public toString(): string {
return this.chars.join('');
}
}
export class Document {
#rows: Row[];
private constructor() {
this.#rows = [];
}
get numRows(): number {
return this.#rows.length;
}
public static empty(): Document {
return new Document();
}
public isEmpty(): boolean {
return this.#rows.length === 0;
}
public async open(filename: string): Promise<Document> {
const { file } = await getRuntime();
// Clear any existing rows
if (!this.isEmpty()) {
this.#rows = [];
}
const rawFile = await file.openFile(filename);
rawFile.split(/\r?\n/)
.forEach((row) => this.appendRow(row));
return this;
}
public row(i: number): Row | null {
if (this.#rows[i] !== undefined) {
return this.#rows[i];
}
return null;
}
protected appendRow(s: string): void {
this.#rows.push(new Row(s));
}
}
export default Document;