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
client: improve again tab switching speed
Adorian Doranc1ca5f6883ed
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 112de0ce8f..d938c43d29 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1649,6 +1649,26 @@ pre.code-embed-editor.read-only .cm-activeLine {display: none;}+/* Keeps the style and layout of hidden tabs, so showing one again needs no full relayout. */+@supports (content-visibility: hidden) {+ #center-pane > .split-note-container-widget > .note-split.hidden-ext {+ display: flex !important;+ flex: 0 0 100% !important;+ margin-inline: -100% 0;+ content-visibility: hidden;+ clip-path: inset(50%);+ animation: none;+ }+}++.caret-stop {+ position: absolute;+ width: 0;+ height: 0;+ overflow: hidden;+ user-select: text;+}+.right-dropdown-widget {flex-shrink: 0;}diff --git a/apps/client/src/widgets/containers/split_note_container.spec.tsx b/apps/client/src/widgets/containers/split_note_container.spec.tsxindex 71013a807e..00aeff5cbc 100644--- a/apps/client/src/widgets/containers/split_note_container.spec.tsx+++ b/apps/client/src/widgets/containers/split_note_container.spec.tsx@@ -59,6 +59,14 @@ describe("SplitNoteContainer", () => {return container;}+ it("keeps its splits between the caret stops at both of its ends", async () => {+ const container = await openSplits([ "split-a", "split-b" ]);++ const children = [ ...container.$widget[0].children ];+ expect(children.map((child) => child.getAttribute("data-ntx-id") ?? child.className))+ .toEqual([ "caret-stop", "split-a", "split-b", "caret-stop" ]);+ });+it("stops delivering events to a split once its tab is closed", async () => {const container = await openSplits([ "split-a", "split-b" ]);const [ staysOpen, getsClosed ] = container.children;diff --git a/apps/client/src/widgets/containers/split_note_container.ts b/apps/client/src/widgets/containers/split_note_container.tsindex 367b642a93..8cd005a9fa 100644--- a/apps/client/src/widgets/containers/split_note_container.ts+++ b/apps/client/src/widgets/containers/split_note_container.ts@@ -6,7 +6,7 @@ import { isMobile } from "../../services/utils.js";import type BasicWidget from "../basic_widget.js";import { getTabToward } from "../mobile_widgets/tab_swipe.js";import NoteContextAwareWidget from "../note_context_aware_widget.js";-import { markVisibleSplits } from "../note_wrapper.js";+import { createCaretStop, markVisibleSplits } from "../note_wrapper.js";import FlexContainer from "./flex_container.js";interface SplitNoteWidget extends BasicWidget {@@ -38,6 +38,11 @@ export default class SplitNoteContainer extends FlexContainer<SplitNoteWidget> {this.collapsible();}+ doRender() {+ super.doRender();+ this.$widget.append(createCaretStop(), createCaretStop());+ }+async newNoteContextCreatedEvent({ noteContext }: EventData<"newNoteContextCreated">) {const widget = this.widgetFactory();@@ -46,7 +51,7 @@ export default class SplitNoteContainer extends FlexContainer<SplitNoteWidget> {$renderedWidget.attr("data-ntx-id", noteContext.ntxId);$renderedWidget.on("click", () => appContext.tabManager.activateNoteContext(noteContext.ntxId));- this.$widget.append($renderedWidget);+ this.$widget.children(".caret-stop").last().before($renderedWidget);widget.handleEvent("initialRenderComplete", {});diff --git a/apps/client/src/widgets/note_wrapper.spec.ts b/apps/client/src/widgets/note_wrapper.spec.tsindex d00ba5bbdc..b0e487099e 100644--- a/apps/client/src/widgets/note_wrapper.spec.ts+++ b/apps/client/src/widgets/note_wrapper.spec.ts@@ -95,6 +95,46 @@ describe("NoteWrapperWidget", () => {expect(hasBackgroundEffects(doc)).toBe(false);});+ it("places a caret stop at both ends of the split", () => {+ const widget = new NoteWrapperWidget();+ widget.render();++ const split = widget.$widget[0];+ for (const stop of [ split.firstElementChild, split.lastElementChild ]) {+ expect(stop?.classList.contains("caret-stop")).toBe(true);+ expect(stop?.getAttribute("aria-hidden")).toBe("true");+ expect(stop?.textContent).toBe("");+ }+ });++ it("releases the focus and the selection inside the split it hides, and no others", () => {+ const widget = new NoteWrapperWidget();+ widget.render();+ const inside = document.createElement("input");+ const insideText = document.createTextNode("Inside");+ widget.$widget.append(inside, insideText);+ const outside = document.createElement("input");+ const outsideText = document.createTextNode("Outside");+ document.body.append(widget.$widget[0], outside, outsideText);+ const selection = document.getSelection();++ outside.focus();+ selection?.collapse(outsideText, 1);+ widget.toggleExt(false);+ expect(document.activeElement).toBe(outside);+ expect(selection?.anchorNode).toBe(outsideText);++ widget.toggleExt(true);+ inside.focus();+ selection?.collapse(insideText, 1);+ expect(document.activeElement).toBe(inside);+ widget.toggleExt(false);+ expect(document.activeElement).toBe(document.body);+ expect(selection?.rangeCount).toBe(0);++ document.body.replaceChildren();+ });+it("updates the body classes of the outer splits when its note changes translucency", () => {const container = document.createElement("div");const widget = new NoteWrapperWidget();diff --git a/apps/client/src/widgets/note_wrapper.ts b/apps/client/src/widgets/note_wrapper.tsindex f4023c69f4..b6c2121d42 100644--- a/apps/client/src/widgets/note_wrapper.ts+++ b/apps/client/src/widgets/note_wrapper.ts@@ -21,10 +21,18 @@ export default class NoteWrapperWidget extends FlexContainer<BasicWidget> {doRender() {super.doRender();+ this.$widget.prepend(createCaretStop()).append(createCaretStop());// Adds `note-split` before the note context arrives: `resizer.ts` selects the panes by it.this.refresh();}+ toggleExt(show: boolean | null | "" | undefined) {+ super.toggleExt(show);+ if (!show) {+ releaseFocusAndSelection(this.$widget[0]);+ }+ }+setNoteContextEvent({ noteContext }: EventData<"setNoteContext">) {this.noteContext = noteContext;this.refresh();@@ -139,6 +147,35 @@ export function markVisibleSplits(container: HTMLElement) {bodyClasses.toggle("last-split-bgfx", !!lastVisible?.classList.contains("bgfx"));}+/**+ * Returns an invisible, selectable element. When an editor takes focus, Chromium searches the page+ * for the nearest selectable position, and stops at this element instead of walking through the+ * notes of the hidden tabs.+ */+export function createCaretStop() {+ const stop = document.createElement("div");+ stop.className = "caret-stop";+ stop.setAttribute("aria-hidden", "true");+ stop.textContent = "";+ return stop;+}++/**+ * Blurs the focused element and clears the selection inside a split that is being hidden. Chromium+ * keeps both in a `content-visibility: hidden` split, where resolving the caret walks the note.+ */+function releaseFocusAndSelection(split: HTMLElement) {+ const focused = document.activeElement;+ if (focused instanceof HTMLElement && split.contains(focused)) {+ focused.blur();+ }++ const selection = document.getSelection();+ if (selection?.anchorNode && split.contains(selection.anchorNode)) {+ selection.removeAllRanges();+ }+}+/*** Whether the split should be translucent (`bgfx`), letting the window background effect show through.* This suits notes that render their content on a bare background (media, option pages, and thediff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex 1b03334598..41a2827aec 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -1091,7 +1091,7 @@ export function useWhenShown(ref: RefObject<Element | null> | undefined) {} else if (waiting) {waiting.callback = callback;} else {- // `display: none` gives the element no size, so showing it resizes it.+ // A `ResizeObserver` first reports a hidden element once it is shown.const observer = new ResizeObserver(() => {const current = waitingRef.current;if (current && isShown(element)) {diff --git a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx b/apps/client/src/widgets/type_widgets/code/Code.spec.tsxindex 41d7157160..50f97585ea 100644--- a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.spec.tsx@@ -32,6 +32,13 @@ vi.mock("./CodeMirror", async (importOriginal) => {// The `/` list of a Markdown editor loads the task states from the `_taskStates` subtree.vi.mock("../../../services/task_states", () => ({ getTaskStateDefinitions: async () => [] }));+// jsdom has no `checkVisibility()`, and lays nothing out, so an editor counts as hidden unless a+// test says otherwise.+beforeEach(() => stubVisibility(false));+afterEach(() => {+ Reflect.deleteProperty(HTMLElement.prototype, "checkVisibility");+});+describe("EditableCode", () => {const parent = { registerHandler() {}, removeHandler() {}, componentId: "c" } as any;const markdown = { type: "code", mime: "text/x-markdown" } as const;@@ -54,8 +61,9 @@ describe("EditableCode", () => {vi.restoreAllMocks();});- // jsdom has no layout, so every editor has a null `offsetParent` and counts as hidden.it("reports each note loaded into a hidden editor", async () => {+ // A hidden tab keeps its editor laid out under `content-visibility: hidden`.+ vi.spyOn(HTMLElement.prototype, "offsetParent", "get").mockReturnValue(document.body);const onContentChanged = vi.fn();let container: HTMLElement | undefined;@@ -69,7 +77,7 @@ describe("EditableCode", () => {});it("reports a load into a visible editor once", async () => {- vi.spyOn(HTMLElement.prototype, "offsetParent", "get").mockReturnValue(document.body);+ stubVisibility(true);const onContentChanged = vi.fn();await act(async () => { renderInto(show(noteA, onContentChanged)); });@@ -209,3 +217,10 @@ describe("API log", () => {}});});++function stubVisibility(isVisible: boolean) {+ Object.defineProperty(HTMLElement.prototype, "checkVisibility", {+ configurable: true,+ value: () => isVisible+ });+}diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsxindex f41d648ecb..2734cd3bc7 100644--- a/apps/client/src/widgets/type_widgets/code/Code.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx@@ -135,7 +135,7 @@ export function EditableCode({if (!codeEditor) return;codeEditor.setText(content ?? "");// `setText()` loads a hidden editor without an update, so its listener reports nothing.- if (codeEditor.dom.offsetParent === null) {+ if (!codeEditor.dom.checkVisibility()) {onContentChanged?.(content ?? "");}codeEditor.setMimeType(note.mime);diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.tsindex a7d53353f1..cb36ae57bb 100644--- a/packages/codemirror/src/index.spec.ts+++ b/packages/codemirror/src/index.spec.ts@@ -191,14 +191,21 @@ describe("CodeMirror", () => {describe("setText while hidden", () => {const bigDoc = Array.from({ length: 10_000 }, (_, i) => `line ${i}`).join("\n");- /** happy-dom has no layout, so offsetParent cannot tell hidden from visible on its own. */- function pinOffsetParent(el: HTMLElement, value: Element | null) {- Object.defineProperty(el, "offsetParent", { value, configurable: true });+ /**+ * Pins what `checkVisibility()` reports, as happy-dom renders nothing. A hidden tab keeps+ * its editor laid out under `content-visibility: hidden`, so the `offsetParent` stays set.+ */+ function pinVisibility(el: HTMLElement, isVisible: boolean) {+ Object.defineProperty(el, "checkVisibility", {+ value: () => isVisible,+ configurable: true+ });+ Object.defineProperty(el, "offsetParent", { value: document.body, configurable: true });}it("keeps the viewport small instead of rendering every line of the new document", () => {editor = build();- pinOffsetParent(editor.dom, null);+ pinVisibility(editor.dom, false);editor.setText(bigDoc);expect(editor.getText()).toBe(bigDoc);@@ -206,7 +213,7 @@ describe("CodeMirror", () => {expect(editor.dom.querySelectorAll(".cm-line").length).toBeLessThan(1_000);// The rebuilt view keeps accepting transactions once visible again.- pinOffsetParent(editor.dom, document.body);+ pinVisibility(editor.dom, true);editor.setText("visible again");expect(editor.getText()).toBe("visible again");editor.dispatch({ changes: { from: 0, insert: "still " } });@@ -217,13 +224,13 @@ describe("CodeMirror", () => {const onContentChanged = vi.fn();editor = build({ onContentChanged });- pinOffsetParent(editor.dom, null);+ pinVisibility(editor.dom, false);editor.setText(bigDoc);// The hidden path swaps the state in without an update, so no change notification// fires — hidden loads are programmatic, and the caller resets history right after.expect(onContentChanged).not.toHaveBeenCalled();- pinOffsetParent(editor.dom, document.body);+ pinVisibility(editor.dom, true);editor.setText("typed");expect(onContentChanged).toHaveBeenCalledTimes(1);});diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex b212951af1..7d5d1a5cb1 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -373,14 +373,10 @@ export default class CodeMirror extends EditorView {},annotations: Transaction.addToHistory.of(!isLoad)});- // Dispatching a full-document replacement maps the viewport onto the whole new document.- // A visible editor's next measure shrinks it back, but an editor inside a display:none- // subtree cannot measure (`measure()` bails out off-screen), so every line of the new- // document stays rendered in the DOM for as long as the editor stays hidden — e.g. a- // background tab that received its content after being covered. Rebuilding the view from- // the updated state resets the viewport to the initial estimate instead; the first- // measure after the editor becomes visible then sizes it to the real geometry.- if (this.dom.offsetParent === null) {+ // Dispatching a full-document replacement maps the viewport onto the whole new document,+ // which only a measure shrinks back. A hidden editor, such as one in a background tab, is+ // rebuilt from the new state instead, so it does not keep every line rendered.+ if (!this.dom.checkVisibility()) {this.setState(transaction.state);} else {this.dispatch(transaction);