From b33fc9f0fd2ce43a1e2844bcda6ecbcfb04062e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Trzci=C5=84ski?= Date: Mon, 23 Sep 2024 14:01:48 +0200 Subject: [PATCH] [#66130] add input debouncing to cursor syncing --- src/extensions/syncDualPane.js | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/extensions/syncDualPane.js b/src/extensions/syncDualPane.js index 5222608..12b5ca7 100644 --- a/src/extensions/syncDualPane.js +++ b/src/extensions/syncDualPane.js @@ -3,9 +3,12 @@ import { markdownUpdatedStateEffect } from "../hooks/useText"; import { findNearestElementForLine } from "../hooks/markdownSourceMap"; const previewTopPadding = 20; +const debounceTimeout = 50; -export const syncPreviewWithCursor = (lineMap, preview) => - EditorView.updateListener.of((update) => { +export const syncPreviewWithCursor = (lineMap, preview) => { + let timeout; + + return EditorView.updateListener.of((update) => { const cursorLineBefore = update.startState.doc.lineAt(update.startState.selection.main.head).number; const cursorLineAfter = update.state.doc.lineAt(update.state.selection.main.head).number; const selectionChanged = update.selectionSet && (cursorLineBefore !== cursorLineAfter || cursorLineBefore === 1); @@ -15,17 +18,23 @@ export const syncPreviewWithCursor = (lineMap, preview) => return; } - const [matchingElem, matchingLine] = findNearestElementForLine(cursorLineAfter, lineMap, preview.current); - if (matchingElem) { - scrollPreviewElemIntoView({ - view: update.view, - matchingLine, - matchingElem, - behavior: "smooth", - preview: preview.current, - }); + function sync() { + const [matchingElem, matchingLine] = findNearestElementForLine(cursorLineAfter, lineMap, preview.current); + if (matchingElem) { + scrollPreviewElemIntoView({ + view: update.view, + matchingLine, + matchingElem, + behavior: "smooth", + preview: preview.current, + }); + } } + + clearTimeout(timeout); + timeout = setTimeout(sync, debounceTimeout); }); +}; /** @param {Object} param0 * @param {EditorView} param0.view