A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
feat: remove in-house navigation, use hookrouter
thecodrrd8f1c75419a1
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 99ea34974..573fbbd25 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -9,6 +9,7 @@"emotion-theming": "^10.0.19","fast-sort": "^2.1.1","framer-motion": "^1.10.3",+ "hookrouter": "^1.2.3","immer": "^6.0.3","libsodium-wrappers": "^0.7.6","localforage": "^1.7.3",@@ -28,6 +29,7 @@"zustand": "^2.2.3"},"devDependencies": {+ "@types/hookrouter": "^2.2.3","babel-eslint": "^10.1.0","babel-loader": "8.1.0","eslint": "^6.8.0",diff --git a/apps/web/src/app.js b/apps/web/src/app.jsindex b335044c0..3da3b916d 100644--- a/apps/web/src/app.js+++ b/apps/web/src/app.js@@ -9,11 +9,11 @@ import { useStore as useUserStore } from "./stores/user-store";import { useStore as useNotesStore } from "./stores/note-store";import Animated from "./components/animated";import NavigationMenu from "./components/navigationmenu";-import NavigationContainer from "./navigation/container";-import RootNavigator from "./navigation/navigators/rootnavigator";-import EditorNavigator from "./navigation/navigators/editornavigator";import { isMobile } from "./utils/dimensions";import { db } from "./common";+import { useRoutes } from "hookrouter";+import routes from "./navigation/routes";+import Editor from "./components/editor";function App() {const [show, setShow] = usePersistentState("isContainerVisible", true);@@ -23,6 +23,7 @@ function App() {const initNotes = useNotesStore((store) => store.init);const openLastSession = useEditorStore((store) => store.openLastSession);const sessionId = useEditorStore((store) => store.session.id);+ const routeResult = useRoutes(routes);useEffect(() => {refreshColors();@@ -58,7 +59,9 @@ function App() {return (<ThemeProvider><Flex id="app" bg="background" height="100%">- <NavigationMenu toggleNavigationContainer={() => setShow(!show)} />+ <NavigationMenu+ toggleNavigationContainer={(state) => setShow(state || !show)}+ /><Flex variant="rowFill"><Animated.Flexvariant="columnFill"@@ -75,13 +78,10 @@ function App() {borderColor: "border",}}>- <NavigationContainer- navigator={RootNavigator}- variant="columnFill"- />+ {routeResult}</Animated.Flex><Flex width={[show ? 0 : "100%", 0, "100%"]}>- <NavigationContainer navigator={EditorNavigator} />+ <Editor /></Flex></Flex><Box id="dialogContainer" />diff --git a/apps/web/src/common/index.js b/apps/web/src/common/index.jsindex c1ea661af..8212687ef 100644--- a/apps/web/src/common/index.js+++ b/apps/web/src/common/index.js@@ -1,5 +1,6 @@import StorageInterface from "../interfaces/storage";import Database from "notes-core/api/";+import SelectionOptions from "./selectionoptions";export const db = new Database(StorageInterface);@@ -13,4 +14,12 @@ export const COLORS = {gray: "#9E9E9E",};+export const SELECTION_OPTIONS_MAP = {+ notes: SelectionOptions.NotesOptions,+ notebooks: SelectionOptions.NotebooksOptions,+ favorites: SelectionOptions.FavoritesOptions,+ trash: SelectionOptions.TrashOptions,+ topics: SelectionOptions.TopicOptions,+};+export const DEFAULT_CONTEXT = { colors: [], tags: [], notebook: {} };diff --git a/apps/web/src/components/button/index.js b/apps/web/src/components/button/index.jsindex 37416fa8f..259377294 100644--- a/apps/web/src/components/button/index.js+++ b/apps/web/src/components/button/index.js@@ -9,8 +9,8 @@ function Button(props) {<Flexbg="primary"width={props.width}- py={3}- px={3}+ py={2}+ px={2}mx={2}flexDirection="row"alignItems="center"@@ -22,9 +22,9 @@ function Button(props) {fontWeight: "body",":hover": {cursor: "pointer",- bg: theme.colors.primary + "dd"+ bg: theme.colors.primary + "dd",},- ...props.style+ ...props.style,}}onClick={props.onClick}>diff --git a/apps/web/src/components/editor/header.js b/apps/web/src/components/editor/header.jsindex 8dc527864..7a25d20d1 100644--- a/apps/web/src/components/editor/header.js+++ b/apps/web/src/components/editor/header.js@@ -7,7 +7,6 @@ import TitleBox from "./title-box";import { useStore, SESSION_STATES } from "../../stores/editor-store";import { timeConverter } from "../../utils/time";import { countWords } from "../../utils/string";-import EditorNavigator from "../../navigation/navigators/editornavigator";const TextSeperator = () => {return (diff --git a/apps/web/src/components/editor/index.js b/apps/web/src/components/editor/index.jsindex 44a253d94..32f440ded 100644--- a/apps/web/src/components/editor/index.js+++ b/apps/web/src/components/editor/index.js@@ -9,17 +9,22 @@ import { useStore as useUserStore } from "../../stores/user-store";import Animated from "../animated";import EditorMenu from "./editormenu";import Header from "./header";+import { useHashParam } from "../../utils/useHashParam";+import SplitEditor from "../spliteditor";function Editor() {const delta = useStore((store) => store.session.content.delta);const sessionState = useStore((store) => store.session.state);const setSession = useStore((store) => store.setSession);const saveSession = useStore((store) => store.saveSession);+ const openSession = useStore((store) => store.openSession);const isFocusMode = useAppStore((store) => store.isFocusMode);const isTrial = useUserStore((store) => store.user.notesnook?.subscription?.isTrial);const quillRef = useRef();+ const [noteId] = useHashParam("note");+ const [diff] = useHashParam("diff");useEffect(() => {// move the toolbar outside (easiest way)@@ -30,6 +35,12 @@ function Editor() {}}, []);+ useEffect(() => {+ if (!noteId) return;+ (async () => await openSession(noteId))();+ }, [openSession, noteId]);++ if (diff) return <SplitEditor diffId={diff} />;return (<Animated.Flexwidth={["0%", "0%", "100%"]}diff --git a/apps/web/src/components/icons/index.js b/apps/web/src/components/icons/index.jsindex 97637ad00..7599d2f16 100644--- a/apps/web/src/components/icons/index.js+++ b/apps/web/src/components/icons/index.js@@ -53,7 +53,8 @@ export const MoreVertical = createIcon(Icons.mdiDotsVertical);export const Trash = createIcon(Icons.mdiTrashCanOutline);export const Search = createIcon(Icons.mdiMagnify);export const Menu = createIcon(Icons.mdiMenu);-export const Login = createIcon(Icons.mdiLogin);+export const Login = createIcon(Icons.mdiLoginVariant);+export const Logout = createIcon(Icons.mdiLogoutVariant);export const FocusMode = createIcon(Icons.mdiFullscreen);export const NormalMode = createIcon(Icons.mdiFullscreenExit);export const Settings = createIcon(Icons.mdiCogOutline);@@ -66,12 +67,14 @@ export const Export = createIcon(Icons.mdiExport);/** Properties Icons */export const ChevronLeft = createIcon(Icons.mdiChevronLeft);export const Close = createIcon(Icons.mdiClose);-export const Tag = createIcon(Icons.mdiTagOutline);+export const Tag = createIcon(Icons.mdiTagTextOutline);export const Pin = createIcon(Icons.mdiPinOutline);export const PinFilled = createIcon(Icons.mdiPin);/** Settings Icons */export const User = createIcon(Icons.mdiAccountOutline);+export const DarkMode = createIcon(Icons.mdiWeatherNight);+export const LightMode = createIcon(Icons.mdiWeatherSunny);export const Theme = createIcon(Icons.mdiThemeLightDark);export const Checkmark = createIcon(Icons.mdiCheck);diff --git a/apps/web/src/components/navigation-menu/index.js b/apps/web/src/components/navigation-menu/index.jsindex af5d587a9..01a6010fa 100644--- a/apps/web/src/components/navigation-menu/index.js+++ b/apps/web/src/components/navigation-menu/index.js@@ -1,35 +1,60 @@-import React, { useEffect } from "react";+import React, { useEffect, useState } from "react";import ReactDOM from "react-dom";import { Flex } from "rebass";-import RootNavigator, {- bottomRoutes,- routes,-} from "../../navigation/navigators/rootnavigator";-import { usePersistentState } from "../../utils/hooks";-import { useStore } from "../../stores/app-store";-import { COLORS } from "../../common";-import { toTitleCase } from "../../utils/string";-import * as Icon from "../icons";import { useStore as useAppStore } from "../../stores/app-store";+import * as Icon from "../icons";+import { useStore as useUserStore } from "../../stores/user-store";+import { useStore as useThemeStore } from "../../stores/theme-store";import Animated from "../animated";-import NavItem from "../navitem";-import { objectMap } from "../../utils/object";+import NavigationItem from "./navigation-item";import { isMobile } from "../../utils/dimensions";+import { navigate } from "hookrouter";+import { toTitleCase } from "../../utils/string";+import { COLORS } from "../../common";+import { showLogInDialog } from "../dialogs/logindialog";+import { usePath } from "hookrouter";++const routes = [+ { title: "Home", path: "/", icon: Icon.Home },+ {+ title: "Notebooks",+ path: "/notebooks",+ icon: Icon.Notebook,+ },+ {+ title: "Favorites",+ path: "/favorites",+ icon: Icon.StarOutline,+ },+ { title: "Trash", path: "/trash", icon: Icon.Trash },+ { title: "Tags", path: "/tags", icon: Icon.Tag },+];++const bottomRoutes = [+ {+ title: "Settings",+ path: "/settings",+ icon: Icon.Settings,+ },+];function NavigationMenu(props) {const { toggleNavigationContainer } = props;- const [selectedRoute, setSelectedRoute] = usePersistentState("route", "home");+ const path = usePath(false);+ const [selectedRoute, setSelectedRoute] = useState(path);const isFocusMode = useAppStore((store) => store.isFocusMode);- const colors = useStore((store) => store.colors);- const isSideMenuOpen = useStore((store) => store.isSideMenuOpen);- const toggleSideMenu = useStore((store) => store.toggleSideMenu);+ const colors = useAppStore((store) => store.colors);+ const isSideMenuOpen = useAppStore((store) => store.isSideMenuOpen);+ const toggleSideMenu = useAppStore((store) => store.toggleSideMenu);+ const isSyncing = useUserStore((store) => store.isSyncing);+ const isLoggedIn = useUserStore((store) => store.isLoggedIn);+ const logout = useUserStore((store) => store.logout);+ const theme = useThemeStore((store) => store.theme);+ const toggleNightMode = useThemeStore((store) => store.toggleNightMode);useEffect(() => {- RootNavigator.onNavigate = (route) => {- setSelectedRoute(route.key);- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ setSelectedRoute(path);+ }, [path]);return (<Animated.Flex@@ -77,58 +102,77 @@ function NavigationMenu(props) {msOverflowStyle: "none",}}>- {objectMap(routes, (_, item) => (- <NavItem- key={item.key}- item={item}- selected={selectedRoute === item.key}- onSelected={() => {- if (selectedRoute === item.key) toggleNavigationContainer();- else if (RootNavigator.navigate(item.key))- setSelectedRoute(item.key);+ {routes.map((item) => (+ <NavigationItem+ key={item.path}+ title={item.title}+ icon={item.icon}+ selected={selectedRoute === item.path}+ onClick={() => {+ setSelectedRoute(item.path);+ if (selectedRoute === item.path)+ return toggleNavigationContainer();+ toggleNavigationContainer(true);+ navigate(item.path);+ }}+ />+ ))}+ {colors.map((color) => (+ <NavigationItem+ key={color.title}+ title={toTitleCase(color.title)}+ icon={Icon.Circle}+ color={COLORS[color.title]}+ onClick={() => {+ navigate(`/colors/${color.title}`);}}/>))}- {colors.map((color) => {- return (- <NavItem- onSelected={async () => {- setSelectedRoute(undefined);- RootNavigator.navigate(- "color",- {- title: toTitleCase(color.title),- context: {- type: "color",- value: color.title,- },- },- true- );- }}- key={color.title}- item={{- color: COLORS[color.title],- title: toTitleCase(color.title),- icon: Icon.Circle,- count: color.noteIds.length,- }}- />- );- })}</Flex><Flex flexDirection="column">- {Object.values(bottomRoutes).map((item) => (- <NavItem- onSelected={async () => {- const shouldSelect = item.onClick- ? await item.onClick()- : item.component && RootNavigator.navigate(item.key);- if (shouldSelect) setSelectedRoute(item.key);+ {theme === "light" ? (+ <NavigationItem+ title="Enable dark mode"+ icon={Icon.DarkMode}+ onClick={toggleNightMode}+ />+ ) : (+ <NavigationItem+ title="Enable light mode"+ icon={Icon.LightMode}+ onClick={toggleNightMode}+ />+ )}+ {isLoggedIn ? (+ <>+ <NavigationItem+ title="Sync"+ isLoading={isSyncing}+ icon={Icon.Sync}+ />+ <NavigationItem+ title="Logout"+ icon={Icon.Logout}+ onClick={logout}+ />+ </>+ ) : (+ <NavigationItem+ title="Login"+ icon={Icon.Login}+ onClick={showLogInDialog}+ />+ )}+ {bottomRoutes.map((item) => (+ <NavigationItem+ key={item.path}+ title={item.title}+ icon={item.icon}+ onClick={() => {+ navigate(item.path);+ setSelectedRoute(item.key);}}- key={item.key}- item={item}- selected={selectedRoute === item.key}+ selected={selectedRoute === item.path}/>))}</Flex>diff --git a/apps/web/src/components/navigation-menu/navigation-item.js b/apps/web/src/components/navigation-menu/navigation-item.jsnew file mode 100644index 000000000..a72ea96d4--- /dev/null+++ b/apps/web/src/components/navigation-menu/navigation-item.js@@ -0,0 +1,39 @@+import React from "react";+import { Flex, Button, Text } from "rebass";++function NavigationItem(props) {+ const { icon: Icon, color, title, isLoading } = props;++ return (+ <Button+ variant="icon"+ py={3}+ label={title}+ title={title}+ onClick={props.onClick}+ >+ <Flex+ justifyContent={["flex-start", "center", "center"]}+ alignItems="center"+ ml={[1, 0, 0]}+ sx={{ position: "relative" }}+ >+ <Icon+ size={18}+ sx={{ mr: [1, 0, 0] }}+ color={props.selected ? "primary" : color || "icon"}+ rotate={isLoading}+ />+ <Text+ variant="body"+ display={["flex", "none", "none"]}+ color={props.selected ? "primary" : "text"}+ ml={1}+ >+ {title}+ </Text>+ </Flex>+ </Button>+ );+}+export default NavigationItem;diff --git a/apps/web/src/components/navitem/index.js b/apps/web/src/components/navitem/index.jsdeleted file mode 100644index b51cdd8d9..000000000--- a/apps/web/src/components/navitem/index.js+++ /dev/null@@ -1,45 +0,0 @@-import React, { useState, useEffect } from "react";-import { Flex, Button, Text } from "rebass";-import { useStore as useUserStore } from "../../stores/user-store";--function NavItem(props) {- const { key, animatable, icon: Icon, color, title, count } = props.item;- const [isLoading, setIsLoading] = useState(false);- const isSyncing = useUserStore((store) => store.isSyncing);-- useEffect(() => {- if (animatable) {- if (key === "sync") setIsLoading(isSyncing);- }- }, [isSyncing, setIsLoading, animatable, key]);-- return (- <Button variant="icon" py={3} title={title} onClick={props.onSelected}>- <Flex- justifyContent={["flex-start", "center", "center"]}- alignItems="center"- ml={[1, 0, 0]}- sx={{ position: "relative" }}- >- <Icon- size={18}- sx={{ mr: [1, 0, 0] }}- color={props.selected ? "primary" : color || "icon"}- rotate={isLoading}- />- <Text- variant="body"- display={["flex", "none", "none"]}- color={props.selected ? "primary" : "text"}- ml={1}- >- {title}- </Text>- <Text sx={{ position: "absolute", top: -2, right: 0 }} fontSize={9}>- {count > 99 ? "99+" : count}- </Text>- </Flex>- </Button>- );-}-export default NavItem;diff --git a/apps/web/src/components/note/index.js b/apps/web/src/components/note/index.jsindex 2419d5c2f..16aeb1bcb 100644--- a/apps/web/src/components/note/index.js+++ b/apps/web/src/components/note/index.js@@ -13,6 +13,7 @@ import { useTheme } from "emotion-theming";import Colors from "../menu/colors";import { isMobile } from "../../utils/dimensions";import { showExportDialog } from "../dialogs/exportdialog";+import { setHashParam, useHashParam } from "../../utils/useHashParam";function menuItems(note, context) {return [@@ -104,6 +105,7 @@ function menuItems(note, context) {function Note(props) {const { item, index, pinnable } = props;const note = item;+ //const [, setNoteId] = useHashParam("note", "");const selectedNote = useStore((store) => store.selectedNote);// we will never be opening a note side-by-side in Mobileconst isOpened = isMobile() ? false : selectedNote === note.id;@@ -118,8 +120,12 @@ function Note(props) {body={note.headline}id={note.id}index={index}- onClick={async () => {- await editorStore.openSession(note);+ onClick={() => {+ if (note.conflicted) {+ setHashParam({ diff: note.id });+ } else {+ setHashParam({ note: note.id });+ }}}info={<Flex flex="1 1 auto" justifyContent="space-between">diff --git a/apps/web/src/components/notebook/index.js b/apps/web/src/components/notebook/index.jsindex d5dec0c49..e99998491 100644--- a/apps/web/src/components/notebook/index.js+++ b/apps/web/src/components/notebook/index.js@@ -56,10 +56,10 @@ class Notebook extends React.Component {body={notebook.description}subBody={<Flex sx={{ marginBottom: 1, marginTop: 1 }}>- {notebook.topics.slice(1, 4).map((topic) => (+ {notebook.topics.slice(1, 4).map((topic, index) => (<FlexonClick={(e) => {- onTopicClick(notebook, topic);+ onTopicClick(notebook, index + 1);e.stopPropagation();}}key={topic.title}diff --git a/apps/web/src/components/properties/index.js b/apps/web/src/components/properties/index.jsindex f20677428..a985cf3ed 100644--- a/apps/web/src/components/properties/index.js+++ b/apps/web/src/components/properties/index.js@@ -10,7 +10,6 @@ import Animated from "../animated";import Toggle from "./toggle";import { toTitleCase } from "../../utils/string";import { showMoveNoteDialog } from "../dialogs/movenotedialog";-import RootNavigator from "../../navigation/navigators/rootnavigator";const tools = [{ key: "pinned", icons: { on: Icon.PinFilled, off: Icon.Pin }, label: "Pin" },@@ -133,11 +132,11 @@ function Properties() {color="primary"sx={{ cursor: "pointer" }}onClick={() => {- RootNavigator.navigate(+ /* RootNavigator.navigate("notebooks",{ params: { id: notebookData.id } },true- );+ ); */}}>{notebook.title}@@ -148,11 +147,11 @@ function Properties() {color="primary"sx={{ cursor: "pointer" }}onClick={() => {- RootNavigator.navigate(+ /* RootNavigator.navigate("notebooks",{ params: notebookData },true- );+ ); */}}>{notebookData.topic}diff --git a/apps/web/src/navigation/route.js b/apps/web/src/components/route-container/index.jssimilarity index 62%rename from apps/web/src/navigation/route.jsrename to apps/web/src/components/route-container/index.jsindex 45d442dea..fb45d3a62 100644--- a/apps/web/src/navigation/route.js+++ b/apps/web/src/components/route-container/index.js@@ -1,43 +1,53 @@import React from "react";+import Animated from "../animated";import { Box, Flex, Heading, Text } from "rebass";-import * as Icon from "../components/icons";-import ThemeProvider from "../components/theme-provider";-import { useStore } from "../stores/app-store";-import { useStore as useSelectionStore } from "../stores/selection-store";--function Route(props) {- const navigator = props.params.navigator || props.navigator;+import * as Icon from "../icons";+import { useStore } from "../../stores/app-store";+import { useStore as useSelectionStore } from "../../stores/selection-store";+import { SELECTION_OPTIONS_MAP } from "../../common";+function RouteContainer(props) {+ const { type, route, canGoBack, title, subtitle } = props;return (- <ThemeProvider>- <Flex flexDirection="column" px={2}>- <Header {...props} />- </Flex>- {props.route.component && (- <props.route.component- navigator={navigator}- onDone={props.onDone}- {...props.params}- />- )}- </ThemeProvider>+ <Animated.Flex+ sx={{ overflow: "hidden" }}+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{ duration: 0.2, ease: "easeIn" }}+ exit={{ opacity: 0 }}+ flexDirection="column"+ flex="1 1 auto"+ >+ <Header+ canGoBack={canGoBack}+ title={title}+ subtitle={subtitle}+ selectionOptions={SELECTION_OPTIONS_MAP[type]}+ />+ {route}+ </Animated.Flex>);}-export default Route;++export default RouteContainer;function Header(props) {- const { route, canGoBack, backAction } = props;- const { title, titleColor, params, options, noHeader } = route;+ const { title, subtitle, canGoBack, selectionOptions } = props;const toggleSideMenu = useStore((store) => store.toggleSideMenu);- if ((!title && !params.title) || noHeader) return null;+ if (!title && !subtitle) return null;return (- <>+ <Flex mx={2} flexDirection="column"><Flex alignItems="center" justifyContent="space-between"><Flex alignItems="center" py={2}>{canGoBack && (- <Box onClick={backAction} ml={-2} height={38} width={38}>+ <Box+ onClick={() => window.history.back()}+ ml={-2}+ height={38}+ width={38}+ ><Icon.ChevronLeft size={38} color="fontPrimary" /></Box>)}@@ -50,13 +60,13 @@ function Header(props) {}}size={28}/>- <Heading fontSize="heading" color={titleColor || "text"}>- {title || params.title}+ <Heading fontSize="heading" color={"text"}>+ {title}</Heading></Flex>- <SelectionOptions options={options} />+ <SelectionOptions options={selectionOptions} /></Flex>- {params.subtitle && (+ {subtitle && (<Textvariant="title"color="primary"@@ -65,11 +75,11 @@ function Header(props) {cursor: "normal",}}>- {params.subtitle}+ {subtitle}</Text>)}<SelectionBox />- </>+ </Flex>);}diff --git a/apps/web/src/components/search/index.js b/apps/web/src/components/search/index.jsindex 85545703a..49c8099d1 100644--- a/apps/web/src/components/search/index.js+++ b/apps/web/src/components/search/index.js@@ -2,19 +2,21 @@ import React from "react";import { Flex, Box } from "rebass";import { Input } from "@rebass/forms";import * as Icon from "../icons";-import { useStore } from "../../stores/searchstore";import "./search.css";-import RootNavigator from "../../navigation/navigators/rootnavigator";+import { navigate } from "hookrouter";+import { useStore } from "../../stores/searchstore";-var query = "";+var query;function Search(props) {- const search = useStore(store => store.search);+ const search = useStore((store) => store.search);+ const { type } = props;+return (<Flexvariant="rowCenter"px={2}sx={{- position: "relative"+ position: "relative",}}><Input@@ -22,15 +24,14 @@ function Search(props) {name="search"autoFocus={!!query}defaultValue={query}- placeholder={`Search your ${props.type}`}- onChange={e => {+ placeholder={`Search your ${type}`}+ onChange={(e) => {query = e.target.value;- if (query.length >= 1) {- search(query);- RootNavigator.navigate("search");- } else {- RootNavigator.goBack();+ if (query.length <= 0) return window.history.back();+ if (query.length === 1) {+ navigate("/search");}+ search(query);}}/><Box@@ -39,7 +40,7 @@ function Search(props) {position: "absolute",right: 0,mr: 3,- color: "hover"+ color: "hover",}}><Icon.Search size={28} />diff --git a/apps/web/src/components/spliteditor/deltatoggle.js b/apps/web/src/components/spliteditor/deltatoggle.jsindex 6125f3fc3..5cb345eff 100644--- a/apps/web/src/components/spliteditor/deltatoggle.js+++ b/apps/web/src/components/spliteditor/deltatoggle.js@@ -1,8 +1,10 @@-import React from "react";+import React, { useCallback } from "react";import { Flex, Text, Button } from "rebass";import { timeConverter } from "../../utils/time";import DeltaTransformer from "quill/core/delta";-import { useStore } from "../../stores/mergestore";+import { store as notestore } from "../../stores/note-store";+import { db } from "../../common";+import { setHashParam } from "../../utils/useHashParam";const deltaTransformer = new DeltaTransformer();@@ -16,8 +18,39 @@ function DeltaToggle(props) {label,dateEdited,editors,+ note,} = props;- const resolveConflict = useStore((store) => store.resolveConflict);++ const resolveConflict = useCallback(+ async (selectedContent, otherContent) => {+ selectedContent.delta = {+ data: { ops: selectedContent.delta },+ resolved: true,+ };+ await db.notes.add({+ id: note.id,+ content: selectedContent,+ conflicted: false,+ });+ if (otherContent) {+ otherContent.delta = {+ data: { ops: otherContent.delta },+ };+ await db.notes.add({+ ...note,+ content: otherContent,+ id: undefined,+ dateCreated: undefined,+ dateEdited: undefined,+ conflicted: false,+ title: note.title + " (DUPLICATE)",+ });+ }+ notestore.refresh();+ setHashParam({ note: note.id });+ },+ [note]+ );return (<Flex flexDirection="column" sx={sx}>diff --git a/apps/web/src/components/spliteditor/index.js b/apps/web/src/components/spliteditor/index.jsindex f307ab810..e2fbc03c9 100644--- a/apps/web/src/components/spliteditor/index.js+++ b/apps/web/src/components/spliteditor/index.js@@ -1,19 +1,41 @@-import React, { useState, useRef } from "react";+import React, { useState, useRef, useEffect } from "react";import { Flex, Box, Text } from "rebass";import SimpleEditor from "./simpleeditor";import DeltaTransformer from "quill/core/delta";import DeltaToggle from "./deltatoggle";-import { useStore } from "../../stores/mergestore";+import { store as notesStore } from "../../stores/note-store";+import { db } from "../../common";+import { setHashParam } from "../../utils/useHashParam";const deltaTransformer = new DeltaTransformer();function SplitEditor(props) {- const conflictedNote = useStore((store) => store.conflictedNote);- const remoteDelta = useStore((store) => store.remoteDelta);- const localDelta = useStore((store) => store.localDelta);+ const { diffId } = props;++ const [conflictedNote, setConflictedNote] = useState();+ const [remoteDelta, setRemoteDelta] = useState();+ const [localDelta, setLocalDelta] = useState();++ useEffect(() => {+ let note = db.notes.note(diffId);+ if (!note) {+ setHashParam({ note: 0 });+ return;+ }+ notesStore.setSelectedNote(diffId);+ note = note.data;+ (async function () {+ const delta = await db.delta.raw(note.content.delta);+ setConflictedNote(note);+ setLocalDelta({ ...delta, conflicted: false });+ setRemoteDelta(delta.conflicted);+ })();+ }, [diffId]);+const [localEditor, remoteEditor] = [useRef(), useRef()];const [selectedDelta, setSelectedDelta] = useState(-1);- if (!conflictedNote) return null;++ if (!conflictedNote || !localDelta || !remoteDelta) return null;return (<Flex width="100%" flex="1 1 auto" flexDirection="column"><Flex@@ -33,6 +55,7 @@ function SplitEditor(props) {isSelected={selectedDelta === 0}isOtherSelected={selectedDelta === 1}onToggle={() => setSelectedDelta((s) => (s === 0 ? -1 : 0))}+ note={conflictedNote}editors={() => ({selectedEditor: remoteEditor.current.quill,otherEditor: localEditor.current.quill,@@ -54,6 +77,7 @@ function SplitEditor(props) {sx={{ flex: "0.1 1 auto", alignItems: "flex-end" }}direction="row-reverse"label="Incoming note"+ note={conflictedNote}isSelected={selectedDelta === 1}isOtherSelected={selectedDelta === 0}dateEdited={remoteDelta.dateEdited}diff --git a/apps/web/src/navigation/container.js b/apps/web/src/navigation/container.jsdeleted file mode 100644index 474d9553e..000000000--- a/apps/web/src/navigation/container.js+++ /dev/null@@ -1,10 +0,0 @@-import React, { useEffect } from "react";-import { Flex } from "rebass";--function NavigationContainer(props) {- useEffect(() => {- props.navigator.onLoad(props.params);- }, [props.params, props.navigator]);- return <Flex className={props.navigator.root} variant="columnFill" />;-}-export default NavigationContainer;diff --git a/apps/web/src/navigation/index.js b/apps/web/src/navigation/index.jsdeleted file mode 100644index d5c44150f..000000000--- a/apps/web/src/navigation/index.js+++ /dev/null@@ -1,165 +0,0 @@-import React from "react";-import ReactDOM from "react-dom";-import Animated from "../components/animated";-import { AnimatePresence } from "framer-motion";-import { store as selectionStore } from "../stores/selection-store";-import { store as appStore } from "../stores/app-store";-import Route from "./route";-import Config from "../utils/config";-import { isMobile } from "../utils/dimensions";-import { qclone } from "qclone";--class Navigator {- constructor(root, routes, options = {}) {- this.routes = routes;- this.root = root;- this.options = options;- this.history = [];- this.lastRoute = undefined;- this.onNavigate = () => {};- }-- onLoad = (params = null) => {- if (!this.options.persist) return;-- const opts = Config.get(this.root, {- history: [],- lastRoute: this.getRoute(this.options.default),- });- this.history = opts.history;- this.lastRoute = undefined;- this.navigate(- opts.lastRoute.key,- { ...opts.lastRoute.params, ...params, noPersist: true },- true- );- };-- getRoute(key) {- return qclone(this.routes[key]);- }-- pushToHistory() {- const lastItem = this.history[this.history.length - 1];- if (this.lastRoute) {- if (lastItem && lastItem.key === this.lastRoute.key) return;- const route = qclone(this.lastRoute);- if (route.params && route.params.noPersist) {- route.params = {};- }- this.history.push(route);- }- }-- setLastRoute(route) {- if (!this.options.persist) return;-- this.lastRoute = route;-- // cache the route in localStorage- // NOTE: we delete the navigator key if any so it's always new across refreshes- const copy = qclone(route);- if (copy.params.navigator) delete copy.params.navigator;- Config.set(this.root, {- history: this.history,- lastRoute: copy,- });- }-- getRoot() {- return document.querySelector(`.${this.root}`);- }-- getNavigationRoute(routeName, params = {}, force = false) {- let route = this.getRoute(routeName);-- if (!force && (!route || this.lastRoute === route)) {- return false;- }-- this.onNavigate(route);-- route.params = { ...route.params, ...params };-- this.pushToHistory();- this.setLastRoute(route);- return route;- }-- navigate(routeName, params = {}, force = false) {- const route = this.getNavigationRoute(routeName, params, force);- if (!route) return false;- return this.renderRoute(route);- }-- navigateWithResult(routeName, params = {}, force = false) {- return new Promise((resolve) => {- const route = this.getNavigationRoute(routeName, params, force);- if (!route) return false;- this.renderRoute(route, resolve);- });- }-- renderRoute(route, onDone = null) {- let root = this.getRoot();- if (!root) {- return false;- }-- // exit selection mode on navigate- selectionStore.toggleSelectionMode(false);-- ReactDOM.render(- <AnimatePresence exitBeforeEnter={true}>- <Animated.Flex- sx={{ overflow: "hidden" }}- key={route.key}- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{ duration: 0.2, ease: "easeOut" }}- exit={{ opacity: 0 }}- flexDirection="column"- flex="1 1 auto"- >- <Route- navigator={this}- route={route}- params={route.params}- canGoBack={- this.options.backButtonEnabled && this.history.length > 0- }- onDone={onDone}- backAction={() => this.goBack()}- />- </Animated.Flex>- </AnimatePresence>,- root- );- if (isMobile()) appStore.toggleSideMenu(false);- return true;- }-- goBack(params = {}) {- let route = this.history.pop();- if (!route) return false;- if (!route.component) route.component = this.getRoute(route.key).component;-- this.setLastRoute(route);- return this.renderRoute(this._mergeParams(route, params));- }-- restore(params = {}) {- if (!this.lastRoute) {- return false;- }- return this.renderRoute(this._mergeParams(this.lastRoute, params));- }-- _mergeParams(route, params) {- return {- ...route,- params: { ...route.params, ...params },- };- }-}-export default Navigator;diff --git a/apps/web/src/navigation/navigators/editornavigator.js b/apps/web/src/navigation/navigators/editornavigator.jsdeleted file mode 100644index f3fe4ff37..000000000--- a/apps/web/src/navigation/navigators/editornavigator.js+++ /dev/null@@ -1,17 +0,0 @@-import Editor from "../../components/editor";-import SplitEditor from "../../components/spliteditor";-import Navigator from "../index";-import { createRoute } from "../routes";-import Unlock from "../../components/unlock";--const routes = {- ...createRoute("editor", Editor),- ...createRoute("unlock", Unlock),- ...createRoute("split", SplitEditor),-};--const EditorNavigator = new Navigator("EditorNavigator", routes, {- default: "editor",- persist: false,-});-export default EditorNavigator;diff --git a/apps/web/src/navigation/navigators/index.js b/apps/web/src/navigation/navigators/index.jsdeleted file mode 100644index 387d31100..000000000--- a/apps/web/src/navigation/navigators/index.js+++ /dev/null@@ -1,5 +0,0 @@-export const NotebookNavigator = require("./nbnavigator").default;-export const RootNavigator = require("./rootnavigator").default;-export const SettingsNavigator = require("./settingnavigator").default;-export const TagNavigator = require("./tagnavigator").default;-//export const EditorNavigator = require("./editornavigator").default;diff --git a/apps/web/src/navigation/navigators/nbnavigator.js b/apps/web/src/navigation/navigators/nbnavigator.jsdeleted file mode 100644index 6f8a7a8ff..000000000--- a/apps/web/src/navigation/navigators/nbnavigator.js+++ /dev/null@@ -1,24 +0,0 @@-import { Notebooks, Notes, Topics } from "../../views";-import Navigator from "../index";-import { createRoute } from "../routes";-import SelectionModeOptions from "../../common/selectionoptions";--const routes = {- ...createRoute("notebooks", Notebooks, {- title: "Notebooks",- options: SelectionModeOptions.NotebooksOptions,- }),- ...createRoute("topics", Topics, {- options: SelectionModeOptions.TopicOptions,- }),- ...createRoute("notes", Notes, {- options: SelectionModeOptions.NotesOptions,- }),-};--const NotebookNavigator = new Navigator("NotebookNavigator", routes, {- backButtonEnabled: true,- persist: true,- default: "notebooks",-});-export default NotebookNavigator;diff --git a/apps/web/src/navigation/navigators/rootnavigator.js b/apps/web/src/navigation/navigators/rootnavigator.jsdeleted file mode 100644index 30d2ff860..000000000--- a/apps/web/src/navigation/navigators/rootnavigator.js+++ /dev/null@@ -1,94 +0,0 @@-import { Home, Trash, Notes, Account } from "../../views";-import * as Icon from "../../components/icons";-import {- createRoute,- createNavigatorRoute,- createNormalRoute,- createDeadRoute,-} from "../routes";-import Navigator from "../index";-import SelectionModeOptions from "../../common/selectionoptions";-import Search from "../../views/Search";-import { store as userStore } from "../../stores/user-store";-import { store as themeStore } from "../../stores/theme-store";-import { showLogInDialog } from "../../components/dialogs/logindialog";-import { NotebookNavigator, TagNavigator, SettingsNavigator } from "./index";-import FavoritesPlaceholder from "../../components/placeholders/favorites-placeholder";--export const bottomRoutes = {- ...createDeadRoute("nightmode", Icon.Theme, {- title: "Night mode",- onClick: () => themeStore.toggleNightMode(),- }),- ...createDeadRoute("sync", Icon.Sync, {- title: "Sync",- onClick: async () => userStore.sync(),- animatable: true,- }),- ...createNormalRoute("account", Account, Icon.User, {- title: "Account",- onClick: async () => {- if (!userStore.get().isLoggedIn) {- await showLogInDialog();- return false;- } else return RootNavigator.navigate("account");- },- }),- ...createNavigatorRoute(- "settings",- Icon.Settings,- "Settings",- SettingsNavigator- ),-};--export const routes = {- ...createNormalRoute("home", Home, Icon.Home, {- title: "Home",- options: SelectionModeOptions.NotesOptions,- }),- ...createNavigatorRoute(- "notebooks",- Icon.Notebook,- "Notebooks",- NotebookNavigator- ),- ...createRoute(- "favorites",- Notes,- {- icon: Icon.StarOutline,- title: "Favorites",- options: SelectionModeOptions.FavoritesOptions,- },- {- context: { type: "favorites" },- placeholder: FavoritesPlaceholder,- }- ),- ...createNormalRoute("trash", Trash, Icon.Trash, {- title: "Trash",- options: SelectionModeOptions.TrashOptions,- }),- ...createNavigatorRoute("tags", Icon.Tag, "Tags", TagNavigator),-};--const invisibleRoutes = {- ...createRoute("color", Notes, {- icon: Icon.Circle,- options: SelectionModeOptions.NotesOptions,- }),- ...createRoute("search", Search, { title: "Search" }),-};--const RootNavigator = new Navigator(- "RootNavigator",- { ...routes, ...bottomRoutes, ...invisibleRoutes },- {- backButtonEnabled: false,- default: "home",- persist: true,- }-);--export default RootNavigator;diff --git a/apps/web/src/navigation/navigators/settingnavigator.js b/apps/web/src/navigation/navigators/settingnavigator.jsdeleted file mode 100644index 489d14b12..000000000--- a/apps/web/src/navigation/navigators/settingnavigator.js+++ /dev/null@@ -1,16 +0,0 @@-import { Settings, Account } from "../../views";-import Navigator from "../index";-import { createRoute } from "../routes";--const routes = {- ...createRoute("settings", Settings, { title: "Settings" }),- ...createRoute("account", Account, { title: "Account" }),-};--const SettingsNavigator = new Navigator("SettingsNavigator", routes, {- backButtonEnabled: true,- default: "settings",- persist: true,-});--export default SettingsNavigator;diff --git a/apps/web/src/navigation/navigators/tagnavigator.js b/apps/web/src/navigation/navigators/tagnavigator.jsdeleted file mode 100644index d40f00324..000000000--- a/apps/web/src/navigation/navigators/tagnavigator.js+++ /dev/null@@ -1,19 +0,0 @@-import { Notes, Tags } from "../../views";-import Navigator from "../index";-import { createRoute } from "../routes";-import SelectionModeOptions from "../../common/selectionoptions";--const routes = {- ...createRoute("tags", Tags, { title: "Tags" }),- ...createRoute("notes", Notes, {- options: SelectionModeOptions.NotesOptions,- }),-};--const TagNavigator = new Navigator("TagNavigator", routes, {- backButtonEnabled: true,- default: "tags",- persist: true,-});--export default TagNavigator;diff --git a/apps/web/src/navigation/routes.js b/apps/web/src/navigation/routes.jsindex 437de02f9..a71beb8d3 100644--- a/apps/web/src/navigation/routes.js+++ b/apps/web/src/navigation/routes.js@@ -1,29 +1,44 @@-import NavigationContainer from "./container";+import React from "react";+import Editor from "../components/editor";+import FavoritesPlaceholder from "../components/placeholders/favorites-placeholder";+import RouteContainer from "../components/route-container";+import { toTitleCase } from "../utils/string";+import Home from "../views/home";+import Notebooks from "../views/notebooks";+import Notes from "../views/notes.js";+import Search from "../views/search";+import Settings from "../views/settings";+import Tags from "../views/tags";+import Trash from "../views/trash";-export function createRoute(key, component, props = {}, params = {}) {- return {- [key]: {- key,- component,- ...props,- params,- },- };-}+const routes = {+ "/": () => <RouteContainer type="notes" title="Home" route={<Home />} />,+ "/notebooks*": () => <RouteContainer route={<Notebooks />} />,+ "/favorites": () => (+ <RouteContainer+ key="favorites"+ title="Favorites"+ route={+ <Notes+ placeholder={FavoritesPlaceholder}+ context={{ type: "favorites" }}+ />+ }+ />+ ),+ "/trash": () => (+ <RouteContainer type="trash" title="Trash" route={<Trash />} />+ ),+ "/tags*": () => <RouteContainer route={<Tags />} />,+ "/colors/:color": ({ color }) => (+ <RouteContainer+ type="notes"+ title={`${toTitleCase(color)}`}+ route={<Notes context={{ type: "color", value: color }} />}+ />+ ),+ "/settings": () => <RouteContainer title="Settings" route={<Settings />} />,+ "/search": () => <RouteContainer title="Search" route={<Search />} />,+};-export function createNavigatorRoute(key, icon, title, navigator) {- return createRoute(- key,- NavigationContainer,- { icon, title, noHeader: true },- { navigator }- );-}--export function createNormalRoute(key, component, icon, props = {}) {- return createRoute(key, component, { title: component.name, icon, ...props });-}--export function createDeadRoute(key, icon, props = {}) {- return createRoute(key, undefined, { icon, ...props });-}+export default routes;diff --git a/apps/web/src/stores/editor-store.js b/apps/web/src/stores/editor-store.jsindex 0cc1a00ae..2b5bba234 100644--- a/apps/web/src/stores/editor-store.js+++ b/apps/web/src/stores/editor-store.js@@ -2,11 +2,10 @@ import createStore from "../common/store";import { store as noteStore } from "./note-store";import { store as appStore } from "./app-store";import { store as tagStore } from "./tag-store";-import { store as mergeStore } from "./mergestore";import { db } from "../common";import BaseStore from ".";-import EditorNavigator from "../navigation/navigators/editornavigator";import { isMobile } from "../utils/dimensions";+import { setHashParam } from "../utils/useHashParam";const SESSION_STATES = { stale: "stale", new: "new" };const DEFAULT_SESSION = {@@ -39,21 +38,23 @@ class EditorStore extends BaseStore {if (isMobile()) return;const id = localStorage.getItem("lastOpenedNote");- const note = db.notes.note(id);- if (!id || !note) {- return EditorNavigator.navigate("editor");+ if (id) {+ setHashParam({ note: id });}- await this.openSession(note.data);};- openSession = async (note) => {+ openSession = async (noteId) => {+ let note = db.notes.note(noteId);+ if (!note) return this.newSession();+ note = note.data;+clearTimeout(this.get().session.timeout);+ noteStore.setSelectedNote(note.id);if (note.conflicted) {- return await mergeStore.openConflict(note);+ setHashParam({ diff: noteId });+ return;}-- noteStore.setSelectedNote(note.id);saveLastOpenedNote(note.id);let content = {};@@ -63,11 +64,11 @@ class EditorStore extends BaseStore {delta: await db.notes.note(note).delta(),};} else {- content = await EditorNavigator.navigateWithResult("unlock", {+ /* content = await EditorNavigator.navigateWithResult("unlock", {id: note.id,});console.log(content);- if (!content) return;+ if (!content) return; */}this.set((state) => {@@ -78,8 +79,6 @@ class EditorStore extends BaseStore {state: SESSION_STATES.new,};});-- EditorNavigator.navigate("editor");};saveSession = (oldSession) => {@@ -114,11 +113,16 @@ class EditorStore extends BaseStore {noteStore.refresh();saveLastOpenedNote(!this.get().session.locked && id);++ if (!oldSession.index) {+ setHashParam({ note: id }, false);+ }});};newSession = (context = {}) => {- EditorNavigator.navigate("editor");+ setHashParam({ note: 0 });+clearTimeout(this.get().session.timeout);this.set(function (state) {state.session = {diff --git a/apps/web/src/stores/mergestore.js b/apps/web/src/stores/mergestore.jsdeleted file mode 100644index 058fb85e4..000000000--- a/apps/web/src/stores/mergestore.js+++ /dev/null@@ -1,59 +0,0 @@-import createStore from "../common/store";-import { db } from "../common";-import { store as noteStore } from "./note-store";-import { store as editorStore } from "./editor-store";-import EditorNavigator from "../navigation/navigators/editornavigator";-import BaseStore from "./index";--class MergeStore extends BaseStore {- conflictedNote;- localDelta;- remoteDelta;-- openConflict = async (note) => {- noteStore.setSelectedNote(note.id);- const delta = await db.delta.raw(note.content.delta);- this.set((state) => {- state.conflictedNote = note;- state.localDelta = { ...delta, conflicted: false };- state.remoteDelta = delta.conflicted;- });- EditorNavigator.navigate("split");- };-- resolveConflict = async (selectedContent, otherContent) => {- const note = this.get().conflictedNote;- selectedContent.delta = {- data: { ops: selectedContent.delta },- resolved: true,- };- await db.notes.add({- id: note.id,- content: selectedContent,- conflicted: false,- });- if (otherContent) {- otherContent.delta = {- data: { ops: otherContent.delta },- };- await db.notes.add({- ...note,- content: otherContent,- id: undefined,- dateCreated: undefined,- dateEdited: undefined,- title: note.title + " (DUPLICATE)",- });- }- this.set((state) => {- state.conflictedNote = undefined;- state.localDelta = undefined;- state.remoteDelta = undefined;- });- noteStore.refresh();- await editorStore.openSession(note);- };-}--const [useStore, store] = createStore(MergeStore);-export { useStore, store };diff --git a/apps/web/src/stores/note-store.js b/apps/web/src/stores/note-store.jsindex f64651c0e..adcce76a4 100644--- a/apps/web/src/stores/note-store.js+++ b/apps/web/src/stores/note-store.js@@ -3,6 +3,7 @@ import createStore from "../common/store";import { store as editorStore } from "./editor-store";import Vault from "../common/vault";import BaseStore from ".";+import { navigate } from "hookrouter";class NoteStore extends BaseStore {notes = {@@ -13,13 +14,25 @@ class NoteStore extends BaseStore {context = undefined;selectedNote = 0;- init = () => {+ init = async () => {db.ev.subscribe("notes:removeEmptyNote", (id) => {const { session, newSession } = editorStore.get();if (session.id === id) {newSession();}});++ /* const note = db.notes.note("b2ce3a6053afab9cb1d8012d").data;+ const delta = await db.delta.raw(note.content.delta);++ const note2 = db.notes.note("b2f68f306c560dab97aa196a").data;+ const delta2 = await db.delta.raw(note2.content.delta);++ const delta3 = { ...delta, conflicted: delta2 };++ await db.delta.add(delta3);+ await db.notes.add({ id: note.id, conflicted: true, resolved: false });+ console.log(delta3); */};setSelectedNote = (id) => {@@ -45,11 +58,12 @@ class NoteStore extends BaseStore {break;case "color":notes = db.notes.colored(context.value);+ if (!notes.length) return navigate("/");break;case "topic":- notes = db.notebooks- .notebook(context.value.id)- .topics.topic(context.value.topic).all;+ const notebook = db.notebooks.notebook(context.value.id);+ const topic = notebook.topics.topic(context.value.topic);+ notes = topic.all;break;case "favorites":notes = db.notes.favorites;diff --git a/apps/web/src/stores/user-store.js b/apps/web/src/stores/user-store.jsindex 8a752907a..517312168 100644--- a/apps/web/src/stores/user-store.js+++ b/apps/web/src/stores/user-store.js@@ -2,7 +2,6 @@ import createStore from "../common/store";import { db } from "../common";import { store as appStore } from "./app-store";import BaseStore from "./index";-import RootNavigator from "../navigation/navigators/rootnavigator";import config from "../utils/config";class UserStore extends BaseStore {@@ -81,7 +80,6 @@ class UserStore extends BaseStore {});config.clear();await appStore.refresh();- RootNavigator.navigate("home");});};}diff --git a/apps/web/src/utils/useHashParam.js b/apps/web/src/utils/useHashParam.jsnew file mode 100644index 000000000..c7f155ac5--- /dev/null+++ b/apps/web/src/utils/useHashParam.js@@ -0,0 +1,47 @@+import { useState, useEffect, useCallback } from "react";++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) => {+ //const [prefix, searchParams] = getHashSearchParams();+ const searchParams = new URLSearchParams();+ const prefix = "";++ 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) {+ 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 };diff --git a/apps/web/src/views/Account.js b/apps/web/src/views/Account.jsdeleted file mode 100644index b3cf13930..000000000--- a/apps/web/src/views/Account.js+++ /dev/null@@ -1,46 +0,0 @@-import React, { useEffect, useState } from "react";-import { Flex, Button, Text } from "rebass";-import { useStore, store } from "../stores/user-store";--function Account() {- const logout = useStore((store) => store.logout);- const initUser = useStore((store) => store.init);- const [user, setUser] = useState({});- useEffect(() => {- initUser().then(() => {- setUser(store.get().user);- });- }, [initUser]);-- return (- <Flex variant="columnFill">- <Text variant="title" textAlign="center" py="5px">- {user.username}- </Text>- <Text variant="subtitle" textAlign="center" py="5px">- {user.email}- </Text>- <Text- alignSelf="center"- fontSize="title"- bg="primary"- color="static"- px="5px"- my="5px"- sx={{ borderRadius: "5px" }}- >- Beta- </Text>- <Button- variant="list"- onClick={async () => {- await logout();- }}- >- Logout- </Button>- </Flex>- );-}--export default Account;diff --git a/apps/web/src/views/Home.js b/apps/web/src/views/home.jssimilarity index 100%rename from apps/web/src/views/Home.jsrename to apps/web/src/views/home.jsdiff --git a/apps/web/src/views/index.js b/apps/web/src/views/index.jsindex 54a0ad7cd..4eff3bb45 100644--- a/apps/web/src/views/index.js+++ b/apps/web/src/views/index.js@@ -1,9 +1,9 @@-export const Home = require("./Home").default;-export const Notebooks = require("./Notebooks").default;-export const Notes = require("./Notes").default;-export const Topics = require("./Topics").default;-export const Settings = require("./Settings").default;-export const Trash = require("./Trash").default;+export const Home = require("./home").default;+export const Notebooks = require("./notebooks").default;+export const Notes = require("./notes.js").default;+export const Topics = require("./topics").default;+export const Settings = require("./settings.js").default;+export const Trash = require("./trash").default;export const Account = require("./Account").default;-export const Tags = require("./Tags").default;-export const Search = require("./Search").default;+export const Tags = require("./tags").default;+export const Search = require("./search").default;diff --git a/apps/web/src/views/Notebooks.js b/apps/web/src/views/notebooks.jssimilarity index 51%rename from apps/web/src/views/Notebooks.jsrename to apps/web/src/views/notebooks.jsindex cf2dd881b..074fd0333 100644--- a/apps/web/src/views/Notebooks.js+++ b/apps/web/src/views/notebooks.js@@ -4,36 +4,59 @@ import AddNotebookDialog 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 Topics from "./topics.js";+import Notes from "./notes.js";+import { useRoutes, navigate } from "hookrouter";+import RouteContainer from "../components/route-container";import { db } from "../common";+const routes = {+ "/": () => (+ <RouteContainer type="notebooks" title="Notebooks" route={<Notebooks />} />+ ),+ "/:notebook": ({ notebook }) => (+ <RouteContainer+ type="topics"+ title={db.notebooks.notebook(notebook).title}+ canGoBack+ route={<Topics notebookId={notebook} />}+ />+ ),+ "/:notebook/:topic": ({ notebook, topic }) => {+ const nb = db.notebooks.notebook(notebook);+ const topicItem = nb.topics.all[topic];+ if (!topicItem) return navigate(`/notebooks/${nb.id}`);++ return (+ <RouteContainer+ type="notes"+ title={nb.title}+ canGoBack+ subtitle={topicItem.title}+ route={+ <Notes+ context={{+ type: "topic",+ value: { id: notebook, topic: topicItem.title },+ }}+ />+ }+ />+ );+ },+};++function NotebooksContainer() {+ const routeResult = useRoutes(routes);+ return routeResult;+}+function Notebooks(props) {const [open, setOpen] = useState(false);useEffect(() => store.refresh(), []);const notebooks = useStore((state) => state.notebooks);const add = useStore((state) => state.add);- useEffect(() => {- if (props.id) {- const notebook = db.notebooks.notebook(props.id);- if (props.topic) {- props.navigator.navigate("notes", {- title: notebook.title,- subtitle: props.topic,- context: {- type: "topic",- value: { id: props.id, topic: props.topic },- },- });- } else {- props.navigator.navigate("topics", {- title: notebook.title,- topics: notebook.data.topics,- notebook: notebook.data,- });- }- }- }, [props.id, props.topic, props.navigator]);-return (<><ListContainer@@ -44,21 +67,10 @@ function Notebooks(props) {index={index}item={item}onClick={() => {- props.navigator.navigate("topics", {- title: item.title,- topics: item.topics,- notebook: item,- });+ navigate(`/notebooks/${item.id}`);}}onTopicClick={(notebook, topic) =>- props.navigator.navigate("notes", {- title: notebook.title,- subtitle: topic.title,- context: {- type: "topic",- value: { id: notebook.id, topic: topic.title },- },- })+ navigate(`/notebooks/${notebook.id}/${topic}`)}/>)}@@ -84,13 +96,4 @@ function Notebooks(props) {);}-/* function NotebooksContainer() {- return (- <NavigationContainer- variant="columnFill"- navigator={require("../navigation/navigators/nbnavigator").default}- />- );-} */--export default Notebooks;+export default NotebooksContainer;diff --git a/apps/web/src/views/Notes.js b/apps/web/src/views/notes.jssimilarity index 100%rename from apps/web/src/views/Notes.jsrename to apps/web/src/views/notes.jsdiff --git a/apps/web/src/views/Search.js b/apps/web/src/views/search.jssimilarity index 72%rename from apps/web/src/views/Search.jsrename to apps/web/src/views/search.jsindex c455be40a..d5b74a5df 100644--- a/apps/web/src/views/Search.js+++ b/apps/web/src/views/search.js@@ -4,12 +4,19 @@ import SearchInput from "../components/search";import { useStore } from "../stores/searchstore";import SearchPlaceholder from "../components/placeholders/search-placeholder";+window.addEventListener("load", () => {+ const path = window.location.pathname;+ if (path === "/search") window.location = "/";+});+function Search() {const results = useStore((store) => store.results);const item = useStore((store) => store.item);+ const type = useStore((store) => store.type);+return (<>- <SearchInput type={""} />+ <SearchInput type={type} /><ListContainernoSearchitems={results}diff --git a/apps/web/src/views/Settings.js b/apps/web/src/views/settings.jssimilarity index 100%rename from apps/web/src/views/Settings.jsrename to apps/web/src/views/settings.jsdiff --git a/apps/web/src/views/Tags.js b/apps/web/src/views/tags.jssimilarity index 64%rename from apps/web/src/views/Tags.jsrename to apps/web/src/views/tags.jsindex b7479c951..42d8ecf2a 100644--- a/apps/web/src/views/Tags.js+++ b/apps/web/src/views/tags.js@@ -4,6 +4,9 @@ import ListContainer from "../components/list-container";import ListItem from "../components/list-item";import { useStore, store } from "../stores/tag-store";import TagsPlaceholder from "../components/placeholders/tags-placeholder";+import Notes from "./notes";+import { useRoutes, navigate } from "hookrouter";+import RouteContainer from "../components/route-container";function TagNode({ title }) {return (@@ -16,11 +19,28 @@ function TagNode({ title }) {);}-function Tags(props) {+const routes = {+ "/": () => <RouteContainer title="Tags" route={<Tags />} />,+ "/:tag": ({ tag }) => (+ <RouteContainer+ type="notes"+ title={`#${tag}`}+ route={<Notes type="notes" context={{ type: "tag", value: tag }} />}+ />+ ),+};++function TagsContainer() {+ const routeResult = useRoutes(routes);+ return routeResult;+}++function Tags() {const tags = useStore((store) => store.tags);useEffect(() => {store.refresh();}, []);+return (<ListContainertype="tags"@@ -35,10 +55,7 @@ function Tags(props) {title={<TagNode title={title} />}info={`${noteIds.length} notes`}onClick={() => {- props.navigator.navigate("notes", {- title: "#" + title,- context: { type: "tag", value: title },- });+ navigate(`/tags/${title}`);}}/>);@@ -48,4 +65,4 @@ function Tags(props) {);}-export default Tags;+export default TagsContainer;diff --git a/apps/web/src/views/Topics.js b/apps/web/src/views/topics.jssimilarity index 55%rename from apps/web/src/views/Topics.jsrename to apps/web/src/views/topics.jsindex c24069731..f3ca57143 100644--- a/apps/web/src/views/Topics.js+++ b/apps/web/src/views/topics.js@@ -4,8 +4,11 @@ import { Flex } from "rebass";import ListContainer from "../components/list-container";import { useStore as useNbStore } from "../stores/notebook-store";import { showTopicDialog } from "../components/dialogs/topicdialog";+import { navigate } from "hookrouter";function Topics(props) {+ const { notebookId } = props;+const setSelectedNotebookTopics = useNbStore((store) => store.setSelectedNotebookTopics);@@ -19,38 +22,41 @@ function Topics(props) {}, [selectedNotebookTopics]);useEffect(() => {- setSelectedNotebookTopics(props.notebook.id);- }, [setSelectedNotebookTopics, props.notebook.id]);+ setSelectedNotebookTopics(notebookId);+ }, [setSelectedNotebookTopics, notebookId]);return (- <ListContainer- type="topics"- items={topics}- item={(index, item) => (- <Topic- index={index}- item={item}- onClick={() => {- let topic = item;- props.navigator.navigate("notes", {+ <>+ <ListContainer+ type="topics"+ items={topics}+ item={(index, item) => (+ <Topic+ index={index}+ item={item}+ onClick={() => {+ //let topic = item;+ navigate(`/notebooks/${notebookId}/${index}`);+ /* props.navigator.navigate("notes", {title: props.notebook.title,subtitle: topic.title,context: {type: "topic",value: { id: props.notebook.id, topic: topic.title },},- });- }}- />- )}- placeholder={Flex}- button={{- content: "Add more topics",- onClick: async () => {- await showTopicDialog(props.notebook.id);- },- }}- />+ }); */+ }}+ />+ )}+ placeholder={Flex}+ button={{+ content: "Add more topics",+ onClick: async () => {+ await showTopicDialog(props.notebook.id);+ },+ }}+ />+ </>);}export default Topics;diff --git a/apps/web/src/views/Trash.js b/apps/web/src/views/trash.jssimilarity index 100%rename from apps/web/src/views/Trash.jsrename to apps/web/src/views/trash.jsdiff --git a/apps/web/yarn.lock b/apps/web/yarn.lockindex 53d67d078..82d81886e 100644--- a/apps/web/yarn.lock+++ b/apps/web/yarn.lock@@ -1616,6 +1616,14 @@"@types/minimatch" "*""@types/node" "*"+"@types/hookrouter@^2.2.3":+ version "2.2.3"+ resolved "https://registry.yarnpkg.com/@types/hookrouter/-/hookrouter-2.2.3.tgz#edddbaa50acf2970aa1023ff8d2d9121d89e3d17"+ integrity sha512-cgkXYVf6xG59VSbKUt1/JMXnpEEc1UdqWjMKOMYXPy+U5fGScRqmqrdZNlKX9H07sAir82txWbi5356UvjEnxA==+ dependencies:+ "@types/react" "*"+ csstype "^3.0.2"+"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0":version "2.0.1"resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.1.tgz#42995b446db9a48a11a07ec083499a860e9138ff"@@ -1656,11 +1664,24 @@resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0"integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==+"@types/prop-types@*":+ version "15.7.3"+ resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.3.tgz#2ab0d5da2e5815f94b0b9d4b95d1e5f243ab2ca7"+ integrity sha512-KfRL3PuHmqQLOG+2tGpRO26Ctg+Cq1E01D2DMriKEATHgWLfeNDmq9e29Q9WIky0dQ3NPkd1mzYH8Lm936Z9qw==+"@types/q@^1.5.1":version "1.5.2"resolved "https://registry.yarnpkg.com/@types/q/-/q-1.5.2.tgz#690a1475b84f2a884fd07cd797c00f5f31356ea8"integrity sha512-ce5d3q03Ex0sy4R14722Rmt6MT07Ua+k4FwDfdcToYJcMKNtRVQvJ6JCAPdAmAnbRb6CsX6aYb9m96NGod9uTw==+"@types/react@*":+ version "16.9.49"+ resolved "https://registry.yarnpkg.com/@types/react/-/react-16.9.49.tgz#09db021cf8089aba0cdb12a49f8021a69cce4872"+ integrity sha512-DtLFjSj0OYAdVLBbyjhuV9CdGVHCkHn2R+xr3XkBvK2rS1Y1tkc14XSGjYgm5Fjjr90AxH9tiSzc1pCFMGO06g==+ dependencies:+ "@types/prop-types" "*"+ csstype "^3.0.2"+"@types/stack-utils@^1.0.1":version "1.0.1"resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-1.0.1.tgz#0a851d3bd96498fa25c33ab7278ed3bd65f06c3e"@@ -3592,6 +3613,11 @@ csstype@^2.5.7:resolved "https://registry.yarnpkg.com/csstype/-/csstype-2.6.10.tgz#e63af50e66d7c266edb6b32909cfd0aabe03928b"integrity sha512-D34BqZU4cIlMCY93rZHbrq9pjTAQJ3U8S8rfBqjwHxkGPThWFjzZDQpgMJY0QViLxth6ZKYiwFBo14RdN44U/w==+csstype@^3.0.2:+ version "3.0.3"+ resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.0.3.tgz#2b410bbeba38ba9633353aff34b05d9755d065f8"+ integrity sha512-jPl+wbWPOWJ7SXsWyqGRk3lGecbar0Cb0OvZF/r/ZU011R4YqiRehgkQ9p4eQfo9DSDLqLL3wHwfxeJiuIsNag==+cyclist@^1.0.1:version "1.0.1"resolved "https://registry.yarnpkg.com/cyclist/-/cyclist-1.0.1.tgz#596e9698fd0c80e12038c2b82d6eb1b35b6224d9"@@ -5220,6 +5246,11 @@ hoist-non-react-statics@^3.3.0:dependencies:react-is "^16.7.0"+hookrouter@^1.2.3:+ version "1.2.3"+ resolved "https://registry.yarnpkg.com/hookrouter/-/hookrouter-1.2.3.tgz#a65599a1be376b51734caf7c4f7f8aba59bb2c77"+ integrity sha512-n0mqEBGgXIxYRNMHlwCzoyTOk0OB5Es3jwUyA3+2l5nte/52n0CMMj1bmoCabC8K43YTUEr0zzexTBfo//tq2Q==+hosted-git-info@^2.1.4:version "2.8.8"resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.8.tgz#7539bd4bc1e0e0a895815a2e0262420b12858488"