Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

web: debounce selection updates in editor

Abdullah Attafd868aec9516
diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsx
index 386c5c92c..461e43bea 100644
--- a/apps/web/src/components/editor/tiptap.tsx
+++ b/apps/web/src/components/editor/tiptap.tsx
@@ -52,7 +52,7 @@ import { getCurrentPreset } from "../../common/toolbar-config";
import { useIsUserPremium } from "../../hooks/use-is-user-premium";
import { showBuyDialog } from "../../common/dialog-controller";
import { useStore as useSettingsStore } from "../../stores/setting-store";
-import { debounceWithId } from "../../utils/debounce";
+import { debounceWithId, inlineDebounce } from "../../utils/debounce";
import { store as editorstore } from "../../stores/editor-store";
type TipTapProps = {
@@ -215,20 +215,36 @@ function TipTap(props: TipTapProps) {
});
},
onSelectionUpdate: ({ editor, transaction }) => {
- const content = editor.state.doc.content;
- configure((old) => ({
- statistics: {
- words: {
- total:
- old.statistics?.words.total ||
- countWords(content.textBetween(0, content.size, "\n", " ")),
- selected: getSelectedWords(
+ inlineDebounce(
+ "tiptap:onSelectionUpdate",
+ () => {
+ const isEmptySelection = transaction.selection.empty;
+ configure((old) => {
+ const oldSelected = old.statistics?.words?.selected;
+ const oldWords = old.statistics?.words.total || 0;
+ if (isEmptySelection)
+ return oldSelected
+ ? {
+ statistics: { words: { total: oldWords, selected: 0 } }
+ }
+ : old;
+
+ const selectedWords = getSelectedWords(
editor as Editor,
transaction.selection
- )
- }
- }
- }));
+ );
+ return {
+ statistics: {
+ words: {
+ total: oldWords,
+ selected: selectedWords
+ }
+ }
+ };
+ });
+ },
+ 500
+ );
},
theme,
onOpenAttachmentPicker: (_editor, type) => {
diff --git a/apps/web/src/utils/debounce.ts b/apps/web/src/utils/debounce.ts
index 6ebf08f11..4e8dae7e4 100644
--- a/apps/web/src/utils/debounce.ts
+++ b/apps/web/src/utils/debounce.ts
@@ -48,3 +48,9 @@ export function debounceWithId<F extends (...args: never[]) => void>(
return debounced;
}
+
+const DEBOUNCE_TIMEOUTS: Record<string, NodeJS.Timeout> = {};
+export function inlineDebounce(id: string, func: () => void, waitFor: number) {
+ clearTimeout(DEBOUNCE_TIMEOUTS[id]);
+ DEBOUNCE_TIMEOUTS[id] = setTimeout(func, waitFor);
+}