From dd955b06499a7cbcf5a5944be9d679e4bf0467e8 Mon Sep 17 00:00:00 2001 From: liquidev Date: Fri, 25 Oct 2024 22:53:52 +0200 Subject: [PATCH] code-editor: make Backspace remove full indents at the start of a line --- static/code-editor.js | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/static/code-editor.js b/static/code-editor.js index 4e1b4e6..086c9cd 100644 --- a/static/code-editor.js +++ b/static/code-editor.js @@ -26,6 +26,8 @@ export class CodeEditor extends HTMLElement { this.textArea.rows = 1; this.keyShortcuts = { + Backspace: () => this.backspace(), + Enter: () => this.enter(), Tab: () => this.tab(), @@ -251,6 +253,28 @@ export class CodeEditor extends HTMLElement { } } + backspace() { + this.pushHistory({ allowMerge: true }); + + let selection = this.getSelection(); + selection.collapse(); + + let start = getLineStart(this.code, selection.start); + let leading = this.code.substring(start, selection.cursor); + let isAtIndent = /^ +$/.test(leading); + let positionInLine = selection.cursor - start; + let charactersToRemove = isAtIndent + ? this.indentWidth - (positionInLine % this.indentWidth) + : 1; + + selection.cursor -= charactersToRemove; + selection.clampCursor(this.code); + this.replace(selection, ""); + selection.collapse(); + + this.setSelection(selection); + } + enter() { this.pushHistory({ allowMerge: false }); @@ -335,16 +359,20 @@ export class Selection { this.cursor = Math.max(0, Math.min(this.cursor, text.length)); } + collapse() { + this.anchor = this.cursor; + } + set(text, n) { this.cursor = n; this.clampCursor(text); - this.anchor = this.cursor; + this.collapse(); } advance(text, n) { this.cursor += n; this.clampCursor(text); - this.anchor = this.cursor; + this.collapse(); } }