From ddab992f1fee3a0ab9d25b4282c327f966eb6d8b Mon Sep 17 00:00:00 2001 From: BearToCode Date: Thu, 7 Nov 2024 10:45:35 +0100 Subject: [PATCH] fix: improve speculative updates Append text to the previous node instead of to the start of the next one, when possible --- packages/carta-md/src/lib/internal/speculative.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/carta-md/src/lib/internal/speculative.ts b/packages/carta-md/src/lib/internal/speculative.ts index c75efc01..b623a988 100644 --- a/packages/carta-md/src/lib/internal/speculative.ts +++ b/packages/carta-md/src/lib/internal/speculative.ts @@ -44,14 +44,21 @@ export function speculativeHighlightUpdate(container: HTMLDivElement, from: stri advance(change.value.length); }; const addedCallback = (change: Change) => { - const node = textNodes.at(currentNodeIdx) ?? createTemporaryNode(container); + const node = + currentNodeCharIdx == 0 + ? textNodes.at(currentNodeIdx - 1) + : textNodes.at(currentNodeIdx) ?? createTemporaryNode(container); if (!node) return; // Could not create a temporary node const text = node.textContent ?? ''; - const pre = text.slice(0, currentNodeCharIdx); - const post = text.slice(currentNodeCharIdx); + if (currentNodeCharIdx == 0) { + node.textContent = text + change.value; + } else { + const pre = text.slice(0, currentNodeCharIdx); + const post = text.slice(currentNodeCharIdx); + node.textContent = pre + change.value + post; + } - node.textContent = pre + change.value + post; advance(change.value.length); }; const removedCallback = (change: Change) => {