Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(toc): highlight active heading while scrolling
SiriusXTb23d0184529c
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 039310f8fa..f3bf30182d 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1468,7 +1468,9 @@"description": "Table of contents will appear in text notes when the note has more than a defined number of headings. You can customize this number:","unit": "headings","disable_info": "You can also use this option to effectively disable TOC by setting a very high number.",- "shortcut_info": "You can configure a keyboard shortcut for quickly toggling the right pane (including TOC) in the Options -> Shortcuts (name 'toggleRightPane')."+ "shortcut_info": "You can configure a keyboard shortcut for quickly toggling the right pane (including TOC) in the Options -> Shortcuts (name 'toggleRightPane').",+ "active_heading_enabled": "Show active heading",+ "active_heading_description": "While reading a note, sync the table of contents with the currently viewed heading."},"text_auto_read_only_size": {"title": "Automatic Read-Only Size",@@ -1921,7 +1923,9 @@"toc": {"table_of_contents": "Table of Contents","options": "Options",- "no_headings": "No headings."+ "no_headings": "No headings.",+ "modal_title": "Configure Table of Contents",+ "menu_configure": "Configure table of contents..."},"watched_file_update_status": {"file_last_modified": "File <code class=\"file-path\"></code> has been last modified on <span class=\"file-last-modified\"></span>.",diff --git a/apps/client/src/widgets/sidebar/TableOfContents.tsx b/apps/client/src/widgets/sidebar/TableOfContents.tsxindex 4cdf618db7..1a20521ab3 100644--- a/apps/client/src/widgets/sidebar/TableOfContents.tsx+++ b/apps/client/src/widgets/sidebar/TableOfContents.tsx@@ -1,14 +1,17 @@import "./TableOfContents.css";import { attributeChangeAffectsHeading, CKTextEditor, ModelElement, type ModelNode } from "@triliumnext/ckeditor5";+import { createPortal } from "preact/compat";import clsx from "clsx";-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useEffect, useRef, useState, useMemo } from "preact/hooks";import { t } from "../../services/i18n";import { randomString } from "../../services/utils";-import { useActiveNoteContext, useContentElement, useGetContextData, useIsNoteReadOnly, useMathRendering, useNoteProperty, useTextEditor } from "../react/hooks";+import { useActiveNoteContext, useContentElement, useGetContextData, useIsNoteReadOnly, useMathRendering, useNoteProperty, useTextEditor, useTriliumOptionBool } from "../react/hooks";import Icon from "../react/Icon";+import Modal from "../react/Modal";import RawHtml from "../react/RawHtml";+import { TableOfContentOptions } from "../type_widgets/options/text_notes";import RightPanelWidget from "./RightPanelWidget";//#region Generic impl.@@ -28,30 +31,60 @@ export interface HeadingContext {activeHeadingId?: string | null;}+function TableOfContentOptionsModal({ shown, setShown }: { shown: boolean, setShown(value: boolean): void }) {+ return (+ <Modal+ className="toc-options-modal"+ size="md"+ title={t("toc.modal_title")}+ show={shown}+ onHidden={() => setShown(false)}+ >+ <TableOfContentOptions />+ </Modal>+ );+}+export default function TableOfContents() {const { note, noteContext } = useActiveNoteContext();const noteType = useNoteProperty(note, "type");const noteMime = useNoteProperty(note, "mime");const { isReadOnly } = useIsNoteReadOnly(note, noteContext);+ const [shown, setShown] = useState(false);return (- <RightPanelWidget id="toc" title={t("toc.table_of_contents")} grow>- {((noteType === "text" && isReadOnly) || (noteType === "doc")) && <ReadOnlyTextTableOfContents />}- {noteType === "text" && !isReadOnly && <EditableTextTableOfContents />}- {noteType === "file" && noteMime === "application/pdf" && <ContextDataTableOfContents />}- {note?.isMarkdown() && <ContextDataTableOfContents />}- </RightPanelWidget>+ <>+ <RightPanelWidget+ id="toc"+ title={t("toc.table_of_contents")}+ contextMenuItems={[+ {+ title: t("toc.menu_configure"),+ uiIcon: "bx bx-cog",+ handler: () => setShown(true)+ }+ ]}+ grow+ >+ {((noteType === "text" && isReadOnly) || (noteType === "doc")) && <ReadOnlyTextTableOfContents />}+ {noteType === "text" && !isReadOnly && <EditableTextTableOfContents />}+ {noteType === "file" && noteMime === "application/pdf" && <ContextDataTableOfContents />}+ {note?.isMarkdown() && <ContextDataTableOfContents />}+ </RightPanelWidget>+ {createPortal(<TableOfContentOptionsModal shown={shown} setShown={setShown} />, document.body)}+ </>);}function ContextDataTableOfContents() {const data = useGetContextData("toc");+ const [tocActiveHeadingEnabled] = useTriliumOptionBool("tocActiveHeadingEnabled");return (<AbstractTableOfContentsheadings={data?.headings || []}- scrollToHeading={data?.scrollToHeading || (() => {})}- activeHeadingId={data?.activeHeadingId}+ scrollToHeading={data?.scrollToHeading || (() => { })}+ activeHeadingId={tocActiveHeadingEnabled ? data?.activeHeadingId : null}/>);}@@ -83,12 +116,22 @@ function TableOfContentsHeading({ heading, scrollToHeading, activeHeadingId }: {const [ collapsed, setCollapsed ] = useState(false);const isActive = heading.id === activeHeadingId;const contentRef = useRef<HTMLElement>(null);+ const itemRef = useRef<HTMLLIElement>(null);++ useEffect(() => {+ if (isActive) {+ itemRef.current?.scrollIntoView({+ block: "nearest",+ behavior: "smooth"+ });+ }+ }, [isActive]);useMathRendering(contentRef, [heading.text]);return (<>- <li className={clsx(collapsed && "collapsed", isActive && "active")}>+ <li ref={itemRef} className={clsx(collapsed && "collapsed", isActive && "active")}>{heading.children.length > 0 && (<IconclassName="collapse-button"@@ -146,6 +189,7 @@ function EditableTextTableOfContents() {const { note, noteContext } = useActiveNoteContext();const textEditor = useTextEditor(noteContext);const [ headings, setHeadings ] = useState<CKHeading[]>([]);+ const [ tocActiveHeadingEnabled ] = useTriliumOptionBool("tocActiveHeadingEnabled");useEffect(() => {if (!textEditor) return;@@ -173,6 +217,25 @@ function EditableTextTableOfContents() {return () => textEditor.model.document.off("change:data", changeCallback);}, [ textEditor, note ]);+ const scrollingContainer = useMemo(() => {+ if (!tocActiveHeadingEnabled) return null;+ return textEditor?.editing.view+ .getDomRoot()+ ?.closest(".scrolling-container") as HTMLElement | null;+ }, [tocActiveHeadingEnabled, textEditor]);++ const getHeadingElement = useCallback((heading: CKHeading) => {+ if (!tocActiveHeadingEnabled) return null;++ const viewEl = textEditor?.editing.mapper.toViewElement(heading.element);+ if (!viewEl) return null;++ const domEl = textEditor?.editing.view.domConverter.mapViewToDom(viewEl);+ return domEl instanceof HTMLElement ? domEl : null;+ }, [tocActiveHeadingEnabled, textEditor]);++ const activeHeadingId = useActiveHeading({ headings, getHeadingElement, scrollingContainer });+const scrollToHeading = useCallback((heading: CKHeading) => {if (!textEditor) return;@@ -186,6 +249,7 @@ function EditableTextTableOfContents() {return <AbstractTableOfContentsheadings={headings}scrollToHeading={scrollToHeading}+ activeHeadingId={activeHeadingId}/>;}@@ -258,15 +322,39 @@ interface DomHeading extends RawHeading {function ReadOnlyTextTableOfContents() {const { noteContext } = useActiveNoteContext();const contentEl = useContentElement(noteContext);- const headings = extractTocFromStaticHtml(contentEl);+ const [ headings, setHeadings ] = useState<DomHeading[] >([]);+ const [tocActiveHeadingEnabled] = useTriliumOptionBool("tocActiveHeadingEnabled");++ useEffect(() => {+ if (!contentEl) return;+ setHeadings(extractTocFromStaticHtml(contentEl));++ const observer = new MutationObserver(() => {+ setHeadings(extractTocFromStaticHtml(contentEl));+ });++ observer.observe(contentEl, { childList: true });++ return () => observer.disconnect();+ }, [contentEl]);const scrollToHeading = useCallback((heading: DomHeading) => {heading.element.scrollIntoView();}, []);+ const scrollingContainer = useMemo(() => {+ if (!tocActiveHeadingEnabled) return null;+ return contentEl?.closest(".scrolling-container") as HTMLElement | null;+ }, [contentEl, tocActiveHeadingEnabled]);++ const getHeadingElement = useCallback((heading: DomHeading) => heading.element, []);++ const activeHeadingId = useActiveHeading({ headings, getHeadingElement, scrollingContainer });+return <AbstractTableOfContentsheadings={headings}scrollToHeading={scrollToHeading}+ activeHeadingId={activeHeadingId}/>;}@@ -275,6 +363,7 @@ function extractTocFromStaticHtml(el: HTMLElement | null) {const headings: DomHeading[] = [];for (const headingEl of el.querySelectorAll<HTMLHeadingElement>("h1,h2,h3,h4,h5,h6")) {+ if (headingEl.closest(".include-note")) continue;headings.push({id: randomString(),level: parseInt(headingEl.tagName.substring(1), 10),@@ -286,3 +375,49 @@ function extractTocFromStaticHtml(el: HTMLElement | null) {return headings;}//#endregion++function useActiveHeading<T extends RawHeading>({ headings, scrollingContainer, getHeadingElement }: {+ headings: T[];+ getHeadingElement: (heading: T) => HTMLElement | null;+ scrollingContainer: HTMLElement | null | undefined;+}) {+ const [activeHeadingId, setActiveHeadingId] = useState<string | null>(null);++ useEffect(() => {+ if (!scrollingContainer) return;+ const activeLineY = scrollingContainer.getBoundingClientRect().top + 200;+ let timeoutId: number | undefined;++ function updateActiveHeading() {+ let activeHeading: T | null = null;++ for (const heading of headings) {+ const headingEl = getHeadingElement(heading);++ if (headingEl && headingEl.getBoundingClientRect().top <= activeLineY) {+ activeHeading = heading;+ } else {+ break;+ }+ }++ setActiveHeadingId(activeHeading?.id ?? null);+ }++ function handleScroll() {+ window.clearTimeout(timeoutId);+ timeoutId = window.setTimeout(updateActiveHeading, 100);+ }++ scrollingContainer.addEventListener("scroll", handleScroll);++ updateActiveHeading();++ return () => {+ window.clearTimeout(timeoutId);+ scrollingContainer.removeEventListener("scroll", handleScroll);+ };+ }, [headings, scrollingContainer, getHeadingElement]);++ return scrollingContainer ? activeHeadingId : null;+}\ No newline at end of filediff --git a/apps/client/src/widgets/type_widgets/options/text_notes.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.tsxindex 2d324de950..4f357c8a00 100644--- a/apps/client/src/widgets/type_widgets/options/text_notes.tsx+++ b/apps/client/src/widgets/type_widgets/options/text_notes.tsx@@ -362,21 +362,27 @@ interface ThemeData {function TableOfContent() {const [ minTocHeadings, setMinTocHeadings ] = useTriliumOption("minTocHeadings");- return (!isNewLayout &&+ return (<OptionsSection title={t("table_of_contents.title")}>- <FormText>{t("table_of_contents.description")}</FormText>+ <TableOfContentOptions />- <FormGroup name="min-toc-headings">- <FormTextBoxWithUnit- type="number"- min={0} max={999999999999999} step={1}- unit={t("table_of_contents.unit")}- currentValue={minTocHeadings} onChange={setMinTocHeadings}- />- </FormGroup>-- <FormText>{t("table_of_contents.disable_info")}</FormText>- <FormText>{t("table_of_contents.shortcut_info")}</FormText>+ {!isNewLayout && (+ <>+ <FormText>{t("table_of_contents.description")}</FormText>++ <FormGroup name="min-toc-headings">+ <FormTextBoxWithUnit+ type="number"+ min={0} max={999999999999999} step={1}+ unit={t("table_of_contents.unit")}+ currentValue={minTocHeadings} onChange={setMinTocHeadings}+ />+ </FormGroup>++ <FormText>{t("table_of_contents.disable_info")}</FormText>+ <FormText>{t("table_of_contents.shortcut_info")}</FormText>+ </>+ )}</OptionsSection>);}@@ -398,6 +404,22 @@ function HighlightsList() {);}+export function TableOfContentOptions() {+ const [ tocActiveHeadingEnabled, setTocActiveHeadingEnabled ] = useTriliumOptionBool("tocActiveHeadingEnabled");++ return (+ <>+ <OptionsRowWithToggle+ name="active-heading-enabled"+ label={t("table_of_contents.active_heading_enabled")}+ description={t("table_of_contents.active_heading_description")}+ currentValue={tocActiveHeadingEnabled}+ onChange={setTocActiveHeadingEnabled}+ />+ </>+ );+}+export function HighlightsListOptions() {const [ highlightsList, setHighlightsList ] = useTriliumOptionJson<string[]>("highlightsList");diff --git a/apps/server/src/routes/api/options.ts b/apps/server/src/routes/api/options.tsindex 3ab6ca0a7e..3eea166d32 100644--- a/apps/server/src/routes/api/options.ts+++ b/apps/server/src/routes/api/options.ts@@ -79,6 +79,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["compressImages","downloadImagesAutomatically","minTocHeadings",+ "tocActiveHeadingEnabled","highlightsList","checkForUpdates","disableTray",diff --git a/apps/server/src/services/options_init.ts b/apps/server/src/services/options_init.tsindex 1437a836ff..9708ba68fd 100644--- a/apps/server/src/services/options_init.ts+++ b/apps/server/src/services/options_init.ts@@ -160,6 +160,7 @@ const defaultOptions: DefaultOption[] = [{ name: "compressImages", value: "true", isSynced: true },{ name: "downloadImagesAutomatically", value: "true", isSynced: true },{ name: "minTocHeadings", value: "5", isSynced: true },+ { name: "tocActiveHeadingEnabled", value: "false", isSynced: true },{ name: "highlightsList", value: '["underline","color","bgColor"]', isSynced: true },{ name: "checkForUpdates", value: "true", isSynced: true },{ name: "disableTray", value: "false", isSynced: false },diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 5ecc585e61..ccfb3f7d81 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -121,6 +121,7 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActimaxContentWidth: number;centerContent: boolean;minTocHeadings: number;+ tocActiveHeadingEnabled: boolean;eraseUnusedAttachmentsAfterSeconds: number;eraseUnusedAttachmentsAfterTimeScale: number;logRetentionDays: number;