Implement merging lines of text from either end of a row

This commit is contained in:
Timothy Warren 2023-11-22 15:11:32 -05:00
parent 1198311628
commit 2babbf5c68
2 changed files with 39 additions and 3 deletions

View File

@ -67,12 +67,34 @@ export class Document {
} }
public delete(at: Position): void { public delete(at: Position): void {
const row = this.row(at.y); const len = this.numRows;
if (row === null) { if (at.y >= len) {
return; return;
} }
row.delete(at.x); const row = this.row(at.y)!;
const mergeNextRow = at.x === row.size - 1 && at.y < len - 1;
const mergeIntoPrevRow = at.x === 0 && at.y > 0;
// If we are at the end of a line, and press delete,
// add the contents of the next row, and delete
// the merged row object
if (mergeNextRow) {
// At the end of a line, pressing delete will merge
// the next line into the current on
const rowToAppend = this.#rows.at(at.y + 1)!.toString();
row.append(rowToAppend);
this.deleteRow(at.y + 1);
} else if (mergeIntoPrevRow) {
// At the beginning of a line, merge the current line
// into the previous Row
const rowToAppend = row.toString();
this.#rows[at.y - 1].append(rowToAppend);
this.deleteRow(at.y);
} else {
row.delete(at.x);
}
row.updateRender(); row.updateRender();
this.dirty = true; this.dirty = true;
@ -90,6 +112,15 @@ export class Document {
this.dirty = true; this.dirty = true;
} }
/**
* Delete the specified row
* @param at - the index of the row to delete
* @private
*/
private deleteRow(at: number): void {
this.#rows.splice(at, 1);
}
private rowsToString(): string { private rowsToString(): string {
return this.#rows.map((r) => r.toString()).join('\n'); return this.#rows.map((r) => r.toString()).join('\n');
} }

View File

@ -33,6 +33,11 @@ export class Row {
return this.render.slice(offset).join(''); return this.render.slice(offset).join('');
} }
public append(s: string): void {
this.chars = this.chars.concat(chars(s));
this.updateRender();
}
public insertChar(at: number, c: string): void { public insertChar(at: number, c: string): void {
const newSlice = Util.chars(c); const newSlice = Util.chars(c);
if (at >= this.size) { if (at >= this.size) {