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 Doran3391a6d3a08d
diff --git a/apps/client/src/services/block_reference.spec.ts b/apps/client/src/services/block_reference.spec.tsindex ecc73642e4..4cdac7557e 100644--- a/apps/client/src/services/block_reference.spec.ts+++ b/apps/client/src/services/block_reference.spec.ts@@ -359,10 +359,16 @@ describe("buildBlockReferenceMenuItems", () => {expect(showMessage).toHaveBeenCalledWith("block_reference.no_reference_on_clipboard", 3000, "bx bx-info-circle");- clipboard.read.mockResolvedValue({ html: "", text: href });- runItem(paste[1]);+ // A reference copied from another instance is to a note this one does not have.+ clipboard.read.mockResolvedValue({ html: "", text: `https://other.example/${href}` });+ runItem(paste[0]);await vi.waitFor(() => expect(pasteTarget.release).toHaveBeenCalledTimes(2));- expect(showError).toHaveBeenCalledWith("block_reference.not_found");+ runItem(paste[1]);+ await vi.waitFor(() => expect(pasteTarget.release).toHaveBeenCalledTimes(3));+ expect(getNote.mock.calls).toEqual([ [ "note1", true ], [ "note1", true ] ]);+ expect(showError.mock.calls).toEqual([+ [ "block_reference.not_found" ], [ "block_reference.not_found" ]+ ]);expect(pasteTarget.paste).not.toHaveBeenCalled();});});diff --git a/apps/client/src/services/block_reference.ts b/apps/client/src/services/block_reference.tsindex 8852874dcf..e1f2e55c00 100644--- a/apps/client/src/services/block_reference.ts+++ b/apps/client/src/services/block_reference.ts@@ -260,12 +260,13 @@ function getPasteMenuItems(/*** Reads the clipboard and pastes the HTML that `toHtml` makes of the block reference on it, at* the selection the menu was opened on. The selection is pinned before the read, which can wait- * on a permission prompt. `toHtml` returns `null` for a reference it cannot paste.+ * on a permission prompt. Pastes nothing for a reference to a note that `froca` cannot find, as+ * one copied from another Trilium instance.*/async function pasteBlockReference(editor: CKTextEditor,clipboard: ClipboardAccess,- toHtml: (reference: ClipboardBlockReference) => string | Promise<string | null>+ toHtml: (reference: ClipboardBlockReference) => string | Promise<string>) {const target = editor.capturePasteTarget();try {@@ -275,11 +276,12 @@ async function pasteBlockReference("bx bx-info-circle");return;}-- const html = await toHtml(reference);- if (html) {- target.paste(html, reference.href);+ if (!await froca.getNote(reference.noteId, true)) {+ toast.showError(t("block_reference.not_found"));+ return;}++ target.paste(await toHtml(reference), reference.href);} catch (error) {console.warn("Failed to paste a block reference:", error);} finally {@@ -295,19 +297,11 @@ function getLinkHtml({ href }: ClipboardBlockReference) {return link.outerHTML;}-/** The HTML of an embed of the referenced blocks, or `null` when their note is gone. */+/** The HTML of an embed of the referenced blocks. */async function getExcerptHtml({ noteId, block }: ClipboardBlockReference) {// Imported on demand: `content_renderer` imports `content_renderer_text`, which imports this// module.- const [ note, { EXCERPT_BOX_SIZE } ] = await Promise.all([- froca.getNote(noteId, true),- import("./content_renderer.js")- ]);- if (!note) {- toast.showError(t("block_reference.not_found"));- return null;- }-+ const { EXCERPT_BOX_SIZE } = await import("./content_renderer.js");const embed = document.createElement("figure");embed.className = "include-note";embed.dataset.noteId = noteId;diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsxindex a484f98e50..0500d470b0 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx@@ -375,17 +375,22 @@ describe("ContentEmbed", () => {expect(button("include-note-edit").disabled).toBe(true);});- it("opens an expandable excerpt to edit it", () => {+ it("opens an expandable excerpt to edit it, and focuses it once shown", () => {placeInHostEditor();const { content } = renderBox({ boxSize: "expandable", isExcerpt: true });act(() => {onTestFinished(registerContentEmbedTools(content, EDITABLE_TOOLS));});- expect(contentBox().hidden).toBe(true);+ const box = contentBox();+ const isHiddenOnFocus: boolean[] = [];+ box.addEventListener("focus", () => isHiddenOnFocus.push(box.hasAttribute("hidden")));+ expect(box.hidden).toBe(true);click(button("include-note-edit"));- expect(contentBox().hidden).toBe(false);+ expect(box.hidden).toBe(false);+ expect(document.activeElement).toBe(box);+ expect(isHiddenOnFocus).toEqual([ false ]);});it("gives its content the screen, and takes it back from the overlay button", async () => {diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex f0e5814bde..1b5d03de3a 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -67,6 +67,7 @@ export default function ContentEmbed({useFullscreenEvents(contentRef);useWindowShortcuts(contentRef);const [ isExpanded, setIsExpanded ] = useState(false);+ const focusContentAfterRender = useFocusAfterRender(contentRef);const isExpandable = boxSize === "expandable";const hasFullscreen = !isExcerpt && (boxSize === "medium" || boxSize === "full");@@ -117,7 +118,11 @@ export default function ContentEmbed({<ExcerptEditButtoncontentRef={contentRef}content={content}- onEdit={() => setIsExpanded(true)}+ onEdit={() => {+ setIsExpanded(true);+ // `useEditableEmbed()` focuses the editor once it renders.+ focusContentAfterRender();+ }}/>)}{hasFullscreen && (@@ -252,7 +257,7 @@ function ExcerptBadge() {/*** Turns the editing of an excerpt on and off, as the Editable toggle of its embed does. Disabled* while the content has no editable mode, as in a read-only note or for blocks that cannot be- * edited in place. Opening the editor gives it the focus, and `onEdit` runs first.+ * edited in place. Turning editing on runs `onEdit`, and turning it off focuses the editor around.*/function ExcerptEditButton({ contentRef, content, onEdit }: {contentRef: RefObject<HTMLDivElement | null>;@@ -280,8 +285,6 @@ function ExcerptEditButton({ contentRef, content, onEdit }: {editor.editing.view.focus();} else {onEdit();- // `useEditableEmbed()` moves the focus on to the editor once it renders.- box.focus({ preventScroll: true });}}}/>@@ -310,6 +313,22 @@ function useHasEditableMode(contentRef: RefObject<HTMLElement | null>, content:return hasEditableMode;}+/**+ * Returns a function that focuses the element in `ref` once the render it schedules is committed,+ * so that a state change made with it, such as one that shows the element, applies first.+ */+function useFocusAfterRender(ref: RefObject<HTMLElement | null>) {+ const [ requestCount, setRequestCount ] = useState(0);++ useLayoutEffect(() => {+ if (requestCount) {+ ref.current?.focus({ preventScroll: true });+ }+ }, [ ref, requestCount ]);++ return () => setRequestCount((count) => count + 1);+}+const FOCUSABLE_SELECTOR = "[tabindex], a[href], iframe, webview, "+ ":is(button, input, select, textarea):not(:disabled)";@@ -349,10 +368,6 @@ function ContentEmbedActionButton({ className, action }: {);}-/**- * Opens the menu of the embed for a right click on its title row. The title link is left to the- * handler of every link, which opens the same menu, or a quick edit with Ctrl.- *//*** Runs the window shortcuts, such as switching tabs, from inside the content. The text editor* keeps the keys pressed in an embed from the document, where these shortcuts listen.@@ -444,6 +459,10 @@ function useFullscreenEvents(contentRef: RefObject<HTMLElement | null>) {}, [ contentRef ]);}+/**+ * Opens the menu of the embed for a right click on its title row. The title link is left to the+ * handler of every link, which opens the same menu, or a quick edit with Ctrl.+ */function openMenuOnRightClick(e: MouseEvent, notePath: string, viewScope?: ViewScope) {if (e.target instanceof Element && e.target.closest("a")) {return;