Skip to content

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

editor: build the table of contents from the document

Ammar Ahmedda797bcfa0e3
diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsx
index d4b72db17..32de84308 100644
--- a/apps/web/src/components/editor/tiptap.tsx
+++ b/apps/web/src/components/editor/tiptap.tsx
@@ -309,7 +309,7 @@ function TipTap(props: TipTapProps) {
selected: 0
}
},
- tableOfContents: getTableOfContents(editor.view.dom)
+ tableOfContents: getTableOfContents(editor.state.doc, editor.view.dom)
});
},
onUpdate: ({ editor, transaction }) => {
@@ -319,7 +319,10 @@ function TipTap(props: TipTapProps) {
});
if (changedHeadings.length > 0) {
useEditorManager.getState().updateEditor(id, {
- tableOfContents: getTableOfContents(editor.view.dom)
+ tableOfContents: getTableOfContents(
+ editor.state.doc,
+ editor.view.dom
+ )
});
}
@@ -347,7 +350,7 @@ function TipTap(props: TipTapProps) {
canRedo: editor.can().redo(),
canUndo: editor.can().undo(),
tableOfContents: transaction.getMeta("isUpdatingContent")
- ? getTableOfContents(editor.view.dom)
+ ? getTableOfContents(editor.state.doc, editor.view.dom)
: useEditorManager.getState().getEditor(id)?.tableOfContents
});
},
diff --git a/packages/editor-mobile/src/components/editor.tsx b/packages/editor-mobile/src/components/editor.tsx
index 9f7469ca9..cf3264b01 100644
--- a/packages/editor-mobile/src/components/editor.tsx
+++ b/packages/editor-mobile/src/components/editor.tsx
@@ -302,9 +302,10 @@ const Tiptap = ({
const controller = useEditorController({
update,
getTableOfContents: () => {
- return !containerRef.current
+ const editor = editors[tab.id];
+ return !containerRef.current || !editor
? []
- : getTableOfContents(containerRef.current);
+ : getTableOfContents(editor.state.doc, containerRef.current);
},
scrollTop: () => containerRef.current?.scrollTop || 0,
scrollTo: (top) => {
diff --git a/packages/editor/src/utils/__tests__/toc.test.ts b/packages/editor/src/utils/__tests__/toc.test.ts
new file mode 100644
index 000000000..78df55fcd
--- /dev/null
+++ b/packages/editor/src/utils/__tests__/toc.test.ts
@@ -0,0 +1,98 @@
+/*
+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 { describe, expect, test } from "vitest";
+import { createEditor } from "../../../test-utils/index.js";
+import { BlockId } from "../../extensions/block-id/block-id.js";
+import { Callout } from "../../extensions/callout/callout.js";
+import { Heading } from "../../extensions/heading/heading.js";
+import { getTableOfContents } from "../toc.js";
+
+function tocOf(initialContent: string) {
+ const { editor } = createEditor({
+ extensions: {
+ heading: Heading.configure({ levels: [1, 2, 3, 4, 5, 6] }),
+ blockId: BlockId,
+ callout: Callout
+ },
+ initialContent
+ });
+ return getTableOfContents(editor.state.doc, editor.view.dom);
+}
+
+describe("table of contents", () => {
+ test("lists the note's headings, nested by level", () => {
+ const toc = tocOf(`
+ <h1 data-block-id="a">One</h1>
+ <p>text</p>
+ <h2 data-block-id="b">Two</h2>
+ <h3 data-block-id="c">Three</h3>
+ <h1 data-block-id="d">Another</h1>
+ `);
+
+ expect(toc.map((item) => [item.title, item.level])).toEqual([
+ ["One", 0],
+ ["Two", 1],
+ ["Three", 2],
+ ["Another", 0]
+ ]);
+ expect(toc.map((item) => item.id)).toEqual(["a", "b", "c", "d"]);
+ });
+
+ test("leaves out a heading with no block id to scroll to", () => {
+ const toc = tocOf(`<h1>No id</h1><h2 data-block-id="b">Listed</h2>`);
+ expect(toc.map((item) => item.title)).toEqual(["Listed"]);
+ });
+
+ test("reads headings the DOM is not showing", () => {
+ const { editor } = createEditor({
+ extensions: {
+ heading: Heading.configure({ levels: [1, 2, 3] }),
+ blockId: BlockId
+ },
+ initialContent: `<h1 data-block-id="a">Only heading</h1>`
+ });
+ // whatever is drawn, the document is what the contents are built from
+ editor.view.dom.innerHTML = "";
+
+ expect(
+ getTableOfContents(editor.state.doc, editor.view.dom).map((i) => i.title)
+ ).toEqual(["Only heading"]);
+ });
+});
+
+describe("table of contents nesting", () => {
+ test("a heading inside a quote is still listed", () => {
+ const toc = tocOf(
+ `<h1 data-block-id="a">Top</h1>
+ <blockquote><h2 data-block-id="b">Quoted</h2></blockquote>`
+ );
+ expect(toc.map((item) => item.title)).toEqual(["Top", "Quoted"]);
+ });
+
+ test("a callout's own heading is left out", () => {
+ const toc = tocOf(
+ `<h1 data-block-id="a">Top</h1>
+ <div class="callout" data-callout-type="info">
+ <h2 data-block-id="b">Callout title</h2>
+ </div>`
+ );
+ expect(toc.map((item) => item.title)).toEqual(["Top"]);
+ });
+});
diff --git a/packages/editor/src/utils/toc.ts b/packages/editor/src/utils/toc.ts
index 4e01d927f..087bdcd35 100644
--- a/packages/editor/src/utils/toc.ts
+++ b/packages/editor/src/utils/toc.ts
@@ -17,6 +17,8 @@ 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 as ProsemirrorNode } from "@tiptap/pm/model";
+
export type TOCItem = {
level: number;
title: string;
@@ -24,15 +26,6 @@ export type TOCItem = {
top: number;
};
-const levelsMap: Record<string, number> = {
- H1: 1,
- H2: 2,
- H3: 3,
- H4: 4,
- H5: 5,
- H6: 6
-};
-
function getOffsetTopRelativeTo(
element: HTMLElement,
ancestor: HTMLElement
@@ -50,21 +43,32 @@ function getOffsetTopRelativeTo(
return top;
}
-export function getTableOfContents(content: HTMLElement) {
+/**
+ * Builds the table of contents from the document rather than by querying the
+ * rendered DOM. The document says what headings the note has; the DOM only says
+ * which of them are drawn right now. The pixel offset each entry scrolls to
+ * still comes from the element, found by the heading's block id.
+ *
+ * A callout's first child is its title, which is a heading but is not part of
+ * the note's outline, so callouts are stepped over rather than looked inside.
+ * Headings anywhere else -- in a quote, a list, a table cell -- are listed.
+ */
+export function getTableOfContents(
+ doc: ProsemirrorNode,
+ content: HTMLElement
+): TOCItem[] {
const tableOfContents: TOCItem[] = [];
let level = -1;
let prevHeading = 0;
- for (const heading of content.querySelectorAll<HTMLHeadingElement>(
- "h1, h2, h3, h4, h5, h6"
- )) {
- const title = heading.textContent;
- const id = heading.dataset.blockId;
- if (!id || !title) continue;
- const nodeName = heading.nodeName;
- const currentHeading = levelsMap[nodeName];
-
- const isInsideCallout = !!closestWithin(heading, ".callout", content);
- if (isInsideCallout) continue;
+
+ const visit = (node: ProsemirrorNode) => {
+ if (node.type.name !== "heading") return;
+
+ const title = node.textContent;
+ const id = node.attrs.blockId as string | undefined;
+ if (!id || !title) return;
+
+ const currentHeading = (node.attrs.level as number) || 1;
level =
prevHeading < currentHeading
@@ -75,13 +79,25 @@ export function getTableOfContents(content: HTMLElement) {
level = Math.max(0, level);
prevHeading = currentHeading;
+ const element = content.querySelector<HTMLElement>(
+ `[data-block-id=${JSON.stringify(id)}]`
+ );
+
tableOfContents.push({
level,
title,
id,
- top: getOffsetTopRelativeTo(heading, content)
+ top: element ? getOffsetTopRelativeTo(element, content) : 0
});
- }
+ };
+
+ doc.descendants((node) => {
+ if (node.type.name === "callout") return false;
+ if (node.type.name !== "heading") return true;
+ visit(node);
+ return false;
+ });
+
return tableOfContents;
}
@@ -113,16 +129,3 @@ export function scrollIntoViewById(blockId: string, optionalStyles = "") {
);
}
}
-
-function closestWithin(
- element: Element,
- selector: string,
- boundary: Element
-): Element | null {
- let current: Element | null = element;
- while (current && current !== boundary) {
- if (current.matches(selector)) return current;
- current = current.parentElement;
- }
- return null;
-}