A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
web: migrate navigation to typescript
Abdullah Attaeb8b58a559bf
diff --git a/apps/web/__e2e__/models/app.model.ts b/apps/web/__e2e__/models/app.model.tsindex ee4256e33..5a01aea04 100644--- a/apps/web/__e2e__/models/app.model.ts+++ b/apps/web/__e2e__/models/app.model.ts@@ -111,7 +111,7 @@ export class AppModel {async getRouteHeader() {if (!(await this.routeHeader.isVisible())) return;- return await this.routeHeader.inputValue();+ return await this.routeHeader.innerText();}async isSynced() {diff --git a/apps/web/package.json b/apps/web/package.jsonindex 6e935fd38..92b162064 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -17,6 +17,7 @@"@mdi/js": "^6.9.96","@mdi/react": "^1.6.0","@notesnook-importer/core": "^1.7.1",+ "@notesnook/common": "*","@notesnook/core": "*","@notesnook/crypto": "*","@notesnook/crypto-worker": "*",@@ -26,7 +27,6 @@"@notesnook/logger": "*","@notesnook/streamable-fs": "*","@notesnook/theme": "*",- "@notesnook/common": "*","@notesnook/web-clipper": "*","@react-pdf-viewer/core": "^3.12.0","@react-pdf-viewer/toolbar": "^3.12.0",diff --git a/apps/web/src/common/index.js b/apps/web/src/common/index.jsindex 924bdda66..c3a6d697f 100644--- a/apps/web/src/common/index.js+++ b/apps/web/src/common/index.js@@ -50,10 +50,6 @@ export const CREATE_BUTTON_MAP = {title: "Create a notebook",onClick: () => hashNavigate("/notebooks/create", { replace: true })},- notebook: {- title: "Add a note",- onClick: () => hashNavigate(`/notes/create`, { replace: true })- },topics: {title: "Create a topic",onClick: () => hashNavigate(`/topics/create`, { replace: true })diff --git a/apps/web/src/components/cached-router/index.jsx b/apps/web/src/components/cached-router/index.tsxsimilarity index 51%rename from apps/web/src/components/cached-router/index.jsxrename to apps/web/src/components/cached-router/index.tsxindex a97328a1b..5d290314e 100644--- a/apps/web/src/components/cached-router/index.jsx+++ b/apps/web/src/components/cached-router/index.tsx@@ -17,16 +17,14 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { useEffect } from "react";-import ReactDOM from "react-dom";+import React, { useEffect, useRef } from "react";import { getHomeRoute, NavigationEvents } from "../../navigation";import { store as selectionStore } from "../../stores/selection-store";import useRoutes from "../../hooks/use-routes";import RouteContainer from "../route-container";-import ThemeProvider from "../theme-provider";import routes from "../../navigation/routes";+import { Flex } from "@theme-ui/components";-var cache = {};function CachedRouter() {const [RouteResult, location] = useRoutes(routes, {fallbackRoute: getHomeRoute(),@@ -34,58 +32,38 @@ function CachedRouter() {beforeNavigate: () => selectionStore.toggleSelectionMode(false)}});+ const cachedRoutes = useRef<Record<string, React.FunctionComponent>>({});useEffect(() => {if (!RouteResult) return;NavigationEvents.publish("onNavigate", RouteResult, location);- window.currentViewType = RouteResult.type;- window.currentViewKey = RouteResult.key;-- const key = RouteResult.key || "general";-- const routeContainer = document.getElementById("mainRouteContainer");- routeContainer.childNodes.forEach((node) => {- node.style.display = "none";- });-- var route = document.getElementById(key);- if (route) {- route.style.display = "flex";- if (key !== "general") return;- else {- route.remove();- route = undefined;- }- } else {- cache[key] = false;- }-- if (!cache[key]) {- if (!route) {- cache[key] = key !== "general";- route = document.createElement("div");- route.id = key;- route.className = "route";- routeContainer.appendChild(route);- }- ReactDOM.render(- <ThemeProvider>{RouteResult.component}</ThemeProvider>,- route- );- }}, [RouteResult, location]);+ if (!RouteResult) return null;+ if (RouteResult.key === "general" || !cachedRoutes.current[RouteResult.key])+ cachedRoutes.current[RouteResult.key] = RouteResult.component;+return (<RouteContainer- id="mainRouteContainer"- type={RouteResult?.type}- title={RouteResult?.title}- subtitle={RouteResult?.subtitle}- buttons={RouteResult?.buttons}- isEditable={RouteResult?.isEditable}- onChange={RouteResult?.onChange}- />+ type={RouteResult.type}+ title={RouteResult.title}+ buttons={RouteResult.buttons}+ >+ {Object.entries(cachedRoutes.current).map(([key, Component]) => (+ <Flex+ id={key}+ key={key}+ sx={{+ display: key === RouteResult.key ? "flex" : "none",+ flexDirection: "column",+ flex: 1+ }}+ >+ <Component key={key} />+ </Flex>+ ))}+ </RouteContainer>);}-export default CachedRouter;+export default React.memo(CachedRouter, () => true);diff --git a/apps/web/src/components/hash-router/index.jsx b/apps/web/src/components/hash-router/index.tsxsimilarity index 93%rename from apps/web/src/components/hash-router/index.jsxrename to apps/web/src/components/hash-router/index.tsxindex af9d43748..2e3968c0f 100644--- a/apps/web/src/components/hash-router/index.jsx+++ b/apps/web/src/components/hash-router/index.tsx@@ -23,6 +23,6 @@ import hashroutes from "../../navigation/hash-routes";function HashRouter() {const routeResult = useHashRoutes(hashroutes);- return routeResult || null;+ return React.isValidElement(routeResult) ? routeResult : null;}export default React.memo(HashRouter, () => true);diff --git a/apps/web/src/components/route-container/index.jsx b/apps/web/src/components/route-container/index.tsxsimilarity index 50%rename from apps/web/src/components/route-container/index.jsxrename to apps/web/src/components/route-container/index.tsxindex 5e1ef2a0d..ab97c1bb8 100644--- a/apps/web/src/components/route-container/index.jsx+++ b/apps/web/src/components/route-container/index.tsx@@ -17,50 +17,49 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { useEffect, useRef, useState } from "react";+import { PropsWithChildren } from "react";import { Flex, Text } from "@theme-ui/components";import { ArrowLeft, Menu, Search, Plus } from "../icons";import { useStore } from "../../stores/app-store";-import { CREATE_BUTTON_MAP } from "../../common";import useMobile from "../../hooks/use-mobile";import { navigate } from "../../navigation";-import { Input } from "@theme-ui/components";-function RouteContainer(props) {- const {- id,- type,- title,- isEditable,- onChange,- subtitle,- buttons,- component- } = props;+export type RouteContainerButtons = {+ search?: {+ title: string;+ };+ back?: {+ title: string;+ onClick: () => void;+ };+ create?: {+ title: string;+ onClick: () => void;+ };+};++export type RouteContainerProps = {+ type: string;+ title?: string;+ buttons?: RouteContainerButtons;+};+function RouteContainer(props: PropsWithChildren<RouteContainerProps>) {+ const { type, title, buttons, children } = props;return (<>- <Header- type={type}- title={title}- subtitle={subtitle}- buttons={buttons}- isEditable={isEditable}- onChange={onChange}- />- {component || <Flex id={id} sx={{ flex: 1, flexDirection: "column" }} />}+ <Header type={type} title={title} buttons={buttons} />+ {children}</>);}export default RouteContainer;-function Header(props) {- const { title, subtitle, onChange, buttons, type, isEditable } = props;- const createButtonData = CREATE_BUTTON_MAP[type];+function Header(props: RouteContainerProps) {+ const { title, buttons, type } = props;const toggleSideMenu = useStore((store) => store.toggleSideMenu);const isMobile = useMobile();- // if (!subtitle) return null;return (<Flex mx={2} sx={{ flexDirection: "column", justifyContent: "center" }}><Flex sx={{ alignItems: "center", justifyContent: "space-between" }}>@@ -68,8 +67,7 @@ function Header(props) {{buttons?.back ? (<ArrowLeftsize={24}- title={buttons.back.title}- onClick={buttons.back.action}+ {...buttons.back}sx={{ flexShrink: 0, mr: 2, cursor: "pointer" }}color="text"data-test-id="go-back"@@ -88,12 +86,9 @@ function Header(props) {/>)}{title && (- <RouteTitle- subtitle={subtitle}- title={title}- isEditable={isEditable}- onChange={onChange}- />+ <Text variant="heading" data-test-id="routeHeader" color="text">+ {title}+ </Text>)}</Flex><Flex sx={{ flexShrink: 0 }}>@@ -105,8 +100,7 @@ function Header(props) {onClick={() => navigate(`/search/${type}`)}/>)}-- {!isMobile && createButtonData && (+ {!isMobile && buttons?.create && (<Plusdata-test-id={`${type}-action-button`}color="static"@@ -118,8 +112,7 @@ function Header(props) {size: 28,":hover": { boxShadow: "0px 0px 5px 0px var(--dimPrimary)" }}}- title={createButtonData.title}- onClick={createButtonData.onClick}+ {...buttons.create}/>)}</Flex>@@ -127,57 +120,3 @@ function Header(props) {</Flex>);}--function RouteTitle({ title, subtitle, isEditable, onChange }) {- const [isEditing, setIsEditing] = useState(false);- const ref = useRef();- useEffect(() => {- ref.current.value = title;- }, [title]);-- return (- <Flex sx={{ flexDirection: "column" }}>- {subtitle && <Text variant="subBody">{subtitle}</Text>}- <Input- ref={ref}- variant="clean"- data-test-id="routeHeader"- title={title}- sx={{- overflow: "hidden",- textOverflow: isEditing ? "initial" : "ellipsis",- whiteSpace: "nowrap",-- p: 0,- m: 0,- fontWeight: "bold",- fontFamily: "heading",- fontSize: subtitle ? "subheading" : "heading",- border: "none",- bg: isEditing ? "bgSecondary" : "transparent",-- ":focus-visible": { outline: "none" },- color: "text"- }}- onDoubleClick={(e) => {- setIsEditing(isEditable && true);- e.target.focus();- }}- onKeyUp={(e) => {- if (e.key === "Escape") {- e.target.value = title;- setIsEditing(false);- } else if (e.key === "Enter") {- if (onChange) onChange(e.target.value);- setIsEditing(false);- }- }}- onBlur={(e) => {- if (onChange) onChange(e.target.value);- setIsEditing(false);- }}- readOnly={!isEditing}- />- </Flex>- );-}diff --git a/apps/web/src/hooks/use-hash-routes.js b/apps/web/src/hooks/use-hash-routes.tsxsimilarity index 78%rename from apps/web/src/hooks/use-hash-routes.jsrename to apps/web/src/hooks/use-hash-routes.tsxindex 22bd456d2..a06b90560 100644--- a/apps/web/src/hooks/use-hash-routes.js+++ b/apps/web/src/hooks/use-hash-routes.tsx@@ -19,17 +19,20 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import makeMatcher from "wouter/matcher";import useHashLocation from "./use-hash-location";+import { Params, Routes } from "../navigation/types";-var lastRoute = null;-export default function useHashRoutes(routes) {+let lastRoute: unknown | null = null;+export default function useHashRoutes<T extends string, TRouteResult>(+ routes: Routes<T, TRouteResult>+) {const [{ location, update }] = useHashLocation();if (!update) return lastRoute;const matcher = makeMatcher();- for (var key in routes) {+ for (const key in routes) {const [match, params] = matcher(key, location);if (match) {- const route = routes[key](params);+ const route = routes[key]((params as Params<typeof key>) || {});if (!route) return lastRoute;lastRoute = route;return route;diff --git a/apps/web/src/hooks/use-routes.js b/apps/web/src/hooks/use-routes.tssimilarity index 72%rename from apps/web/src/hooks/use-routes.jsrename to apps/web/src/hooks/use-routes.tsindex b9d4e0169..539e64f84 100644--- a/apps/web/src/hooks/use-routes.js+++ b/apps/web/src/hooks/use-routes.ts@@ -20,8 +20,15 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { useLocation } from "wouter";import makeMatcher from "wouter/matcher";import { navigate, getHomeRoute } from "../navigation";+import { Params, Routes } from "../navigation/types";-export default function useRoutes(routes, options) {+export default function useRoutes<T extends string, TRouteResult>(+ routes: Routes<T, TRouteResult>,+ options?: {+ hooks?: { beforeNavigate: (location: string) => void };+ fallbackRoute?: string;+ }+) {const [location] = useLocation();const matcher = makeMatcher();@@ -29,18 +36,18 @@ export default function useRoutes(routes, options) {options?.hooks?.beforeNavigate(location);- for (var key in routes) {+ for (const key in routes) {const [match, params] = matcher(key, location);if (match) {- const result = routes[key](params);+ const result = routes[key]((params as Params<typeof key>) || {});if (!result) break;- return [result, location];+ return [result, location] as const;}}- if (!options) return [];+ if (!options) return [] as const;const { fallbackRoute } = options;if (fallbackRoute) {navigate(fallbackRoute);}- return [];+ return [] as const;}diff --git a/apps/web/src/navigation/hash-routes.tsx b/apps/web/src/navigation/hash-routes.tsxindex dafc2da77..e0dda9071 100644--- a/apps/web/src/navigation/hash-routes.tsx+++ b/apps/web/src/navigation/hash-routes.tsx@@ -44,8 +44,9 @@ import {} from "../common/dialog-controller";import { hashNavigate } from ".";import Editor from "../components/editor";+import { defineRoutes } from "./types";-const hashroutes = {+const hashroutes = defineRoutes({"/": () => {return (!editorStore.get().session.state && <Editor noteId={0} nonce={"-1"} />@@ -57,7 +58,7 @@ const hashroutes = {"/notebooks/create": () => {showAddNotebookDialog().then(afterAction);},- "/notebooks/:notebookId/edit": ({ notebookId }: { notebookId: string }) => {+ "/notebooks/:notebookId/edit": ({ notebookId }) => {showEditNotebookDialog(notebookId)?.then(afterAction);},"/topics/create": () => {@@ -66,7 +67,7 @@ const hashroutes = {"/reminders/create": () => {showAddReminderDialog().then(afterAction);},- "/reminders/:reminderId/edit": ({ reminderId }: { reminderId: string }) => {+ "/reminders/:reminderId/edit": ({ reminderId }) => {showEditReminderDialog(reminderId).then(afterAction);},"/notebooks/:notebookId/topics/:topicId/edit": ({@@ -81,31 +82,32 @@ const hashroutes = {"/tags/create": () => {showCreateTagDialog().then(afterAction);},- "/tags/:tagId/edit": ({ tagId }: { tagId: string }) => {+ "/tags/:tagId/edit": ({ tagId }) => {showEditTagDialog(tagId)?.then(afterAction);},"/notes/create": () => {closeOpenedDialog();hashNavigate("/notes/create", { addNonce: true, replace: true });},- "/notes/create/:nonce": ({ nonce }: { nonce: string }) => {+ "/notes/create/:nonce": ({ nonce }) => {closeOpenedDialog();return <Editor noteId={0} nonce={nonce} />;},- "/notes/:noteId/edit": ({ noteId }: { noteId: string }) => {+ "/notes/:noteId/edit": ({ noteId }) => {closeOpenedDialog();return <Editor noteId={noteId} />;},- "/notes/:noteId/unlock": ({ noteId }: { noteId: string }) => {+ "/notes/:noteId/unlock": ({ noteId }) => {closeOpenedDialog();return (<RouteContainer+ type="unlock"buttons={{back: isMobile()? {title: "Go back",- action: () =>+ onClick: () =>hashNavigate("/notes/create", {addNonce: true,replace: true@@ -113,11 +115,12 @@ const hashroutes = {}: undefined}}- component={<Unlock noteId={noteId} />}- />+ >+ <Unlock noteId={noteId} />+ </RouteContainer>);},- "/notes/:noteId/conflict": ({ noteId }: { noteId: string }) => {+ "/notes/:noteId/conflict": ({ noteId }) => {closeOpenedDialog();return <DiffViewer noteId={noteId} />;},@@ -127,14 +130,10 @@ const hashroutes = {"/buy/:code": ({ code }: { code: string }) => {showBuyDialog("monthly", code).then(afterAction);},- "/buy/:plan/:code": ({- plan,- code- }: {- plan: "monthly" | "yearly";- code: string;- }) => {- showBuyDialog(plan, code).then(afterAction);+ "/buy/:plan/:code": ({ plan, code }) => {+ showBuyDialog(plan === "monthly" ? "monthly" : "yearly", code).then(+ afterAction+ );},"/welcome": () => {showOnboardingDialog("new")?.then(afterAction);@@ -145,7 +144,7 @@ const hashroutes = {"/settings": () => {showSettings().then(afterAction);}-};+});export default hashroutes;export type HashRoute = keyof typeof hashroutes;diff --git a/apps/web/src/navigation/index.ts b/apps/web/src/navigation/index.tsindex 28424ed0d..818c8760c 100644--- a/apps/web/src/navigation/index.ts+++ b/apps/web/src/navigation/index.ts@@ -20,23 +20,23 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { useState } from "react";import EventManager from "@notesnook/core/utils/event-manager";import Config from "../utils/config";+import { HashRoute } from "./hash-routes";+import { ReplaceParametersInPath } from "./types";+export function navigate(url: string): void;+export function navigate(url: string, replace?: boolean): void;+export function navigate(+ url: string,+ query?: URLSearchParams,+ replace?: boolean+): void;export function navigate(url: string,replaceOrQuery?: boolean | URLSearchParams,replace?: boolean) {- 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();+ url += "?" + replaceOrQuery.toString();} else if (replace === undefined && replaceOrQuery !== undefined) {replace = replaceOrQuery;} else if (replace === undefined && replaceOrQuery === undefined) {@@ -50,12 +50,20 @@ export function navigate(dispatchEvent(new PopStateEvent("popstate"));}-let last = 0;-export function hashNavigate(- url: string,- { replace = false, notify = true, addNonce = false } = {}+type HashNavigateOptions = {+ replace?: boolean;+ notify?: boolean;+ addNonce?: boolean;+};++let lastNonce = 0;+export function hashNavigate<TPath extends HashRoute>(+ path: ReplaceParametersInPath<TPath>,+ options: HashNavigateOptions = {}) {- if (addNonce) url += `/${++last}`;+ const { replace = false, notify = true, addNonce = false } = options;+ let url: string = path;+ if (addNonce) url += `/${++lastNonce}`;if (replace) window.history.replaceState(null, "", `#${url}`);else window.history.pushState(null, "", `#${url}`);@@ -99,7 +107,7 @@ const HOMEPAGE_ROUTE = {1: "/notebooks",2: "/favorites",3: "/tags"-};+} as const;export function getHomeRoute() {return HOMEPAGE_ROUTE[Config.get("homepage", 0)];}diff --git a/apps/web/src/navigation/routes.tsx b/apps/web/src/navigation/routes.tsxindex b7f706f0c..d8cb0f2ad 100644--- a/apps/web/src/navigation/routes.tsx+++ b/apps/web/src/navigation/routes.tsx@@ -29,31 +29,51 @@ import Trash from "../views/trash";import { store as notestore } from "../stores/note-store";import { store as nbstore } from "../stores/notebook-store";import Reminders from "../views/reminders";+import { defineRoutes } from "./types";+import React from "react";+import { RouteContainerButtons } from "../components/route-container";+import { CREATE_BUTTON_MAP } from "../common";-const routes = {- "/notes": () => ({- key: "home",- type: "notes",- title: "Notes",- component: <Home />,- buttons: {- search: {- title: "Search notes"+type RouteResult = {+ key: string;+ type: "notes" | "notebooks" | "reminders" | "trash" | "tags" | "search";+ title?: string;+ component: React.FunctionComponent;+ buttons?: RouteContainerButtons;+};++function defineRoute(route: RouteResult): RouteResult {+ return route;+}++const routes = defineRoutes({+ "/notes": () =>+ defineRoute({+ key: "home",+ type: "notes",+ title: "Notes",+ component: Home,+ buttons: {+ create: CREATE_BUTTON_MAP.notes,+ search: {+ title: "Search notes"+ }}- }- }),- "/notebooks": () => ({- key: "notebooks",- type: "notebooks",- title: "Notebooks",- component: <Notebooks />,- buttons: {- search: {- title: "Search notebooks"+ }),+ "/notebooks": () =>+ defineRoute({+ key: "notebooks",+ type: "notebooks",+ title: "Notebooks",+ component: Notebooks,+ buttons: {+ create: CREATE_BUTTON_MAP.notebooks,+ search: {+ title: "Search notebooks"+ }}- }- }),- "/notebooks/:notebookId": ({ notebookId }: { notebookId: string }) => {+ }),+ "/notebooks/:notebookId": ({ notebookId }) => {const notebook = db.notebooks?.notebook(notebookId);if (!notebook) return false;nbstore.setSelectedNotebook(notebookId);@@ -62,28 +82,23 @@ const routes = {value: { id: notebookId }});- return {+ return defineRoute({key: "notebook",type: "notes",- component: <Topics />,+ component: Topics,buttons: {+ create: CREATE_BUTTON_MAP.notes,back: {title: "Go back to notebooks",- action: () => navigate("/notebooks")+ onClick: () => navigate("/notebooks")},search: {title: `Search ${notebook.title} notes`}}- };+ });},- "/notebooks/:notebookId/:topicId": ({- notebookId,- topicId- }: {- notebookId: string;- topicId: string;- }) => {+ "/notebooks/:notebookId/:topicId": ({ notebookId, topicId }) => {const notebook = db.notebooks?.notebook(notebookId);const topic = notebook?.topics?.topic(topicId)?._topic;if (!topic) return false;@@ -92,137 +107,149 @@ const routes = {type: "topic",value: { id: notebookId, topic: topicId }});- return {+ return defineRoute({key: "notebook",type: "notes",title: topic.title,- component: <Topics />,+ component: Topics,buttons: {+ create: CREATE_BUTTON_MAP.notes,back: {title: `Go back to ${notebook.title}`,- action: () => navigate(`/notebooks/${notebookId}`)+ onClick: () => navigate(`/notebooks/${notebookId}`)},search: {title: `Search ${notebook.title} ${topic.title} notes`}}- };+ });},"/favorites": () => {notestore.setContext({ type: "favorite" });- return {+ return defineRoute({key: "notes",title: "Favorites",type: "notes",- component: <Notes />,+ component: Notes,buttons: {search: {title: "Search favorite notes"}}- };+ });},"/reminders": () => {- return {+ return defineRoute({key: "reminders",title: "Reminders",type: "reminders",- component: <Reminders />,+ component: Reminders,buttons: {+ create: CREATE_BUTTON_MAP.reminders,search: {title: "Search reminders"}}- };+ });},- "/trash": () => ({- key: "trash",- type: "trash",- title: "Trash",- component: <Trash />,- buttons: {- search: {- title: "Search trash"+ "/trash": () =>+ defineRoute({+ key: "trash",+ type: "trash",+ title: "Trash",+ component: Trash,+ buttons: {+ search: {+ title: "Search trash"+ }}- }- }),- "/tags": () => ({- key: "tags",- title: "Tags",- type: "tags",- component: <Tags />,- buttons: {- search: {- title: "Search tags"+ }),+ "/tags": () =>+ defineRoute({+ key: "tags",+ title: "Tags",+ type: "tags",+ component: Tags,+ buttons: {+ create: CREATE_BUTTON_MAP.tags,+ search: {+ title: "Search tags"+ }}- }- }),- "/tags/:tagId": ({ tagId }: { tagId: string }) => {+ }),+ "/tags/:tagId": ({ tagId }) => {const tag = db.tags?.tag(tagId);if (!tag) return false;const { id } = tag;notestore.setContext({ type: "tag", value: id });const title = db.tags?.alias(id);- return {+ return defineRoute({key: "notes",type: "notes",title: `#${title}`,- component: <Notes />,+ component: Notes,buttons: {+ create: CREATE_BUTTON_MAP.notes,back: {title: "Go back to tags",- action: () => navigate("/tags")+ onClick: () => navigate("/tags")},search: {title: `Search #${title} notes`}}- };+ });},- "/colors/:colorId": ({ colorId }: { colorId: string }) => {+ "/colors/:colorId": ({ colorId }) => {const color = db.colors?.tag(colorId);- if (!color) return navigate("/");+ if (!color) {+ navigate("/");+ return false;+ }const { id } = color;const title = db.colors?.alias(id);notestore.setContext({ type: "color", value: id });- return {+ return defineRoute({key: "notes",type: "notes",title: title,- component: <Notes />,+ component: Notes,buttons: {+ create: CREATE_BUTTON_MAP.notes,search: {title: `Search ${title} colored notes`}}- };+ });},"/monographs": () => {notestore.setContext({ type: "monographs" });- return {+ return defineRoute({key: "notes",title: "Monographs",type: "notes",- component: <Notes />,+ component: Notes,buttons: {search: {title: "Search monograph notes"}}- };+ });},- "/search/:type": ({ type }: { type: string }) => ({- type: "search",- title: "Search",- component: <Search type={type} />,- buttons: {- back: {- title: `Go back to ${type}`,- action: () => window.history.back()+ "/search/:type": ({ type }) =>+ defineRoute({+ key: "general",+ type: "search",+ title: "Search",+ component: () => <Search type={type} />,+ buttons: {+ back: {+ title: `Go back to ${type}`,+ onClick: () => window.history.back()+ }}- }- })-};+ })+});export default routes;export type Route = keyof typeof routes;diff --git a/apps/web/src/navigation/types.ts b/apps/web/src/navigation/types.tsnew file mode 100644index 000000000..8565fe105--- /dev/null+++ b/apps/web/src/navigation/types.ts@@ -0,0 +1,45 @@+/*+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/>.+*/++type IsParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : never;++type FilteredParts<Path> = Path extends `${infer PartA}/${infer PartB}`+ ? IsParameter<PartA> | FilteredParts<PartB>+ : IsParameter<Path>;++type ReplaceParameter<Part> = Part extends `:${string}` ? string : Part;++export type ReplaceParametersInPath<Path> =+ Path extends `${infer PartA}/${infer PartB}`+ ? `${ReplaceParameter<PartA>}/${ReplaceParametersInPath<PartB>}`+ : ReplaceParameter<Path>;++export type Params<Path> = {+ [Key in FilteredParts<Path>]: string;+};++export type Routes<T extends string, TRouteResult> = {+ [Path in T]: (params: Params<Path>) => TRouteResult | void;+};++export function defineRoutes<T extends string, TRouteResult>(+ routes: Routes<T, TRouteResult>+): Routes<T, TRouteResult> {+ return routes;+}