scroll/src/common/document.ts

64 lines
1.0 KiB
JavaScript
Raw Normal View History

2023-11-13 15:33:56 -05:00
import { chars } from './utils.ts';
import { getRuntime } from './runtime.ts';
2023-11-13 14:46:04 -05:00
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 {
2023-11-13 14:46:04 -05:00
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 = [];
}
2023-11-13 14:46:04 -05:00
const rawFile = await file.openFile(filename);
rawFile.split(/\r?\n/)
.forEach((row) => this.appendRow(row));
2023-11-13 14:46:04 -05:00
return this;
2023-11-13 14:46:04 -05:00
}
public row(i: number): Row | null {
2023-11-13 14:46:04 -05:00
if (this.#rows[i] !== undefined) {
return this.#rows[i];
}
return null;
}
public appendRow(s: string): void {
this.#rows.push(new Row(s));
}
2023-11-13 14:46:04 -05:00
}
export default Document;