Skip to content

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

mobile: update tabs

Ammar Ahmed83557401f5d6
diff --git a/apps/mobile/app/hooks/use-actions.tsx b/apps/mobile/app/hooks/use-actions.tsx
index 24cb906bc..4bd18f34b 100644
--- a/apps/mobile/app/hooks/use-actions.tsx
+++ b/apps/mobile/app/hooks/use-actions.tsx
@@ -546,7 +546,9 @@ export const useActions = ({
await db.notes.readonly(!currentReadOnly, item?.id);
useTabStore.getState().forEachNoteTab(item.id, (tab) => {
useTabStore.getState().updateTab(tab.id, {
- readonly: !currentReadOnly
+ session: {
+ readonly: !currentReadOnly
+ }
});
});
Navigation.queueRoutesForUpdate();
diff --git a/apps/mobile/app/hooks/use-app-events.tsx b/apps/mobile/app/hooks/use-app-events.tsx
index 909155b51..80b58c730 100644
--- a/apps/mobile/app/hooks/use-app-events.tsx
+++ b/apps/mobile/app/hooks/use-app-events.tsx
@@ -620,13 +620,15 @@ export const useAppEvents = () => {
EV.subscribe(EVENTS.vaultLocked, async () => {
// Lock all notes in all tabs...
for (const tab of useTabStore.getState().tabs) {
- const noteId = useTabStore.getState().getTab(tab.id)?.noteId;
+ const noteId = useTabStore.getState().getTab(tab.id)?.session?.noteId;
if (!noteId) continue;
const note = await db.notes.note(noteId);
const locked = note && (await db.vaults.itemExists(note));
if (locked) {
useTabStore.getState().updateTab(tab.id, {
- locked: true
+ session: {
+ locked: true
+ }
});
if (
tab.id === useTabStore.getState().currentTab &&
diff --git a/apps/mobile/app/navigation/tabs-holder.js b/apps/mobile/app/navigation/tabs-holder.js
index 78a0d0fd4..158a51688 100644
--- a/apps/mobile/app/navigation/tabs-holder.js
+++ b/apps/mobile/app/navigation/tabs-holder.js
@@ -529,7 +529,9 @@ const onChangeTab = async (event) => {
const locked = note && (await db.vaults.itemExists(note));
if (locked) {
useTabStore.getState().updateTab(tab.id, {
- locked: true
+ session: {
+ locked: true
+ }
});
}
}
diff --git a/apps/mobile/app/screens/editor/index.tsx b/apps/mobile/app/screens/editor/index.tsx
index aaa2e8336..95ce63715 100755
--- a/apps/mobile/app/screens/editor/index.tsx
+++ b/apps/mobile/app/screens/editor/index.tsx
@@ -19,6 +19,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
/* eslint-disable @typescript-eslint/no-var-requires */
+import { i18n } from "@lingui/core";
+import { strings } from "@notesnook/intl";
import React, {
forwardRef,
useCallback,
@@ -46,6 +48,7 @@ import {
eUnlockWithPassword
} from "../../utils/events";
import { openLinkInBrowser } from "../../utils/functions";
+import { tabBarRef } from "../../utils/global-refs";
import EditorOverlay from "./loading";
import { EDITOR_URI } from "./source";
import { EditorProps, useEditorType } from "./tiptap/types";
@@ -58,9 +61,6 @@ import {
openInternalLink,
randId
} from "./tiptap/utils";
-import { tabBarRef } from "../../utils/global-refs";
-import { strings } from "@notesnook/intl";
-import { i18n } from "@lingui/core";
const style: ViewStyle = {
height: "100%",
@@ -203,11 +203,13 @@ const useLockedNoteHandler = () => {
useEffect(() => {
for (const tab of useTabStore.getState().tabs) {
- const noteId = useTabStore.getState().getTab(tab.id)?.noteId;
+ const noteId = useTabStore.getState().getTab(tab.id)?.session?.noteId;
if (!noteId) continue;
- if (tabRef.current && tabRef.current.noteLocked) {
+ if (tabRef.current && tabRef.current.session?.noteLocked) {
useTabStore.getState().updateTab(tabRef.current.id, {
- locked: true
+ session: {
+ locked: true
+ }
});
}
}
@@ -228,16 +230,20 @@ const useLockedNoteHandler = () => {
useEffect(() => {
const unlockWithBiometrics = async () => {
try {
- if (!tabRef.current?.noteLocked || !tabRef.current) return;
-
+ if (!tabRef.current?.session?.noteLocked || !tabRef.current) return;
+ console.log("Trying to unlock with biometrics...");
const credentials = await BiometricService.getCredentials(
"Unlock note",
"Unlock note to open it in editor."
);
- if (credentials && credentials?.password && tabRef.current.noteId) {
+ if (
+ credentials &&
+ credentials?.password &&
+ tabRef.current.session?.noteId
+ ) {
const note = await db.vault.open(
- tabRef.current.noteId,
+ tabRef.current.session?.noteId,
credentials?.password
);
@@ -246,7 +252,9 @@ const useLockedNoteHandler = () => {
});
useTabStore.getState().updateTab(tabRef.current.id, {
- locked: false
+ session: {
+ locked: false
+ }
});
}
} catch (e) {
@@ -261,7 +269,7 @@ const useLockedNoteHandler = () => {
password: string;
biometrics?: boolean;
}) => {
- if (!tabRef.current?.noteId || !tabRef.current) return;
+ if (!tabRef.current?.session?.noteId || !tabRef.current) return;
if (!password || password.trim().length === 0) {
ToastManager.show({
heading: strings.passwordNotEntered(),
@@ -271,7 +279,10 @@ const useLockedNoteHandler = () => {
}
try {
- const note = await db.vault.open(tabRef.current?.noteId, password);
+ const note = await db.vault.open(
+ tabRef.current?.session?.noteId,
+ password
+ );
if (enrollBiometrics && note) {
try {
const unlocked = await db.vault.unlock(password);
@@ -302,7 +313,9 @@ const useLockedNoteHandler = () => {
item: note
});
useTabStore.getState().updateTab(tabRef.current.id, {
- locked: false
+ session: {
+ locked: false
+ }
});
} catch (e) {
ToastManager.show({
@@ -314,7 +327,7 @@ const useLockedNoteHandler = () => {
const unlock = () => {
if (
- (tabRef.current?.locked,
+ (tabRef.current?.session?.locked,
useTabStore.getState().biometryAvailable &&
useTabStore.getState().biometryEnrolled &&
!editorState().movedAway)
@@ -325,7 +338,7 @@ const useLockedNoteHandler = () => {
} else {
if (!editorState().movedAway) {
setTimeout(() => {
- if (tabRef.current && tabRef.current?.locked) {
+ if (tabRef.current && tabRef.current?.session?.locked) {
editorController.current?.commands.focus(tabRef.current?.id);
}
}, 100);
@@ -340,13 +353,13 @@ const useLockedNoteHandler = () => {
}),
eSubscribeEvent(eUnlockWithPassword, onSubmit)
];
- if (tabRef.current?.locked && tabBarRef.current?.page() === 2) {
+ if (tabRef.current?.session?.locked && tabBarRef.current?.page() === 2) {
unlock();
}
return () => {
subs.map((s) => s?.unsubscribe());
};
- }, [tab?.id, tab?.locked]);
+ }, [tab?.id, tab?.session?.locked]);
return null;
};
diff --git a/apps/mobile/app/screens/editor/source.ts b/apps/mobile/app/screens/editor/source.ts
index 3f343edf2..b7c31e88b 100644
--- a/apps/mobile/app/screens/editor/source.ts
+++ b/apps/mobile/app/screens/editor/source.ts
@@ -28,5 +28,5 @@ const EditorMobileSourceUrl =
* The url should be something like this: http://192.168.100.126:3000/index.html
*/
export const EDITOR_URI = __DEV__
- ? EditorMobileSourceUrl
+ ? "http://192.168.100.8:3000/index.html"
: EditorMobileSourceUrl;
diff --git a/apps/mobile/app/screens/editor/tiptap/commands.ts b/apps/mobile/app/screens/editor/tiptap/commands.ts
index 1f9b65911..b7bad77da 100644
--- a/apps/mobile/app/screens/editor/tiptap/commands.ts
+++ b/apps/mobile/app/screens/editor/tiptap/commands.ts
@@ -78,13 +78,13 @@ class Commands {
focus = async (tabId: number) => {
if (!this.ref.current) return;
+
+ const locked = useTabStore.getState().getTab(tabId)?.session?.locked;
if (Platform.OS === "android") {
//this.ref.current?.requestFocus();
setTimeout(async () => {
if (!this.ref) return;
textInput.current?.focus();
-
- const locked = useTabStore.getState().getTab(tabId)?.locked;
await this.doAsync(
locked
? `editorControllers[${tabId}]?.focusPassInput();`
@@ -96,7 +96,12 @@ class Commands {
}, 1);
} else {
await sleep(400);
- await this.doAsync(`editors[${tabId}]?.commands.focus()`, "focus");
+ await this.doAsync(
+ locked
+ ? `editorControllers[${tabId}]?.focusPassInput();`
+ : `editors[${tabId}]?.commands.focus()`,
+ "focus"
+ );
}
};
diff --git a/apps/mobile/app/screens/editor/tiptap/use-editor-events.tsx b/apps/mobile/app/screens/editor/tiptap/use-editor-events.tsx
index 7b9530445..7bc851873 100644
--- a/apps/mobile/app/screens/editor/tiptap/use-editor-events.tsx
+++ b/apps/mobile/app/screens/editor/tiptap/use-editor-events.tsx
@@ -76,7 +76,7 @@ import { openLinkInBrowser } from "../../../utils/functions";
import { tabBarRef } from "../../../utils/global-refs";
import { useDragState } from "../../settings/editor/state";
import { EditorMessage, EditorProps, useEditorType } from "./types";
-import { tabHistory, useTabStore } from "./use-tab-store";
+import { useTabStore } from "./use-tab-store";
import { editorState, openInternalLink } from "./utils";
const publishNote = async () => {
@@ -569,6 +569,21 @@ export const useEditorEvents = (
Clipboard.setString(editorMessage.value as string);
break;
}
+ case EditorEvents.saveScroll: {
+ useTabStore.getState().updateTab(editorMessage.tabId, {
+ session: {
+ ...editorMessage.value
+ }
+ });
+ break;
+ }
+ case EditorEvents.newNote: {
+ eSendEvent(eOnLoadNote, {
+ tabId: editorMessage.tabId,
+ newNote: true
+ });
+ break;
+ }
case EditorEvents.tabsChanged: {
// useTabStore.setState({
// tabs: (editorMessage.value as any)?.tabs,
@@ -605,28 +620,15 @@ export const useEditorEvents = (
editorMessage.value
);
- const { hasContent, isLoading, needsRefresh } = editorMessage.value;
-
eSendEvent(eEditorTabFocused, editorMessage.tabId);
- if (needsRefresh) {
- useTabStore.getState().updateTab(editorMessage.tabId, {
- needsRefresh: false
- });
- }
-
- if (
- (isLoading || !hasContent || needsRefresh) &&
- editorMessage.noteId
- ) {
+ if (editorMessage.noteId) {
if (!useSettingStore.getState().isAppLoading) {
const note = await db.notes.note(editorMessage.noteId);
if (note) {
eSendEvent(eOnLoadNote, {
item: note,
- forced: true,
- tabId: editorMessage.tabId,
- refresh: hasContent && needsRefresh ? needsRefresh : false
+ tabId: editorMessage.tabId
});
}
} else {
@@ -637,7 +639,6 @@ export const useEditorEvents = (
if (note) {
eSendEvent(eOnLoadNote, {
item: note,
- forced: true,
tabId: editorMessage.tabId
});
}
@@ -662,12 +663,12 @@ export const useEditorEvents = (
}
case EditorEvents.goBack: {
- tabHistory.back();
+ useTabStore.getState().goBack();
break;
}
case EditorEvents.goForward: {
- tabHistory.forward();
+ useTabStore.getState().goForward();
break;
}
@@ -684,7 +685,9 @@ export const useEditorEvents = (
useTabStore
.getState()
.updateTab(useTabStore.getState().currentTab, {
- readonly: false
+ session: {
+ readonly: false
+ }
});
setTimeout(() => {
Navigation.queueRoutesForUpdate();
diff --git a/apps/mobile/app/screens/editor/tiptap/use-editor.ts b/apps/mobile/app/screens/editor/tiptap/use-editor.ts
index 44751c514..477f46d4b 100644
--- a/apps/mobile/app/screens/editor/tiptap/use-editor.ts
+++ b/apps/mobile/app/screens/editor/tiptap/use-editor.ts
@@ -68,7 +68,7 @@ import { onNoteCreated } from "../../notes/common";
import Commands from "./commands";
import { SessionHistory } from "./session-history";
import { EditorState, SavePayload } from "./types";
-import { syncTabs, useTabStore } from "./use-tab-store";
+import { TabSessionItem, syncTabs, useTabStore } from "./use-tab-store";
import {
clearAppState,
defaultState,
@@ -102,7 +102,6 @@ export const useEditor = (
isPreview?: boolean;
};
})
- | null
| undefined
>
>({});
@@ -122,7 +121,6 @@ export const useEditor = (
const lastContentChangeTime = useRef<Record<string, number>>({});
const lock = useRef(false);
const currentLoadingNoteId = useRef<string>();
- const loadingState = useRef<string>();
const lastTabFocused = useRef(0);
const blockIdRef = useRef<string>();
const postMessage = useCallback(
@@ -162,7 +160,7 @@ export const useEditor = (
return () => {
event?.unsubscribe();
};
- });
+ }, []);
const overlay = useCallback(
(show: boolean, data = { type: "new" }) => {
@@ -195,7 +193,7 @@ export const useEditor = (
const noteId = useTabStore.getState().getNoteIdForTab(tabId);
if (noteId) {
currentNotes.current?.id && db.fs().cancel(noteId);
- currentNotes.current[noteId] = null;
+ currentNotes.current[noteId] = undefined;
currentContents.current[noteId] = null;
editorSessionHistory.clearSession(noteId);
lastContentChangeTime.current[noteId] = 0;
@@ -203,19 +201,11 @@ export const useEditor = (
}
saveCount.current = 0;
- loadingState.current = undefined;
currentLoadingNoteId.current = undefined;
lock.current = false;
resetContent && postMessage(NativeEvents.title, "", tabId);
-
resetContent && (await commands.clearContent(tabId));
resetContent && (await commands.clearTags(tabId));
- useTabStore.getState().updateTab(tabId, {
- noteId: undefined,
- locked: false,
- noteLocked: false,
- readonly: false
- });
},
[commands, editorSessionHistory, postMessage]
);
@@ -235,6 +225,16 @@ export const useEditor = (
try {
if (id && !(await db.notes?.note(id))) {
await reset(tabId);
+ useTabStore.getState().updateTab(tabId, {
+ session: {
+ noteId: undefined,
+ noteLocked: undefined,
+ locked: undefined,
+ readonly: undefined,
+ scrollTop: undefined,
+ selection: undefined
+ }
+ });
return;
}
let note = id ? await db.notes?.note(id) : undefined;
@@ -307,7 +307,9 @@ export const useEditor = (
}
useTabStore.getState().updateTab(tabId, {
- noteId: id
+ session: {
+ noteId: id
+ }
});
const defaultNotebook = db.settings.getDefaultNotebook();
@@ -439,6 +441,7 @@ export const useEditor = (
tabId?: number;
blockId?: string;
presistTab?: boolean;
+ session?: TabSessionItem;
}) => {
loadNoteMutex.runExclusive(async () => {
if (!event) return;
@@ -457,10 +460,21 @@ export const useEditor = (
) {
state.current.ready = true;
}
-
if (event.newNote && !currentLoadingNoteId.current) {
- const tabId = useTabStore.getState().currentTab;
- await reset(tabId, true, true);
+ let tabId;
+ if (useTabStore.getState().tabs.length === 0) {
+ tabId = useTabStore.getState().newTab();
+ } else {
+ tabId = useTabStore.getState().currentTab;
+ await reset(tabId, true, true);
+ if (
+ event.session?.noteId ||
+ useTabStore.getState().getTab(tabId)?.session?.noteId
+ ) {
+ useTabStore.getState().newTabSession(tabId, {});
+ }
+ }
+
setTimeout(() => {
if (state.current?.ready && !state.current.movedAway)
commands.focus(tabId);
@@ -470,91 +484,63 @@ export const useEditor = (
overlay(false);
return;
}
-
const item = event.item;
currentLoadingNoteId.current = item.id;
- const currentTab = useTabStore
- .getState()
- .getTab(useTabStore.getState().currentTab);
- if (currentTab?.previewTab && item.id !== currentTab.noteId) {
- await commands.setLoading(true, useTabStore.getState().currentTab);
- }
const isLockedNote = await db.vaults.itemExists(
event.item as ItemReference
);
const tabLocked =
isLockedNote && !(event.item as NoteWithContent).content;
- let tabId =
- event.tabId || useTabStore.getState().getTabForNote(event.item.id);
+ let tabId = event.tabId;
if (tabId === undefined) tabId = useTabStore.getState().currentTab;
- const isOpened =
- useTabStore.getState().getTabForNote(event.item.id) === tabId;
+ await commands.setLoading(true, tabId);
- if (!isOpened) {
- await commands.setLoading(true, tabId);
- }
-
- useTabStore.getState().updateTab(tabId, {
- readonly: event.item.readonly || readonly,
- ...(isOpened
- ? {
- noteId: event.item.id
- }
- : {
- locked: tabLocked,
- noteLocked: isLockedNote,
- noteId: event.item.id
- })
- });
-
- useTabStore.getState().focusTab(tabId);
+ const session: Partial<TabSessionItem> = event.session || {
+ readonly: event.item.readonly,
+ locked: tabLocked,
+ noteLocked: isLockedNote,
+ noteId: event.item.id
+ };
- if (lastTabFocused.current !== tabId) {
- useTabStore.getState().focusTab(tabId);
- }
+ const tab = useTabStore.getState().getTab(tabId);
- setTimeout(() => {
- if (blockIdRef.current) {
- commands.scrollIntoViewById(blockIdRef.current);
- blockIdRef.current = undefined;
+ if (useTabStore.getState().tabs.length === 0) {
+ useTabStore.getState().newTab({
+ session: session
+ });
+ console.log("Creating a new tab...");
+ } else {
+ if (
+ event.item.id !== tab?.session?.noteId &&
+ tab?.session?.noteId
+ ) {
+ useTabStore.getState().newTabSession(tabId, session);
+ console.log("Creating a new tab session");
+ } else {
+ console.log("Updating tab session");
+ useTabStore.getState().updateTab(tabId, {
+ session: session
+ });
}
- }, 150);
+ }
if (lastTabFocused.current !== tabId) {
- // if ((await waitForEvent(eEditorTabFocused, 1000)) !== tabId) {
- // console.log("tab id did not match after focus in 1000ms");
- // return;
- // }
- currentLoadingNoteId.current = item.id;
- console.log("Waiting for tab to focus");
+ console.log("Waiting for tab to get focus");
return;
}
- state.current.movedAway = false;
- state.current.currentlyEditing = true;
+ if (tabBarRef.current?.page() === 2) {
+ state.current.movedAway = false;
+ }
+ state.current.currentlyEditing = true;
if (!tabLocked) {
await loadContent(item);
- }
-
- if (
- currentNotes.current[item.id] &&
- loadingState.current &&
- currentContents.current[item.id]?.data &&
- loadingState.current === currentContents.current[item.id]?.data
- ) {
- // If note is already loading, return.
- console.log("Note is already loading...");
- return;
- }
-
- if (!state.current.ready) {
- currentNotes.current[item.id] = item;
- currentLoadingNoteId.current = event.item?.id;
- return;
+ } else {
+ commands.focus(tabId);
}
lastContentChangeTime.current[item.id] = item.dateEdited;
@@ -569,14 +555,18 @@ export const useEditor = (
"Saved",
tabId
);
-
await postMessage(NativeEvents.title, item.title, tabId);
overlay(false);
- loadingState.current = currentContents.current[item.id]?.data;
+
+ console.log("LOADING NOTE....", item.id, item.title);
await postMessage(
NativeEvents.html,
- currentContents.current[item.id]?.data || "",
+ {
+ data: currentContents.current[item.id]?.data || "",
+ scrollTop: tab?.session?.scrollTop,
+ selection: tab?.session?.selection
+ },
tabId,
10000
);
@@ -588,7 +578,6 @@ export const useEditor = (
}
}, 300);
- loadingState.current = undefined;
await commands.setTags(item);
commands.setSettings();
setTimeout(() => {
@@ -652,9 +641,9 @@ export const useEditor = (
: false;
if (note) {
- if (!locked && tab?.noteLocked) {
+ if (!locked && tab?.session?.noteLocked) {
// Note lock removed.
- if (tab.locked) {
+ if (tab.session?.locked) {
if (useTabStore.getState().currentTab === tabId) {
eSendEvent(eOnLoadNote, {
item: note,
@@ -662,17 +651,21 @@ export const useEditor = (
});
} else {
useTabStore.getState().updateTab(tabId, {
- locked: false,
- noteLocked: false
+ session: {
+ locked: false,
+ noteLocked: false
+ }
});
commands.setLoading(true, tabId);
}
}
- } else if (!tab?.noteLocked && locked) {
+ } else if (!tab?.session?.noteLocked && locked) {
// Note lock added.
useTabStore.getState().updateTab(tabId, {
- locked: true,
- noteLocked: true
+ session: {
+ locked: true,
+ noteLocked: true
+ }
});
if (useTabStore.getState().currentTab !== tabId) {
commands.clearContent(tabId);
@@ -693,7 +686,9 @@ export const useEditor = (
}
useTabStore.getState().updateTab(tabId, {
- readonly: note.readonly
+ session: {
+ readonly: note.readonly
+ }
});
}
@@ -706,8 +701,10 @@ export const useEditor = (
const decryptedContent = await db.vault?.decryptContent(data);
if (!decryptedContent) {
useTabStore.getState().updateTab(tabId, {
- locked: true,
- noteLocked: true
+ session: {
+ locked: true,
+ noteLocked: true
+ }
});
if (useTabStore.getState().currentTab !== tabId) {
commands.clearContent(tabId);
@@ -851,7 +848,9 @@ export const useEditor = (
if (!appState) return;
state.current.isRestoringState = true;
state.current.currentlyEditing = true;
- state.current.movedAway = false;
+ if (tabBarRef.current?.page() === 2) {
+ state.current.movedAway = false;
+ }
if (!state.current.editorStateRestored) {
state.current.isRestoringState = true;
diff --git a/apps/mobile/app/screens/editor/tiptap/use-tab-store.ts b/apps/mobile/app/screens/editor/tiptap/use-tab-store.ts
index 22f446f42..48f106093 100644
--- a/apps/mobile/app/screens/editor/tiptap/use-tab-store.ts
+++ b/apps/mobile/app/screens/editor/tiptap/use-tab-store.ts
@@ -16,6 +16,8 @@ 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 { TabSessionHistory } from "@notesnook/common";
+import { MMKVLoader } from "react-native-mmkv-storage";
import create from "zustand";
import { persist, StateStorage } from "zustand/middleware";
import { db } from "../../../common/database";
@@ -23,9 +25,8 @@ import { MMKV } from "../../../common/database/mmkv";
import { eSendEvent } from "../../../services/event-manager";
import { eOnLoadNote } from "../../../utils/events";
import { editorController } from "./utils";
-import { TabHistory } from "@notesnook/common";
-class History {
+class TabHistory {
history: number[];
constructor() {
this.history = [0];
@@ -73,47 +74,46 @@ class History {
}
}
-export type TabItem = {
- id: number;
+export type TabSessionItem = {
+ id: string;
noteId?: string;
- previewTab?: boolean;
- readonly?: boolean;
- locked?: boolean;
+ scrollTop?: number;
+ selection?: { to: number; from: number };
noteLocked?: boolean;
- pinned?: boolean;
- needsRefresh?: boolean;
+ locked?: boolean;
+ readonly?: boolean;
};
-const history = new History();
+const TabSessionStorageKV = new MMKVLoader()
+ .withInstanceID("tab-session-storage")
+ .disableIndexing()
+ .initialize();
-export type TabStore = {
- tabs: TabItem[];
- currentTab: number;
- updateTab: (id: number, options: Omit<Partial<TabItem>, "id">) => void;
- focusPreviewTab: (
- noteId: string,
- options: Omit<Partial<TabItem>, "id">
- ) => void;
- removeTab: (index: number) => void;
- moveTab: (index: number, toIndex: number) => void;
- newTab: (options?: Omit<Partial<TabItem>, "id">) => number;
- focusTab: (id: number) => void;
- getNoteIdForTab: (id: number) => string | undefined;
- getTabForNote: (noteId: string) => number | undefined;
- getTabsForNote: (noteId: string) => TabItem[];
- forEachNoteTab: (noteId: string, cb: (tab: TabItem) => void) => void;
- hasTabForNote: (noteId: string) => boolean;
- focusEmptyTab: () => void;
- getCurrentNoteId: () => string | undefined;
- getTab: (tabId: number) => TabItem | undefined;
- history: number[];
- biometryAvailable?: boolean;
- biometryEnrolled?: boolean;
- tabHistory: Record<number, { back_stack: string[]; forward_stack: string[] }>;
- canGoBack?: boolean;
- canGoForward?: boolean;
- sessionId?: string;
-};
+class TabSessionStorage {
+ static storage: typeof TabSessionStorageKV = TabSessionStorageKV;
+
+ static get(id: string): TabSessionItem | null {
+ return TabSessionStorage.storage.getMap(id);
+ }
+
+ static set(id: string, session: TabSessionItem): void {
+ TabSessionStorage.storage.setMap(id, session);
+ }
+
+ static update(id: string, session: Partial<TabSessionItem>) {
+ const currentSession = TabSessionStorage.get(id);
+ const newSession = {
+ ...currentSession,
+ ...session
+ };
+ TabSessionStorage.set(id, newSession as TabSessionItem);
+ return newSession;
+ }
+
+ static remove(id: string) {
+ TabSessionStorageKV.removeItem(id);
+ }
+}
function getId(id: number, tabs: TabItem[]): number {
const exists = tabs.find((t) => t.id === id);
@@ -147,7 +147,7 @@ export function syncTabs(
globalThis.tabStore?.setState(${JSON.stringify(data)});
`);
}
-export const tabHistory = new TabHistory({
+export const tabSessionHistory = new TabSessionHistory({
get() {
return useTabStore.getState();
},
@@ -156,74 +156,182 @@ export const tabHistory = new TabHistory({
...state
});
},
- getCurrentTab: () => useTabStore.getState().currentTab,
- loadSession: async (sessionId: string) => {
- const session = await editorController?.current?.commands.getSession(
- sessionId
- );
- if (session && session.noteId) {
- const note = await db.notes.note(session.noteId);
- if (note) {
- eSendEvent(eOnLoadNote, {
- item: note,
- tabId: useTabStore.getState().currentTab
- });
- return true;
- }
- return false;
- }
- return false;
- },
- newSession: (sessionId, tabId, noteId) => {
- editorController?.current?.commands?.newSession(sessionId, tabId, noteId);
- },
- clearSessionsForTabId: (tabId: number) => {
- editorController?.current?.commands?.deleteSessionsForTabId(tabId);
- },
- getSession: async (sessionId: string) => {
- return (
- (await editorController?.current?.commands.getSession(sessionId)) ||
- undefined
- );
- },
- commit: () => syncTabs("history")
+ getCurrentTab: () => useTabStore.getState().currentTab
});
+export type TabItem = {
+ id: number;
+ pinned?: boolean;
+ needsRefresh?: boolean;
+ session?: Partial<TabSessionItem>;
+};
+
+const history = new TabHistory();
+
+export type TabStore = {
+ tabs: TabItem[];
+ currentTab: number;
+ updateTab: (id: number, options: Omit<Partial<TabItem>, "id">) => void;
+ focusPreviewTab: (
+ noteId: string,
+ options: Omit<Partial<TabItem>, "id">
+ ) => void;
+ removeTab: (index: number) => void;
+ moveTab: (index: number, toIndex: number) => void;
+ newTab: (options?: Omit<Partial<TabItem>, "id">) => number;
+ focusTab: (id: number) => void;
+ getNoteIdForTab: (id: number) => string | undefined;
+ getTabForNote: (noteId: string) => number | undefined;
+ getTabsForNote: (noteId: string) => TabItem[];
+ forEachNoteTab: (noteId: string, cb: (tab: TabItem) => void) => void;
+ hasTabForNote: (noteId: string) => boolean;
+ focusEmptyTab: () => void;
+ getCurrentNoteId: () => string | undefined;
+ getTab: (tabId: number) => TabItem | undefined;
+ newTabSession: (
+ id: number,
+ options: Omit<Partial<TabSessionItem>, "id">
+ ) => void;
+ history: number[];
+ biometryAvailable?: boolean;
+ biometryEnrolled?: boolean;
+ tabSessionHistory: Record<
+ number,
+ { back_stack: string[]; forward_stack: string[] }
+ >;
+ goBack(): void;
+ goForward(): void;
+ loadSession: (id: string) => Promise<boolean>;
+ canGoBack?: boolean;
+ canGoForward?: boolean;
+ sessionId?: string;
+};
+
export const useTabStore = create<TabStore>(
persist(
(set, get) => ({
- tabs: [
- {
- id: 0
- }
- ],
- tabHistory: {},
+ tabs: [],
+ tabSessionHistory: {},
history: [0],
currentTab: 0,
+ newTabSession: (
+ id: number,
+ options: Omit<Partial<TabSessionItem>, "id">
+ ) => {
+ const sessionId = tabSessionHistory.add();
+ const session = {
+ id: sessionId,
+ ...options
+ };
+ TabSessionStorage.set(sessionId, session);
+ const index = get().tabs.findIndex((t) => t.id === id);
+ if (index == -1) return;
+ const tabs = [...get().tabs];
+ tabs[index] = {
+ ...tabs[index],
+ ...options,
+ session: session
+ } as TabItem;
+
+ set({
+ tabs: tabs
+ });
+ syncTabs();
+ },
updateTab: (id: number, options: Omit<Partial<TabItem>, "id">) => {
if (!options) return;
const index = get().tabs.findIndex((t) => t.id === id);
if (index == -1) return;
const tabs = [...get().tabs];
- if (options.noteId) {
- tabHistory.add(options.noteId);
- }
+ const sessionId =
+ options.session?.id || (tabs[index].session?.id as string);
+ const updatedSession = !options.session
+ ? tabs[index].session
+ : TabSessionStorage.update(sessionId, options.session);
tabs[index] = {
...tabs[index],
- ...options
- };
+ ...options,
+ session: updatedSession
+ } as TabItem;
set({
tabs: tabs
});
- syncTabs("tabs");
+ syncTabs();
+ },
+ goBack: async () => {
+ if (!tabSessionHistory.canGoBack()) return;
+ const id = tabSessionHistory.back() as string;
+ const sessionLoaded = await get().loadSession(id);
+ if (!sessionLoaded) {
+ tabSessionHistory.remove(id);
+ TabSessionStorage.remove(id);
+ if (!tabSessionHistory.canGoBack()) {
+ tabSessionHistory.forward();
+ syncTabs();
+ } else {
+ return get().goBack();
+ }
+ } else {
+ syncTabs();
+ }
+ },
+ goForward: async () => {
+ if (!tabSessionHistory.canGoForward()) return;
+ const id = tabSessionHistory.forward() as string;
+ if (!(await get().loadSession(id))) {
+ tabSessionHistory.remove(id);
+ TabSessionStorage.remove(id);
+ if (!tabSessionHistory.canGoForward()) {
+ tabSessionHistory.back();
+ syncTabs();
+ } else {
+ return get().goForward();
+ }
+ } else {
+ syncTabs();
+ }
+ },
+ loadSession: async (id: string) => {
+ const session = TabSessionStorage.get(id);
+ if (!session) return false;
+
+ const note = session?.noteId
+ ? await db.notes.note(session?.noteId)
+ : undefined;
+
+ if (note) {
+ const isLocked = await db.vaults.itemExists(note);
+ if (isLocked && !session?.noteLocked) {
+ session.locked = true;
+ session.noteLocked = true;
+ }
+ session.readonly = note.readonly;
+ } else if (session.noteId) {
+ console.log("Failed to load session...");
+ return false;
+ }
+
+ get().updateTab(get().currentTab, {
+ session: session
+ });
+ console.log("Loading session", session);
+ eSendEvent(eOnLoadNote, {
+ item: note,
+ newNote: !note,
+ tabId: get().currentTab,
+ session: session
+ });
+
+ return true;
},
focusPreviewTab: (
noteId: string,
options: Omit<Partial<TabItem>, "id" | "noteId">
) => {},
+
removeTab: (id: number) => {
const index = get().tabs.findIndex((t) => t.id === id);
if (index > -1) {
@@ -231,47 +339,46 @@ export const useTabStore = create<TabStore>(
const nextTabs = get().tabs.slice();
nextTabs.splice(index, 1);
history.remove(id);
- tabHistory.clearStackForTab(id);
- set({
- tabs: nextTabs
- });
- syncTabs("tabs");
- setTimeout(() => {
- if (nextTabs.length === 0) {
- set({
- tabs: [{ id: 0 }]
- });
- get().focusTab(0);
- } else {
- get().focusTab(
- isFocused ? history.restoreLast() || 0 : get().currentTab
- );
+
+ const tabSessions = tabSessionHistory.getHistory();
+ tabSessions.back.forEach((id) => TabSessionStorage.remove(id));
+ tabSessions.forward.forEach((id) => TabSessionStorage.remove(id));
+ tabSessionHistory.clearStackForTab(id);
+
+ if (nextTabs.length === 0) {
+ set({
+ tabs: [{ id: 0 }]
+ });
+ get().newTabSession(0, {});
+ get().focusTab(0);
+ } else {
+ set({
+ tabs: nextTabs
+ });
+ if (isFocused) {
+ get().focusTab(history.restoreLast() || 0);
}
- });
+ }
+ syncTabs();
}
},
newTab: (options) => {
const id = getId(get().tabs.length, get().tabs);
- const nextTabs = [
- ...get().tabs,
- {
- id: id,
- ...options
- }
- ];
-
- if (options?.noteId) {
- tabHistory.add(options.noteId);
- }
-
set({
- tabs: nextTabs
+ tabs: [
+ ...get().tabs,
+ {
+ id: id,
+ ...options
+ }
+ ]
});
+ get().newTabSession(id, options?.session || {});
get().focusTab(id);
return id;
},
focusEmptyTab: () => {
- const index = get().tabs.findIndex((t) => !t.noteId);
+ const index = get().tabs.findIndex((t) => !t.session?.noteId);
if (index === -1) return get().newTab();
get().focusTab(get().tabs[index].id);
@@ -282,7 +389,7 @@ export const useTabStore = create<TabStore>(
set({
tabs: tabs
});
- syncTabs("tabs");
+ syncTabs();
},
focusTab: (id: number) => {
@@ -291,37 +398,34 @@ export const useTabStore = create<TabStore>(
currentTab: id
});
set({
- canGoBack: tabHistory.canGoBack(),
- canGoForward: tabHistory.canGoForward(),
- sessionId: tabHistory.getCurrentSession()
+ canGoBack: tabSessionHistory.canGoBack(),
+ canGoForward: tabSessionHistory.canGoForward(),
+ sessionId: tabSessionHistory.currentSessionId()
});
- console.log(
- tabHistory.canGoBack(),
- tabHistory.canGoForward(),
- tabHistory.getCurrentSession()
- );
syncTabs();
},
getNoteIdForTab: (id: number) => {
- return get().tabs.find((t) => t.id === id)?.noteId;
+ return get().tabs.find((t) => t.id === id)?.session?.noteId;
},
hasTabForNote: (noteId: string) => {
return (
- typeof get().tabs.find((t) => t.noteId === noteId)?.id === "number"
+ typeof get().tabs.find((t) => t.session?.noteId === noteId)?.id ===
+ "number"
);
},
getTabForNote: (noteId: string) => {
- return get().tabs.find((t) => t.noteId === noteId)?.id;
+ return get().tabs.find((t) => t.session?.noteId === noteId)?.id;
},
getTabsForNote(noteId: string) {
- return get().tabs.filter((t) => t.noteId === noteId);
+ return get().tabs.filter((t) => t.session?.noteId === noteId);
},
forEachNoteTab: (noteId: string, cb: (tab: TabItem) => void) => {
- const tabs = get().tabs.filter((t) => t.noteId === noteId);
+ const tabs = get().tabs.filter((t) => t.session?.noteId === noteId);
tabs.forEach(cb);
},
getCurrentNoteId: () => {
- return get().tabs.find((t) => t.id === get().currentTab)?.noteId;
+ return get().tabs.find((t) => t.id === get().currentTab)?.session
+ ?.noteId;
},
getTab: (tabId) => {
return get().tabs.find((t) => t.id === tabId);
diff --git a/apps/mobile/app/services/notifications.ts b/apps/mobile/app/services/notifications.ts
index b00f84bef..f9be02007 100644
--- a/apps/mobile/app/services/notifications.ts
+++ b/apps/mobile/app/services/notifications.ts
@@ -43,6 +43,7 @@ import { useRelationStore } from "../stores/use-relation-store";
import { useReminderStore } from "../stores/use-reminder-store";
import { useSettingStore } from "../stores/use-setting-store";
import { useUserStore } from "../stores/use-user-store";
+import { eOnLoadNote } from "../utils/events";
import { tabBarRef } from "../utils/global-refs";
import { convertNoteToText } from "../utils/note-to-text";
import { NotesnookModule } from "../utils/notesnook-module";
@@ -449,19 +450,10 @@ async function loadNote(id: string, jump: boolean) {
})
);
- const isLocked = await db.vaults.itemExists({
- type: "note",
- id: id
- });
-
const tab = useTabStore.getState().getTabForNote(id);
- if (tab !== undefined) {
- useTabStore.getState().focusTab(tab);
- } else {
- useTabStore.getState().updateTab(useTabStore.getState().currentTab, {
- noteId: id,
- readonly: note.readonly,
- noteLocked: isLocked
+ if (useTabStore.getState().currentTab !== tab) {
+ eSendEvent(eOnLoadNote, {
+ note: note
});
}
}
diff --git a/apps/mobile/package-lock.json b/apps/mobile/package-lock.json
index 25dd899e3..c6ed00999 100644
--- a/apps/mobile/package-lock.json
+++ b/apps/mobile/package-lock.json
@@ -3832,6 +3832,7 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-freeze": "^1.0.3",
+ "tinycolor2": "1.6.0",
"zustand": "^4.4.7"
},
"devDependencies": {
@@ -28269,6 +28270,10 @@
"@readme/data-urls": "3.0.0",
"@streetwriters/kysely": "^0.27.4",
"@streetwriters/showdown": "^3.0.1-alpha.2",
+ "@tanstack/react-query": "^4.36.1",
+ "@trpc/client": "^10.45.2",
+ "@trpc/react-query": "^10.45.2",
+ "@trpc/server": "^10.45.2",
"absolutify": "^0.1.0",
"async-mutex": "0.5.0",
"buffer": "^6.0.3",
@@ -33599,40 +33604,6 @@
"https://trpc.io/sponsor"
]
},
- "node_modules/@trpc/client": {
- "version": "10.45.2",
- "resolved": "https://registry.npmjs.org/@trpc/client/-/client-10.45.2.tgz",
- "integrity": "sha512-ykALM5kYWTLn1zYuUOZ2cPWlVfrXhc18HzBDyRhoPYN0jey4iQHEFSEowfnhg1RvYnrAVjNBgHNeSAXjrDbGwg==",
- "funding": [
- "https://trpc.io/sponsor"
- ],
- "peerDependencies": {
- "@trpc/server": "10.45.2"
- }
- },
- "node_modules/@trpc/react-query": {
- "version": "10.45.2",
- "resolved": "https://registry.npmjs.org/@trpc/react-query/-/react-query-10.45.2.tgz",
- "integrity": "sha512-BAqb9bGZIscroradlNx+Cc9522R+idY3BOSf5z0jHUtkxdMbjeGKxSSMxxu7JzoLqSIEC+LVzL3VvF8sdDWaZQ==",
- "funding": [
- "https://trpc.io/sponsor"
- ],
- "peerDependencies": {
- "@tanstack/react-query": "^4.18.0",
- "@trpc/client": "10.45.2",
- "@trpc/server": "10.45.2",
- "react": ">=16.8.0",
- "react-dom": ">=16.8.0"
- }
- },
- "node_modules/@trpc/server": {
- "version": "10.45.2",
- "resolved": "https://registry.npmjs.org/@trpc/server/-/server-10.45.2.tgz",
- "integrity": "sha512-wOrSThNNE4HUnuhJG6PfDRp4L2009KDVxsd+2VYH8ro6o/7/jwYZ8Uu5j+VaW+mOmc8EHerHzGcdbGNQSAUPgg==",
- "funding": [
- "https://trpc.io/sponsor"
- ]
- },
"node_modules/@tsconfig/react-native": {
"version": "3.0.2",
"dev": true,
diff --git a/packages/common/src/utils/editor-sessions.ts b/packages/common/src/utils/editor-sessions.ts
deleted file mode 100644
index d0f40be0c..000000000
--- a/packages/common/src/utils/editor-sessions.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
-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/>.
-*/
-
-export type EditorSessionItem = {
- tabId: number;
- noteId: string;
- scrollTop: number;
- from: number;
- to: number;
- id: string;
-};
-
-export class EditorSessions extends Map<string, EditorSessionItem> {
- timer: NodeJS.Timeout | null = null;
- constructor(
- public options: {
- getGlobalNoteState: () => Record<
- string,
- { top: number; from: number; to: number }
- >;
- }
- ) {
- super();
- const savedSessions = localStorage.getItem("editor-sessions");
- if (savedSessions) {
- const parsed = JSON.parse(savedSessions);
- for (const [key, value] of Object.entries(parsed)) {
- this.set(key, value as EditorSessionItem);
- }
- }
- }
-
- save() {
- if (this.timer) {
- clearTimeout(this.timer);
- }
- this.timer = setTimeout(() => {
- localStorage.setItem(
- "editor-sessions",
- JSON.stringify(Object.fromEntries(this.entries()))
- );
- }, 1000);
- }
-
- get(id: string): EditorSessionItem | undefined {
- return super.get(id);
- }
-
- set(id: string, session: EditorSessionItem): this {
- super.set(id, session);
- this.save();
- return this;
- }
-
- delete(key: string): boolean {
- super.delete(key);
- this.save();
- return true;
- }
-
- newSession(
- sessionId: string,
- tabId: number,
- noteId: string
- ): EditorSessionItem {
- const session: EditorSessionItem = {
- tabId,
- noteId,
- scrollTop: 0 || this.options.getGlobalNoteState()?.[noteId]?.top,
- from: 0 || this.options.getGlobalNoteState()?.[noteId]?.from,
- to: 0 || this.options.getGlobalNoteState()?.[noteId]?.to,
- id: sessionId
- };
- this.set(sessionId, session);
- return session;
- }
-
- updateSession(id: string, session: Partial<EditorSessionItem>): this {
- const existing = this.get(id);
- if (existing) {
- this.set(id, { ...existing, ...session });
- }
- return this;
- }
-
- deleteForTabId(tabId: number) {
- for (const [key, value] of this.entries()) {
- if (value.tabId === tabId) {
- this.delete(key);
- }
- }
- }
-}
diff --git a/packages/common/src/utils/index.ts b/packages/common/src/utils/index.ts
index bb2bf118c..af0513fd3 100644
--- a/packages/common/src/utils/index.ts
+++ b/packages/common/src/utils/index.ts
@@ -27,5 +27,4 @@ export * from "./resolve-items.js";
export * from "./migrate-toolbar.js";
export * from "./export-notes.js";
export * from "./dataurl.js";
-export * from "./tab-history.js";
-export * from "./editor-sessions.js";
+export * from "./tab-session-history.js";
diff --git a/packages/common/src/utils/tab-history.ts b/packages/common/src/utils/tab-session-history.ts
similarity index 55%
rename from packages/common/src/utils/tab-history.ts
rename to packages/common/src/utils/tab-session-history.ts
index dcb6c5403..84e104ae2 100644
--- a/packages/common/src/utils/tab-history.ts
+++ b/packages/common/src/utils/tab-session-history.ts
@@ -17,26 +17,24 @@ 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 { EditorSessionItem } from "./editor-sessions";
+import { getId } from "@notesnook/core";
export type TabState = {
- tabHistory: Record<number, { back_stack: string[]; forward_stack: string[] }>;
+ tabSessionHistory: Record<
+ number,
+ { back_stack: string[]; forward_stack: string[] }
+ >;
canGoBack?: boolean;
canGoForward?: boolean;
sessionId?: string;
};
-export class TabHistory {
+export class TabSessionHistory {
constructor(
public options: {
set: (state: TabState) => void;
get: () => TabState;
getCurrentTab: () => number;
- loadSession: (sessionId: string) => Promise<boolean>;
- newSession: (sessionId: string, tabId: number, noteId: string) => void;
- clearSessionsForTabId: (tabid: number) => void;
- getSession: (sessionId: string) => Promise<EditorSessionItem | undefined>;
- commit: () => void;
}
) {}
@@ -44,16 +42,19 @@ export class TabHistory {
return (
this.options
.get()
- .tabHistory[this.options.getCurrentTab()]?.back_stack.slice() || []
+ .tabSessionHistory[this.options.getCurrentTab()]?.back_stack.slice() ||
+ []
);
}
set back_stack(value: string[]) {
const currentTab = this.options.getCurrentTab();
- const tabHistory = this.options.get().tabHistory;
+ const tabHistory = this.options.get().tabSessionHistory;
+ console.log("back_stack", value);
this.options.set({
canGoBack: value.length > 1,
- tabHistory: {
+ sessionId: this.currentSessionId(),
+ tabSessionHistory: {
...tabHistory,
[currentTab]: {
...(tabHistory[currentTab] || {}),
@@ -61,23 +62,26 @@ export class TabHistory {
}
}
});
- this.options.commit();
}
get forward_stack() {
return (
this.options
.get()
- .tabHistory[this.options.getCurrentTab()]?.forward_stack.slice() || []
+ .tabSessionHistory[
+ this.options.getCurrentTab()
+ ]?.forward_stack.slice() || []
);
}
set forward_stack(value: string[]) {
const currentTab = this.options.getCurrentTab();
- const tabHistory = this.options.get().tabHistory;
+ const tabHistory = this.options.get().tabSessionHistory;
+ console.log("forward_stack", value);
this.options.set({
- canGoForward: value.length > 1,
- tabHistory: {
+ canGoForward: value.length > 0,
+ sessionId: this.currentSessionId(),
+ tabSessionHistory: {
...tabHistory,
[currentTab]: {
...(tabHistory[currentTab] || {}),
@@ -85,42 +89,30 @@ export class TabHistory {
}
}
});
- this.options.commit();
}
- async add(noteId: string) {
- const currentItemId = this.back_stack[this.back_stack.length - 1];
- const currentSession = currentItemId
- ? await this.options.getSession(currentItemId)
- : undefined;
-
- if (currentSession && currentSession.noteId === noteId) return;
- const newSessionId = Math.random()
- .toString(36)
- .replace("0.", "es-" || "");
-
+ add() {
+ const sessionId = getId();
const back_stack = this.back_stack;
- back_stack.push(newSessionId);
- this.options.newSession(newSessionId, this.options.getCurrentTab(), noteId);
-
+ back_stack.push(sessionId);
this.back_stack = back_stack;
this.forward_stack = [];
+ return sessionId;
}
clearStackForTab(tabId: number) {
this.options.set({
- tabHistory: {
- ...this.options.get().tabHistory,
+ tabSessionHistory: {
+ ...this.options.get().tabSessionHistory,
[tabId]: {
back_stack: [],
forward_stack: []
}
}
});
- this.options.clearSessionsForTabId(tabId);
}
- async back(): Promise<string | null> {
+ back(): string | null {
if (!this.canGoBack()) return null;
const back_stack = this.back_stack;
@@ -128,39 +120,46 @@ export class TabHistory {
const current_item = back_stack.pop();
const next_item = back_stack[back_stack.length - 1];
- if (next_item) {
- current_item && forward_stack.push(current_item);
+ current_item && forward_stack.push(current_item);
+
+ this.forward_stack = forward_stack;
+ this.back_stack = back_stack;
+
+ console.log("back", this.forward_stack, this.back_stack);
+
+ return next_item;
+ }
+
+ remove(id: string) {
+ const back_stack = this.back_stack;
+ let index = back_stack.findIndex((item) => item === id);
+ if (index === -1) {
+ const forward_stack = this.forward_stack;
+ index = forward_stack.findIndex((item) => item === id);
+ forward_stack.splice(index, 1);
this.forward_stack = forward_stack;
+ } else {
+ back_stack.splice(index, 1);
this.back_stack = back_stack;
-
- if (await this.options.loadSession(next_item)) {
- return next_item;
- } else if (this.back_stack.length > 1) {
- return this.back();
- }
}
- return null;
}
- async forward(): Promise<string | null> {
+ forward(): string | null {
if (!this.canGoForward()) return null;
const back_stack = this.back_stack;
const forward_stack = this.forward_stack;
- const item = forward_stack.pop();
- if (item) {
- this.forward_stack = forward_stack;
- if (await this.options.loadSession(item)) {
- back_stack.push(item);
- this.back_stack = back_stack;
- return item;
- } else if (this.forward_stack.length > 0) {
- return this.forward();
- }
- }
- return null;
+ const item = forward_stack.pop() as string;
+ this.forward_stack = forward_stack;
+ back_stack.push(item);
+ this.back_stack = back_stack;
+ return item;
+ }
+
+ currentSessionId() {
+ return this.back_stack[this.back_stack.length - 1];
}
getHistory() {
@@ -170,10 +169,6 @@ export class TabHistory {
};
}
- getCurrentSession() {
- return this.back_stack[this.back_stack.length - 1];
- }
-
canGoBack() {
return this.back_stack.length > 1;
}
diff --git a/packages/editor-mobile/package-lock.json b/packages/editor-mobile/package-lock.json
index f2450f9cb..ae8068150 100644
--- a/packages/editor-mobile/package-lock.json
+++ b/packages/editor-mobile/package-lock.json
@@ -25,6 +25,7 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-freeze": "^1.0.3",
+ "tinycolor2": "1.6.0",
"zustand": "^4.4.7"
},
"devDependencies": {
@@ -17638,6 +17639,11 @@
"integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
"dev": true
},
+ "node_modules/tinycolor2": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz",
+ "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw=="
+ },
"node_modules/tmpl": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz",
diff --git a/packages/editor-mobile/src/components/editor.tsx b/packages/editor-mobile/src/components/editor.tsx
index 861a289d2..7c2cd9c36 100644
--- a/packages/editor-mobile/src/components/editor.tsx
+++ b/packages/editor-mobile/src/components/editor.tsx
@@ -22,9 +22,9 @@ import {
getFontById,
getTableOfContents,
TiptapOptions,
+ toBlobURL,
usePermissionHandler
} from "@notesnook/editor";
-import { toBlobURL } from "@notesnook/editor";
import { useThemeColors } from "@notesnook/theme";
import FingerprintIcon from "mdi-react/FingerprintIcon";
import {
@@ -38,13 +38,7 @@ import {
import { useEditorController } from "../hooks/useEditorController";
import { useSafeArea } from "../hooks/useSafeArea";
import { useSettings } from "../hooks/useSettings";
-import {
- NoteState,
- TabItem,
- TabStore,
- useTabContext,
- useTabStore
-} from "../hooks/useTabStore";
+import { TabItem, useTabContext, useTabStore } from "../hooks/useTabStore";
import { postAsyncWithTimeout, Settings } from "../utils";
import { EditorEvents } from "../utils/editor-events";
import { pendingSaveRequests } from "../utils/pending-saves";
@@ -91,43 +85,36 @@ const Tiptap = ({
redo
};
- function restoreNoteSelection(state?: NoteState) {
- try {
- if (!tabRef.current.noteId) return;
- const noteState =
- state || useTabStore.getState().getNoteState(tabRef.current.noteId);
+ logger("info", tabRef.current.id, "rendering");
- if (noteState && (noteState.to || noteState.from)) {
+ const restoreNoteSelection = useCallback(
+ (scrollTop?: number, selection?: { to: number; from: number }) => {
+ if (!tabRef.current.session?.noteId) return;
+ const sel = selection || tabRef.current.session?.selection;
+ if (sel && sel.to && sel.from) {
const size = editors[tabRef.current.id]?.state.doc.content.size || 0;
- if (
- noteState.to > 0 &&
- noteState.to <= size &&
- noteState.from > 0 &&
- noteState.from <= size
- ) {
+ if (sel.to > 0 && sel.to <= size && sel.from > 0 && sel.from <= size) {
editors[tabRef.current.id]?.chain().setTextSelection({
- to: noteState.to,
- from: noteState.from
+ to: sel.to,
+ from: sel.from
});
}
}
-
containerRef.current?.scrollTo({
left: 0,
- top: noteState?.top || 0,
+ top: scrollTop || tabRef.current.session?.scrollTop || 0,
behavior: "auto"
});
- } catch (e) {
- logger("error", (e as Error).message, (e as Error).stack);
- }
- }
+ },
+ []
+ );
usePermissionHandler({
claims: {
premium: settings.premium
},
onPermissionDenied: () => {
- post(EditorEvents.pro, undefined, tabRef.current.id, tab.noteId);
+ post(EditorEvents.pro, undefined, tabRef.current.id, tab.session?.noteId);
}
});
@@ -169,9 +156,9 @@ const Tiptap = ({
});
},
element: getContentDiv(),
- editable: !tab.readonly,
+ editable: !tab.session?.readonly,
editorProps: {
- editable: () => !tab.readonly,
+ editable: () => !tab.session?.readonly,
handlePaste: (view, event) => {
const hasFiles = event.clipboardData?.types?.some((type) =>
type.startsWith("Files")
@@ -214,19 +201,12 @@ const Tiptap = ({
copyToClipboard: (text) => {
globalThis.editorControllers[tab.id]?.copyToClipboard(text);
},
- placeholder: strings.startWritingNote(),
onSelectionUpdate: () => {
- if (tabRef.current.noteId) {
- const noteId = tabRef.current.noteId;
+ if (tabRef.current.session?.noteId) {
clearTimeout(noteStateUpdateTimer.current);
noteStateUpdateTimer.current = setTimeout(() => {
- if (tabRef.current.noteId !== noteId) return;
const { to, from } =
editors[tabRef.current?.id]?.state.selection || {};
- useTabStore.getState().setNoteState(noteId, {
- to,
- from
- });
}, 500);
}
},
@@ -245,7 +225,7 @@ const Tiptap = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
getContentDiv,
- tab.readonly,
+ tab.session?.readonly,
settings.doubleSpacedLines,
settings.corsProxy,
settings.dateFormat,
@@ -255,15 +235,19 @@ const Tiptap = ({
tick
]);
- const update = useCallback(() => {
- setTick((tick) => tick + 1);
- globalThis.editorControllers[tabRef.current.id]?.setTitlePlaceholder(
- strings.noteTitle()
- );
- setTimeout(() => {
- editorControllers[tabRef.current.id]?.setLoading(false);
- }, 300);
- }, []);
+ const update = useCallback(
+ (scrollTop?: number, selection?: { to: number; from: number }) => {
+ setTick((tick) => tick + 1);
+ globalThis.editorControllers[tabRef.current.id]?.setTitlePlaceholder(
+ strings.noteTitle()
+ );
+ setTimeout(() => {
+ editorControllers[tabRef.current.id]?.setLoading(false);
+ restoreNoteSelection(scrollTop, selection);
+ }, 300);
+ },
+ [restoreNoteSelection]
+ );
const controller = useEditorController({
update,
@@ -304,65 +288,39 @@ const Tiptap = ({
});
}
- const updateScrollPosition = (state: TabStore) => {
+ const updateFocusedTab = () => {
if (isFocusedRef.current) return;
- if (state.currentTab === tabRef.current.id) {
- isFocusedRef.current = true;
- const noteState = tabRef.current?.noteId
- ? state.getNoteState(tabRef.current.noteId)
- : undefined;
-
- post(
- EditorEvents.tabFocused,
- {
- hasContent:
- !!globalThis.editorControllers[tabRef.current.id]?.content
- .current,
- isLoading: editorControllers[tabRef.current.id]?.loading,
- needsRefresh: tabRef.current?.needsRefresh
- },
- tabRef.current.id,
- state.getCurrentNoteId()
- );
- editorControllers[tabRef.current.id]?.updateTab();
-
- if (noteState) {
- if (
- containerRef.current &&
- containerRef.current?.scrollHeight < noteState.top
- ) {
- console.log("Container too small to scroll.");
- return;
- }
-
- restoreNoteSelection(noteState);
- } else {
- containerRef.current?.scrollTo({
- left: 0,
- top: 0,
- behavior: "auto"
- });
- }
-
- if (
- !globalThis.editorControllers[tabRef.current.id]?.content.current &&
- tabRef.current.noteId
- ) {
- editorControllers[tabRef.current.id]?.setLoading(true);
- }
- } else {
- isFocusedRef.current = false;
+ isFocusedRef.current = true;
+ const noteId =
+ useTabStore.getState().tabs[useTabStore.getState().currentTab]?.session
+ ?.noteId;
+ post(
+ EditorEvents.tabFocused,
+ undefined,
+ useTabStore.getState().currentTab,
+ noteId
+ );
+ editorControllers[tabRef.current.id]?.updateTab();
+
+ restoreNoteSelection();
+
+ if (
+ !globalThis.editorControllers[tabRef.current.id]?.content.current &&
+ tabRef.current.session?.noteId
+ ) {
+ editorControllers[tabRef.current.id]?.setLoading(true);
}
};
- updateScrollPosition(useTabStore.getState());
+ updateFocusedTab();
const unsub = useTabStore.subscribe((state, prevState) => {
if (state.currentTab !== tabRef.current.id) {
isFocusedRef.current = false;
}
- if (state.currentTab === prevState.currentTab) return;
- updateScrollPosition(state);
+ if (state.currentTab === prevState.currentTab && isFocusedRef.current)
+ return;
+ updateFocusedTab();
logger("info", "updating scroll position");
});
logger("info", tabRef.current.id, "active");
@@ -371,7 +329,7 @@ const Tiptap = ({
logger("info", tabRef.current.id, "inactive");
unsub();
};
- }, [getContentDiv]);
+ }, [getContentDiv, restoreNoteSelection]);
const onClickEmptyArea: React.MouseEventHandler<HTMLDivElement> = useCallback(
(event) => {
@@ -446,9 +404,7 @@ const Tiptap = ({
display: isFocused ? "flex" : "none",
flex: 1,
flexDirection: "column",
- maxWidth: "100vw",
- position: "relative",
- overflow: "hidden"
+ maxWidth: "100vw"
}}
ref={editorRoot}
onDoubleClick={onClickEmptyArea}
@@ -557,83 +513,58 @@ const Tiptap = ({
</button>
</div>
- {controller.loading || tab.locked ? (
- <div
- style={{
- width: "100%",
- height: "100%",
- position: "absolute",
- zIndex: 800,
- backgroundColor: colors.primary.background,
- display: "flex",
- flexDirection: "column",
- alignItems: tab.locked ? "center" : "flex-start",
- justifyContent: tab.locked ? "center" : "flex-start",
- boxSizing: "border-box",
- rowGap: 10,
- marginTop: `${50 + insets.top}px`
- }}
- >
- {tab.locked ? (
- <div
- style={{
- flexDirection: "column",
- paddingLeft: 12,
- paddingRight: 12,
- width: "100%",
- display: "flex",
- justifyContent: "center",
- alignItems: "center",
- gap: 10
- }}
- >
- <p
- style={{
- color: colors.primary.paragraph,
- fontSize: 20,
- fontWeight: "600",
- textAlign: "center",
- padding: "0px 20px",
- marginBottom: 0,
- userSelect: "none"
- }}
- >
- {controller.title}
- </p>
- <p
- style={{
- color: colors.primary.paragraph,
- marginTop: 0,
- marginBottom: 0,
- userSelect: "none"
- }}
- >
- This note is locked.
- </p>
+ <div
+ onScroll={controller.scroll}
+ ref={containerRef}
+ style={{
+ overflowY: controller.loading ? "hidden" : "scroll",
+ height: "100%",
+ display: "block",
+ position: "relative"
+ }}
+ >
+ {settings.noHeader || tab.session?.locked ? null : (
+ <>
+ <Tags settings={settings} loading={controller.loading} />
+ <Title
+ titlePlaceholder={controller.titlePlaceholder}
+ readonly={settings.readonly}
+ controller={controllerRef}
+ title={controller.title}
+ fontFamily={settings.fontFamily}
+ dateFormat={settings.dateFormat}
+ timeFormat={settings.timeFormat}
+ loading={controller.loading}
+ />
- <form
- onSubmit={(e) => {
- e.preventDefault();
- const data = new FormData(e.currentTarget);
- const password = data.get("password");
- const biometrics = data.get("enrollBiometrics");
- post("editor-events:unlock", {
- password,
- biometrics: biometrics === "on" ? true : false
- });
- }}
- style={{
- display: "flex",
- flexDirection: "column",
- rowGap: 10
- }}
- >
- <input
- placeholder="Enter password"
- ref={controller.passwordInputRef}
- name="password"
- type="password"
- required
+ <StatusBar
+ container={containerRef}
+ loading={controller.loading}
+ />
+ </>
+ )}
+
+ {controller.loading || tab.session?.locked ? (
+ <div
+ style={{
+ width: "100%",
+ height: "100%",
+ position: "absolute",
+ zIndex: 999,
+ backgroundColor: colors.primary.background,
+ paddingRight: 12,
+ paddingLeft: 12,
+ display: "flex",
+ flexDirection: "column",
+ alignItems: tab.session?.locked ? "center" : "flex-start",
+ justifyContent: tab.session?.locked ? "center" : "flex-start",
+ boxSizing: "border-box",
+ rowGap: 10
+ }}
+ >
+ {tab.session?.locked ? (
+ <>
+ <p
style={{
color: colors.primary.paragraph,
fontSize: 20,
@@ -806,139 +737,10 @@ const Tiptap = ({
width: "94%",
backgroundColor: colors.secondary.background,
borderRadius: 5,
- border: `1px solid ${colors.primary.border}`,
- paddingLeft: 12,
- paddingRight: 12,
- fontSize: "1em",
- backgroundColor: "transparent",
- caretColor: colors.primary.accent,
- color: colors.primary.paragraph
+ marginTop: 10
}}
/>
- <button
- style={{
- backgroundColor: colors.primary.accent,
- borderRadius: 5,
- boxSizing: "border-box",
- border: "none",
- color: colors.static.white,
- width: 300,
- fontSize: "0.9em",
- height: 45,
- display: "flex",
- alignItems: "center",
- justifyContent: "center"
- }}
- onMouseDown={(e) => {
- if (globalThis.keyboardShown) {
- e.preventDefault();
- }
- }}
- >
- <p
- style={{
- userSelect: "none"
- }}
- >
- Unlock note
- </p>
- </button>
-
- {biometryAvailable && !biometryEnrolled ? (
- <div
- style={{
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- gap: 5
- }}
- >
- <input
- type="checkbox"
- name="enrollBiometrics"
- style={{
- accentColor: colors.primary.accent
- }}
- onMouseDown={(e) => {
- if (globalThis.keyboardShown) {
- e.preventDefault();
- }
- }}
- />
-
- <p
- style={{
- color: colors.primary.paragraph,
- marginTop: 0,
- marginBottom: 0,
- userSelect: "none"
- }}
- >
- Enable biometric unlocking
- </p>
- </div>
- ) : null}
- </form>
-
- {biometryEnrolled && biometryAvailable ? (
- <button
- style={{
- backgroundColor: "transparent",
- borderRadius: 5,
- boxSizing: "border-box",
- border: "none",
- color: colors.primary.accent,
- width: 300,
- fontSize: "0.9em",
- height: 45,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- columnGap: 5,
- userSelect: "none"
- }}
- onMouseDown={(e) => {
- if (globalThis.keyboardShown) {
- e.preventDefault();
- }
- }}
- onClick={() => {
- post("editor-events:unlock-biometrics");
- }}
- >
- <FingerprintIcon />
- <p
- style={{
- userSelect: "none"
- }}
- >
- Unlock with biometrics
- </p>
- </button>
- ) : null}
- </div>
- ) : (
- <>
- <Tags settings={settings} loading={controller.loading} />
- <div
- style={{
- display: "flex",
- flexDirection: "column",
- paddingLeft: 12,
- paddingRight: 12,
- width: "100%",
- gap: 10
- }}
- >
- <div
- style={{
- height: 25,
- width: "100%",
- backgroundColor: colors.secondary.background,
- borderRadius: 5
- }}
- />
<div
style={{
flexDirection: "row",
@@ -1006,46 +808,14 @@ const Tiptap = ({
marginTop: 10
}}
/>
- </div>
- </>
- )}
- </div>
- ) : null}
-
- <div
- onScroll={controller.scroll}
- ref={containerRef}
- style={{
- overflowY: controller.loading ? "hidden" : "scroll",
- height: "100%",
- display: "block",
- position: "relative"
- }}
- >
- {settings.noHeader || tab.locked ? null : (
- <>
- <Tags settings={settings} loading={controller.loading} />
- <Title
- titlePlaceholder={controller.titlePlaceholder}
- readonly={settings.readonly}
- controller={controllerRef}
- title={controller.title}
- fontFamily={settings.fontFamily}
- dateFormat={settings.dateFormat}
- timeFormat={settings.timeFormat}
- loading={controller.loading}
- />
-
- <StatusBar
- container={containerRef}
- loading={controller.loading}
- />
- </>
- )}
+ </>
+ )}
+ </div>
+ ) : null}
<div
style={{
- display: tab.locked ? "none" : "block"
+ display: tab.session?.locked ? "none" : "block"
}}
ref={contentPlaceholderRef}
className="theme-scope-editor"
@@ -1053,11 +823,11 @@ const Tiptap = ({
<div
onClick={(e) => {
- if (tab.locked) return;
+ if (tab.session?.locked) return;
onClickBottomArea();
}}
onMouseDown={(e) => {
- if (tab.locked) return;
+ if (tab.session?.locked) return;
if (globalThis.keyboardShown) {
e.preventDefault();
}
diff --git a/packages/editor-mobile/src/components/header.tsx b/packages/editor-mobile/src/components/header.tsx
index 49ade874a..152517586 100644
--- a/packages/editor-mobile/src/components/header.tsx
+++ b/packages/editor-mobile/src/components/header.tsx
@@ -26,6 +26,8 @@ import DotsHorizontalIcon from "mdi-react/DotsHorizontalIcon";
import DotsVerticalIcon from "mdi-react/DotsVerticalIcon";
import FullscreenIcon from "mdi-react/FullscreenIcon";
import MagnifyIcon from "mdi-react/MagnifyIcon";
+import PlusIcon from "mdi-react/PlusIcon";
+
import PencilLockIcon from "mdi-react/PencilLockIcon";
import TableOfContentsIcon from "mdi-react/TableOfContentsIcon";
import React, { useRef, useState } from "react";
@@ -137,7 +139,7 @@ function Header({
) : (
<Button
onPress={() => {
- post(EditorEvents.back, undefined, tab.id, tab.noteId);
+ post(EditorEvents.back, undefined, tab.id, tab.session?.noteId);
}}
preventDefault={false}
style={{
@@ -174,7 +176,12 @@ function Header({
{settings.deviceMode !== "mobile" && !settings.fullscreen ? (
<Button
onPress={() => {
- post(EditorEvents.fullscreen, undefined, tab.id, tab.noteId);
+ post(
+ EditorEvents.fullscreen,
+ undefined,
+ tab.id,
+ tab.session?.noteId
+ );
}}
preventDefault={false}
style={{
@@ -200,14 +207,12 @@ function Header({
</Button>
) : null}
- {tab.readonly ? (
+ {tab.session?.readonly ? (
<Button
onPress={() => {
post(
"editor-events:disable-readonly-mode",
- useTabStore
- .getState()
- .getNoteIdForTab(useTabStore.getState().currentTab)
+ tab.session?.noteId
);
}}
fwdRef={btnRef}
@@ -297,7 +302,12 @@ function Header({
<Button
onPress={() => {
- post(EditorEvents.showTabs, undefined, tab.id, tab.noteId);
+ post(
+ EditorEvents.showTabs,
+ undefined,
+ tab.id,
+ tab.session?.noteId
+ );
}}
preventDefault={false}
style={{
@@ -341,8 +351,13 @@ function Header({
<Button
fwdRef={btnRef}
onPress={() => {
- if (tab.locked) {
- post(EditorEvents.properties, undefined, tab.id, tab.noteId);
+ if (tab.session?.locked) {
+ post(
+ EditorEvents.properties,
+ undefined,
+ tab.id,
+ tab.session?.noteId
+ );
} else {
setOpen(!isOpen);
}
@@ -361,7 +376,7 @@ function Header({
position: "relative"
}}
>
- {tab.locked ? (
+ {tab.session?.locked ? (
<DotsHorizontalIcon
size={25 * settings.fontScale}
style={{
@@ -399,18 +414,26 @@ function Header({
EditorEvents.toc,
editorControllers[tab.id]?.getTableOfContents(),
tab.id,
- tab.noteId
+ tab.session?.noteId
);
break;
case "search":
editor?.commands.startSearch();
break;
+ case "newNote":
+ post(
+ EditorEvents.newNote,
+ undefined,
+ tab.id,
+ tab.session?.noteId
+ );
+ break;
case "properties":
post(
EditorEvents.properties,
undefined,
tab.id,
- tab.noteId
+ tab.session?.noteId
);
break;
default:
@@ -425,13 +448,18 @@ function Header({
alignItems: "center",
flexDirection: "row",
justifyContent: "center",
- width: "100%",
+ flex: 1,
paddingTop: 5
}}
>
<Button
onPress={() => {
- post(EditorEvents.goBack, undefined, tab.id, tab.noteId);
+ post(
+ EditorEvents.goBack,
+ undefined,
+ tab.id,
+ tab.session?.noteId
+ );
setOpen(false);
}}
style={{
@@ -461,7 +489,12 @@ function Header({
<Button
onPress={() => {
- post(EditorEvents.goForward, undefined, tab.id, tab.noteId);
+ post(
+ EditorEvents.goForward,
+ undefined,
+ tab.id,
+ tab.session?.noteId
+ );
setOpen(false);
}}
style={{
@@ -516,6 +549,27 @@ function Header({
</Button>
</div>
+ <MenuItem
+ value="newNote"
+ style={{
+ display: "flex",
+ gap: 10,
+ alignItems: "center"
+ }}
+ >
+ <PlusIcon
+ size={22 * settings.fontScale}
+ color="var(--nn_primary_icon)"
+ />
+ <span
+ style={{
+ color: "var(--nn_primary_paragraph)"
+ }}
+ >
+ New note
+ </span>
+ </MenuItem>
+
<MenuItem
value="toc"
style={{
diff --git a/packages/editor-mobile/src/components/tags.tsx b/packages/editor-mobile/src/components/tags.tsx
index e436c9303..56399757e 100644
--- a/packages/editor-mobile/src/components/tags.tsx
+++ b/packages/editor-mobile/src/components/tags.tsx
@@ -46,7 +46,7 @@ function Tags(props: { settings: Settings; loading?: boolean }): JSX.Element {
editor.commands.blur();
editorTitles[tab.id]?.current?.blur();
}
- post(EditorEvents.newtag, undefined, tab.id, tab.noteId);
+ post(EditorEvents.newtag, undefined, tab.id, tab.session?.noteId);
};
const fontScale = props.settings?.fontScale || 1;
@@ -127,7 +127,7 @@ function Tags(props: { settings: Settings; loading?: boolean }): JSX.Element {
}}
onClick={(e) => {
e.preventDefault();
- post(EditorEvents.tag, tag, tab.id, tab.noteId);
+ post(EditorEvents.tag, tag, tab.id, tab.session?.noteId);
}}
>
#{tag.alias}
diff --git a/packages/editor-mobile/src/components/tiptap.tsx b/packages/editor-mobile/src/components/tiptap.tsx
index 28bced355..b1f91f210 100644
--- a/packages/editor-mobile/src/components/tiptap.tsx
+++ b/packages/editor-mobile/src/components/tiptap.tsx
@@ -36,7 +36,7 @@ export default function TiptapEditorWrapper(props: {
return (
<>
- {tab.locked ? null : (
+ {tab.session?.locked ? null : (
<EmotionEditorToolbarTheme>
<Toolbar
className="theme-scope-editorToolbar"
diff --git a/packages/editor-mobile/src/components/title.tsx b/packages/editor-mobile/src/components/title.tsx
index 751122c5f..00672a849 100644
--- a/packages/editor-mobile/src/components/title.tsx
+++ b/packages/editor-mobile/src/components/title.tsx
@@ -17,8 +17,7 @@ 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 { getFontById } from "@notesnook/editor";
-import { replaceDateTime } from "@notesnook/editor";
+import { getFontById, replaceDateTime } from "@notesnook/editor";
import React, { RefObject, useCallback, useEffect, useRef } from "react";
import { EditorController } from "../hooks/useEditorController";
import { useTabContext } from "../hooks/useTabStore";
diff --git a/packages/editor-mobile/src/hooks/useEditorController.ts b/packages/editor-mobile/src/hooks/useEditorController.ts
index 6e6604fcf..f2b173735 100644
--- a/packages/editor-mobile/src/hooks/useEditorController.ts
+++ b/packages/editor-mobile/src/hooks/useEditorController.ts
@@ -133,7 +133,10 @@ export function useEditorController({
scrollTo,
scrollTop
}: {
- update: () => void;
+ update: (
+ scrollTop?: number,
+ selection?: { to: number; from: number }
+ ) => void;
getTableOfContents: () => any[];
scrollTo: (top: number) => void;
scrollTop: () => number;
@@ -157,9 +160,9 @@ export function useEditorController({
scroll: null
});
- if (!tabRef.current.noteId && loading) {
+ if (!tabRef.current.session?.noteId && loading) {
setTimeout(() => {
- if (!tabRef.current.noteId && loading) {
+ if (!tabRef.current.session?.noteId && loading) {
setLoading(false);
}
}, 3000);
@@ -174,14 +177,14 @@ export function useEditorController({
EditorEvents.contentchange,
undefined,
tabRef.current.id,
- tabRef.current.noteId
+ tabRef.current.session?.noteId
);
const params = [
{
title
},
tabRef.current.id,
- tabRef.current.noteId,
+ tabRef.current.session?.noteId,
currentSessionId
];
const pendingTitleIds = await pendingSaveRequests.getPendingTitleIds();
@@ -237,7 +240,7 @@ export function useEditorController({
EditorEvents.contentchange,
undefined,
tabRef.current.id,
- tabRef.current.noteId
+ tabRef.current.session?.noteId
);
if (!editor) return;
if (typeof timers.current.change === "number") {
@@ -252,7 +255,7 @@ export function useEditorController({
ignoreEdit: ignoreEdit
},
tabRef.current.id,
- tabRef.current.noteId,
+ tabRef.current.session?.noteId,
currentSessionId
];
@@ -303,14 +306,24 @@ export function useEditorController({
if (timers.current.scroll !== null) clearTimeout(timers.current.scroll);
timers.current.scroll = setTimeout(() => {
if (
- tabRef.current.noteId &&
- tabRef.current.noteId === useTabStore.getState().getCurrentNoteId()
+ tabRef.current.session?.noteId &&
+ tabRef.current.session?.noteId ===
+ useTabStore.getState().getCurrentNoteId()
) {
- useTabStore.getState().setNoteState(tabRef.current.noteId, {
- top: value
- });
+ post(
+ EditorEvents.saveScroll,
+ {
+ scrollTop: value,
+ selection: {
+ to: editors[tabRef.current.id]?.state.selection.to,
+ from: editors[tabRef.current.id]?.state.selection.from
+ }
+ },
+ tabRef.current.id,
+ tabRef.current.session?.noteId
+ );
}
- }, 16);
+ }, 300);
},
[]
);
@@ -321,12 +334,12 @@ export function useEditorController({
}, [update]);
useEffect(() => {
- if (tab.locked) {
+ if (tab.session?.locked) {
htmlContentRef.current = "";
setLoading(true);
onUpdate();
}
- }, [tab.locked, onUpdate]);
+ }, [tab.session?.locked, onUpdate]);
const onMessage = useCallback(
(event: Event & { data?: string }) => {
@@ -342,38 +355,35 @@ export function useEditorController({
const editor = editors[tabRef.current.id];
switch (type) {
case "native:updatehtml": {
- htmlContentRef.current = value;
-
+ htmlContentRef.current = value.data;
if (tabRef.current.id !== useTabStore.getState().currentTab) {
updateTabOnFocus.current = true;
} else {
if (!editor) break;
- const noteState = tabRef.current?.noteId
- ? useTabStore.getState().getNoteState(tabRef.current?.noteId)
- : null;
- const top = scrollTop() || noteState?.top || 0;
editor?.commands.setContent(htmlContentRef.current, false, {
preserveWhitespace: true
});
- if (noteState && editor.isFocused) {
- editor.commands.setTextSelection({
- from: noteState.from,
- to: noteState.to
- });
+ if (value.selection) {
+ editor.commands.setTextSelection(value.selection);
}
- scrollTo?.(top || 0);
+ scrollTo?.(value.scrollTop || 0);
+ setLoading(false);
countWords(0);
}
break;
}
case "native:html":
- htmlContentRef.current = value;
+ if (htmlContentRef.current === value.data) {
+ setLoading(false);
+ break;
+ }
+ htmlContentRef.current = value.data;
logger("info", "LOADING NOTE HTML");
if (!editor) break;
- update();
+ update(value.scrollTop, value.selection);
setTimeout(() => {
countWords(0);
}, 300);
@@ -407,7 +417,7 @@ export function useEditorController({
}
post(type); // Notify that message was delivered successfully.
},
- [update, countWords, setTheme]
+ [update, setTheme, scrollTo, countWords]
);
useEffect(() => {
@@ -422,7 +432,7 @@ export function useEditorController({
EditorEvents.filepicker,
type,
tabRef.current.id,
- tabRef.current.noteId
+ tabRef.current.session?.noteId
);
}, []);
@@ -431,7 +441,7 @@ export function useEditorController({
EditorEvents.download,
attachment,
tabRef.current.id,
- tabRef.current.noteId
+ tabRef.current.session?.noteId
);
}, []);
const previewAttachment = useCallback((attachment: Attachment) => {
@@ -439,11 +449,16 @@ export function useEditorController({
EditorEvents.previewAttachment,
attachment,
tabRef.current.id,
- tabRef.current.noteId
+ tabRef.current.session?.noteId
);
}, []);
const openLink = useCallback((url: string) => {
- post(EditorEvents.link, url, tabRef.current.id, tabRef.current.noteId);
+ post(
+ EditorEvents.link,
+ url,
+ tabRef.current.id,
+ tabRef.current.session?.noteId
+ );
return true;
}, []);
diff --git a/packages/editor-mobile/src/hooks/useTabStore.ts b/packages/editor-mobile/src/hooks/useTabStore.ts
index fa85ed6e1..46a2cf2c3 100644
--- a/packages/editor-mobile/src/hooks/useTabStore.ts
+++ b/packages/editor-mobile/src/hooks/useTabStore.ts
@@ -28,78 +28,33 @@ globalThis.statusBars = {};
export type TabItem = {
id: number;
- noteId?: string;
- /**
- * @deprecated
- */
- previewTab?: boolean;
- readonly?: boolean;
- locked?: boolean;
- noteLocked?: boolean;
+ session?: {
+ noteId?: string;
+ readonly?: boolean;
+ locked?: boolean;
+ noteLocked?: boolean;
+ scrollTop?: number;
+ selection?: { to: number; from: number };
+ };
pinned?: boolean;
needsRefresh?: boolean;
};
-export type NoteState = {
- top: number;
- to: number;
- from: number;
-};
-
export type TabStore = {
tabs: TabItem[];
currentTab: number;
scrollPosition: Record<number, number>;
- noteState: Record<string, NoteState>;
- updateTab: (id: number, options: Omit<Partial<TabItem>, "id">) => void;
- removeTab: (index: number) => void;
- moveTab: (index: number, toIndex: number) => void;
- newTab: (noteId?: string, previewTab?: boolean) => void;
- focusTab: (id: number) => void;
- setScrollPosition: (id: number, position: number) => void;
- getNoteIdForTab: (id: number) => string | undefined;
- getTabForNote: (noteId: string) => number | undefined;
- hasTabForNote: (noteId: string) => boolean;
- focusEmptyTab: () => void;
- focusPreviewTab: (
- noteId: string,
- options: Omit<Partial<TabItem>, "id">
- ) => void;
- getCurrentNoteId: () => string | undefined;
- getTab: (tabId: number) => TabItem | undefined;
- setNoteState: (noteId: string, state: Partial<NoteState>) => void;
biometryAvailable?: boolean;
biometryEnrolled?: boolean;
canGoBack?: boolean;
canGoForward?: boolean;
sessionId?: string;
- getNoteState: (noteId: string) => NoteState | undefined;
+ getCurrentNoteId: () => string | undefined;
};
-function getId(id: number, tabs: TabItem[]): number {
- const exists = tabs.find((t) => t.id === id);
- if (exists) {
- return getId(id + 1, tabs);
- }
- return id;
-}
-
export const useTabStore = create(
persist<TabStore>(
(set, get) => ({
- noteState: {},
- getNoteState: (noteId: string) => {
- const sessionId = get().sessionId;
- const session = sessionId ? global.sessions.get(sessionId) : undefined;
- if (session?.noteId === noteId) {
- return {
- top: session.scrollTop,
- to: session.to,
- from: session.from
- };
- }
- return undefined;
- },
tabs: [
{
id: 0
@@ -107,116 +62,9 @@ export const useTabStore = create(
],
currentTab: 0,
scrollPosition: {},
- setNoteState: (noteId: string, state: Partial<NoteState>) => {
- if (editorControllers[get().currentTab]?.loading) return;
-
- const sessionId = get().sessionId;
- if (sessionId) {
- globalThis.sessions.updateSession(sessionId, {
- from: state.from,
- to: state.to,
- scrollTop: state.top
- });
- }
-
- const noteState = {
- ...get().noteState
- };
- noteState[noteId] = {
- ...get().noteState[noteId],
- ...state
- };
-
- set({
- noteState
- });
- },
- updateTab: (id: number, options: Omit<Partial<TabItem>, "id">) => {
- const index = get().tabs.findIndex((t) => t.id === id);
- if (index == -1) return;
- const tabs = [...get().tabs];
- tabs[index] = {
- ...tabs[index],
- ...options
- };
- set({
- tabs: tabs
- });
- },
- removeTab: (index: number) => {
- const scrollPosition = { ...get().scrollPosition };
- if (scrollPosition[index]) {
- delete scrollPosition[index];
- }
- globalThis.editorControllers[index] = undefined;
- globalThis.editors[index] = null;
-
- set({
- scrollPosition
- });
- },
- focusPreviewTab: (noteId: string, options) => {},
- focusEmptyTab: () => {
- const index = get().tabs.findIndex((t) => !t.noteId);
- if (index == -1) return get().newTab();
- const tabs = [...get().tabs];
- tabs[index] = {
- ...tabs[index]
- };
- set({
- currentTab: tabs[index].id
- });
- },
- newTab: (noteId?: string, previewTab?: boolean) => {
- const id = getId(get().tabs.length, get().tabs);
- const nextTabs = [
- ...get().tabs,
- {
- id: id,
- noteId
- }
- ];
- set({
- tabs: nextTabs,
- currentTab: id
- });
- },
- moveTab: (index: number, toIndex: number) => {
- const tabs = get().tabs.slice();
- tabs.splice(toIndex, 0, tabs.slice(index, 1)[0]);
- set({
- tabs: tabs
- });
- },
- focusTab: (id: number) => {
- set({
- currentTab: id
- });
- },
- setScrollPosition: (id: number, position: number) => {
- set({
- scrollPosition: {
- ...get().scrollPosition,
- [id]: position
- }
- });
- },
- getNoteIdForTab: (id: number) => {
- return get().tabs.find((t) => t.id === id)?.noteId;
- },
- hasTabForNote: (noteId: string) => {
- return (
- typeof get().tabs.find((t) => t.noteId === noteId)?.id === "number"
- );
- },
- getTabForNote: (noteId: string) => {
- return get().tabs.find((t) => t.noteId === noteId)?.id;
- },
getCurrentNoteId: () => {
- return get().tabs.find((t) => t.id === get().currentTab)?.noteId;
- },
- getTab: (tabId) => {
- return get().tabs.find((t) => t.id === tabId);
+ return get().tabs.find((t) => t.id === get().currentTab)?.session
+ ?.noteId;
}
}),
{
diff --git a/packages/editor-mobile/src/utils/editor-events.ts b/packages/editor-mobile/src/utils/editor-events.ts
index 4c0845439..2d036d2b4 100644
--- a/packages/editor-mobile/src/utils/editor-events.ts
+++ b/packages/editor-mobile/src/utils/editor-events.ts
@@ -52,5 +52,7 @@ export const EditorEvents = {
error: "editorError",
dbLogger: "editor-events:dbLogger",
goBack: "editor-events:go-back",
- goForward: "editor-events:go-forward"
+ goForward: "editor-events:go-forward",
+ saveScroll: "editor-events:save-scroll",
+ newNote: "editor-events:new-note"
} as const;
diff --git a/packages/editor-mobile/src/utils/index.ts b/packages/editor-mobile/src/utils/index.ts
index 607fce31d..4d6983fff 100644
--- a/packages/editor-mobile/src/utils/index.ts
+++ b/packages/editor-mobile/src/utils/index.ts
@@ -21,7 +21,7 @@ import { Editor, ToolbarGroupDefinition } from "@notesnook/editor";
import { ThemeDefinition } from "@notesnook/theme";
import { Dispatch, MutableRefObject, RefObject, SetStateAction } from "react";
import { EditorController } from "../hooks/useEditorController";
-import { EditorSessions } from "@notesnook/common";
+
import { EditorEvents } from "./editor-events";
globalThis.sessionId = "notesnook-editor";
@@ -63,7 +63,6 @@ declare global {
};
var readonlyEditor: boolean;
- var sessions: EditorSessions;
var statusBars: Record<
number,
| React.MutableRefObject<{
@@ -300,10 +299,3 @@ export function getTheme() {
}
return undefined;
}
-
-const editorSessions = new EditorSessions({
- getGlobalNoteState: () => {
- return globalThis.tabStore.getState().noteState;
- }
-});
-globalThis.sessions = editorSessions;