From 08ab6ecbaac8660ad6029f68726e4d00b56566c5 Mon Sep 17 00:00:00 2001 From: bakk Date: Sat, 5 Jun 2021 00:26:12 +0200 Subject: [PATCH] web: Fixed caret jumping to end after highlight --- web/src/KalkCalculator.svelte | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/web/src/KalkCalculator.svelte b/web/src/KalkCalculator.svelte index 708f37e..166abfc 100644 --- a/web/src/KalkCalculator.svelte +++ b/web/src/KalkCalculator.svelte @@ -48,8 +48,11 @@ let hasBeenInteractedWith = false; function setText(text: string) { - const highlighted = highlight(text); + const [highlighted, offset] = highlight(text); + const prevCursorPos = inputElement.selectionStart; setHtml(highlighted); + inputElement.selectionStart = prevCursorPos + offset; + inputElement.selectionEnd = inputElement.selectionStart; } function setHtml(html: string) { @@ -117,7 +120,7 @@ const [result, success] = calculate(kalk, input); output = success - ? highlight(result) + ? highlight(result)[0] : `${result}`; } @@ -145,6 +148,9 @@ // of the input field. This piece of code will put the cursor at the end, // which therefore will need to be done afterwards, so that it doesn't just get moved back again. if (event.key == "ArrowUp" || event.key == "ArrowDown") { + // Don't do anything if it's multi-line + if (inputElement.value.match(/\r|\r\n|\n/)) return; + const change = event.key == "ArrowUp" ? 1 : -1; selectedLineOffset += change; @@ -213,9 +219,8 @@ input += ")"; } else if (input == "=") { input = " = "; - } else if (input == "Σ") { + } else if (input == "∑") { input += "()"; - offset = -1; } else if (input == "∫") { input += "()"; offset = -1; @@ -244,9 +249,10 @@ if (autofocus) element.focus(); } - function highlight(input: string): string { - if (!input) return ""; + function highlight(input: string): [string, number] { + if (!input) return ["", 0]; let result = input; + let offset = 0; result = result.replace( /(?[<>&]|(\n\s*\}?|\s+))|(?([+\-/*%^!≈]|if|otherwise)|(?[^!-@\s_|^⌊⌋⌈⌉≈\[\]\{\}≠≥≤]+(_\d+)?))/g, (substring, _, html, _2, op, identifier) => { @@ -254,14 +260,17 @@ if (substring == "<") return "<"; if (substring == ">") return ">"; if (substring == "&") return "&"; - if (substring.match(/\s+/)) return " "; if (substring.startsWith("\n")) { if (substring.endsWith("}")) { return "
}"; } else { + if (!substring.match(/\n\s\s/)) offset += 2; return "
  "; } } + if (substring.match(/\s+/)) { + return " ".repeat(substring.length); + } } if (identifier) { @@ -305,6 +314,8 @@ } } + offset -= substring.length - newSubstring.length; + return `${newSubstring}`; } @@ -316,7 +327,7 @@ } ); - return result; + return [result, offset]; }