Skip to content

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

fix: improve note saving — make it faster and resilient

thecodrrfde86db58d0a
diff --git a/apps/web/__e2e__/editor.test.js b/apps/web/__e2e__/editor.test.js
index ce6d54091..d7ee9fee7 100644
--- a/apps/web/__e2e__/editor.test.js
+++ b/apps/web/__e2e__/editor.test.js
@@ -1,4 +1,5 @@
const { Page, test, expect } = require("@playwright/test");
+const List = require("./utils/listitemidbuilder");
const {
createNote,
NOTE,
@@ -6,6 +7,7 @@ const {
getEditorTitle,
getEditorContent,
getEditorContentAsHTML,
+ editNote,
} = require("./utils");
const {
checkNotePresence,
@@ -230,3 +232,82 @@ test("last line doesn't get saved if it's font is different", async () => {
expect(content).toMatchSnapshot(`last-line-with-different-font.txt`);
});
+
+test("editing a note and switching immediately to another note and making an edit shouldn't overlap both notes", async ({
+ page,
+}) => {
+ await createNoteAndCheckPresence({
+ title: "Test note 1",
+ content: "53ad8e4e40ebebd0f400498d",
+ });
+
+ await createNoteAndCheckPresence({
+ title: "Test note 2",
+ content: "f054d19e9a2f46eff7b9bb25",
+ });
+
+ const selector1 = `[data-item-index="1"] div`;
+ const selector2 = `[data-item-index="2"] div`;
+
+ for (let i = 0; i < 10; ++i) {
+ await page.click(selector2);
+
+ await editNote(null, `Test note 1 (${i}) `, true);
+
+ await page.click(selector1);
+
+ await editNote(null, `Test note 2 (${i})`, true);
+
+ await page.waitForTimeout(100);
+ }
+
+ await page.click(selector1);
+ expect(await getEditorContent()).toMatchSnapshot(
+ `fast-switch-and-edit-note-2.txt`
+ );
+
+ await page.click(selector2);
+ expect(await getEditorContent()).toMatchSnapshot(
+ `fast-switch-and-edit-note-1.txt`
+ );
+});
+
+test("editing a note and switching immediately to another note and editing the title shouldn't overlap both notes", async ({
+ page,
+}, { setTimeout }) => {
+ setTimeout(0);
+ await createNoteAndCheckPresence({
+ title: "Test note 1",
+ content: "53ad8e4e40ebebd0f400498d",
+ });
+
+ await createNoteAndCheckPresence({
+ title: "Test note 2",
+ content: "f054d19e9a2f46eff7b9bb25",
+ });
+
+ const selector1 = `[data-item-index="1"] div`;
+ const selector2 = `[data-item-index="2"] div`;
+
+ for (let i = 0; i < 10; ++i) {
+ await page.click(selector2);
+
+ await editNote(`Test note 2 (${i})`, null, true);
+
+ await page.click(selector1);
+
+ await editNote(`Test note 2 (${i})`, null, true);
+
+ await page.waitForTimeout(100);
+ }
+
+ await page.click(selector1);
+ expect(await getEditorTitle()).toMatchSnapshot(
+ `fast-switch-and-edit-note-title-2.txt`
+ );
+
+ await page.click(selector2);
+ expect(await getEditorTitle()).toMatchSnapshot(
+ `fast-switch-and-edit-note-title-1.txt`
+ );
+});
diff --git a/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-1-Chromium-linux.txt b/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-1-Chromium-linux.txt
new file mode 100644
index 000000000..c5c3d9a70
--- /dev/null
+++ b/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-1-Chromium-linux.txt
@@ -0,0 +1 @@
+Test note 1 (9) Test note 1 (8) Test note 1 (7) Test note 1 (6) Test note 1 (5) Test note 1 (4) Test note 1 (3) Test note 1 (2) Test note 1 (1) Test note 1 (0) 53ad8e4e40ebebd0f400498d
\ No newline at end of file
diff --git a/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-2-Chromium-linux.txt b/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-2-Chromium-linux.txt
new file mode 100644
index 000000000..0365eeded
--- /dev/null
+++ b/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-2-Chromium-linux.txt
@@ -0,0 +1 @@
+Test note 2 (9)Test note 2 (8)Test note 2 (7)Test note 2 (6)Test note 2 (5)Test note 2 (4)Test note 2 (3)Test note 2 (2)Test note 2 (1)Test note 2 (0)f054d19e9a2f46eff7b9bb25
\ No newline at end of file
diff --git a/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-title-1-Chromium-linux.txt b/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-title-1-Chromium-linux.txt
new file mode 100644
index 000000000..f9d2c80fb
--- /dev/null
+++ b/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-title-1-Chromium-linux.txt
@@ -0,0 +1 @@
+Test note 2 (8)
\ No newline at end of file
diff --git a/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-title-2-Chromium-linux.txt b/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-title-2-Chromium-linux.txt
new file mode 100644
index 000000000..c8a4b6fd3
--- /dev/null
+++ b/apps/web/__e2e__/editor.test.js-snapshots/fast-switch-and-edit-note-title-2-Chromium-linux.txt
@@ -0,0 +1 @@
+Test note 2 (9)
\ No newline at end of file
diff --git a/apps/web/__e2e__/notes.test.js b/apps/web/__e2e__/notes.test.js
index 0924e00ca..91c2b88b3 100644
--- a/apps/web/__e2e__/notes.test.js
+++ b/apps/web/__e2e__/notes.test.js
@@ -310,7 +310,7 @@ test.describe("run tests independently", () => {
await page.click(getTestId("properties"));
await expect(
- isPresent(getTestId("properties-Red-check"))
+ isPresent(getTestId("properties-red-check"))
).resolves.toBeTruthy();
await page.click(getTestId("properties-close"));
@@ -423,7 +423,7 @@ test.describe("run tests independently", () => {
await page.click(getTestId("properties"));
- await page.click(getTestId("properties-Red"));
+ await page.click(getTestId("properties-red"));
await checkNoteColored(noteSelector);
});
@@ -469,95 +469,3 @@ test.describe("run tests independently", () => {
);
});
});
-
-test.describe("stress tests", () => {
- // if (!isTestAll())
- test.skip();
-
- test.beforeEach(async ({ page: _page, baseURL }) => {
- page = _page;
- global.page = _page;
- await page.goto(baseURL);
- await page.waitForSelector(getTestId("routeHeader"));
- });
-
- test("create & verify 100 notes", async ({}, info) => {
- info.setTimeout(0);
-
- const lorem = new LoremIpsum({
- sentencesPerParagraph: {
- max: 8,
- min: 4,
- },
- wordsPerSentence: {
- max: 16,
- min: 4,
- },
- });
-
- for (let i = 0; i < 100; ++i) {
- await test.step(`creating test note ${i + 1}`, async () => {
- const title = lorem.generateSentences(1);
- const content = lorem.generateSentences(2);
-
- await createNoteAndCheckPresence({ title, content }, "home", 0);
-
- expect(await getEditorTitle()).toBe(title);
-
- expect(await getEditorContent()).toBe(content);
- });
- }
- });
-
- test("create & switch between 100 notes", async ({ page }, info) => {
- info.setTimeout(0);
-
- const lorem = new LoremIpsum({
- sentencesPerParagraph: {
- max: 8,
- min: 4,
- },
- wordsPerSentence: {
- max: 16,
- min: 4,
- },
- });
-
- const NOTES_COUNT = 100;
-
- let notes = [];
- for (let i = 0; i < NOTES_COUNT; ++i) {
- await test.step(`creating test note ${i + 1}`, async () => {
- const title = lorem.generateSentences(1);
- const content = lorem.generateSentences(2);
-
- await createNoteAndCheckPresence({ title, content }, "home", 0);
-
- expect(await getEditorTitle()).toBe(title);
-
- expect(await getEditorContent()).toBe(content);
-
- notes.push({ title, content });
- });
- }
-
- await page.reload();
-
- for (let i = NOTES_COUNT - 1; i >= 0; i--) {
- await test.step(`switching test note ${i + 1}`, async () => {
- const note = notes[i];
- let noteSelector = await checkNotePresence(
- "home",
- NOTES_COUNT - 1 - i,
- note
- );
-
- await page.click(noteSelector);
-
- expect(await getEditorTitle()).toBe(note.title);
-
- expect(await getEditorContent()).toBe(note.content);
- });
- }
- });
-});
diff --git a/apps/web/__e2e__/utils/index.js b/apps/web/__e2e__/utils/index.js
index a11fe9e8d..9ba445c26 100644
--- a/apps/web/__e2e__/utils/index.js
+++ b/apps/web/__e2e__/utils/index.js
@@ -45,7 +45,7 @@ async function createNote(note, actionButtonId) {
await editNote(note.title, note.content);
}
-async function editNote(title, content) {
+async function editNote(title, content, noDelay = false) {
await page.waitForSelector(".mce-content-body");
// await page.waitForTimeout(1000);
@@ -57,14 +57,14 @@ async function editNote(title, content) {
});
if (content) {
- await page.waitForTimeout(100);
+ if (!noDelay) await page.waitForTimeout(100);
await page.focus(".mce-content-body");
await page.type(".mce-content-body", content);
}
- await page.waitForTimeout(200);
+ if (!noDelay) await page.waitForTimeout(200);
}
async function downloadFile(downloadActionSelector, encoding) {
diff --git a/apps/web/package.json b/apps/web/package.json
index 86a358f3c..31ab1c5c7 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -12,7 +12,7 @@
"@notesnook/crypto": "^1.0.0",
"@notesnook/desktop": "file:desktop",
"@rebass/forms": "^4.0.6",
- "@streetwriters/tinymce-plugins": "^1.5.15",
+ "@streetwriters/tinymce-plugins": "^1.5.17",
"@tinymce/tinymce-react": "^3.13.0",
"async-mutex": "^0.3.2",
"axios": "^0.21.4",
diff --git a/apps/web/src/common/vault.js b/apps/web/src/common/vault.js
index 7d97578d7..922a72697 100644
--- a/apps/web/src/common/vault.js
+++ b/apps/web/src/common/vault.js
@@ -82,6 +82,8 @@ class Vault {
case db.vault.ERRORS.vaultLocked:
return Vault.unlockVault();
default:
+ showToast("error", message);
+ console.error(message);
return false;
}
})
diff --git a/apps/web/src/components/editor/header.js b/apps/web/src/components/editor/header.js
index 5fb743bd3..650534fbc 100644
--- a/apps/web/src/components/editor/header.js
+++ b/apps/web/src/components/editor/header.js
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import TitleBox from "./title-box";
-import { useStore } from "../../stores/editor-store";
+import { useStore, store } from "../../stores/editor-store";
import { Input } from "@rebass/forms";
import * as Icon from "../icons";
import { Flex } from "rebass";
@@ -13,8 +13,8 @@ function Header({ readonly }) {
const id = useStore((store) => store.session.id);
const tags = useStore((store) => store.session.tags);
const setTag = useStore((store) => store.setTag);
- const setSession = useStore((store) => store.setSession);
-
+ const setTitle = useStore((store) => store.setTitle);
+ console.log(title, id);
const filterableTags = useMemo(() => {
return db.tags.all.filter((t) => tags.every((tag) => tag !== t.title));
}, [tags]);
@@ -24,12 +24,10 @@ function Header({ readonly }) {
<TitleBox
readonly={readonly}
title={title}
- changeInterval={100}
- setTitle={(title) =>
- setSession((state) => {
- state.session.title = title;
- })
- }
+ setTitle={(title) => {
+ const sessionId = store.get().session.id;
+ setTitle(sessionId, title);
+ }}
/>
{!readonly && id && (
diff --git a/apps/web/src/components/editor/index.js b/apps/web/src/components/editor/index.js
index 1cc3b299b..1f5611bc1 100644
--- a/apps/web/src/components/editor/index.js
+++ b/apps/web/src/components/editor/index.js
@@ -19,9 +19,9 @@ import Toolbar from "./toolbar";
import EditorLoading from "./loading";
import { db } from "../../common/db";
import { AppEventManager, AppEvents } from "../../common/app-events";
-import debounce from "just-debounce-it";
import { FlexScrollContainer } from "../scroll-container";
import { formatDate } from "notes-core/utils/date";
+import { debounce, debounceWithId } from "../../utils/debounce";
const ReactMCE = React.lazy(() => import("./tinymce"));
// const EMPTY_CONTENT = "<p><br></p>";
@@ -40,7 +40,17 @@ function updateWordCount(editor) {
if (!editor.countWords) return;
AppEventManager.publish(AppEvents.UPDATE_WORD_COUNT, editor.countWords());
}
+
+function onEditorChange(noteId, sessionId, content) {
+ if (!content) return;
+
+ editorstore.get().saveSessionContent(noteId, sessionId, {
+ type: "tiny",
+ data: content,
+ });
+}
const debouncedUpdateWordCount = debounce(updateWordCount, 1000);
+const debouncedOnEditorChange = debounceWithId(onEditorChange, 100);
function Editor({ noteId, nonce }) {
const editorRef = useRef();
@@ -109,9 +119,9 @@ function Editor({ noteId, nonce }) {
const disablePreviewMode = useCallback(
async (cancelled) => {
- const { id, content } = editorstore.get().session;
+ const { id, sessionId, content } = editorstore.get().session;
if (!cancelled) {
- await editorstore.get().setSessionContent(content);
+ await editorstore.get().saveSessionContent(id, sessionId, content);
}
await startSession(id, true);
},
@@ -257,13 +267,8 @@ function Editor({ noteId, nonce }) {
onSave={saveSession}
sessionId={sessionId}
onChange={(content, editor) => {
- if (!content) return;
-
- editorstore.get().setSessionContent({
- type: "tiny",
- data: content,
- });
-
+ const { id, sessionId } = editorstore.get().session;
+ debouncedOnEditorChange(sessionId, id, sessionId, content);
debouncedUpdateWordCount(editor);
}}
changeInterval={100}
diff --git a/apps/web/src/components/editor/tinymce.js b/apps/web/src/components/editor/tinymce.js
index bcddd83c1..7712d7cc3 100644
--- a/apps/web/src/components/editor/tinymce.js
+++ b/apps/web/src/components/editor/tinymce.js
@@ -45,7 +45,6 @@ import { useIsUserPremium } from "../../hooks/use-is-user-premium";
import { AppEventManager, AppEvents } from "../../common/app-events";
import { EV, EVENTS } from "notes-core/common";
import { downloadAttachment } from "../../common/attachments";
-import debounce from "just-debounce-it";
const markdownPatterns = [
{ start: "```", replacement: "<pre></pre>" },
@@ -261,18 +260,17 @@ function TinyMCE(props) {
}
}
- const onEditorChange = debounce((e) => {
+ const onEditorChange = async (e) => {
if (
e.type === "execcommand" &&
ignoredCommand.includes(e.command.toLowerCase())
)
return;
- if (!editor.getHTML) return;
- editor.getHTML().then((html) => {
- onChange(html, editor);
- });
- }, changeInterval);
+ if (!editor.getHTML) return;
+ const html = await editor.getHTML();
+ onChange(html, editor);
+ };
function onScrollIntoView(e) {
e.preventDefault();
@@ -306,18 +304,12 @@ function TinyMCE(props) {
}
}
+ editor.onEditorChange = onEditorChange;
editor.on("ScrollIntoView", onScrollIntoView);
editor.on("tap", onTap);
editor.on(changeEvents, onEditorChange);
editor.on("keyup", onKeyUp);
editor.on("paste", onPaste);
- editor.once("remove", () => {
- editor.off("ScrollIntoView", onScrollIntoView);
- editor.off("tap", onTap);
- editor.off(changeEvents, onEditorChange);
- editor.off("keyup", onKeyUp);
- editor.off("paste", onPaste);
- });
},
toolbar_persist: true,
toolbar_sticky: false,
diff --git a/apps/web/src/components/editor/titlebox.js b/apps/web/src/components/editor/titlebox.js
index e91b72e09..3cb95069e 100644
--- a/apps/web/src/components/editor/titlebox.js
+++ b/apps/web/src/components/editor/titlebox.js
@@ -2,9 +2,8 @@ import React, { useCallback, useEffect, useRef, useState } from "react";
import { Text, Flex } from "rebass";
import { Input } from "@rebass/forms";
-var changeTimeout;
function TitleBox(props) {
- const { title, setTitle, changeInterval, shouldFocus, readonly } = props;
+ const { title, setTitle, shouldFocus, readonly } = props;
const [height, setHeight] = useState(0);
const inputRef = useRef();
@@ -32,7 +31,7 @@ function TitleBox(props) {
useEffect(() => {
if (!inputRef.current) return;
- clearTimeout(changeTimeout);
+ console.log("TITLE!", title);
inputRef.current.value = title;
resize();
}, [title, resize]);
@@ -76,11 +75,7 @@ function TitleBox(props) {
}}
onChange={(e) => {
resize();
- clearTimeout(changeTimeout);
- changeTimeout = setTimeout(
- setTitle.bind(this, e.target.value),
- changeInterval
- );
+ setTitle(e.target.value);
}}
/>
</Flex>
@@ -88,6 +83,7 @@ function TitleBox(props) {
}
export default React.memo(TitleBox, (prevProps, nextProps) => {
+ console.log("React.memo", prevProps.title === nextProps.title);
return (
prevProps.shouldFocus === nextProps.shouldFocus &&
prevProps.title === nextProps.title &&
diff --git a/apps/web/src/components/editor/toolbar.js b/apps/web/src/components/editor/toolbar.js
index 562c0b34b..a7c45015e 100644
--- a/apps/web/src/components/editor/toolbar.js
+++ b/apps/web/src/components/editor/toolbar.js
@@ -20,7 +20,7 @@ function Toolbar(props) {
const [isFullscreen, setIsFullscreen] = useState(false);
const isFocusMode = useAppStore((store) => store.isFocusMode);
const toggleFocusMode = useAppStore((store) => store.toggleFocusMode);
- const setSession = useStore((store) => store.setSession);
+ const setTitle = useStore((store) => store.setTitle);
const toggleProperties = useStore((store) => store.toggleProperties);
const clearSession = useStore((store) => store.clearSession);
const title = useStore((store) => store.session.title);
@@ -185,9 +185,7 @@ function Toolbar(props) {
color="text"
onChange={(e) => {
const title = e.target.value;
- setSession((state) => {
- state.session.title = title;
- });
+ setTitle(sessionId, title);
}}
sx={{
p: 0,
diff --git a/apps/web/src/interfaces/fs.js b/apps/web/src/interfaces/fs.js
index c68948c22..42c2431e7 100644
--- a/apps/web/src/interfaces/fs.js
+++ b/apps/web/src/interfaces/fs.js
@@ -257,7 +257,7 @@ async function uploadFile(filename, requestOptions) {
}
)
.catch((e) => {
- throw new Error("Could not complete multi-part upload.", e);
+ throw new S3Error("Could not complete multi-part upload.", e);
});
await fileHandle.addAdditionalData("uploaded", true);
diff --git a/apps/web/src/stores/editor-store.js b/apps/web/src/stores/editor-store.js
index 51e7543ca..864a8192f 100644
--- a/apps/web/src/stores/editor-store.js
+++ b/apps/web/src/stores/editor-store.js
@@ -141,77 +141,64 @@ class EditorStore extends BaseStore {
appStore.setIsEditorOpen(true);
};
- saveSession = (oldSession, content) => {
- return savingMutex.runExclusive(() => {
- const session = this.get().session;
- if (session.readonly) return; // do not allow saving of readonly session
-
- this.setSaveState(0);
- return this._saveFn()({ ...session, content })
- .then(async (id) => {
- let note = db.notes.note(id)?.data;
- if (!note) {
- this.setSaveState(-1);
- return;
- }
-
- /* eslint-disable */
- storeSync: {
- if (oldSession?.tags?.length !== session.tags.length)
- tagStore.refresh();
-
- if (oldSession?.color !== session.color) appStore.refreshNavItems();
-
- if (!oldSession?.context) break storeSync;
-
- const { type, value } = oldSession.context;
- if (type === "topic") await db.notes.move(value, id);
- else if (type === "color") await db.notes.note(id).color(value);
- else if (type === "tag") await db.notes.note(id).tag(value);
-
- // update the note.
- note = db.notes.note(id)?.data;
- }
- /* eslint-enable */
-
- if (!this.get().session.id) {
- noteStore.setSelectedNote(id);
- }
-
- const attachments = db.attachments.ofNote(note.id, "all");
- this.set((state) => {
- state.session.id = note.id;
- state.session.notebooks = note.notebooks;
- state.session.saveState = 1;
- state.session.attachmentsLength = attachments.length;
- });
-
- if (!oldSession) {
- noteStore.refresh();
- attachmentStore.refresh();
- return;
- } else if (attachments?.length !== oldSession.attachmentsLength) {
- attachmentStore.refresh();
- }
-
- if (
- note.headline !== oldSession.headline ||
- note.title !== oldSession.title
- )
- noteStore.refresh();
-
- if (!oldSession.id) {
- hashNavigate(`/notes/${id}/edit`, { replace: true });
- }
- })
- .catch((err) => {
- this.setSaveState(-1);
- console.error(err);
- if (session.locked) {
- hashNavigate(`/notes/${session.id}/unlock`, { replace: true });
- }
- });
- });
+ saveSession = async (sessionId, session) => {
+ const currentSession = this.get().session;
+ if (currentSession.readonly) return; // do not allow saving of readonly session
+
+ this.setSaveState(0);
+
+ try {
+ const id = await this._getSaveFn()({ ...session, id: sessionId });
+ if (currentSession && currentSession.id !== sessionId) return;
+
+ let note = db.notes.note(id)?.data;
+ if (!note) throw new Error("Note not saved.");
+
+ if (currentSession.context) {
+ const { type, value } = currentSession.context;
+ if (type === "topic") await db.notes.move(value, id);
+ else if (type === "color") await db.notes.note(id).color(value);
+ else if (type === "tag") await db.notes.note(id).tag(value);
+ // update the note.
+ note = db.notes.note(id)?.data;
+ }
+
+ const shouldRefreshNotes =
+ currentSession.context ||
+ !sessionId ||
+ note.title !== currentSession.title ||
+ note.headline !== currentSession.headline;
+ if (shouldRefreshNotes) noteStore.refresh();
+
+ const attachments = db.attachments.ofNote(id, "all");
+ if (attachments.length !== currentSession.attachmentsLength) {
+ attachmentStore.refresh();
+ }
+
+ this.set((state) => {
+ for (let key in session) {
+ if (key === "content") continue;
+ state.session[key] = session[key];
+ }
+
+ state.session.notebooks = note.notebooks;
+ state.session.context = null;
+ state.session.id = note.id;
+ state.session.saveState = 1;
+ state.session.attachmentsLength = attachments.length;
+ });
+
+ if (!sessionId) {
+ noteStore.setSelectedNote(id);
+ hashNavigate(`/notes/${id}/edit`, { replace: true });
+ }
+ } catch (err) {
+ this.setSaveState(-1);
+ console.error(err);
+ if (session.locked) {
+ hashNavigate(`/notes/${session.id}/unlock`, { replace: true });
+ }
+ }
};
newSession = async (nonce) => {
@@ -247,15 +234,16 @@ class EditorStore extends BaseStore {
if (shouldNavigate) hashNavigate(`/`, { replace: true });
};
- setSession = (set) => {
- const oldSession = qclone(this.get().session);
- this.set(set);
- return this.saveSession(oldSession);
+ setTitle = (sessionId, title) => {
+ return this.saveSession(sessionId, { title });
+ };
+
+ toggle = (sessionId, name, value) => {
+ return this.saveSession(sessionId, { [name]: value });
};
- setSessionContent = (content) => {
- const session = qclone(this.get().session);
- return this.saveSession(session, content);
+ saveSessionContent = (noteId, sessionId, content) => {
+ return this.saveSession(noteId, { sessionId, content });
};
getSessionContent = async () => {
@@ -298,7 +286,7 @@ class EditorStore extends BaseStore {
* @param {Boolean} isLocked
* @returns {(note: any) => Promise<string>}
*/
- _saveFn = () => {
+ _getSaveFn = () => {
return this.get().session.locked
? db.vault.save.bind(db.vault)
: db.notes.add.bind(db.notes);
diff --git a/apps/web/src/stores/note-store.js b/apps/web/src/stores/note-store.js
index e8e80c7e1..805736c64 100644
--- a/apps/web/src/stores/note-store.js
+++ b/apps/web/src/stores/note-store.js
@@ -154,9 +154,9 @@ class NoteStore extends BaseStore {
* @private
*/
_syncEditor = (noteId, action, value) => {
- const { session, setSession } = editorStore.get();
+ const { session, toggle } = editorStore.get();
if (session.id !== noteId) return false;
- setSession((state) => (state.session[action] = value), true);
+ toggle(session.id, action, value);
return true;
};
}
diff --git a/apps/web/src/utils/debounce.ts b/apps/web/src/utils/debounce.ts
new file mode 100644
index 000000000..c55b5a048
--- /dev/null
+++ b/apps/web/src/utils/debounce.ts
@@ -0,0 +1,54 @@
+// type GenericFunction<TArgs, TReturn> = (...args: TArgs[]) => TReturn;
+
+// export function debounce<TArgs>(fn: GenericFunction<TArgs, unknown>, wait: number) {
+// let timeout: NodeJS.Timeout | null = null;
+// let debounceId: string | null = null;
+
+// var debounceWrapper = function (id: string, ...args: TArgs) {
+// if (!wait) {
+// return fn.apply(this, args);
+// }
+
+// if (id === debounceId) clearTimeout(timeout);
+// debounceId = id;
+
+// timeout = setTimeout(() => {
+// fn(...args);
+// }, wait);
+// };
+
+// return debounceWrapper;
+// }
+
+export function debounce<F extends (...args: any) => any>(
+ func: F,
+ waitFor: number
+) {
+ let timeout: NodeJS.Timeout | null;
+
+ const debounced = (...args: any) => {
+ if (timeout) clearTimeout(timeout);
+ timeout = setTimeout(() => func(...args), waitFor);
+ };
+
+ return debounced as (...args: Parameters<F>) => ReturnType<F>;
+}
+
+export function debounceWithId<F extends (...args: any) => any>(
+ func: F,
+ waitFor: number
+) {
+ var timeout: NodeJS.Timeout | null = null;
+ var debounceId: string | null = null;
+
+ const debounced = (id: string, ...args: any) => {
+ if (timeout && id === debounceId) clearTimeout(timeout);
+ debounceId = id;
+ timeout = setTimeout(() => {
+ console.log(id, debounceId);
+ func(...args);
+ }, waitFor);
+ };
+
+ return debounced as (id: string, ...args: Parameters<F>) => ReturnType<F>;
+}