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: fix some issues
Adorian Doran17d44cb137b2
diff --git a/apps/client/src/widgets/containers/left_pane_container.spec.ts b/apps/client/src/widgets/containers/left_pane_container.spec.tsindex 2a4f01a2ed..27c62fe542 100644--- a/apps/client/src/widgets/containers/left_pane_container.spec.ts+++ b/apps/client/src/widgets/containers/left_pane_container.spec.ts@@ -121,6 +121,33 @@ describe("LeftPaneContainer", () => {expect(host.hasClass("hidden-int")).toBe(false);});+ it("moves the focus to the note when its shortcut closes a peek from the tree", () => {+ mount(false);+ document.body.insertAdjacentHTML(+ "beforeend", `<button class="left-pane-peek-button"></button>`+ );+ const tree = container.$widget.find(".tree-stub")[0];+ const peekButton = document.querySelector<HTMLElement>(".left-pane-peek-button");+ tree.tabIndex = -1;++ container.peekLeftPaneEvent();+ tree.focus();+ expect(document.activeElement).toBe(tree);+ triggerEvent.mockClear();+ container.peekLeftPaneEvent();+ expect(container.$widget.hasClass("hidden-int")).toBe(true);+ expect(triggerEvent).toHaveBeenCalledWith("focusOnDetail", { ntxId: undefined });++ // The peek button closing it keeps the focus.+ container.peekLeftPaneEvent();+ peekButton?.focus();+ expect(document.activeElement).toBe(peekButton);+ triggerEvent.mockClear();+ container.peekLeftPaneEvent();+ expect(container.$widget.hasClass("hidden-int")).toBe(true);+ expect(triggerEvent).not.toHaveBeenCalledWith("focusOnDetail", expect.anything());+ });+it("gives its peek up to another pane's, and stays docked", () => {mount(false);const host = container.$widget;diff --git a/apps/client/src/widgets/containers/left_pane_container.ts b/apps/client/src/widgets/containers/left_pane_container.tsindex 654c9a7f26..de86305a32 100644--- a/apps/client/src/widgets/containers/left_pane_container.ts+++ b/apps/client/src/widgets/containers/left_pane_container.ts@@ -70,6 +70,7 @@ export default class LeftPaneContainer extends Container<Component> {this.mode = reducePaneMode(prev, action);if (this.mode === prev) return;+ const hasFocus = this.$widget[0]?.contains(document.activeElement) ?? false;this.applyMode();const persist = persistedPaneVisible(prev, this.mode);@@ -79,8 +80,9 @@ export default class LeftPaneContainer extends Container<Component> {if (this.mode !== "closed") {this.triggerEvent("focusTree", {});- } else if (action === "close" || action === "toggleDocked") {- // Only a hard close moves the focus. A dismissed peek leaves it on the pressed element.+ } else if (action === "close" || action === "toggleDocked"+ || (action === "togglePeek" && hasFocus)) {+ // A dismissed peek, or one the peek button closes, leaves the focus where it is.const ntxId = appContext.tabManager.getActiveContext()?.ntxId;const noteContainer = document.querySelector(`.note-split[data-ntx-id="${ntxId}"]`);if (!noteContainer?.contains(document.activeElement)) {diff --git a/apps/client/src/widgets/react/Card.css b/apps/client/src/widgets/react/Card.cssindex c2436467f1..5feffe7845 100644--- a/apps/client/src/widgets/react/Card.css+++ b/apps/client/src/widgets/react/Card.css@@ -379,7 +379,6 @@ body[dir=rtl] .tn-card-option::after {}}- /* Transparent: each button paints itself, and the gaps show the card through. */.tn-card-section.tn-card-adders {display: flex;gap: var(--card-section-gap);@@ -388,8 +387,6 @@ body[dir=rtl] .tn-card-option::after {background: transparent;}- /* Painted as a segment rather than a button, all of one width, undoing what Bootstrap and the- theme give a button. */.tn-card-adders > button.tn-card-adder.btn {display: flex;flex: 1 1 0;@@ -418,7 +415,6 @@ body[dir=rtl] .tn-card-option::after {}}- /* The row is transparent, so its buttons carry the card's corners. */.tn-card-adders:first-of-type > button.tn-card-adder:first-child {border-start-start-radius: var(--card-border-radius);}diff --git a/apps/client/src/widgets/react/editor_save_race.spec.tsx b/apps/client/src/widgets/react/editor_save_race.spec.tsxindex 2fb5296573..74e952ae1c 100644--- a/apps/client/src/widgets/react/editor_save_race.spec.tsx+++ b/apps/client/src/widgets/react/editor_save_race.spec.tsx@@ -15,7 +15,7 @@* standing in for a slow blob fetch (remote server / PWA).*/import { deferred } from "@triliumnext/commons";-import { render } from "preact";+import { render, type RefObject } from "preact";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -37,15 +37,17 @@ vi.stubGlobal("logInfo", vi.fn());let currentSpacedUpdate: SpacedUpdate<SavedData | undefined> | undefined;/** Stand-in for EditableText: `editor.content` plays the role of the live CKEditor document. */-function FakeEditor({ note, noteContext, editor }: {+function FakeEditor({ note, noteContext, editor, shownRef }: {note: FNote;noteContext: NoteContext | null;editor: { content: string };+ shownRef?: RefObject<Element | null>;}) {currentSpacedUpdate = useEditorSpacedUpdate({note,noteContext,noteType: "text",+ shownRef,getData: () => ({ content: editor.content }),onContentChange(newContent) {editor.content = newContent;@@ -61,7 +63,7 @@ function getSpacedUpdate(): SpacedUpdate<SavedData | undefined> {return currentSpacedUpdate;}-function setupEditorHarness({ withParent = false } = {}) {+function setupEditorHarness({ withParent = false, withShownRef = false } = {}) {const noteA = buildNote({ title: "Note A", type: "text", content: "AAA" });const noteB = buildNote({ title: "Note B", type: "text", content: "BBB" });@@ -88,10 +90,15 @@ function setupEditorHarness({ withParent = false } = {}) {const parent = withParent ? new Component() : null;const noteContext = withParent ? new NoteContext("test-ntx") : null;+ const shownRef = withShownRef ? { current: container } : undefined;async function show(note: FNote) {await act(async () => {- const editorEl = <FakeEditor note={note} noteContext={noteContext} editor={editor} />;+ const editorEl = (+ <FakeEditor+ note={note} noteContext={noteContext} editor={editor} shownRef={shownRef}+ />+ );render(parent ? <ParentComponent.Provider value={parent}>{editorEl}</ParentComponent.Provider> : editorEl,container@@ -211,32 +218,61 @@ describe("note switch save race (#9614)", () => {cleanupContainer = harness.container;const { noteA, editor, parent, show } = harness;await show(noteA);- const savedElsewhere = async (content: string) => {- noteA.getBlob = async () => new FBlob({- blobId: `blob-${content}`,- content,- contentLength: content.length,- dateModified: "",- utcDateModified: ""- });- const loadResults = new LoadResults([]);- loadResults.addNoteContent(noteA.noteId, "another-editor");- await act(async () => {- await parent?.handleEvent("entitiesReloaded", { loadResults });- });- await vi.advanceTimersByTimeAsync(20);- };editor.content = "AAA typed here";getSpacedUpdate().scheduleUpdate();- await savedElsewhere("AAA typed elsewhere");+ await reportSave(parent, noteA, "another-editor", "AAA typed elsewhere");expect(editor.content).toBe("AAA typed here");await vi.advanceTimersByTimeAsync(1500);- await savedElsewhere("AAA typed elsewhere again");+ await reportSave(parent, noteA, "another-editor", "AAA typed elsewhere again");expect(editor.content).toBe("AAA typed elsewhere again");});+ it("drops a save made elsewhere while hidden once a later save here replaces it", async () => {+ const resizeCallbacks: (() => void)[] = [];+ const { ResizeObserver } = globalThis;+ globalThis.ResizeObserver = class {+ constructor(callback: () => void) {+ resizeCallbacks.push(callback);+ }+ observe() {}+ disconnect() {}+ } as unknown as typeof ResizeObserver;+ const harness = setupEditorHarness({ withParent: true, withShownRef: true });+ cleanupContainer = harness.container;+ const { noteA, editor, parent, container, putsTo, show } = harness;+ const showContainer = async () => {+ container.style.display = "";+ await act(async () => {+ for (const callback of resizeCallbacks) callback();+ });+ };++ try {+ await show(noteA);+ editor.content = "AAA typed here";+ getSpacedUpdate().scheduleUpdate();+ container.style.display = "none";+ await reportSave(parent, noteA, "another-editor", "AAA typed elsewhere");+ await vi.advanceTimersByTimeAsync(1500);+ expect(putsTo(noteA)).toContainEqual({+ url: `notes/${noteA.noteId}/data`, content: "AAA typed here"+ });+ await reportSave(parent, noteA, parent?.componentId ?? "");+ await showContainer();+ expect(editor.content).toBe("AAA typed here");++ container.style.display = "none";+ await reportSave(parent, noteA, "another-editor", "AAA typed elsewhere again");+ expect(editor.content).toBe("AAA typed here");+ await showContainer();+ expect(editor.content).toBe("AAA typed elsewhere again");+ } finally {+ globalThis.ResizeObserver = ResizeObserver;+ }+ });+it("awaits async event handlers registered by React components (the contract NoteContext.setNote relies on)", async () => {const parent = new Component();let flushed = false;@@ -321,6 +357,27 @@ describe("editing some blocks of a note", () => {});});+/** Reports a save of `note` by `componentId`, which reads back as `content` when it is given. */+async function reportSave(+ parent: Component | null, note: FNote, componentId: string, content?: string+) {+ if (content !== undefined) {+ note.getBlob = async () => new FBlob({+ blobId: `blob-${content}`,+ content,+ contentLength: content.length,+ dateModified: "",+ utcDateModified: ""+ });+ }+ const loadResults = new LoadResults([]);+ loadResults.addNoteContent(note.noteId, componentId);+ await act(async () => {+ await parent?.handleEvent("entitiesReloaded", { loadResults });+ });+ await vi.advanceTimersByTimeAsync(20);+}+/** Renders an editor of the blocks of `note` that `block` points at. */async function showBlockEditor(note: FNote, block: string) {const editor: { content: string; block: string | undefined } = { content: "", block };diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex d9793cb61d..8d6b8265e7 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -851,6 +851,8 @@ export function useNoteBlob<T extends { content: string } = FBlob>(note: FNote |}): T | null | undefined {const [ blob, setBlob ] = useState<T | null>();const requestIdRef = useRef(0);+ /** The request whose content, saved elsewhere, waits for `shownRef` to show. */+ const waitingRequestIdRef = useRef<number | undefined>(undefined);const missedContentChangeRef = useRef(false);const whenShown = useWhenShown(opts?.shownRef);@@ -865,6 +867,7 @@ export function useNoteBlob<T extends { content: string } = FBlob>(note: FNote |async function refresh(isSavedElsewhere = false) {const requestId = ++requestIdRef.current;const isWaiting = isSavedElsewhere && !!opts?.shownRef;+ waitingRequestIdRef.current = isWaiting ? requestId : undefined;if (note && !isWaiting) {reportLoadState("loading");}@@ -906,6 +909,10 @@ export function useNoteBlob<T extends { content: string } = FBlob>(note: FNote |// The change came from our own component, so the refetch was skipped; remember it so// the content is brought up to date when the widget is displayed again.missedContentChangeRef.current = true;+ } else if (loadResults.isNoteContentReloaded(note.noteId)+ && waitingRequestIdRef.current === requestIdRef.current) {+ // A later save here outdates the content that waits to show.+ requestIdRef.current++;}});