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
refactor(client): remove the old layout's right sidebar
Elian Doranc9999db95216
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 6329b162f0..cdd984f7a7 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -314,7 +314,6 @@ export type CommandMappings = {zoomFactor: string;};- reEvaluateRightPaneVisibility: CommandData;runActiveNote: CommandData;scrollContainerTo: CommandData & {position: number;@@ -522,18 +521,6 @@ type EventMappings = {setNoteContext: {noteContext: NoteContext;};- reEvaluateHighlightsListWidgetVisibility: {- noteId: string | undefined;- };- reEvaluateTocWidgetVisibility: {- noteId: string | undefined;- };- showHighlightsListWidget: {- noteId: string;- };- showTocWidget: {- noteId: string;- };showSearchError: {error: string;};diff --git a/apps/client/src/layouts/desktop_layout.tsx b/apps/client/src/layouts/desktop_layout.tsxindex 806a87485a..c10b0d4fd9 100644--- a/apps/client/src/layouts/desktop_layout.tsx+++ b/apps/client/src/layouts/desktop_layout.tsx@@ -15,7 +15,6 @@ import NoteList from "../widgets/collections/NoteList.jsx";import ContentHeader from "../widgets/containers/content_header.js";import FlexContainer from "../widgets/containers/flex_container.js";import LeftPaneContainer from "../widgets/containers/left_pane_container.js";-import RightPaneContainer from "../widgets/containers/right_pane_container.js";import RootContainer from "../widgets/containers/root_container.js";import ScrollingContainer from "../widgets/containers/scrolling_container.js";import SplitNoteContainer from "../widgets/containers/split_note_container.js";@@ -24,7 +23,6 @@ import UploadAttachmentsDialog from "../widgets/dialogs/upload_attachments.js";import FindWidget from "../widgets/find.js";import FloatingButtons from "../widgets/FloatingButtons.jsx";import { DESKTOP_FLOATING_BUTTONS } from "../widgets/FloatingButtonsDefinitions.jsx";-import HighlightsListWidget from "../widgets/highlights_list.js";import LauncherContainer from "../widgets/launch_bar/LauncherContainer.jsx";import SpacerWidget from "../widgets/launch_bar/SpacerWidget.jsx";import InlineTitle from "../widgets/layout/InlineTitle.jsx";@@ -48,7 +46,6 @@ import SharedInfo from "../widgets/shared_info.jsx";import RightPanelContainer from "../widgets/sidebar/RightPanelContainer.jsx";import TabRowWidget from "../widgets/tab_row.js";import TabHistoryNavigationButtons from "../widgets/TabHistoryNavigationButtons.jsx";-import TocWidget from "../widgets/toc.js";import WatchedFileUpdateStatusWidget from "../widgets/watched_file_update_status.js";import { applyModals } from "./layout_commons.js";@@ -170,12 +167,6 @@ export default class DesktopLayout {.child(...this.customWidgets.get("center-pane")))- .optChild(!isNewLayout,- new RightPaneContainer()- .child(new TocWidget())- .child(new HighlightsListWidget())- .child(...this.customWidgets.get("right-pane"))- ).optChild(isNewLayout, <RightPanelContainer widgetsByParent={this.customWidgets} />)).optChild(!launcherPaneIsHorizontal && isNewLayout, <StatusBar />)diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex 2f1546deb3..0d481e9ea1 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -61,17 +61,6 @@ export interface ViewScope {* built for the width of a note either spills out of them or eats the room the note is left.*/floatingToolbar?: boolean;- highlightsListPreviousVisible?: boolean;- highlightsListTemporarilyHidden?: boolean;- tocTemporarilyHidden?: boolean;- /*- * The reason for adding tocPreviousVisible is to record whether the previous state of the toc is hidden or displayed,- * and then let it be displayed/hidden at the initial time. If there is no such value,- * when the right panel needs to display highlighttext but not toc, every time the note content is changed,- * toc will appear and then close immediately, because getToc(html) function will consume time- */- tocPreviousVisible?: boolean;- tocCollapsedHeadings?: Set<string>;/** When set, scrolls to a bookmark anchor within the note after navigation. */bookmark?: string;/**diff --git a/apps/client/src/services/resizer.spec.ts b/apps/client/src/services/resizer.spec.tsindex 5540e97899..9b05382bdd 100644--- a/apps/client/src/services/resizer.spec.ts+++ b/apps/client/src/services/resizer.spec.ts@@ -26,17 +26,6 @@ function flushRaf() {}}-/** Force `$("#right-pane").is(":visible")` to a chosen value (no layout in happy-dom). */-function setRightPaneVisible(visible: boolean) {- const origIs = ($ as any).fn.is;- return vi.spyOn(($ as any).fn, "is").mockImplementation(function (this: any, sel: any, ...rest: any[]) {- if (sel === ":visible") {- return visible;- }- return origIs.call(this, sel, ...rest);- });-}-/*** Force `$("#launcher-pane").outerWidth()` to a chosen pixel value (happy-dom has* no layout, so it otherwise returns 0). Used to exercise the vertical-layout@@ -57,13 +46,12 @@ function setLauncherPaneWidth(px: number) {* singleton that never resets) with options.get/getInt stubbed to the supplied* values.*/-async function loadResizer(opts: { layoutOrientation?: string; leftPaneWidth?: number | null; rightPaneWidth?: number | null } = {}) {+async function loadResizer(opts: { layoutOrientation?: string; leftPaneWidth?: number | null } = {}) {vi.resetModules();const optionsModule = (await import("./options.js")).default;optionsModule.get = vi.fn((key) => (key === "layoutOrientation" ? (opts.layoutOrientation ?? "horizontal") : "")) as typeof optionsModule.get;optionsModule.getInt = vi.fn((key) => {if (key === "leftPaneWidth") return opts.leftPaneWidth ?? null;- if (key === "rightPaneWidth") return opts.rightPaneWidth ?? null;return null;}) as typeof optionsModule.getInt;optionsModule.save = vi.fn(async () => {}) as typeof optionsModule.save;@@ -92,8 +80,7 @@ beforeEach(() => {<div id="rest-pane"></div><div id="center-pane"><div class="split-note-container-widget"></div>- </div>- <div id="right-pane"></div>`;+ </div>`;});afterEach(() => {@@ -229,58 +216,6 @@ describe("setupLeftPaneResizer", () => {});});-describe("setupRightPaneResizer", () => {- it("when right pane is hidden, stretches center pane to full width", async () => {- const isSpy = setRightPaneVisible(false);- const { resizer } = await loadResizer();-- resizer.setupRightPaneResizer();-- expect($("#center-pane").css("width")).toBe("100%");- expect(SplitMock).not.toHaveBeenCalled();- isSpy.mockRestore();- });-- it("when right pane is visible, creates a Split and persists drag results", async () => {- const isSpy = setRightPaneVisible(true);- const { resizer, options } = await loadResizer({ rightPaneWidth: 25 });-- resizer.setupRightPaneResizer();-- expect(SplitMock).toHaveBeenCalledTimes(1);- const [elements, config] = SplitMock.mock.calls[0];- expect(elements).toEqual(["#center-pane", "#right-pane"]);- expect(config.sizes).toEqual([75, 25]);- expect(config.minSize).toEqual([300, 180]);-- config.onDragEnd([60.2, 39.8]);- expect(options.save).toHaveBeenCalledWith("rightPaneWidth", 40);-- // onDragEnd also mutates the module-level cache: a subsequent rebuild must use- // the NEW (dragged + rounded) width 40, not the original 25 -> sizes [60, 40].- resizer.setupRightPaneResizer();- expect(SplitMock).toHaveBeenCalledTimes(2);- expect(SplitMock.mock.calls[1][1].sizes).toEqual([60, 40]);- isSpy.mockRestore();- });-- it("clamps an undefined/too-small right pane width up to 5 and destroys a previous instance", async () => {- const isSpy = setRightPaneVisible(true);- const destroy = vi.fn();- SplitMock.mockImplementation(() => ({ destroy }));- const { resizer } = await loadResizer({ rightPaneWidth: null });-- resizer.setupRightPaneResizer();- expect(SplitMock.mock.calls[0][1].sizes).toEqual([95, 5]);- expect(destroy).not.toHaveBeenCalled();-- resizer.setupRightPaneResizer();- expect(destroy).toHaveBeenCalledTimes(1);- expect(SplitMock).toHaveBeenCalledTimes(2);- isSpy.mockRestore();- });-});-describe("note split resizers", () => {function panel(ntxId: string) {const el = document.createElement("div");diff --git a/apps/client/src/services/resizer.ts b/apps/client/src/services/resizer.tsindex af2fb77e15..ef35f3c1ea 100644--- a/apps/client/src/services/resizer.ts+++ b/apps/client/src/services/resizer.ts@@ -7,8 +7,6 @@ let leftPaneWidth: number;let reservedPx: number;let layoutOrientation: string;let leftInstance: ReturnType<typeof Split> | null;-let rightPaneWidth: number;-let rightInstance: ReturnType<typeof Split> | null;const noteSplitMap = new Map<string[], ReturnType<typeof Split> | undefined>(); // key: a group of ntxIds, value: the corresponding Split instanceconst noteSplitRafMap = new Map<string[], number>();@@ -57,40 +55,6 @@ function setupLeftPaneResizer(leftPaneVisible: boolean) {}}-function setupRightPaneResizer() {- if (rightInstance) {- rightInstance.destroy();- rightInstance = null;- }-- const rightPaneVisible = $("#right-pane").is(":visible");-- if (!rightPaneVisible) {- $("#center-pane").css("width", "100%");-- return;- }-- rightPaneWidth = rightPaneWidth ?? (options.getInt("rightPaneWidth") ?? 0);- if (!rightPaneWidth || rightPaneWidth < 5) {- rightPaneWidth = 5;- }-- /* v8 ignore next -- redundant guard: a falsy rightPaneVisible already returned above */- if (rightPaneVisible) {- rightInstance = Split(["#center-pane", "#right-pane"], {- sizes: [100 - rightPaneWidth, rightPaneWidth],- gutterSize: DEFAULT_GUTTER_SIZE,- minSize: [300, 180],- rtl: glob.isRtl,- onDragEnd: (sizes) => {- rightPaneWidth = Math.round(sizes[1]);- options.save("rightPaneWidth", Math.round(sizes[1]));- }- });- }-}-function findKeyByNtxId(ntxId: string): string[] | undefined {// Find the corresponding key in noteSplitMap based on ntxIdfor (const key of noteSplitMap.keys()) {@@ -170,7 +134,6 @@ function createSplitInstance(targetNtxIds: string[]) {export default {setupLeftPaneResizer,- setupRightPaneResizer,setupNoteSplitResizer,delNoteSplitResizer,moveNoteSplitResizerdiff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex c180f8e1b3..713fc24363 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -2804,41 +2804,6 @@ footer.webview-footer button {100% { opacity: 0.3; }}-/* Right Pane Tab Styles */-#right-pane-tab-container {- display: flex;- gap: 10px;-}--.right-pane-tab {- padding: 5px 10px;- cursor: pointer;- border-radius: 5px;- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;- transition: background-color 0.2s ease;-}--.right-pane-tab:hover {- background-color: var(--hover-item-background-color);-}--.right-pane-tab.active {- background-color: var(--primary-color);- color: white;-}--.right-pane-tab .tab-title {- display: flex;- align-items: center;- gap: 5px;-}--.right-pane-tab .tab-title .tn-icon {- font-size: 1.1em;-}-.admonition {--accent-color: var(--card-border-color);background: color-mix(in srgb, var(--accent-color) 15%, transparent);diff --git a/apps/client/src/stylesheets/theme-next/shell.css b/apps/client/src/stylesheets/theme-next/shell.cssindex 8958f195df..aa86bd4125 100644--- a/apps/client/src/stylesheets/theme-next/shell.css+++ b/apps/client/src/stylesheets/theme-next/shell.css@@ -1872,11 +1872,6 @@ body.desktop.experimental-feature-new-layout .vertical-layout #right-pane {top: 0;}-#right-pane .toc-widget,-#right-pane .highlights-list-widget {- padding: 0 0 0 10px;-}-#right-pane .toc li,#right-pane .highlights-list li {padding-top: 2px;diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 6919796e54..41753190ee 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -637,7 +637,6 @@"hide_relations": "Comma delimited names of relations which should be hidden. All other ones will be displayed.","title_template": "Default title of notes created as children of this note. The value is evaluated as JavaScript string \n and thus can be enriched with dynamic content via the injected <code>now</code> and <code>parentNote</code> variables. Examples:\n \n <ul>\n <li><code>${parentNote.getLabelValue('authorName')}'s literary works</code></li>\n <li><code>Log for ${now.format('YYYY-MM-DD HH:mm:ss')}</code></li>\n </ul>\n \n See <a href=\"https://triliumnext.github.io/Docs/Wiki/default-note-title.html\">wiki with details</a>, API docs for <a href=\"https://zadam.github.io/trilium/backend_api/Note.html\">parentNote</a> and <a href=\"https://day.js.org/docs/en/display/format\">now</a> for details.","template": "This note will appear in the selection of available template when creating new note.",- "toc": "<code>#toc</code> or <code>#toc=show</code> will force the Table of Contents to be shown, <code>#toc=hide</code> will force hiding it. If the label doesn't exist, the global setting is observed.","color": "Defines color of the note in note tree, links etc. Use any valid CSS color value like 'red' or #a13d5f.","keyboard_shortcut": "Defines a keyboard shortcut which will immediately jump to this note. Example: 'ctrl+alt+e'. Requires frontend reload for the change to take effect.","keep_current_hoisting": "Opening this link won't change hoisting even if the note is not displayable in the current hoisted subtree.",@@ -645,7 +644,6 @@"execute_description": "Longer description of the current code note displayed together with the execute button.","exclude_from_note_map": "Notes with this label will be hidden from the Note Map.","new_notes_on_top": "New notes will be created at the top of the parent note, not on the bottom.",- "hide_highlight_widget": "Hides the Highlights List for this note, leaving it shown on every other.","run_on_note_creation": "Executes when note is created on backend. Use this relation if you want to run the script for all notes created under a specific subtree. In that case, create it on the subtree root note and make it inheritable. A new note created within the subtree (any depth) will trigger the script.","run_on_child_note_creation": "Executes when new note is created under the note where this relation is defined.","run_on_note_title_change": "Executes when note title is changed (includes note creation as well).",@@ -1086,12 +1084,6 @@"edit_button": {"edit_this_note": "Edit this note"},- "show_toc_widget_button": {- "show_toc": "Show Table of Contents"- },- "show_highlights_list_widget_button": {- "show_highlights_list": "Show Highlights List"- },"options": {"title": "Options","back": "Back to all options",@@ -2108,17 +2100,7 @@"italic": "Italic text","underline": "Underlined text","color": "Colored text",- "bg_color": "Text with background color",- "visibility_title": "Highlights List visibility",- "visibility_description": "You can hide the highlights widget per-note by adding a #hideHighlightWidget label.",- "shortcut_info": "You can configure a keyboard shortcut for quickly toggling the right pane (including Highlights) in the Options -> Shortcuts (name 'toggleRightPane')."- },- "table_of_contents": {- "title": "Table of Contents",- "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')."+ "bg_color": "Text with background color"},"text_auto_read_only_size": {"title": "Automatic Read-Only Size",@@ -2779,10 +2761,8 @@"replace_all": "Replace all"},"highlights_list_2": {- "title": "Highlights List","title_with_count_one": "{{count}} highlight","title_with_count_other": "{{count}} highlights",- "options": "Options","menu_configure": "Configure highlights list...","no_highlights": "No highlights found."},@@ -2901,7 +2881,6 @@},"toc": {"table_of_contents": "Table of Contents",- "options": "Options","no_headings": "No headings."},"watched_file_update_status": {diff --git a/apps/client/src/widgets/FloatingButtonsDefinitions.tsx b/apps/client/src/widgets/FloatingButtonsDefinitions.tsxindex f152ae148e..30de0da6dd 100644--- a/apps/client/src/widgets/FloatingButtonsDefinitions.tsx+++ b/apps/client/src/widgets/FloatingButtonsDefinitions.tsx@@ -55,8 +55,6 @@ export const DESKTOP_FLOATING_BUTTONS: FloatingButtonsList = [SwitchSplitOrientationButton,DisplayModeSwitcher,EditButton,- ShowTocWidgetButton,- ShowHighlightsListWidgetButton,RunActiveNoteButton,OpenTriliumApiDocsButton,OpenElectronApiDocsButton,@@ -166,42 +164,6 @@ function EditButton({ note, noteContext }: FloatingButtonContext) {/>;}-function ShowTocWidgetButton({ note, noteContext, isDefaultViewMode }: FloatingButtonContext) {- const [ isEnabled, setIsEnabled ] = useState(false);- useTriliumEvent("reEvaluateTocWidgetVisibility", () => {- setIsEnabled(note.type === "text" && isDefaultViewMode && !!noteContext.viewScope?.tocTemporarilyHidden);- });-- return isEnabled && <FloatingButton- text={t("show_toc_widget_button.show_toc")}- icon="bx bx-spreadsheet bx-rotate-180"- onClick={() => {- if (noteContext?.viewScope && noteContext.noteId) {- noteContext.viewScope.tocTemporarilyHidden = false;- appContext.triggerEvent("showTocWidget", { noteId: noteContext.noteId });- }- }}- />;-}--function ShowHighlightsListWidgetButton({ note, noteContext, isDefaultViewMode }: FloatingButtonContext) {- const [ isEnabled, setIsEnabled ] = useState(false);- useTriliumEvent("reEvaluateHighlightsListWidgetVisibility", () => {- setIsEnabled(note.type === "text" && isDefaultViewMode && !!noteContext.viewScope?.highlightsListTemporarilyHidden);- });-- return isEnabled && <FloatingButton- text={t("show_highlights_list_widget_button.show_highlights_list")}- icon="bx bx-bookmarks"- onClick={() => {- if (noteContext?.viewScope && noteContext.noteId) {- noteContext.viewScope.highlightsListTemporarilyHidden = false;- appContext.triggerEvent("showHighlightsListWidget", { noteId: noteContext.noteId });- }- }}- />;-}-function RunActiveNoteButton({ note }: FloatingButtonContext) {const isEnabled = (note.mime.startsWith("application/javascript") || note.mime === "text/x-sqlite;schema=trilium");return isEnabled && <FloatingButtondiff --git a/apps/client/src/widgets/attribute_widgets/attr_help.ts b/apps/client/src/widgets/attribute_widgets/attr_help.tsindex ac3a83590d..7cdfeb60b3 100644--- a/apps/client/src/widgets/attribute_widgets/attr_help.ts+++ b/apps/client/src/widgets/attribute_widgets/attr_help.ts@@ -59,7 +59,6 @@ export const ATTR_HELP: AttrHelpMap = {hideRelations: t("attribute_detail.hide_relations"),titleTemplate: t("attribute_detail.title_template"),template: t("attribute_detail.template"),- toc: t("attribute_detail.toc"),color: t("attribute_detail.color"),keyboardShortcut: t("attribute_detail.keyboard_shortcut"),keepCurrentHoisting: t("attribute_detail.keep_current_hoisting"),@@ -67,7 +66,6 @@ export const ATTR_HELP: AttrHelpMap = {executeDescription: t("attribute_detail.execute_description"),excludeFromNoteMap: t("attribute_detail.exclude_from_note_map"),newNotesOnTop: t("attribute_detail.new_notes_on_top"),- hideHighlightWidget: t("attribute_detail.hide_highlight_widget"),printLandscape: t("attribute_detail.print_landscape"),printPageSize: t("attribute_detail.print_page_size"),printScale: t("attribute_detail.print_scale"),diff --git a/apps/client/src/widgets/containers/right_pane_container.ts b/apps/client/src/widgets/containers/right_pane_container.tsdeleted file mode 100644index 5e267851d5..0000000000--- a/apps/client/src/widgets/containers/right_pane_container.ts+++ /dev/null@@ -1,59 +0,0 @@-import type { EventData, EventNames } from "../../components/app_context.js";-import splitService from "../../services/resizer.js";-import type BasicWidget from "../basic_widget.js";-import FlexContainer from "./flex_container.js";--export default class RightPaneContainer extends FlexContainer<BasicWidget> {- private rightPaneHidden: boolean;- private firstRender: boolean;-- constructor() {- super("column");-- this.id("right-pane");- this.css("height", "100%");- this.collapsible();-- this.rightPaneHidden = false;- this.firstRender = true;- }-- isEnabled() {- return super.isEnabled() && !this.rightPaneHidden && this.children.length > 0 && !!this.children.find((ch) => ch.isEnabled() && ch.canBeShown());- }-- async handleEventInChildren<T extends EventNames>(name: T, data: EventData<T>) {- const promise = super.handleEventInChildren(name, data);-- if (["activeContextChanged", "noteSwitchedAndActivated", "noteSwitched"].includes(name)) {- // the right pane is displayed only if some child widget is active,- // we'll reevaluate the visibility based on events which are probable to cause visibility change- // but these events need to be finished and only then we check- if (promise) {- promise.then(() => this.reEvaluateRightPaneVisibilityCommand());- } else {- this.reEvaluateRightPaneVisibilityCommand();- }- }-- return promise;- }-- reEvaluateRightPaneVisibilityCommand() {- const oldToggle = !this.isHiddenInt();- const newToggle = this.isEnabled();-- if (oldToggle !== newToggle || this.firstRender) {- this.toggleInt(newToggle);-- splitService.setupRightPaneResizer();- this.firstRender = false;- }- }-- toggleRightPaneEvent() {- this.rightPaneHidden = !this.rightPaneHidden;-- this.reEvaluateRightPaneVisibilityCommand();- }-}diff --git a/apps/client/src/widgets/highlights_list.spec.ts b/apps/client/src/widgets/highlights_list.spec.tsdeleted file mode 100644index 01d8df83c9..0000000000--- a/apps/client/src/widgets/highlights_list.spec.ts+++ /dev/null@@ -1,22 +0,0 @@-// @vitest-environment jsdom-// DOMPurify relies on browser-faithful DOM traversal (NodeIterator); happy-dom-// mishandles it and strips valid markup (surfaced by dompurify 3.4.8). Run the-// sanitization-dependent specs under jsdom, which matches real-browser behavior.-import { describe, expect, it } from "vitest";-import HighlightsListWidget from "./highlights_list.js";--describe("getHighlightList", () => {- let widget = new HighlightsListWidget();-- it("supports old italics", async () => {- const highlights = await widget.getHighlightList("This is <i>italic</i> text", [ "italic" ]);- expect(highlights.$highlightsList.html()).toBe("<li><i>italic</i></li>");- expect(highlights.findSubStr).toContain("i:not(.include-note-wrapper i)");- });-- it("supports new italics", async () => {- const highlights = await widget.getHighlightList("This is <em>italic</em> text", [ "italic" ]);- expect(highlights.$highlightsList.html()).toBe("<li><em>italic</em></li>");- expect(highlights.findSubStr).toContain("em:not(.include-note-wrapper em)");- });-})diff --git a/apps/client/src/widgets/highlights_list.ts b/apps/client/src/widgets/highlights_list.tsdeleted file mode 100644index a15af64493..0000000000--- a/apps/client/src/widgets/highlights_list.ts+++ /dev/null@@ -1,339 +0,0 @@-/**- * Widget: Show highlighted text in the right pane- *- * By design, there's no support for nonsensical or malformed constructs:- * - For example, if there is a formula in the middle of the highlighted text, the two ends of the formula will be regarded as two entries- */--import appContext, { type EventData } from "../components/app_context.js";-import type FNote from "../entities/fnote.js";-import attributeService from "../services/attributes.js";-import { t } from "../services/i18n.js";-import options from "../services/options.js";-import OnClickButtonWidget from "./buttons/onclick_button.js";-import RightPanelWidget from "./right_panel_widget.js";-import DOMPurify, { type Config as DOMPurifyConfig } from "dompurify";--/**- * DOMPurify configuration for highlight list items. Highlighted spans are- * extracted from note content and inserted into the DOM, so they are sanitized- * to prevent XSS. Uses the built-in HTML and MathML profiles (so inline math- * markup survives), then restricts to inline-only content via FORBID_TAGS.- */-const HIGHLIGHT_PURIFY_CONFIG: DOMPurifyConfig = {- USE_PROFILES: { html: true, mathMl: true },- FORBID_TAGS: [- "script", "style", "iframe", "object", "embed", "link", "meta",- "base", "noscript", "template", "form", "input", "textarea",- "button", "select", "option",- "div", "p", "h1", "h2", "h3", "h4", "h5", "h6",- "blockquote", "pre", "section", "article", "aside", "nav",- "header", "footer", "main", "figure", "figcaption",- "table", "thead", "tbody", "tfoot", "tr", "th", "td",- "ul", "ol", "li", "dl", "dt", "dd",- "hr", "img", "video", "audio", "picture", "canvas",- "svg", "foreignObject"- ],- FORBID_ATTR: [- "onerror", "onload", "onclick", "onmouseover", "onfocus",- "onblur", "onsubmit", "onreset", "onchange", "oninput",- "onkeydown", "onkeyup", "onkeypress"- ],- RETURN_DOM: false,- RETURN_DOM_FRAGMENT: false-};--const TPL = /*html*/`<div class="highlights-list-widget">- <style>- .highlights-list-widget {- padding: 10px;- contain: none;- overflow: auto;- position: relative;- }-- .highlights-list > ol {- padding-inline-start: 20px;- }-- .highlights-list li {- cursor: pointer;- margin-bottom: 3px;- text-align: justify;- word-wrap: break-word;- hyphens: auto;- }-- .highlights-list li:hover {- font-weight: bold;- }- </style>-- <span class="highlights-list"></span>-</div>`;--export default class HighlightsListWidget extends RightPanelWidget {- private $highlightsList!: JQuery<HTMLElement>;-- get widgetTitle() {- return t("highlights_list_2.title");- }-- get widgetButtons() {- return [- new OnClickButtonWidget()- .icon("bx-cog")- .title(t("highlights_list_2.options"))- .titlePlacement("left")- .onClick(() => appContext.tabManager.openContextWithNote("_optionsTextNotes", { activate: true }))- .class("icon-action"),- new OnClickButtonWidget()- .icon("bx-x")- .titlePlacement("left")- .onClick((widget: OnClickButtonWidget) => widget.triggerCommand("closeHlt"))- .class("icon-action")- ];- }-- isEnabled() {- return (- super.isEnabled() && this.note != null && this.note.type === "text" && !this.noteContext?.viewScope?.highlightsListTemporarilyHidden && this.noteContext?.viewScope?.viewMode === "default"- );- }-- async doRenderBody() {- this.$body.empty().append($(TPL));- this.$highlightsList = this.$body.find(".highlights-list");- }-- async refreshWithNote(note: FNote | null | undefined) {- /* The reason for adding highlightsListPreviousVisible is to record whether the previous state- of the highlightsList is hidden or displayed, and then let it be displayed/hidden at the initial time.- If there is no such value, when the right panel needs to display toc but not highlighttext,- every time the note content is changed, highlighttext Widget will appear and then close immediately,- because getHlt function will consume time */- if (this.noteContext?.viewScope?.highlightsListPreviousVisible) {- this.toggleInt(true);- } else {- this.toggleInt(false);- }-- const optionsHighlightsList = JSON.parse(options.get("highlightsList"));-- if (note?.isLabelTruthy("hideHighlightWidget") || !optionsHighlightsList.length) {- this.toggleInt(false);- this.triggerCommand("reEvaluateRightPaneVisibility");- return;- }-- let $highlightsList: JQuery<HTMLElement> | null = null;- let hlLiCount = -1;- // Check for type text unconditionally in case alwaysShowWidget is set- if (note && this.note?.type === "text") {- const noteComplement = await note.getNoteComplement();- if (noteComplement && "content" in noteComplement) {- ({ $highlightsList, hlLiCount } = await this.getHighlightList(noteComplement.content, optionsHighlightsList));- }- }- this.$highlightsList.empty();- if ($highlightsList) {- this.$highlightsList.append($highlightsList);- }- if (hlLiCount > 0) {- this.toggleInt(true);- if (this.noteContext?.viewScope) {- this.noteContext.viewScope.highlightsListPreviousVisible = true;- }- } else {- this.toggleInt(false);- if (this.noteContext?.viewScope) {- this.noteContext.viewScope.highlightsListPreviousVisible = false;- }- }-- this.triggerCommand("reEvaluateRightPaneVisibility");- }-- async getHighlightList(content: string, optionsHighlightsList: string[]) {- // matches a span containing background-color- const regex1 = /<span[^>]*style\s*=\s*[^>]*background-color:[^>]*?>[\s\S]*?<\/span>/gi;- // matches a span containing color- const regex2 = /<span[^>]*style\s*=\s*[^>]*[^-]color:[^>]*?>[\s\S]*?<\/span>/gi;- // match italics- const regex3 = /(<i>[\s\S]*?<\/i>|<em>[\s\S]*?<\/em>)/gi;- // match bold- const regex4 = /<strong>[\s\S]*?<\/strong>/gi;- // match underline- const regex5 = /<u>[\s\S]*?<\/u>/g;- // Possible values in optionsHighlightsList: '["bold","italic","underline","color","bgColor"]'- // element priority: span>i>strong>u- let findSubStr = "",- combinedRegexStr = "";- if (optionsHighlightsList.includes("bgColor")) {- findSubStr += `,span[style*="background-color"]`- + `:not(.include-note-wrapper span[style*="background-color"])`;- combinedRegexStr += `|${regex1.source}`;- }- if (optionsHighlightsList.includes("color")) {- findSubStr += `,span[style*="color"]:not(.include-note-wrapper span[style*="color"])`;- combinedRegexStr += `|${regex2.source}`;- }- if (optionsHighlightsList.includes("italic")) {- findSubStr += `,i:not(.include-note-wrapper i)`;- findSubStr += `,em:not(.include-note-wrapper em)`;- combinedRegexStr += `|${regex3.source}`;- }- if (optionsHighlightsList.includes("bold")) {- findSubStr += `,strong:not(.include-note-wrapper strong)`;- combinedRegexStr += `|${regex4.source}`;- }- if (optionsHighlightsList.includes("underline")) {- findSubStr += `,u:not(.include-note-wrapper u)`;- combinedRegexStr += `|${regex5.source}`;- }-- findSubStr = findSubStr.substring(1);- combinedRegexStr = `(${combinedRegexStr.substring(1)})`;- const combinedRegex = new RegExp(combinedRegexStr, "gi");- const $highlightsList = $("<ol>");- let prevEndIndex = -1,- hlLiCount = 0;-- for (let match: RegExpMatchArray | null = null, hltIndex = 0; (match = combinedRegex.exec(content)) !== null; hltIndex++) {- const subHtml = match[0];- const startIndex = match.index;- const endIndex = combinedRegex.lastIndex;-- // Ignore footnotes.- if (subHtml.startsWith('<strong><a href="#fnref')) {- continue;- }-- if (prevEndIndex !== -1 && startIndex === prevEndIndex) {- // If the previous element is connected to this element in HTML, then concatenate them into one.- $highlightsList.children().last().append(DOMPurify.sanitize(subHtml, HIGHLIGHT_PURIFY_CONFIG) as string);- } else {- const hasText = $(subHtml).text().trim();-- if (hasText) {- $highlightsList.append(- $("<li>")- .html(DOMPurify.sanitize(subHtml, HIGHLIGHT_PURIFY_CONFIG) as string)- .on("click", () => this.jumpToHighlightsList(findSubStr, hltIndex))- );-- hlLiCount++;- } else {- // hide li if its text content is empty- continue;- }- }- prevEndIndex = endIndex;- }- return {- $highlightsList,- hlLiCount,- findSubStr- };- }-- async jumpToHighlightsList(findSubStr: string, itemIndex: number) {- if (!this.noteContext) {- return;- }-- const isReadOnly = await this.noteContext.isReadOnly();- let targetElement;- if (isReadOnly) {- const $container = await this.noteContext.getContentElement();- if ($container) {- targetElement = $container- .find(findSubStr)- .filter(function () {- if (findSubStr.indexOf("color") >= 0 && findSubStr.indexOf("background-color") < 0) {- const color = this.style.color;- const $el = $(this as HTMLElement);- return !($el.prop("tagName") === "SPAN" && color === "");- }- return true;-- })- .filter(function () {- const $el = $(this as HTMLElement);- return (- $el.parent(findSubStr).length === 0 &&- $el.parent().parent(findSubStr).length === 0 &&- $el.parent().parent().parent(findSubStr).length === 0 &&- $el.parent().parent().parent().parent(findSubStr).length === 0- );- });- }- } else {- const textEditor = await this.noteContext.getTextEditor();- const el = textEditor?.editing.view.domRoots.values().next().value;- if (el) {- targetElement = $(el)- .find(findSubStr)- .filter(function () {- // When finding span[style*="color"] but not looking for span[style*="background-color"],- // the background-color error will be regarded as color, so it needs to be filtered- const $el = $(this as HTMLElement);- if (findSubStr.indexOf("color") >= 0 && findSubStr.indexOf("background-color") < 0) {- const color = this.style.color;- return !($el.prop("tagName") === "SPAN" && color === "");- }- return true;-- })- .filter(function () {- // Need to filter out the child elements of the element that has been found- const $el = $(this as HTMLElement);- return (- $el.parent(findSubStr).length === 0 &&- $el.parent().parent(findSubStr).length === 0 &&- $el.parent().parent().parent(findSubStr).length === 0 &&- $el.parent().parent().parent().parent(findSubStr).length === 0- );- });- }- }-- if (targetElement && targetElement[itemIndex]) {- targetElement[itemIndex].scrollIntoView({- behavior: "smooth",- block: "center"- });- } else {- console.warn("Unable to find the target element in the highlights list.");- }- }-- async closeHltCommand() {- if (this.noteContext?.viewScope) {- this.noteContext.viewScope.highlightsListTemporarilyHidden = true;- }- await this.refresh();- this.triggerCommand("reEvaluateRightPaneVisibility");- appContext.triggerEvent("reEvaluateHighlightsListWidgetVisibility", { noteId: this.noteId });- }-- async showHighlightsListWidgetEvent({ noteId }: EventData<"showHighlightsListWidget">) {- if (this.noteId === noteId) {- await this.refresh();- this.triggerCommand("reEvaluateRightPaneVisibility");- appContext.triggerEvent("reEvaluateHighlightsListWidgetVisibility", { noteId: this.noteId });- }- }-- async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {- if (this.noteId && loadResults.isNoteContentReloaded(this.noteId)) {- await this.refresh();- } else if (- loadResults- .getAttributeRows()- .find((attr) => attr.type === "label" && (attr.name?.toLowerCase().includes("readonly") || attr.name === "hideHighlightWidget") && attributeService.isAffecting(attr, this.note))- ) {- await this.refresh();- }- }-}diff --git a/apps/client/src/widgets/toc.ts b/apps/client/src/widgets/toc.tsdeleted file mode 100644index c07734bd3a..0000000000--- a/apps/client/src/widgets/toc.ts+++ /dev/null@@ -1,515 +0,0 @@-/**- * Table of contents widget- * (c) Antonio Tejada 2022- *- * By design, there's no support for nonsensical or malformed constructs:- * - headings inside elements (e.g. Trilium allows headings inside tables, but- * not inside lists)- * - nested headings when using raw HTML <H2><H3></H3></H2>- * - malformed headings when using raw HTML <H2></H3></H2><H3>- * - etc.- *- * In those cases, the generated TOC may be incorrect, or the navigation may lead- * to the wrong heading (although what "right" means in those cases is not- * clear), but it won't crash.- */-import { t } from "../services/i18n.js";-import attributeService from "../services/attributes.js";-import RightPanelWidget from "./right_panel_widget.js";-import options from "../services/options.js";-import OnClickButtonWidget from "./buttons/onclick_button.js";-import appContext, { type EventData } from "../components/app_context.js";-import type FNote from "../entities/fnote.js";-import DOMPurify, { type Config as DOMPurifyConfig } from "dompurify";--/**- * DOMPurify configuration for ToC headings. Uses DOMPurify's built-in HTML- * and MathML profiles for proper namespace handling (required for KaTeX- * rendered equations), then restricts to inline-only elements via FORBID_TAGS.- */-const TOC_PURIFY_CONFIG: DOMPurifyConfig = {- USE_PROFILES: { html: true, mathMl: true },- // Block elements that should never appear in a ToC heading- FORBID_TAGS: [- "script", "style", "iframe", "object", "embed", "link", "meta",- "base", "noscript", "template", "form", "input", "textarea",- "button", "select", "option",- // Block-level elements — headings should only contain inline content- "div", "p", "h1", "h2", "h3", "h4", "h5", "h6",- "blockquote", "pre", "section", "article", "aside", "nav",- "header", "footer", "main", "figure", "figcaption",- "table", "thead", "tbody", "tfoot", "tr", "th", "td",- "ul", "ol", "li", "dl", "dt", "dd",- "hr", "img", "video", "audio", "picture", "canvas",- "svg", "foreignObject"- ],- FORBID_ATTR: [- "onerror", "onload", "onclick", "onmouseover", "onfocus",- "onblur", "onsubmit", "onreset", "onchange", "oninput",- "onkeydown", "onkeyup", "onkeypress"- ],- RETURN_DOM: false,- RETURN_DOM_FRAGMENT: false-};--const TPL = /*html*/`<div class="toc-widget">- <style>- .toc-widget {- padding: 10px;- contain: none;- overflow: auto;- position: relative;- padding-inline-start:0px !important;- }-- .toc ol {- position: relative;- overflow: hidden;- padding-inline-start: 0px;- transition: max-height 0.3s ease;- }-- .toc li.collapsed + ol {- display:none;- }-- .toc li + ol:before {- content: "";- position: absolute;- height: 100%;- border-inline-start: 1px solid var(--main-border-color);- z-index: 10;- }-- .toc li {- display: flex;- position: relative;- list-style: none;- align-items: center;- padding-inline-start: 7px;- cursor: pointer;- text-align: justify;- word-wrap: break-word;- hyphens: auto;- }-- .toc > ol {- --toc-depth-level: 1;- }- .toc > ol > ol {- --toc-depth-level: 2;- }- .toc > ol > ol > ol {- --toc-depth-level: 3;- }- .toc > ol > ol > ol > ol {- --toc-depth-level: 4;- }- .toc > ol > ol > ol > ol > ol {- --toc-depth-level: 5;- }-- .toc > ol ol::before {- inset-inline-start: calc((var(--toc-depth-level) - 2) * 20px + 14px);- }-- .toc li {- padding-inline-start: calc((var(--toc-depth-level) - 1) * 20px + 4px);- }-- .toc li .collapse-button {- display: flex;- position: relative;- width: 21px;- height: 21px;- flex-shrink: 0;- align-items: center;- justify-content: center;- transition: transform 0.3s ease;- }-- .toc li.collapsed .collapse-button {- transform: rotate(-90deg);- }-- .toc li .item-content {- margin-inline-start: 25px;- flex: 1;- }-- .toc li .collapse-button + .item-content {- margin-inline-start: 4px;- }-- .toc li:hover {- font-weight: bold;- }- </style>-- <span class="toc"></span>-</div>`;--interface Toc {- $toc: JQuery<HTMLElement>;- headingCount: number;-}--export default class TocWidget extends RightPanelWidget {-- private $toc!: JQuery<HTMLElement>;- private tocLabelValue?: string | null;-- get widgetTitle() {- return t("toc.table_of_contents");- }-- get widgetButtons() {- return [- new OnClickButtonWidget()- .icon("bx-cog")- .title(t("toc.options"))- .titlePlacement("left")- .onClick(() => appContext.tabManager.openContextWithNote("_optionsTextNotes", { activate: true }))- .class("icon-action"),- new OnClickButtonWidget()- .icon("bx-x")- .titlePlacement("left")- .onClick((widget) => widget.triggerCommand("closeToc"))- .class("icon-action")- ];- }-- isEnabled() {- if (!super.isEnabled() || !this.note) {- return false;- }-- const isHelpNote = this.note.type === "doc" && this.note.noteId.startsWith("_help");- const isTextNote = this.note.type === "text";- const isNoteSupported = isTextNote || isHelpNote;-- return isNoteSupported- && !this.noteContext?.viewScope?.tocTemporarilyHidden- && this.noteContext?.viewScope?.viewMode === "default";- }-- async doRenderBody() {- this.$body.empty().append($(TPL));- this.$toc = this.$body.find(".toc");- }-- async refreshWithNote(note: FNote) {-- this.toggleInt(!!this.noteContext?.viewScope?.tocPreviousVisible);-- this.tocLabelValue = note.getLabelValue("toc");-- if (this.tocLabelValue === "hide") {- this.toggleInt(false);- this.triggerCommand("reEvaluateRightPaneVisibility");- return;- }-- if (!this.note || !this.noteContext?.viewScope) {- return;- }-- // Check for type text unconditionally in case alwaysShowWidget is set- if (this.note.type === "text") {- const blob = await note.getBlob();- if (blob) {- const toc = await this.getToc(blob.content);- this.#updateToc(toc);- }- return;- }-- if (this.note.type === "doc") {- /**- * For document note types, we obtain the content directly from the DOM since it allows us to obtain processed data without- * requesting data twice. However, when immediately navigating to a new note the new document is not yet attached to the hierarchy,- * resulting in an empty TOC. The fix is to simply wait for it to pop up.- * TODO: Use a better method that is not prone to unnecessary delays and race conditions.- */- setTimeout(async () => {- const $contentEl = await this.noteContext?.getContentElement();- if ($contentEl) {- const content = $contentEl.html();- const toc = await this.getToc(content);- this.#updateToc(toc);- } else {- console.warn("Unable to get content element for doctype");- }- }, 250);- }- }-- #updateToc({ $toc, headingCount }: Toc) {- this.$toc.empty();- if ($toc) {- this.$toc.append($toc);- }-- const tocLabelValue = this.tocLabelValue;-- const visible = tocLabelValue === "" || tocLabelValue === "show" || headingCount >= (options.getInt("minTocHeadings") ?? 0);- this.toggleInt(visible);- if (this.noteContext?.viewScope) {- this.noteContext.viewScope.tocPreviousVisible = visible;- }-- this.triggerCommand("reEvaluateRightPaneVisibility");- }-- /**- * Rendering formulas in strings using katex- *- * @param html Note's html content- * @returns The HTML content with mathematical formulas rendered by KaTeX.- */- async replaceMathTextWithKatax(html: string) {- const mathTextRegex = /<span class="math-tex">\\\(([\s\S]*?)\\\)<\/span>/g;- var matches = [...html.matchAll(mathTextRegex)];- let modifiedText = html;-- if (matches.length > 0) {- // KaTeX is heavy, so the math service is only loaded when there are formulas to render.- const { default: katex } = await import("../services/math.js");-- for (const match of matches) {- let latexCode = match[1];- let rendered;-- try {- rendered = katex.renderToString(latexCode, {- throwOnError: false- });- } catch (e) {- console.error("KaTeX rendering error:", e);- rendered = match[0]; // Fall back to original on error- }-- // Replace the matched formula in the modified text- modifiedText = modifiedText.replace(match[0], rendered);- }- }- return modifiedText;- }-- /**- * Builds a jquery table of contents.- *- * @param html Note's html content- * @returns ordered list table of headings, nested by heading level- * with an onclick event that will cause the document to scroll to- * the desired position.- */- async getToc(html: string): Promise<Toc> {- // Regular expression for headings <h1>...</h1> using non-greedy- // matching and backreferences- const headingTagsRegex = /<h(\d+)[^>]*>(.*?)<\/h\1>/gi;-- // Use jquery to build the table rather than html text, since it makes- // it easier to set the onclick event that will be executed with the- // right captured callback context- let $toc = $("<ol>");- // Note heading 2 is the first level Trilium makes available to the note- let curLevel = 2;- const $ols = [$toc];- let $previousLi: JQuery<HTMLElement> | undefined;-- if (!(this.noteContext?.viewScope?.tocCollapsedHeadings instanceof Set)) {- this.noteContext!.viewScope!.tocCollapsedHeadings = new Set<string>();- }- const tocCollapsedHeadings = this.noteContext!.viewScope!.tocCollapsedHeadings as Set<string>;- const validHeadingKeys = new Set<string>(); // Used to clean up obsolete entries in tocCollapsedHeadings-- let headingCount = 0;- for (let m: RegExpMatchArray | null = null, headingIndex = 0; (m = headingTagsRegex.exec(html)) !== null; headingIndex++) {- //- // Nest/unnest whatever necessary number of ordered lists- //- const newLevel = parseInt(m[1]);- const levelDelta = newLevel - curLevel;- if (levelDelta > 0) {- // Open as many lists as newLevel - curLevel- for (let i = 0; i < levelDelta; i++) {- const $ol = $("<ol>");- $ols[$ols.length - 1].append($ol);- $ols.push($ol);-- if ($previousLi) {- const headingKey = `h${newLevel}_${headingIndex}_${$previousLi?.text().trim()}`;- this.setupCollapsibleHeading($ol, $previousLi, headingKey, tocCollapsedHeadings, validHeadingKeys);- }- }- } else if (levelDelta < 0) {- // Close as many lists as curLevel - newLevel- // be careful not to empty $ols completely, the root element should stay (could happen with a rogue h1 element)- for (let i = 0; i < -levelDelta && $ols.length > 1; ++i) {- $ols.pop();- }- }- curLevel = newLevel;-- //- // Create the list item and set up the click callback- //-- const headingText = await this.replaceMathTextWithKatax(m[2]);- const $itemContent = $('<div class="item-content">').html(DOMPurify.sanitize(headingText, TOC_PURIFY_CONFIG) as string);- const $li = $("<li>").append($itemContent)- .on("click", () => this.jumpToHeading(headingIndex));- $ols[$ols.length - 1].append($li);- headingCount = headingIndex;- $previousLi = $li;- }-- // Clean up unused entries in tocCollapsedHeadings- for (const key of tocCollapsedHeadings) {- if (!validHeadingKeys.has(key)) {- tocCollapsedHeadings.delete(key);- }- }-- $toc = this.pullLeft($toc);-- return {- $toc,- headingCount- };- }-- /**- * Reduce indent if a larger headings are not being used: https://github.com/zadam/trilium/issues/4363- */- pullLeft($toc: JQuery<HTMLElement>) {- while (true) {- const $children = $toc.children();-- if ($children.length !== 1) {- break;- }-- const $first = $toc.children(":first");-- if ($first[0].tagName.toLowerCase() !== "ol") {- break;- }-- $toc = $first;- }- return $toc;- }-- async jumpToHeading(headingIndex: number) {- if (!this.note || !this.noteContext) {- return;- }-- // A readonly note can change state to "readonly disabled- // temporarily" (ie "edit this note" button) without any- // intervening events, do the readonly calculation at navigation- // time and not at outline creation time- // See https://github.com/zadam/trilium/issues/2828- const isDocNote = this.note.type === "doc";- const isReadOnly = await this.noteContext.isReadOnly();-- let $container: JQuery<HTMLElement> | null = null;- if (isReadOnly || isDocNote) {- $container = await this.noteContext.getContentElement();- } else {- const textEditor = await this.noteContext.getTextEditor();- if (textEditor?.sourceElement) {- $container = $(textEditor.sourceElement);- }- }-- const headingElement = $container- ?.find(":header:not(.include-note :header)")?.[headingIndex];- headingElement?.scrollIntoView({ behavior: "smooth" });- }-- async setupCollapsibleHeading($ol: JQuery<HTMLElement>, $previousLi: JQuery<HTMLElement>, headingKey: string, tocCollapsedHeadings: Set<string>, validHeadingKeys: Set<string>) {- if ($previousLi && $previousLi.find(".collapse-button").length === 0) {- const $collapseButton = $('<div class="collapse-button bx bx-chevron-down"></div>');- $previousLi.prepend($collapseButton);-- // Restore the previous collapsed state- if (tocCollapsedHeadings?.has(headingKey)) {- $previousLi.addClass("collapsed");- validHeadingKeys.add(headingKey);- } else {- $previousLi.removeClass("collapsed");- }-- $collapseButton.on("click", (event) => {- event.stopPropagation();- if ($previousLi.hasClass("animating")) return;- const willCollapse = !$previousLi.hasClass("collapsed");- $previousLi.addClass("animating");-- if (willCollapse) { // Collapse- $ol.css("maxHeight", `${$ol.prop("scrollHeight")}px`);- requestAnimationFrame(() => {- requestAnimationFrame(() => {- $ol.css("maxHeight", "0px");- $collapseButton.css("transform", "rotate(-90deg)");- });- });- setTimeout(() => {- $ol.css("maxHeight", "");- $previousLi.addClass("collapsed");- $previousLi.removeClass("animating");- }, 300);- } else { // Expand- $previousLi.removeClass("collapsed");- $ol.css("maxHeight", "0px");- requestAnimationFrame(() => {- $ol.css("maxHeight", `${$ol.prop("scrollHeight")}px`);- $collapseButton.css("transform", "");- });- setTimeout(() => {- $ol.css("maxHeight", "");- $previousLi.removeClass("animating");- }, 300);- }-- if (willCollapse) { // Store collapsed headings- tocCollapsedHeadings!.add(headingKey);- } else {- tocCollapsedHeadings!.delete(headingKey);- }- });- }- }-- async closeTocCommand() {- if (this.noteContext?.viewScope) {- this.noteContext.viewScope.tocTemporarilyHidden = true;- }- await this.refresh();- this.triggerCommand("reEvaluateRightPaneVisibility");- appContext.triggerEvent("reEvaluateTocWidgetVisibility", { noteId: this.noteId });- }-- async showTocWidgetEvent({ noteId }: EventData<"showTocWidget">) {- if (this.noteId === noteId) {- await this.refresh();- this.triggerCommand("reEvaluateRightPaneVisibility");- appContext.triggerEvent("reEvaluateTocWidgetVisibility", { noteId: this.noteId });- }- }-- async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {- if (this.noteId && loadResults.isNoteContentReloaded(this.noteId)) {- await this.refresh();- } else if (- loadResults- .getAttributeRows()- .find((attr) => attr.type === "label" && ((attr.name ?? "").toLowerCase().includes("readonly") || attr.name === "toc") && attributeService.isAffecting(attr, this.note))- ) {- await this.refresh();- }- }-}diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.spec.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.spec.tsxindex 9a262c3fec..2b654c6ea2 100644--- a/apps/client/src/widgets/type_widgets/options/text_notes.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/text_notes.spec.tsx@@ -10,11 +10,6 @@ const mocks = vi.hoisted(() => ({vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));-// The new layout drops the right pane's own settings; this file's page is the old-layout one.-vi.mock("../../../services/experimental_features", () => ({- isExperimentalFeatureEnabled: () => false-}));-vi.mock("../../../services/syntax_highlight", () => ({ensureMimeTypesForHighlighting: async () => {},loadHighlightingTheme: vi.fn()@@ -85,15 +80,6 @@ describe("the page's shape", () => {// A pair of pictures, given a card that stands back behind them.expect(host.querySelector(".thumbnail-selector-option-card .radio-with-illustration")).not.toBeNull();});-- it("tells what the highlights list is made of apart from where it is shown", () => {- open();-- expect(cardHeadings()).toEqual(expect.arrayContaining([- "highlights_list.title",- "highlights_list.visibility_title"- ]));- });});describe("the formatting toolbar", () => {diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.tsxindex fa14782814..830930b7ba 100644--- a/apps/client/src/widgets/type_widgets/options/text_notes.tsx+++ b/apps/client/src/widgets/type_widgets/options/text_notes.tsx@@ -5,17 +5,14 @@ import { getThemeVariant, Themes } from "@triliumnext/highlightjs";import type { CSSProperties } from "preact";import { useEffect, useMemo, useRef, useState } from "preact/hooks";-import { isExperimentalFeatureEnabled } from "../../../services/experimental_features";import { t } from "../../../services/i18n";import { ensureMimeTypesForHighlighting, loadHighlightingTheme } from "../../../services/syntax_highlight";import { formatDateTime, toggleBodyClass } from "../../../services/utils";import ActionButton from "../../react/ActionButton";import { Card, CardSection, OptionCardSection } from "../../react/Card";import Dropdown from "../../react/Dropdown";-import FormGroup from "../../react/FormGroup";import { FormListItem } from "../../react/FormList";import FormSelect, { FormSelectGroup, FormSelectWithGroups } from "../../react/FormSelect";-import FormText from "../../react/FormText";import FormTextBox, { FormTextBoxWithUnit } from "../../react/FormTextBox";import FormToggle from "../../react/FormToggle";import { useColorScheme, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";@@ -29,8 +26,6 @@ import ThemeModeSelector from "./components/ThemeModeSelector";import { HighlightsListOptions } from "./highlights_list_options";import HelpButton from "../../react/HelpButton";-const isNewLayout = isExperimentalFeatureEnabled("new-layout");-export default function TextNoteSettings() {return (<>@@ -41,7 +36,6 @@ export default function TextNoteSettings() {<AutomaticReplacements /><Editor /><CodeBlockStyle />- <TableOfContent /><HighlightsList /><RelatedSettings items={[{@@ -674,50 +668,12 @@ interface ThemeData {title: string;}-function TableOfContent() {- const [ minTocHeadings, setMinTocHeadings ] = useTriliumOption("minTocHeadings");-- return (!isNewLayout &&- <Card className="text-notes-toc"- heading={t("table_of_contents.title")}- description={t("table_of_contents.description")}- >+function HighlightsList() {+ return (+ <Card heading={t("highlights_list.title")}><CardSection>- <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>+ <HighlightsListOptions /></CardSection></Card>);}--function HighlightsList() {- return (- <>- <Card heading={t("highlights_list.title")}>- <CardSection>- <HighlightsListOptions />- </CardSection>- </Card>-- {/* Its own card rather than a heading inside the one above: what the list is made of and- where it is shown are two subjects, and a card heading is what tells them apart. */}- {!isNewLayout && (- <Card heading={t("highlights_list.visibility_title")}>- <CardSection>- <FormText>{t("highlights_list.visibility_description")}</FormText>- <FormText>{t("highlights_list.shortcut_info")}</FormText>- </CardSection>- </Card>- )}- </>- );-}diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.tsindex 3ab0e100bd..ce28afccd3 100644--- a/packages/commons/src/lib/builtin_attributes.ts+++ b/packages/commons/src/lib/builtin_attributes.ts@@ -187,8 +187,6 @@ const BUILTIN_ATTRIBUTES = [{ type: "label", name: "textSnippetDescription", valueType: "text", hasUserValue: true },// Offers the note's content as an instruction in the text editor's AI assistant menu.{ type: "label", name: "aiQuickAction", valueType: "boolean" },- // Forces the table of contents open or shut; without the label the heading count decides.- { type: "label", name: "toc", valueType: "select", selectOptions: [ "show", "hide" ] },{ type: "label", name: "color", valueType: "color" },{ type: "label", name: "keepCurrentHoisting", valueType: "boolean" },{ type: "label", name: "executeButton", valueType: "boolean" },@@ -207,7 +205,6 @@ const BUILTIN_ATTRIBUTES = [{ type: "label", name: "mediaNotesPlayMode", valueType: "select", selectOptions: [ "loop", "next" ] },{ type: "label", name: "collection", valueType: "boolean" },{ type: "label", name: "webViewSrc", valueType: "url", isDangerous: true },- { type: "label", name: "hideHighlightWidget", valueType: "boolean" },{ type: "label", name: "iconPack", valueType: "text", isDangerous: true },{ type: "label", name: "docName", valueType: "text", isDangerous: true },{ type: "label", name: "docUrl", valueType: "url", isDangerous: true },diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 244134ed4b..d6ce6cc679 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -156,7 +156,6 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActiautoReadonlySizeCode: number;maxContentWidth: number;centerContent: boolean;- minTocHeadings: number;eraseUnusedAttachmentsAfterSeconds: number;eraseUnusedAttachmentsAfterTimeScale: number;logRetentionDays: number;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 603ab5b5ff..50b423655e 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -104,7 +104,6 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["centerContent","compressImages","downloadImagesAutomatically",- "minTocHeadings","highlightsList","checkForUpdates","disableTray",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 2ff6a0b561..c9216a64b8 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -221,7 +221,6 @@ const defaultOptions: DefaultOption[] = [{ name: "centerContent", value: "false", isSynced: false },{ name: "compressImages", value: "true", isSynced: true },{ name: "downloadImagesAutomatically", value: "true", isSynced: true },- { name: "minTocHeadings", value: "5", isSynced: true },{ name: "highlightsList", value: '["underline","color","bgColor"]', isSynced: true },{ name: "checkForUpdates", value: "true", isSynced: true },{ name: "disableTray", value: "false", isSynced: false },