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: add support for table of contents
Abdullah Attab0b5bd235f40
diff --git a/apps/web/src/components/editor/action-bar.tsx b/apps/web/src/components/editor/action-bar.tsxindex 84082e79e..36d4058ac 100644--- a/apps/web/src/components/editor/action-bar.tsx+++ b/apps/web/src/components/editor/action-bar.tsx@@ -30,6 +30,7 @@ import {Pin,Properties,Search,+ TableOfContents,Unlock} from "../icons";import { ScrollContainer } from "@notesnook/ui";@@ -86,6 +87,15 @@ export function EditorActionBar() {setIsFullscreen((s) => !s);}},+ {+ title: "Table of contents",+ icon: TableOfContents,+ enabled:+ activeSession &&+ activeSession.type !== "new" &&+ activeSession.type !== "locked",+ onClick: () => useEditorStore.getState().toggleTableOfContents()+ },{title: "Search",icon: Search,diff --git a/apps/web/src/components/editor/index.tsx b/apps/web/src/components/editor/index.tsxindex 13e4da735..92aa2bcaa 100644--- a/apps/web/src/components/editor/index.tsx+++ b/apps/web/src/components/editor/index.tsx@@ -62,6 +62,7 @@ import { Freeze } from "react-freeze";import { EditorActionBar } from "./action-bar";import { UnlockView } from "../unlock";import DiffViewer from "../diff-viewer";+import TableOfContents from "./table-of-contents";const PDFPreview = React.lazy(() => import("../pdf-preview"));@@ -147,6 +148,7 @@ function EditorView({ id }: { id: string }) {const arePropertiesVisible = useEditorStore((store) => store.arePropertiesVisible);+ const isTOCVisible = useEditorStore((store) => store.isTOCVisible);const toggleProperties = useEditorStore((store) => store.toggleProperties);const isReadonly = useEditorStore((store) => store.getSession(id, ["default"])?.note?.readonly@@ -287,8 +289,6 @@ function EditorView({ id }: { id: string }) {isMobile: isMobile || isTablet}}/>-- {arePropertiesVisible && <Properties id={id} />}<DropZone id={id} overlayRef={overlayRef} /></Flex></Allotment.Pane>@@ -328,6 +328,8 @@ function EditorView({ id }: { id: string }) {</Allotment.Pane>)}</Allotment>+ {arePropertiesVisible && <Properties id={id} />}+ {isTOCVisible && <TableOfContents id={id} />}</ScopedThemeProvider>);}@@ -437,6 +439,7 @@ export function Editor(props: EditorProps) {}}onLoad={() => {restoreSelection(id);+ restoreScrollPosition(id);setIsLoading(false);}}onSelectionChange={({ from, to }) =>@@ -524,7 +527,7 @@ function EditorChrome(};const editorMargins = useEditorStore((store) => store.editorMargins);const editorContainerRef = useRef<HTMLElement>(null);- const editorScrollRef = useRef<HTMLElement>();+ const editorScrollRef = useRef<HTMLElement>(null);useEffect(() => {if (!editorScrollRef.current) return;@@ -580,10 +583,7 @@ function EditorChrome({/* <Toolbar /> */}<FlexScrollContainerid={`${id}_editorScroll`}- scrollRef={(ref) => {- editorScrollRef.current = ref || undefined;- restoreScrollPosition(id);- }}+ scrollRef={editorScrollRef}style={{display: "flex",flexDirection: "column",diff --git a/apps/web/src/components/editor/manager.ts b/apps/web/src/components/editor/manager.tsindex af3607783..58b6aead8 100644--- a/apps/web/src/components/editor/manager.ts+++ b/apps/web/src/components/editor/manager.ts@@ -21,20 +21,17 @@ import { useCallback } from "react";import { IEditor, NoteStatistics } from "./types";import createStore from "../../common/store";import BaseStore from "../../stores";-import type { ToolbarDefinition } from "@notesnook/editor";+import type { TOCItem, ToolbarDefinition } from "@notesnook/editor";import Config from "../../utils/config";import { getCurrentPreset } from "../../common/toolbar-config";type EditorConfig = { fontFamily: string; fontSize: number };-type EditorState = {- selection?: { from: number; to: number };- scrollPosition?: number;-};type EditorContext = {editor?: IEditor;canUndo?: boolean;canRedo?: boolean;statistics?: NoteStatistics;+ tableOfContents?: TOCItem[];};class EditorManager extends BaseStore<EditorManager> {diff --git a/apps/web/src/components/editor/table-of-contents.tsx b/apps/web/src/components/editor/table-of-contents.tsxnew file mode 100644index 000000000..318191838--- /dev/null+++ b/apps/web/src/components/editor/table-of-contents.tsx@@ -0,0 +1,167 @@+/*+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/>.+*/++/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import React, { useEffect, useState } from "react";+import { ArrowLeft } from "../icons";+import { useEditorStore } from "../../stores/editor-store";+import { AnimatedFlex } from "../animated";+import ScrollContainer from "../scroll-container";+import { ScopedThemeProvider } from "../theme-provider";+import { Section } from "../properties";+import { scrollIntoViewById } from "@notesnook/editor";+import { Button, Flex } from "@theme-ui/components";+import { useEditorManager } from "./manager";++type TableOfContentsProps = {+ id: string;+};+function TableOfContents(props: TableOfContentsProps) {+ const { id } = props;++ const [active, setActive] = useState<string[]>([]);+ const toggleTableOfContents = useEditorStore(+ (store) => store.toggleTableOfContents+ );+ const session = useEditorStore((store) =>+ store.getSession(id, ["default", "unlocked", "readonly"])+ );+ const tableOfContents = useEditorManager(+ (store) => store.editors[id].tableOfContents || []+ );++ useEffect(() => {+ const editorScroll = document.getElementById(`${id}_editorScroll`);+ if (!editorScroll) return;+ function onScroll() {+ const scrollTop = editorScroll?.scrollTop || 0;+ const height = editorScroll?.clientHeight || 0;+ const active = tableOfContents.filter((t, i, array) => {+ const next = array.at(i + 1);+ const viewport = scrollTop + height - 160;+ const lessThanNext = next ? scrollTop <= next.top : true;+ const isInViewport = t.top <= viewport && t.top >= scrollTop;+ const isActive = scrollTop >= t.top && lessThanNext;+ return isInViewport || isActive;+ });+ setActive(active.map((a) => a.id));+ }+ editorScroll.addEventListener("scroll", onScroll);+ onScroll();+ return () => {+ editorScroll.removeEventListener("scroll", onScroll);+ };+ }, [id]);++ if (!session) return null;+ return (+ <AnimatedFlex+ animate={{+ x: 0+ }}+ transition={{+ duration: 0.1,+ bounceDamping: 1,+ bounceStiffness: 1,+ ease: "easeOut"+ }}+ initial={{ x: 600 }}+ sx={{+ display: "flex",+ position: "absolute",+ right: 0,+ top: 0,+ zIndex: 1,+ height: "100%",+ width: "300px",+ borderLeft: "1px solid",+ borderLeftColor: "border"+ }}+ >+ <ScopedThemeProvider+ scope="editorSidebar"+ sx={{+ flex: 1,+ display: "flex",+ bg: "background",+ overflowY: "hidden",+ overflowX: "hidden",+ flexDirection: "column"+ }}+ >+ <ScrollContainer>+ <Section+ title="Table of contents"+ button={+ <ArrowLeft+ data-test-id="toc-close"+ onClick={() => toggleTableOfContents(false)}+ size={18}+ sx={{ mr: 1, cursor: "pointer" }}+ />+ }+ >+ <Flex sx={{ mt: 2, flexDirection: "column" }}>+ {tableOfContents.map((t) => (+ <Button+ variant="menuitem"+ key={t.id}+ sx={{+ textAlign: "left",+ paddingLeft: `${t.level * 5}px`,+ py: 1,+ borderLeft: "5px solid transparent",+ borderColor: active.includes(t.id)+ ? "accent-selected"+ : "transparent",+ color: active.includes(t.id)+ ? "accent-selected"+ : "paragraph"+ }}+ onClick={() => scrollIntoViewById(t.id)}+ >+ {t.title}+ </Button>+ ))}+ </Flex>+ </Section>+ </ScrollContainer>+ </ScopedThemeProvider>+ </AnimatedFlex>+ );+}+export default React.memo(TableOfContents);diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsxindex bb44c3bb9..8a92d14cb 100644--- a/apps/web/src/components/editor/tiptap.tsx+++ b/apps/web/src/components/editor/tiptap.tsx@@ -35,7 +35,8 @@ import {countWords,getFontById,TiptapOptions,- Attachment+ Attachment,+ getTableOfContents} from "@notesnook/editor";import { Box, Flex } from "@theme-ui/components";import { useState } from "react";@@ -53,7 +54,6 @@ import {useToolbarConfig,useEditorManager} from "./manager";-import { createPortal } from "react-dom";import { useIsUserPremium } from "../../hooks/use-is-user-premium";import { showBuyDialog } from "../../common/dialog-controller";import { useStore as useSettingsStore } from "../../stores/setting-store";@@ -61,6 +61,8 @@ import { debounce } from "@notesnook/common";import { ScopedThemeProvider } from "../theme-provider";import { writeText } from "clipboard-polyfill";import { useStore as useThemeStore } from "../../stores/theme-store";+import { toBlobURL } from "@notesnook/editor/dist/utils/downloader";+import { getChangedNodes } from "@notesnook/editor/dist/utils/prosemirror";export type OnChangeHandler = (content: () => string,@@ -199,11 +201,22 @@ function TipTap(props: TipTapProps) {total: getTotalWords(editor as Editor),selected: 0}- }+ },+ tableOfContents: getTableOfContents(editor.view.dom)});editor.commands.refreshSearch();},onUpdate: ({ editor, transaction }) => {+ const changedHeadings = getChangedNodes(transaction, {+ descend: false,+ predicate: (n) => n.isBlock && n.type.name === "heading"+ });+ if (changedHeadings.length > 0) {+ useEditorManager.getState().updateEditor(id, {+ tableOfContents: getTableOfContents(editor.view.dom)+ });+ }+onContentChange?.();deferredUpdateWordCount(id, () => editor.state.doc.content);@@ -212,7 +225,6 @@ function TipTap(props: TipTapProps) {const ignoreEdit = transaction.getMeta("ignoreEdit") as boolean;if (preventSave || !editor.isEditable || !onChange) return;- console.log("CHANGING", onChange);onChange(() => getHTMLFromFragment(editor.state.doc.content, editor.schema),ignoreEdit@@ -413,16 +425,6 @@ function TiptapWrapper(}export default TiptapWrapper;-function Portal(props: PropsWithChildren<{ containerId?: string }>) {- const { containerId, children } = props;- const container = containerId && document.getElementById(containerId);- return container ? (- <>{createPortal(children, container, containerId)}</>- ) : (- <>{children}</>- );-}-function toIEditor(editor: Editor): IEditor {return {focus: ({ position, scrollIntoView } = {}) => {diff --git a/apps/web/src/components/icons/index.tsx b/apps/web/src/components/icons/index.tsxindex 0de4fc06e..5e437e3b4 100644--- a/apps/web/src/components/icons/index.tsx+++ b/apps/web/src/components/icons/index.tsx@@ -209,7 +209,8 @@ import {mdiDesktopClassic,mdiBellBadgeOutline,mdiDotsHorizontal,- mdiCalendarBlank+ mdiCalendarBlank,+ mdiFormatListBulleted} from "@mdi/js";import { useTheme } from "@emotion/react";import { Theme } from "@notesnook/theme";@@ -332,6 +333,7 @@ export const Trash = createIcon(mdiTrashCanOutline);export const TopicRemove = createIcon(mdiBookmarkRemoveOutline);export const NotebookRemove = createIcon(mdiBookRemoveOutline);export const Search = createIcon(mdiMagnify);+export const TableOfContents = createIcon(mdiFormatListBulleted);export const Menu = createIcon(mdiMenu);export const Login = createIcon(mdiLoginVariant);export const Email = createIcon(mdiEmailAlertOutline);diff --git a/apps/web/src/components/properties/index.tsx b/apps/web/src/components/properties/index.tsxindex 228d2f37e..9c343bffd 100644--- a/apps/web/src/components/properties/index.tsx+++ b/apps/web/src/components/properties/index.tsx@@ -348,7 +348,7 @@ function SessionHistory({ noteId }: { noteId: string }) {}type SectionProps = { title: string; subtitle?: string; button?: JSX.Element };-function Section({+export function Section({title,subtitle,button,diff --git a/apps/web/src/components/scroll-container/index.tsx b/apps/web/src/components/scroll-container/index.tsxindex 1a0e5fd06..d2b50212d 100644--- a/apps/web/src/components/scroll-container/index.tsx+++ b/apps/web/src/components/scroll-container/index.tsx@@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import React, { PropsWithChildren } from "react";+import React, { PropsWithChildren, useLayoutEffect } from "react";import { MacScrollbar, MacScrollbarProps } from "mac-scrollbar";import "mac-scrollbar/dist/mac-scrollbar.css";diff --git a/apps/web/src/stores/editor-store.ts b/apps/web/src/stores/editor-store.tsindex 4d4c6626d..a25b7c97b 100644--- a/apps/web/src/stores/editor-store.ts+++ b/apps/web/src/stores/editor-store.ts@@ -142,6 +142,7 @@ class EditorStore extends BaseStore<EditorStore> {activeSessionId?: string;arePropertiesVisible = false;+ isTOCVisible = false;editorMargins = Config.get("editor:margins", true);history: string[] = [];@@ -440,6 +441,7 @@ class EditorStore extends BaseStore<EditorStore> {// do not allow saving of readonly sessionif (partial.note?.readonly) return;+ console.log(currentSession);if (currentSession.saveState === SaveState.Saving ||currentSession.id !== id@@ -527,12 +529,13 @@ class EditorStore extends BaseStore<EditorStore> {setDocumentTitle(settingStore.get().hideNoteTitle ? undefined : note.title);+ this.setSaveState(id, SaveState.Saved);} catch (err) {showToast("error",err instanceof Error ? err.stack || err.message : JSON.stringify(err));- this.setSaveState(id, -1);+ this.setSaveState(id, SaveState.NotSaved);console.error(err);if (err instanceof Error) logger.error(err);if (isLockedSession(currentSession)) {@@ -608,6 +611,14 @@ class EditorStore extends BaseStore<EditorStore> {);};+ toggleTableOfContents = (toggleState?: boolean) => {+ this.set(+ (state) =>+ (state.isTOCVisible =+ toggleState !== undefined ? toggleState : !state.isTOCVisible)+ );+ };+toggleEditorMargins = (toggleState?: boolean) => {this.set((state) => {state.editorMargins =diff --git a/packages/editor/src/extensions/block-id/blockid.ts b/packages/editor/src/extensions/block-id/blockid.tsindex 20ec968a0..0c9165275 100644--- a/packages/editor/src/extensions/block-id/blockid.ts+++ b/packages/editor/src/extensions/block-id/blockid.ts@@ -1,4 +1,23 @@-import { Node } from "@tiptap/core";+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { Node, NodeWithPos } from "@tiptap/core";import { Plugin } from "@tiptap/pm/state";import { nanoid } from "nanoid";import { getChangedNodes } from "../../utils/prosemirror";@@ -36,7 +55,7 @@ export const BlockId = Node.create({addProseMirrorPlugins() {return [new Plugin({- appendTransaction: (_transactions, oldState, newState) => {+ appendTransaction: (transactions, oldState, newState) => {// no changesif (newState.doc === oldState.doc) {return;@@ -44,9 +63,9 @@ export const BlockId = Node.create({const tr = newState.tr;const blockIds = new Set<string>();- const blocksWithoutBlockId: any[] = [];+ const blocksWithoutBlockId: NodeWithPos[] = [];- for (const tr of _transactions) {+ for (const tr of transactions) {blocksWithoutBlockId.push(...getChangedNodes(tr, {descend: false,@@ -62,6 +81,7 @@ export const BlockId = Node.create({);}+ console.log(blocksWithoutBlockId);for (const { node, pos } of blocksWithoutBlockId) {const id = nanoid(8);tr.setNodeMarkup(pos, undefined, {diff --git a/packages/editor/src/utils/toc.ts b/packages/editor/src/utils/toc.tsindex c57ed9306..6ff192f66 100644--- a/packages/editor/src/utils/toc.ts+++ b/packages/editor/src/utils/toc.ts@@ -1,17 +1,40 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++export type TOCItem = {+ level: number;+ title: string;+ id: string;+ top: number;+};+export function getTableOfContents(content: HTMLElement) {const headings = content.querySelectorAll("h1, h2, h3, h4, h5, h6");- const tableOfContents: {- level: number;- title: string | null;- id: string | null;- top: number;- }[] = [];+ const tableOfContents: TOCItem[] = [];for (let i = 0; i < headings.length; i++) {const heading = headings[i];const level = parseInt(heading.tagName[1]);const title = heading.textContent;const id = heading.getAttribute("data-block-id");+ if (!id || !title) continue;+tableOfContents.push({level,title,