A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
web: better ux when autosave is off (#6610) (#6849)
01zulfic701baaa2cab
diff --git a/apps/web/__e2e__/editor.test.ts b/apps/web/__e2e__/editor.test.tsindex b5b9e2246..fff0c7056 100644--- a/apps/web/__e2e__/editor.test.ts+++ b/apps/web/__e2e__/editor.test.ts@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { test, expect } from "@playwright/test";import { AppModel } from "./models/app.model";-import { NOTE, TITLE_ONLY_NOTE } from "./utils";+import { getTestId, NOTE, TITLE_ONLY_NOTE } from "./utils";test("focus mode", async ({ page }) => {const app = new AppModel(page);@@ -270,3 +270,103 @@ test("#1468 count words separated by newlines", async ({ page }) => {expect((await notes.editor.getWordCount()) === 10).toBeTruthy();});++test("disable autosave when note crosses MAX_AUTO_SAVEABLE_WORDS", async ({+ page+}) => {+ const app = new AppModel(page);+ await app.goto();+ const notes = await app.goToNotes();+ const content = "a ".repeat(100);++ await notes.createNote({+ title: "many words",+ content+ });++ expect(+ await app.toasts.waitForToast(+ "Auto-save is disabled for large notes. Press Ctrl + S to save."+ )+ ).toBe(true);+ await expect(notes.editor.notSavedIcon).toBeVisible();+});++test("when autosave is disabled, pressing ctrl+s should save the note", async ({+ page+}) => {+ const app = new AppModel(page);+ await app.goto();+ const notes = await app.goToNotes();+ const content = "a ".repeat(100);+ await notes.createNote({+ title: NOTE.title,+ content+ });++ await page.keyboard.press("Control+s");++ await expect(notes.editor.savedIcon).toBeVisible();+});++test("when autosave is disabled, switching to another note should save the note", async ({+ page+}) => {+ const app = new AppModel(page);+ await app.goto();+ const notes = await app.goToNotes();+ const content = "a ".repeat(100);+ const note1 = await notes.createNote({+ title: "Test note 1"+ });+ const note2 = await notes.createNote({+ title: "Test note 2"+ });+ await note1?.openNote();+ await notes.editor.setContent(content);++ await note2?.openNote();++ await note1?.openNote();+ await expect(notes.editor.savedIcon).toBeVisible();+ expect(await notes.editor.getContent("text")).toBe(content.trim());+});++test("when autosave is disabled, creating a new note should save the note", async ({+ page+}) => {+ const app = new AppModel(page);+ await app.goto();+ const notes = await app.goToNotes();+ const content = "a ".repeat(100);+ const note = await notes.createNote({+ title: NOTE.title,+ content+ });++ await notes.newNote();++ await note?.openNote();+ await expect(notes.editor.savedIcon).toBeVisible();+ expect(await notes.editor.getContent("text")).toBe(content.trim());+});++test("when autosave is disabled, closing the note should save it", async ({+ page+}) => {+ const app = new AppModel(page);+ await app.goto();+ const notes = await app.goToNotes();+ const content = "a ".repeat(100);+ const note = await notes.createNote({+ title: "Title",+ content+ });++ const noteTab = await notes.editor.findTab((await note!.getId())!);+ await noteTab?.close();++ await note?.openNote();+ await expect(notes.editor.savedIcon).toBeVisible();+ expect(await notes.editor.getContent("text")).toBe(content.trim());+});diff --git a/apps/web/__e2e__/models/base-item.model.ts b/apps/web/__e2e__/models/base-item.model.tsindex 6f4e9ca8e..919ff0bf8 100644--- a/apps/web/__e2e__/models/base-item.model.ts+++ b/apps/web/__e2e__/models/base-item.model.ts@@ -46,7 +46,7 @@ export class BaseItemModel {}async getId() {- return await this.locator.getAttribute("id");+ return (await this.locator.getAttribute("id"))?.replace("id_", "");}async getTitle() {diff --git a/apps/web/__e2e__/models/editor.model.ts b/apps/web/__e2e__/models/editor.model.tsindex 3ebbee955..3b3ce1d6a 100644--- a/apps/web/__e2e__/models/editor.model.ts+++ b/apps/web/__e2e__/models/editor.model.ts@@ -19,6 +19,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { Locator, Page } from "@playwright/test";import { getTestId } from "../utils";+import { TabItemModel } from "./tab-item.model";+import { iterateList } from "./utils";export class EditorModel {private readonly page: Page;@@ -33,6 +35,9 @@ export class EditorModel {private readonly wordCountText: Locator;private readonly dateEditedText: Locator;private readonly searchButton: Locator;+ private readonly tabsList: Locator;+ readonly savedIcon: Locator;+ readonly notSavedIcon: Locator;constructor(page: Page) {this.page = page;@@ -51,6 +56,9 @@ export class EditorModel {this.wordCountText = page.locator(getTestId("editor-word-count"));this.dateEditedText = page.locator(getTestId("editor-date-edited"));this.searchButton = page.locator(getTestId("Search"));+ this.savedIcon = page.locator(getTestId("editor-save-state-saved"));+ this.notSavedIcon = page.locator(getTestId("editor-save-state-notsaved"));+ this.tabsList = page.locator(getTestId("tabs"));}async waitForLoading(title?: string, content?: string) {@@ -227,4 +235,11 @@ export class EditorModel {.replace(" words", ""));}++ async findTab(id: string) {+ for await (const item of iterateList(this.tabsList.locator(".tab"))) {+ const tabModel = new TabItemModel(item, this.page);+ if ((await tabModel.getId()) === id) return tabModel;+ }+ }}diff --git a/apps/web/__e2e__/models/tab-item.model.ts b/apps/web/__e2e__/models/tab-item.model.tsnew file mode 100644index 000000000..c760f1f17--- /dev/null+++ b/apps/web/__e2e__/models/tab-item.model.ts@@ -0,0 +1,36 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { Locator, Page } from "@playwright/test";+import { getTestId } from "../utils";++export class TabItemModel {+ private readonly closeButton: Locator;+ constructor(private readonly locator: Locator, page: Page) {+ this.closeButton = locator.locator(getTestId("tab-close-button"));+ }++ async getId() {+ const testId = await this.locator.getAttribute("data-test-id");+ return testId?.replace("tab-", "");+ }+ close() {+ return this.closeButton.click();+ }+}diff --git a/apps/web/__e2e__/notes.test.ts b/apps/web/__e2e__/notes.test.tsindex 8d0368df9..8506375e6 100644--- a/apps/web/__e2e__/notes.test.ts+++ b/apps/web/__e2e__/notes.test.ts@@ -20,6 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { test, expect } from "@playwright/test";import { AppModel } from "./models/app.model";import {+ getTestId,groupByOptions,NOTE,orderByOptions,diff --git a/apps/web/src/components/editor/action-bar.tsx b/apps/web/src/components/editor/action-bar.tsxindex 1d4ec53ac..f18e0a08e 100644--- a/apps/web/src/components/editor/action-bar.tsx+++ b/apps/web/src/components/editor/action-bar.tsx@@ -30,6 +30,7 @@ import {Lock,NormalMode,Note,+ NoteRemove,Pin,Properties,Publish,@@ -44,6 +45,7 @@ import {} from "../icons";import { ScrollContainer } from "@notesnook/ui";import {+ SaveState,SessionType,isLockedSession,useEditorStore@@ -281,6 +283,7 @@ function TabStrip() {e.stopPropagation();useEditorStore.getState().newSession();}}+ data-test-id="tabs"><ReorderableListitems={sessions}@@ -302,89 +305,95 @@ function TabStrip() {sessions.splice(to, 0, fromTab);useEditorStore.setState({ sessions });}}- renderItem={({ item: session, index: i }) => (- <Tab- id={session.id}- key={session.id}- title={- session.title ||- ("note" in session ? session.note.title : "Untitled")- }- isTemporary={!!session.preview}- isActive={session.id === activeSessionId}- isPinned={!!session.pinned}- isLocked={isLockedSession(session)}- type={session.type}- onKeepOpen={() =>- useEditorStore- .getState()- .updateSession(- session.id,- [session.type],- (s) => (s.preview = false)- )- }- onFocus={() => {- if (session.id !== activeSessionId) {- useEditorStore.getState().openSession(session.id);+ renderItem={({ item: session, index: i }) => {+ const isUnsaved =+ session.type === "default" &&+ session.saveState === SaveState.NotSaved;+ return (+ <Tab+ id={session.id}+ key={session.id}+ title={+ session.title ||+ ("note" in session ? session.note.title : "Untitled")}- }}- onClose={() =>- useEditorStore.getState().closeSessions(session.id)- }- onCloseAll={() =>- useEditorStore- .getState()- .closeSessions(- ...sessions.filter((s) => !s.pinned).map((s) => s.id)- )- }- onCloseOthers={() =>- useEditorStore- .getState()- .closeSessions(- ...sessions- .filter((s) => s.id !== session.id && !s.pinned)- .map((s) => s.id)- )- }- onCloseToTheRight={() =>- useEditorStore- .getState()- .closeSessions(- ...sessions- .filter((s, index) => index > i && !s.pinned)- .map((s) => s.id)- )- }- onCloseToTheLeft={() =>- useEditorStore- .getState()- .closeSessions(- ...sessions- .filter((s, index) => index < i && !s.pinned)- .map((s) => s.id)+ isUnsaved={isUnsaved}+ isTemporary={!!session.preview}+ isActive={session.id === activeSessionId}+ isPinned={!!session.pinned}+ isLocked={isLockedSession(session)}+ type={session.type}+ onKeepOpen={() =>+ useEditorStore+ .getState()+ .updateSession(+ session.id,+ [session.type],+ (s) => (s.preview = false)+ )+ }+ onFocus={() => {+ if (session.id !== activeSessionId) {+ useEditorStore.getState().openSession(session.id);+ }+ }}+ onClose={() =>+ useEditorStore.getState().closeSessions(session.id)+ }+ onCloseAll={() =>+ useEditorStore+ .getState()+ .closeSessions(+ ...sessions.filter((s) => !s.pinned).map((s) => s.id)+ )+ }+ onCloseOthers={() =>+ useEditorStore+ .getState()+ .closeSessions(+ ...sessions+ .filter((s) => s.id !== session.id && !s.pinned)+ .map((s) => s.id)+ )+ }+ onCloseToTheRight={() =>+ useEditorStore+ .getState()+ .closeSessions(+ ...sessions+ .filter((s, index) => index > i && !s.pinned)+ .map((s) => s.id)+ )+ }+ onCloseToTheLeft={() =>+ useEditorStore+ .getState()+ .closeSessions(+ ...sessions+ .filter((s, index) => index < i && !s.pinned)+ .map((s) => s.id)+ )+ }+ onRevealInList={() =>+ AppEventManager.publish(+ AppEvents.revealItemInList,+ "note" in session ? session.note.id : session.id,+ true)- }- onRevealInList={() =>- AppEventManager.publish(- AppEvents.revealItemInList,- "note" in session ? session.note.id : session.id,- true- )- }- onPin={() => {- useEditorStore.setState((state) => {- // preview tabs can never be pinned.- if (!session.pinned) state.sessions[i].preview = false;- state.sessions[i].pinned = !session.pinned;- state.sessions.sort((a, b) =>- a.pinned === b.pinned ? 0 : a.pinned ? -1 : 1- );- });- }}- />- )}+ }+ onPin={() => {+ useEditorStore.setState((state) => {+ // preview tabs can never be pinned.+ if (!session.pinned) state.sessions[i].preview = false;+ state.sessions[i].pinned = !session.pinned;+ state.sessions.sort((a, b) =>+ a.pinned === b.pinned ? 0 : a.pinned ? -1 : 1+ );+ });+ }}+ />+ );+ }}/></Flex></ScrollContainer>@@ -398,6 +407,7 @@ type TabProps = {isTemporary: boolean;isPinned: boolean;isLocked: boolean;+ isUnsaved: boolean;type: SessionType;onKeepOpen: () => void;onFocus: () => void;@@ -417,6 +427,7 @@ function Tab(props: TabProps) {isTemporary,isPinned,isLocked,+ isUnsaved,type,onKeepOpen,onFocus,@@ -436,6 +447,8 @@ function Tab(props: TabProps) {? Readonly: type === "deleted"? Trash+ : isUnsaved+ ? NoteRemove: Note;const { attributes, listeners, setNodeRef, transform, transition, active } =useSortable({ id });@@ -444,6 +457,7 @@ function Tab(props: TabProps) {<Flexref={setNodeRef}className="tab"+ data-test-id={`tab-${id}`}sx={{borderRadius: "default",cursor: "pointer",@@ -544,7 +558,13 @@ function Tab(props: TabProps) {if (e.button == 0) onFocus();}}>- <Icon size={16} color={isActive ? "accent-selected" : "icon"} />+ <Icon+ data-test-id={`tab-icon${isUnsaved ? "-unsaved" : ""}`}+ size={16}+ color={+ isUnsaved ? "accent-error" : isActive ? "accent-selected" : "icon"+ }+ /><Textvariant="body"sx={{@@ -590,6 +610,7 @@ function Tab(props: TabProps) {}}}className="closeTabButton"+ data-test-id={"tab-close-button"}size={16}/>)}diff --git a/apps/web/src/components/editor/footer.tsx b/apps/web/src/components/editor/footer.tsxindex 7d7675966..aa18c707c 100644--- a/apps/web/src/components/editor/footer.tsx+++ b/apps/web/src/components/editor/footer.tsx@@ -121,6 +121,13 @@ function EditorFooter() {) : null}{SaveStateIcon && (<SaveStateIcon+ data-test-id={`editor-save-state-${+ saveState === SaveState.Saved+ ? "saved"+ : saveState === SaveState.NotSaved+ ? "notsaved"+ : "loading"+ }`}size={13}color={saveState === SaveState.Saveddiff --git a/apps/web/src/components/editor/index.tsx b/apps/web/src/components/editor/index.tsxindex eb7ed7cc9..54f94824b 100644--- a/apps/web/src/components/editor/index.tsx+++ b/apps/web/src/components/editor/index.tsx@@ -71,9 +71,12 @@ import { logger } from "../../utils/logger";import { PanelGroup, Panel, PanelResizeHandle } from "react-resizable-panels";import { NoteLinkingDialog } from "../../dialogs/note-linking-dialog";import { strings } from "@notesnook/intl";+import { onPageVisibilityChanged } from "../../utils/page-visibility";const PDFPreview = React.lazy(() => import("../pdf-preview"));+const autoSaveToast = { show: true, hide: () => {} };+async function saveContent(noteId: string,ignoreEdit: boolean,@@ -439,9 +442,17 @@ export function Editor(props: EditorProps) {readonly: false,focusMode: false};+ const saveSessionContentIfNotSaved = useEditorStore(+ (store) => store.saveSessionContentIfNotSaved+ );+ const setEditorSaveState = useEditorStore((store) => store.setSaveState);useScrollToBlock(session);useEffect(() => {+ if (!autoSaveToast.show) {+ autoSaveToast.hide();+ }+const event = AppEventManager.subscribe(AppEvents.UPDATE_ATTACHMENT_PROGRESS,({ hash, loaded, total }: AttachmentProgress) => {@@ -458,6 +469,15 @@ export function Editor(props: EditorProps) {};}, [id]);+ useEffect(() => {+ const unsub = onPageVisibilityChanged((_, hidden) => {+ if (hidden) {+ saveSessionContentIfNotSaved(id);+ }+ });+ return () => unsub();+ }, []);+return (<EditorChrome {...props}><Tiptap@@ -559,6 +579,25 @@ export function Editor(props: EditorProps) {const link = await NoteLinkingDialog.show({ attributes });return link || undefined;}}+ onAutoSaveDisabled={() => {+ setEditorSaveState(id, SaveState.NotSaved);+ if (autoSaveToast.show === false) return;+ const { hide } = showToast(+ "error",+ "Auto-save is disabled for large notes. Press Ctrl + S to save.",+ [+ {+ text: "Dismiss",+ onClick: () => {+ hide();+ }+ }+ ],+ Infinity+ );+ autoSaveToast.show = false;+ autoSaveToast.hide = hide;+ }}>{headless ? null : (<>diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsxindex 3f1b6d3c1..7aad00088 100644--- a/apps/web/src/components/editor/tiptap.tsx+++ b/apps/web/src/components/editor/tiptap.tsx@@ -55,7 +55,7 @@ import { debounce } from "@notesnook/common";import { ScopedThemeProvider } from "../theme-provider";import { useStore as useThemeStore } from "../../stores/theme-store";import { writeToClipboard } from "../../utils/clipboard";-import { useEditorStore } from "../../stores/editor-store";+import { SaveState, useEditorStore } from "../../stores/editor-store";import { parseInternalLink } from "@notesnook/core";import Skeleton from "react-loading-skeleton";import useMobile from "../../hooks/use-mobile";@@ -63,6 +63,7 @@ import useTablet from "../../hooks/use-tablet";import { TimeFormat } from "@notesnook/core";import { BuyDialog } from "../../dialogs/buy-dialog";import { EDITOR_ZOOM } from "./common";+import { showToast } from "../../utils/toast";export type OnChangeHandler = (content: () => string,@@ -89,6 +90,7 @@ type TipTapProps = {) => Promise<LinkAttributes | undefined>;onAttachFile?: (file: File) => void;onFocus?: () => void;+ onAutoSaveDisabled: () => void;content?: () => string | undefined;readonly?: boolean;nonce?: number;@@ -132,6 +134,7 @@ function TipTap(props: TipTapProps) {onInsertInternalLink,onContentChange,onFocus = () => {},+ onAutoSaveDisabled,content,editorContainer,readonly,@@ -148,6 +151,7 @@ function TipTap(props: TipTapProps) {} = props;const isUserPremium = useIsUserPremium();+ const setEditorSaveState = useEditorStore((store) => store.setSaveState);const autoSave = useRef(true);const { toolbarConfig } = useToolbarConfig();@@ -347,6 +351,9 @@ function TipTap(props: TipTapProps) {(s) => s.editors[id]?.statistics?.words.total,(totalWords) => {autoSave.current = !totalWords || totalWords < MAX_AUTO_SAVEABLE_WORDS;+ if (!autoSave.current) {+ onAutoSaveDisabled();+ }});return () => {@@ -576,7 +583,9 @@ function toIEditor(editor: Editor): IEditor {},{ query: (a) => a.hash === hash, preventUpdate: true }),- startSearch: () => editor.commands.startSearch()+ startSearch: () => editor.commands.startSearch(),+ getContent: () =>+ getHTMLFromFragment(editor.state.doc.content, editor.schema)};}diff --git a/apps/web/src/components/editor/types.ts b/apps/web/src/components/editor/types.tsindex 7ba813cdf..f6bba6473 100644--- a/apps/web/src/components/editor/types.ts+++ b/apps/web/src/components/editor/types.ts@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { Attachment } from "@notesnook/editor";-export const MAX_AUTO_SAVEABLE_WORDS = 100_000;+export const MAX_AUTO_SAVEABLE_WORDS = IS_TESTING ? 100 : 100_000;export type NoteStatistics = {words: {@@ -39,4 +39,5 @@ export interface IEditor {attachFile: (file: Attachment) => void;sendAttachmentProgress: (hash: string, progress: number) => void;startSearch: () => void;+ getContent: () => string;}diff --git a/apps/web/src/components/icons/index.tsx b/apps/web/src/components/icons/index.tsxindex 11afa98bd..20b486974 100644--- a/apps/web/src/components/icons/index.tsx+++ b/apps/web/src/components/icons/index.tsx@@ -218,7 +218,8 @@ import {mdiServerSecurity,mdiOpenInNew,mdiTagOutline,- mdiChatQuestionOutline+ mdiChatQuestionOutline,+ mdiNoteRemoveOutline} from "@mdi/js";import { useTheme } from "@emotion/react";import { Theme } from "@notesnook/theme";@@ -313,6 +314,7 @@ function createIcon(path: string, rotate = false) {export const Plus = createIcon(mdiPlus);export const Note = createIcon(mdiNoteOutline);+export const NoteRemove = createIcon(mdiNoteRemoveOutline);export const Notes = createIcon(mdiNoteMultipleOutline);export const Minus = createIcon(mdiMinus);export const Notebook = createIcon(mdiBookOutline);diff --git a/apps/web/src/stores/editor-store.ts b/apps/web/src/stores/editor-store.tsindex 5434097ed..83ec32238 100644--- a/apps/web/src/stores/editor-store.ts+++ b/apps/web/src/stores/editor-store.ts@@ -49,6 +49,7 @@ import { hashNavigate } from "../navigation";import { AppEventManager, AppEvents } from "../common/app-events";import Vault from "../common/vault";import { Mutex } from "async-mutex";+import { useEditorManager } from "../components/editor/manager";export enum SaveState {NotSaved = -1,@@ -501,6 +502,12 @@ class EditorStore extends BaseStore<EditorStore> {const session = this.get().sessions.find((s) => s.id === id);if (!session) id = undefined;+ const activeSession = this.getActiveSession();++ if (activeSession) {+ this.saveSessionContentIfNotSaved(activeSession.id);+ }+if (id &&!settingStore.get().hideNoteTitle &&@@ -848,7 +855,6 @@ class EditorStore extends BaseStore<EditorStore> {sessionId});}-setDocumentTitle(settingStore.get().hideNoteTitle ? undefined : note.title);@@ -870,6 +876,25 @@ class EditorStore extends BaseStore<EditorStore> {});};+ saveSessionContentIfNotSaved = (sessionId: string) => {+ const sessionSaveState = this.getSession(sessionId, ["default"])?.saveState;+ if (sessionSaveState === SaveState.NotSaved) {+ const editor = useEditorManager.getState().getEditor(sessionId);+ const content = editor?.editor?.getContent();+ this.saveSession(+ sessionId,+ content+ ? {+ content: {+ data: content,+ type: "tiptap"+ }+ }+ : {}+ );+ }+ };+newSession = () => {const state = useEditorStore.getState();const session = state.sessions.find((session) => session.type === "new");@@ -896,6 +921,8 @@ class EditorStore extends BaseStore<EditorStore> {continue;}+ this.saveSessionContentIfNotSaved(session.id);+db.fs().cancel(session.id).catch(console.error);if (state.history.includes(session.id))state.history.splice(state.history.indexOf(session.id), 1);