Skip to content

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

feat: add more reliable hash based routing for dialogs

thecodrr8f7ab929ba25
diff --git a/apps/web/src/app.js b/apps/web/src/app.js
index 82ebfe4a0..930b4a21e 100644
--- a/apps/web/src/app.js
+++ b/apps/web/src/app.js
@@ -1,9 +1,8 @@
import React, { useEffect, useState } from "react";
import "./app.css";
-import { Flex, Box } from "rebass";
+import { Flex } from "rebass";
import ThemeProvider from "./components/theme-provider";
import { useStore } from "./stores/app-store";
-import { useStore as useEditorStore } from "./stores/editor-store";
import { useStore as useUserStore } from "./stores/user-store";
import { useStore as useNotesStore } from "./stores/note-store";
import Animated from "./components/animated";
@@ -23,7 +22,9 @@ import {
showPasswordChangedNotice,
} from "./components/dialogs/confirm";
import StatusBar from "./components/statusbar";
-import useRoutes from "./utils/useRouter";
+import useRoutes from "./utils/use-routes";
+import useHashRoutes from "./utils/use-hash-routes";
+import hashroutes from "./navigation/hash-routes";
function App() {
const [show, setShow] = useState(true);
@@ -33,12 +34,10 @@ function App() {
const addReminder = useStore((store) => store.addReminder);
const initUser = useUserStore((store) => store.init);
const initNotes = useNotesStore((store) => store.init);
- const openLastSession = useEditorStore((store) => store.openLastSession);
const isEditorOpen = useStore((store) => store.isEditorOpen);
const toggleSideMenu = useStore((store) => store.toggleSideMenu);
const isMobile = useMobile();
const isTablet = useTablet();
- const routeResult = useRoutes(routes);
useEffect(
function initializeApp() {
@@ -80,10 +79,6 @@ function App() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isFocusMode]);
- useEffect(() => {
- openLastSession();
- }, [openLastSession]);
-
useEffect(() => {
if (!isMobile && !isTablet) return;
setShow(!isEditorOpen);
@@ -134,16 +129,15 @@ function App() {
}}
>
{isMobile && <Banner />}
- {routeResult}
+ <Routes />
</Animated.Flex>
<Flex
width={[show ? 0 : "100%", show ? 0 : "100%", "100%"]}
flexDirection="column"
>
- <Editor />
+ <EditorSwitch />
</Flex>
</Flex>
- <Box id="dialogContainer" />
<GlobalMenuWrapper />
</Flex>
<StatusBar />
@@ -152,3 +146,13 @@ function App() {
);
}
export default App;
+
+function Routes() {
+ const routeResult = useRoutes(routes);
+ return routeResult;
+}
+
+function EditorSwitch() {
+ const routeResult = useHashRoutes(hashroutes);
+ return routeResult || <Editor />;
+}
diff --git a/apps/web/src/common/index.js b/apps/web/src/common/index.js
index 09adbb32b..0080c6021 100644
--- a/apps/web/src/common/index.js
+++ b/apps/web/src/common/index.js
@@ -13,6 +13,7 @@ import { Text } from "rebass";
import { showLoadingDialog } from "../components/dialogs/loadingdialog";
import Config from "../utils/config";
import { store as userstore } from "../stores/user-store";
+import { hashNavigate } from "../navigation";
export const db = new Database(StorageInterface, EventSource);
db.host({
@@ -53,9 +54,12 @@ export const SELECTION_OPTIONS_MAP = {
export const CREATE_BUTTON_MAP = {
notes: {
title: "Make a note",
- onClick: () => editorStore.newSession(noteStore.get().context),
+ onClick: () => hashNavigate("/notes/create"),
+ },
+ notebooks: {
+ title: "Create a notebook",
+ onClick: () => hashNavigate("/notebooks/create"),
},
- notebooks: { title: "Create a notebook", onClick: showAddNotebookDialog },
topics: { title: "Add a topic", onClick: showTopicDialog },
};
diff --git a/apps/web/src/components/dialogs/add-notebook-dialog.js b/apps/web/src/components/dialogs/add-notebook-dialog.js
index e043ff02d..6047bf0bd 100644
--- a/apps/web/src/components/dialogs/add-notebook-dialog.js
+++ b/apps/web/src/components/dialogs/add-notebook-dialog.js
@@ -261,7 +261,9 @@ function TopicItem(props) {
);
}
-export function showEditNotebookDialog(notebook) {
+export function showEditNotebookDialog(notebookId) {
+ const notebook = db.notebooks.notebook(notebookId)?.data;
+ if (!notebook) return false;
return showDialog((perform) => (
<AddNotebookDialog
isOpen={true}
@@ -291,13 +293,13 @@ export function showEditNotebookDialog(notebook) {
));
}
-export function showAddNotebookDialog(notebook) {
+export function showAddNotebookDialog() {
return showDialog((perform) => (
<AddNotebookDialog
isOpen={true}
onDone={async (nb) => {
// add the notebook to db
- await store.add({ ...notebook, ...nb });
+ await store.add({ ...nb });
showToast("success", "Notebook added successfully!");
perform(true);
diff --git a/apps/web/src/components/dialogs/dialog.js b/apps/web/src/components/dialogs/dialog.js
index ea10e93bf..985730d98 100644
--- a/apps/web/src/components/dialogs/dialog.js
+++ b/apps/web/src/components/dialogs/dialog.js
@@ -5,7 +5,7 @@ import ThemeProvider from "../theme-provider";
import * as Icon from "../icons";
import Modal from "react-modal";
import { useTheme } from "emotion-theming";
-import { getHashParam, setHashParam } from "../../utils/useHashParam";
+import { hashNavigate } from "../../navigation";
function Dialog(props) {
const theme = useTheme();
@@ -144,26 +144,18 @@ export function showDialog(dialog) {
if (root) {
return new Promise((resolve) => {
const perform = (result) => {
- window.removeEventListener("hashchange", onHashChange);
ReactDOM.unmountComponentAtNode(root);
- setHashParam(undefined, false, false, false);
+ hashNavigate("/");
resolve(result);
};
- window.addEventListener("hashchange", onHashChange);
-
- function onHashChange() {
- if (!getHashParam("dialog")) perform(false);
- }
-
const PropDialog = dialog(perform);
- setHashParam(
- { dialog: PropDialog.type.name.toLowerCase() },
- true,
- true,
- true
- );
ReactDOM.render(<ThemeProvider>{PropDialog}</ThemeProvider>, root);
});
}
return Promise.reject("No element with id 'dialogContainer'");
}
+
+export function closeOpenedDialog() {
+ const root = document.getElementById("dialogContainer");
+ ReactDOM.unmountComponentAtNode(root);
+}
diff --git a/apps/web/src/components/editor/index.js b/apps/web/src/components/editor/index.js
index 2423e06d1..c989f11ea 100644
--- a/apps/web/src/components/editor/index.js
+++ b/apps/web/src/components/editor/index.js
@@ -11,10 +11,6 @@ import { useStore as useAppStore } from "../../stores/app-store";
import { useStore as useUserStore } from "../../stores/user-store";
import Animated from "../animated";
import Header from "./header";
-import { useHashParam } from "../../utils/useHashParam";
-import SplitEditor from "../spliteditor";
-import Unlock from "../unlock";
-import RouteContainer from "../route-container";
import useMobile from "../../utils/use-mobile";
import useTablet from "../../utils/use-tablet";
import { SUBSCRIPTION_STATUS } from "../../common";
@@ -25,7 +21,7 @@ import EditorLoading from "./loading";
const ReactQuill = React.lazy(() => import("./react-quill"));
-function Editor() {
+function Editor(props) {
const sessionState = useStore((store) => store.session.state);
const contentType = useStore((store) => store.session.content?.type);
const setSession = useStore((store) => store.setSession);
@@ -47,8 +43,6 @@ function Editor() {
}, [isTablet, isMobile]);
const quillRef = useRef();
- const [diff] = useHashParam("diff");
- const [unlock] = useHashParam("unlock");
useEffect(() => {
if (contentType !== "delta") return;
@@ -93,15 +87,6 @@ function Editor() {
}
}, [sessionState, quillRef, contentType]);
- if (unlock)
- return (
- <RouteContainer
- onlyBackButton={isMobile}
- route={<Unlock noteId={unlock} />}
- />
- );
-
- if (diff) return <SplitEditor diffId={diff} />;
return (
<Flex
flexDirection="column"
diff --git a/apps/web/src/components/editor/toolbar.js b/apps/web/src/components/editor/toolbar.js
index a06027945..5a06caecd 100644
--- a/apps/web/src/components/editor/toolbar.js
+++ b/apps/web/src/components/editor/toolbar.js
@@ -8,6 +8,7 @@ import { EventManagers } from "../../utils/observablearray";
import Animated from "../animated";
function Toolbar(props) {
+ console.log("TOOLBACR");
const { quill } = props;
const sessionState = useStore((store) => store.session.state);
const sessionId = useStore((store) => store.session.sessionId);
diff --git a/apps/web/src/components/group-header/index.js b/apps/web/src/components/group-header/index.js
index 1c7981783..76b176118 100644
--- a/apps/web/src/components/group-header/index.js
+++ b/apps/web/src/components/group-header/index.js
@@ -78,6 +78,7 @@ function GroupHeader(props) {
style={{
display: isExpanded ? "flex" : "none",
}}
+ justifyContent="center"
sx={{
position: "absolute",
zIndex: 1,
@@ -120,6 +121,7 @@ function IconButton(props) {
":hover": { bg: "hover" },
...sx,
}}
+ alignItems="center"
>
<Text variant="subtitle" fontWeight="normal" sx={textStyle}>
{text}
@@ -197,6 +199,7 @@ function GroupByMenu(props) {
<Flex
key={item.title}
justifyContent="space-between"
+ alignItems="center"
p={1}
px={2}
sx={{ cursor: "pointer", ":hover": { bg: "shade" } }}
diff --git a/apps/web/src/components/navigation-menu/index.js b/apps/web/src/components/navigation-menu/index.js
index 56ef7f07a..caece02de 100644
--- a/apps/web/src/components/navigation-menu/index.js
+++ b/apps/web/src/components/navigation-menu/index.js
@@ -7,7 +7,7 @@ import { useStore as useUserStore } from "../../stores/user-store";
import { useStore as useThemeStore } from "../../stores/theme-store";
import Animated from "../animated";
import NavigationItem from "./navigation-item";
-import { navigate } from "../../navigation";
+import { hashNavigate, navigate } from "../../navigation";
import { toTitleCase } from "../../utils/string";
import { COLORS } from "../../common";
import { showLogInDialog } from "../dialogs/logindialog";
@@ -207,7 +207,7 @@ function NavigationMenu(props) {
<NavigationItem
title="Login"
icon={Icon.Login}
- onClick={showLogInDialog}
+ onClick={() => hashNavigate("/login")}
/>
)}
{bottomRoutes.map((item) => (
diff --git a/apps/web/src/components/note/index.js b/apps/web/src/components/note/index.js
index b0eb96808..f7c983bc6 100644
--- a/apps/web/src/components/note/index.js
+++ b/apps/web/src/components/note/index.js
@@ -11,10 +11,10 @@ import { db, COLORS } from "../../common";
import { useTheme } from "emotion-theming";
import Colors from "../menu/colors";
import { showExportDialog } from "../dialogs/exportdialog";
-import { setHashParam } from "../../utils/useHashParam";
import { showItemDeletedToast } from "../../common/toasts";
import { showUnpinnedToast } from "../../common/toasts";
import { showToast } from "../../utils/toast";
+import { hashNavigate } from "../../navigation";
const pin = async (note) => {
await store.pin(note.id);
@@ -166,9 +166,9 @@ function Note(props) {
bg={color}
onClick={() => {
if (note.conflicted) {
- setHashParam({ diff: note.id });
+ hashNavigate(`/notes/${note.id}/conflict`);
} else {
- setHashParam({ note: note.id });
+ hashNavigate(`/notes/${note.id}/edit`);
}
}}
info={
diff --git a/apps/web/src/components/notebook/index.js b/apps/web/src/components/notebook/index.js
index 11a22476d..863e406cb 100644
--- a/apps/web/src/components/notebook/index.js
+++ b/apps/web/src/components/notebook/index.js
@@ -8,6 +8,7 @@ import { showDeleteConfirmation } from "../dialogs/confirm";
import { showItemDeletedToast, showUnpinnedToast } from "../../common/toasts";
import { db } from "../../common";
import * as Icon from "../icons";
+import { hashNavigate } from "../../navigation";
const pin = async (notebook, index) => {
await store.pin(notebook, index);
@@ -28,9 +29,7 @@ function menuItems(notebook, index) {
},
{
title: "Edit",
- onClick: async () => {
- if (await showEditNotebookDialog(notebook)) store.refresh();
- },
+ onClick: () => hashNavigate(`/notebooks/${notebook.id}/edit`),
},
{
title: "Delete",
diff --git a/apps/web/src/components/reminder-bar/index.js b/apps/web/src/components/reminder-bar/index.js
index 207850813..f951da643 100644
--- a/apps/web/src/components/reminder-bar/index.js
+++ b/apps/web/src/components/reminder-bar/index.js
@@ -24,7 +24,7 @@ function ReminderBar() {
onClick={reminder?.action}
justifyContent="space-between"
>
- <Flex>
+ <Flex alignItems="center">
<reminder.icon size={14} color="primary" sx={{ mr: 1 }} />
<Text variant="subBody" fontSize={10} color="primary">
{reminder.title}
diff --git a/apps/web/src/components/spliteditor/deltatoggle.js b/apps/web/src/components/spliteditor/deltatoggle.js
index fbbbd542e..92fb3774f 100644
--- a/apps/web/src/components/spliteditor/deltatoggle.js
+++ b/apps/web/src/components/spliteditor/deltatoggle.js
@@ -4,7 +4,7 @@ import { timeConverter } from "../../utils/time";
import DeltaTransformer from "quill/core/delta";
import { store as notestore } from "../../stores/note-store";
import { db } from "../../common";
-import { setHashParam } from "../../utils/useHashParam";
+import { hashNavigate } from "../../navigation";
const deltaTransformer = new DeltaTransformer();
@@ -49,7 +49,7 @@ function DeltaToggle(props) {
});
}
notestore.refresh();
- setHashParam({ note: note.id });
+ hashNavigate(`/notes/${note.id}/edit`);
},
[note]
);
diff --git a/apps/web/src/components/spliteditor/index.js b/apps/web/src/components/spliteditor/index.js
index 4b7bfe376..e0715b7e1 100644
--- a/apps/web/src/components/spliteditor/index.js
+++ b/apps/web/src/components/spliteditor/index.js
@@ -5,13 +5,13 @@ import DeltaTransformer from "quill/core/delta";
import DeltaToggle from "./deltatoggle";
import { store as notesStore } from "../../stores/note-store";
import { db } from "../../common";
-import { setHashParam } from "../../utils/useHashParam";
import { useStore as useAppStore } from "../../stores/app-store";
+import { hashNavigate } from "../../navigation";
const deltaTransformer = new DeltaTransformer();
function SplitEditor(props) {
- const { diffId } = props;
+ const { noteId } = props;
const setIsEditorOpen = useAppStore((store) => store.setIsEditorOpen);
const [conflictedNote, setConflictedNote] = useState();
@@ -19,12 +19,12 @@ function SplitEditor(props) {
const [localDelta, setLocalDelta] = useState();
useEffect(() => {
- let note = db.notes.note(diffId);
+ let note = db.notes.note(noteId);
if (!note) {
- setHashParam({ note: 0 });
+ hashNavigate(`/notes/create`);
return;
}
- notesStore.setSelectedNote(diffId);
+ notesStore.setSelectedNote(noteId);
note = note.data;
(async function () {
const delta = await db.content.raw(note.contentId);
@@ -32,7 +32,7 @@ function SplitEditor(props) {
setLocalDelta({ ...delta, conflicted: false });
setRemoteDelta(delta.conflicted);
})();
- }, [diffId]);
+ }, [noteId]);
useEffect(() => {
setIsEditorOpen(true);
diff --git a/apps/web/src/index.js b/apps/web/src/index.js
index 2dc8d34a2..8387768b2 100644
--- a/apps/web/src/index.js
+++ b/apps/web/src/index.js
@@ -8,8 +8,9 @@ import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import Modal from "react-modal";
-import rootroutes from "./navigation/rootRoutes";
-import useRoutes from "./utils/useRouter";
+import App from "./App";
+import { MotionConfig, AnimationFeature, GesturesFeature } from "framer-motion";
+import Splash from "./views/splash";
// Sentry.init({
// dsn:
@@ -27,14 +28,24 @@ import useRoutes from "./utils/useRouter";
// });
Modal.setAppElement("#root");
-ReactDOM.render(<Root />, document.getElementById("root"), () => {});
+ReactDOM.render(
+ <MotionConfig features={[AnimationFeature, GesturesFeature]}>
+ <Splash
+ onLoadingFinished={() => {
+ ReactDOM.render(
+ <MotionConfig features={[AnimationFeature, GesturesFeature]}>
+ <App />
+ </MotionConfig>,
+ document.getElementById("root")
+ );
+ }}
+ />
+ </MotionConfig>,
+ document.getElementById("root"),
+ () => {}
+);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.register();
-
-function Root() {
- const routeResult = useRoutes(rootroutes, { fallbackRoute: "/" });
- return routeResult;
-}
diff --git a/apps/web/src/navigation/hash-routes.js b/apps/web/src/navigation/hash-routes.js
new file mode 100644
index 000000000..87bb29aee
--- /dev/null
+++ b/apps/web/src/navigation/hash-routes.js
@@ -0,0 +1,48 @@
+import React from "react";
+import {
+ showAddNotebookDialog,
+ showEditNotebookDialog,
+} from "../components/dialogs/addnotebookdialog";
+import { closeOpenedDialog } from "../components/dialogs/dialog";
+import { showLogInDialog } from "../components/dialogs/logindialog";
+import Editor from "../components/editor";
+import RouteContainer from "../components/route-container";
+import SplitEditor from "../components/spliteditor";
+import Unlock from "../components/unlock";
+import { store as editorStore } from "../stores/editor-store";
+import { store as noteStore } from "../stores/note-store";
+import { isMobile } from "../utils/dimensions";
+
+const hashroutes = {
+ "/": () => {
+ closeOpenedDialog();
+ },
+ "/notebooks/create": () => {
+ showAddNotebookDialog();
+ },
+ "/notebooks/:notebookId/edit": ({ notebookId }) => {
+ showEditNotebookDialog(notebookId);
+ },
+ "/notes/:noteId/edit": ({ noteId }) => {
+ editorStore.openSession(noteId);
+ },
+ "/notes/:noteId/unlock": ({ noteId }) => {
+ return (
+ <RouteContainer
+ onlyBackButton={isMobile()}
+ route={<Unlock noteId={noteId} />}
+ />
+ );
+ },
+ "/notes/:noteId/conflict": ({ noteId }) => {
+ return <SplitEditor noteId={noteId} />;
+ },
+ "/notes/create": () => {
+ editorStore.newSession(noteStore.get().context);
+ },
+ "/login": () => {
+ showLogInDialog();
+ },
+};
+
+export default hashroutes;
diff --git a/apps/web/src/navigation/index.js b/apps/web/src/navigation/index.js
index b52c80f2f..eb11520bb 100644
--- a/apps/web/src/navigation/index.js
+++ b/apps/web/src/navigation/index.js
@@ -23,6 +23,30 @@ export function navigate(url, replaceOrQuery, replace) {
dispatchEvent(new PopStateEvent("popstate", null));
}
+export function hashNavigate(url, replace, notify = true) {
+ window.history[`${replace ? "replace" : "push"}State`](null, null, `#${url}`);
+ if (notify) dispatchEvent(new HashChangeEvent("hashchange"));
+ // if (typeof url !== "string") {
+ // throw new Error(`"url" must be a string, was provided a(n) ${typeof url}`);
+ // }
+ // if (Array.isArray(replaceOrQuery)) {
+ // throw new Error(
+ // '"replaceOrQuery" must be boolean, object, or URLSearchParams'
+ // );
+ // }
+
+ // if (replaceOrQuery !== null && typeof replaceOrQuery === "object") {
+ // url += "?" + new URLSearchParams(replaceOrQuery).toString();
+ // } else if (replace === undefined && replaceOrQuery !== undefined) {
+ // replace = replaceOrQuery;
+ // } else if (replace === undefined && replaceOrQuery === undefined) {
+ // replace = false;
+ // }
+
+ // window.history[`${replace ? "replace" : "push"}State`](null, null, url);
+ // dispatchEvent(new PopStateEvent("popstate", null));
+}
+
export function useQueryParams(
parseFn = parseQuery
//serializeFn = serializeQuery
diff --git a/apps/web/src/navigation/rootRoutes.js b/apps/web/src/navigation/rootRoutes.js
deleted file mode 100644
index 33a13b251..000000000
--- a/apps/web/src/navigation/rootRoutes.js
+++ /dev/null
@@ -1,28 +0,0 @@
-import React from "react";
-import ReactDOM from "react-dom";
-import App from "../App";
-import { MotionConfig, AnimationFeature, GesturesFeature } from "framer-motion";
-import Splash from "../views/splash";
-import AccountRecovery from "../views/recovery";
-import EmailConfirmed from "../views/emailconfirmed";
-
-const rootroutes = {
- "/": () => (
- <MotionConfig features={[AnimationFeature, GesturesFeature]}>
- <Splash
- onLoadingFinished={() => {
- ReactDOM.render(
- <MotionConfig features={[AnimationFeature, GesturesFeature]}>
- <App />
- </MotionConfig>,
- document.getElementById("root")
- );
- }}
- />
- </MotionConfig>
- ),
- "/accountRecovery": () => <AccountRecovery />,
- "/emailConfirmed": () => <EmailConfirmed />,
-};
-
-export default rootroutes;
diff --git a/apps/web/src/navigation/rootroutes.js b/apps/web/src/navigation/rootroutes.js
new file mode 100644
index 000000000..b7fb7ddab
--- /dev/null
+++ b/apps/web/src/navigation/rootroutes.js
@@ -0,0 +1,10 @@
+import React from "react";
+import AccountRecovery from "../views/recovery";
+import EmailConfirmed from "../views/emailconfirmed";
+
+const rootroutes = {
+ "/accountRecovery": () => <AccountRecovery />,
+ "/emailConfirmed": () => <EmailConfirmed />,
+};
+
+export default rootroutes;
diff --git a/apps/web/src/stores/app-store.js b/apps/web/src/stores/app-store.js
index df3169caf..21ff1cdea 100644
--- a/apps/web/src/stores/app-store.js
+++ b/apps/web/src/stores/app-store.js
@@ -27,7 +27,6 @@ class AppStore extends BaseStore {
notebookStore.refresh();
trashStore.refresh();
tagStore.refresh();
- editorStore.openLastSession();
this.refreshColors();
this.refreshMenuPins();
};
diff --git a/apps/web/src/stores/editor-store.js b/apps/web/src/stores/editor-store.js
index 4ee917a19..67d57ecc4 100644
--- a/apps/web/src/stores/editor-store.js
+++ b/apps/web/src/stores/editor-store.js
@@ -4,12 +4,16 @@ import { store as appStore } from "./app-store";
import { store as tagStore } from "./tag-store";
import { db } from "../common";
import BaseStore from ".";
-import { isMobile, isTablet } from "../utils/dimensions";
-import { getHashParam, setHashParam } from "../utils/useHashParam";
import { qclone } from "qclone";
import { EV } from "notes-core/common";
+import { hashNavigate } from "../navigation";
-const SESSION_STATES = { stale: "stale", new: "new", locked: "locked" };
+const SESSION_STATES = {
+ stale: "stale",
+ new: "new",
+ locked: "locked",
+ unlocked: "unlocked",
+};
const DEFAULT_SESSION = {
notebooks: undefined,
state: undefined,
@@ -34,59 +38,39 @@ class EditorStore extends BaseStore {
arePropertiesVisible = false;
init = () => {
- window.addEventListener("hashchange", async () => {
- const note = getHashParam("note");
-
- if (this.get().session.id === note) return;
-
- if (isMobile() && !note && appStore.get().isEditorOpen) {
- return this.clearSession();
- }
-
- if (note) await this.openSession(note);
- });
-
EV.subscribe("user:loggedOut", () => this.get().newSession());
};
- openLastSession = () => {
- // Do not reopen last session on mobile
- if (isMobile() && isTablet()) return;
- const id = localStorage.getItem("lastOpenedNote");
-
- if (id) {
- db.notes.init().then(() => {
- setHashParam({ note: id });
- });
- }
- };
-
openLockedSession = async (note) => {
- setHashParam({});
- setHashParam({ note: note.id }, false);
- saveLastOpenedNote(note.id);
this.set((state) => {
state.session = {
...DEFAULT_SESSION,
...note,
content: note.content,
- state: SESSION_STATES.new,
+ state: SESSION_STATES.unlocked,
};
});
appStore.setIsEditorOpen(true);
+ hashNavigate(`/notes/${note.id}/edit`);
};
openSession = async (noteId) => {
+ const session = this.get().session;
+ console.log(session);
+ if (session.id === noteId && session.state === SESSION_STATES.unlocked) {
+ this.set((state) => (state.session.state = SESSION_STATES.new));
+ return;
+ }
+
+ await db.notes.init();
let note = db.notes.note(noteId);
if (!note) return;
note = qclone(note.data);
noteStore.setSelectedNote(note.id);
- if (note.locked) return setHashParam({ unlock: noteId });
- if (note.conflicted) return setHashParam({ diff: noteId });
-
- saveLastOpenedNote(note.id);
+ if (note.locked) return hashNavigate(`/notes/${noteId}/unlock`, true);
+ if (note.conflicted) return hashNavigate(`/notes/${noteId}/conflict`, true);
let content = await db.content.raw(note.contentId);
@@ -140,12 +124,6 @@ class EditorStore extends BaseStore {
});
noteStore.refresh();
-
- saveLastOpenedNote(!this.get().session.locked && id);
-
- if (!oldSession?.index) {
- setHashParam({ note: id }, false);
- }
});
};
@@ -158,9 +136,7 @@ class EditorStore extends BaseStore {
state: SESSION_STATES.new,
};
});
- saveLastOpenedNote();
noteStore.setSelectedNote(0);
- setHashParam({ note: 0 });
};
clearSession = () => {
@@ -171,9 +147,8 @@ class EditorStore extends BaseStore {
state: SESSION_STATES.new,
};
});
- saveLastOpenedNote();
noteStore.setSelectedNote(0);
- setHashParam({});
+ hashNavigate(`/`);
};
setSession = (set) => {
@@ -240,11 +215,6 @@ class EditorStore extends BaseStore {
}
}
-function saveLastOpenedNote(id) {
- if (!id) return localStorage.removeItem("lastOpenedNote");
- localStorage.setItem("lastOpenedNote", id);
-}
-
/**
* @type {[import("zustand").UseStore<EditorStore>, EditorStore]}
*/
diff --git a/apps/web/src/utils/use-hash-routes.js b/apps/web/src/utils/use-hash-routes.js
new file mode 100644
index 000000000..718d1357f
--- /dev/null
+++ b/apps/web/src/utils/use-hash-routes.js
@@ -0,0 +1,15 @@
+import makeMatcher from "wouter/matcher";
+import useHashLocation from "./use-hash-location";
+
+export default function useHashRoutes(routes) {
+ const [location] = useHashLocation();
+ const matcher = makeMatcher();
+
+ for (var key in routes) {
+ const [match, params] = matcher(key, location);
+ console.log("isMatch:", match, key, location);
+ if (match) {
+ return routes[key](params);
+ }
+ }
+}
diff --git a/apps/web/src/utils/useRouter.js b/apps/web/src/utils/use-routes.js
similarity index 70%
rename from apps/web/src/utils/useRouter.js
rename to apps/web/src/utils/use-routes.js
index 92510c853..6b7e89f87 100644
--- a/apps/web/src/utils/useRouter.js
+++ b/apps/web/src/utils/use-routes.js
@@ -1,10 +1,10 @@
import React from "react";
-import { useRouter } from "wouter";
+import { useLocation } from "wouter";
+import makeMatcher from "wouter/matcher";
export default function useRoutes(routes, options) {
- const router = useRouter();
- const [location] = router.hook();
- const matcher = router.matcher;
+ const [location] = useLocation();
+ const matcher = makeMatcher();
for (var key in routes) {
const [match, params] = matcher(key, location);
diff --git a/apps/web/src/utils/useHashLocation.js b/apps/web/src/utils/useHashLocation.js
new file mode 100644
index 000000000..164539fb9
--- /dev/null
+++ b/apps/web/src/utils/useHashLocation.js
@@ -0,0 +1,26 @@
+import { useState, useEffect } from "react";
+import { hashNavigate } from "../navigation";
+
+// returns the current hash location in a normalized form
+// (excluding the leading '#' symbol)
+const currentLocation = () => {
+ console.log("currentLocation", window.location);
+ return window.location.hash.replace(/^#/, "") || "/";
+};
+
+export default function useHashLocation() {
+ const [loc, setLoc] = useState(currentLocation());
+
+ useEffect(() => {
+ // this function is called whenever the hash changes
+ const handler = () => {
+ setLoc(currentLocation());
+ };
+
+ // subscribe to hash changes
+ window.addEventListener("hashchange", handler);
+ return () => window.removeEventListener("hashchange", handler);
+ }, []);
+
+ return [loc, hashNavigate];
+}
diff --git a/apps/web/src/utils/useHashParam.js b/apps/web/src/utils/useHashParam.js
deleted file mode 100644
index 3d185332b..000000000
--- a/apps/web/src/utils/useHashParam.js
+++ /dev/null
@@ -1,58 +0,0 @@
-import { useState, useEffect } from "react";
-import { isMobile } from "./dimensions";
-
-const getHashSearchParams = () => {
- const hash = window.location.hash.slice(1);
- const [prefix, query] = hash.split("?");
-
- return [prefix, new URLSearchParams(query)];
-};
-
-const getHashParam = (key) => {
- const [, searchParams] = getHashSearchParams(window.location);
- return searchParams.get(key);
-};
-
-const setHashParam = (
- obj,
- notify = true,
- append = false,
- forcePush = false
-) => {
- const [prefix, searchParams] = append
- ? getHashSearchParams()
- : ["", new URLSearchParams()];
-
- for (let key in obj) {
- let value = obj[key];
- searchParams.set(key, value);
- }
-
- const search = searchParams.toString();
- let hash = search ? `${prefix}?${search}` : prefix;
- if (window.history.replaceState) {
- if (isMobile() || forcePush) {
- window.history.pushState(null, null, `#${hash}`);
- } else {
- window.history.replaceState(null, null, `#${hash}`);
- }
-
- if (notify) window.dispatchEvent(new HashChangeEvent("hashchange"));
- } else {
- window.location.hash = hash;
- }
-};
-
-const useHashParam = (key, defaultValue) => {
- const [innerValue, setInnerValue] = useState(getHashParam(key));
-
- useEffect(() => {
- const handleHashChange = () => setInnerValue(getHashParam(key));
- window.addEventListener("hashchange", handleHashChange);
- return () => window.removeEventListener("hashchange", handleHashChange);
- }, [key]);
-
- return [innerValue || defaultValue];
-};
-
-export { setHashParam, useHashParam, getHashParam };
diff --git a/apps/web/src/utils/useHashRoute.js b/apps/web/src/utils/useHashRoute.js
new file mode 100644
index 000000000..cc5830dd3
--- /dev/null
+++ b/apps/web/src/utils/useHashRoute.js
@@ -0,0 +1,8 @@
+import makeMatcher from "wouter/matcher";
+import useHashLocation from "./use-hash-location";
+
+export default function useHashRoute(pattern) {
+ const [location] = useHashLocation();
+ const matcher = makeMatcher();
+ return matcher(pattern, location);
+}
diff --git a/apps/web/src/views/notebooks.js b/apps/web/src/views/notebooks.js
index b94b92822..ebce41dd3 100644
--- a/apps/web/src/views/notebooks.js
+++ b/apps/web/src/views/notebooks.js
@@ -3,6 +3,7 @@ import { showAddNotebookDialog } from "../components/dialogs/addnotebookdialog";
import ListContainer from "../components/list-container";
import { useStore, store } from "../stores/notebook-store";
import NotebooksPlaceholder from "../components/placeholders/notebooks-placeholder";
+import { hashNavigate } from "../navigation";
function Notebooks() {
useEffect(() => store.refresh(), []);
@@ -16,7 +17,7 @@ function Notebooks() {
placeholder={NotebooksPlaceholder}
button={{
content: "Create a notebook",
- onClick: showAddNotebookDialog,
+ onClick: () => hashNavigate("/notebooks/create"),
}}
/>
</>