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
test: cover include-note guard, canvas note-drop and interactive-mount wiring
Elian Doran4740a407eadd
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex 646083ceb8..23675b28e7 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -86,10 +86,11 @@ vi.mock("@triliumnext/commons/src/lib/markdown_renderer", async (orig) => ({}));// --- Imports AFTER the mocks. ---+import appContext from "../components/app_context.js";import FAttachment from "../entities/fattachment.js";import { buildNote } from "../test/easy-froca.js";-import froca from "./froca.js";import { disposeInteractiveContent, getRenderedContent as rawGetRenderedContent } from "./content_renderer.js";+import froca from "./froca.js";import server from "./server.js";// getRenderedContent declares an explicit `this` parameter; bind it so callers don't need to.@@ -457,6 +458,37 @@ describe("generic FNote fallback / webView", () => {expect($renderedContent.hasClass("no-preview")).toBe(false);});+ it("points a freshly mounted .component element at appContext so embedded command buttons resolve", async () => {+ // The real renderReactWidgetAtElement runs here; make the mounted widget emit a bare+ // ".component" element (as a real widget root would) with no component prop yet.+ webViewComponent.mockImplementationOnce(() => h("div", { class: "component" }));+ const note = buildNote({ title: "WICmp", type: "webView", "#webViewSrc": "https://example.com" });++ const { $renderedContent } = await getRenderedContent(note, { interactive: true });++ const $component = $renderedContent.find(".note-detail-web-view .component");+ expect($component.length).toBe(1);+ expect($component.prop("component")).toBe(appContext);+ });++ it("leaves a .component element that already carries a component prop untouched", async () => {+ const preexisting = { marker: "already-wired" };+ webViewComponent.mockImplementationOnce(() => h("div", {+ class: "component",+ ref: (el: HTMLElement | null) => {+ if (el) {+ $(el).prop("component", preexisting);+ }+ }+ }));+ const note = buildNote({ title: "WICmp2", type: "webView", "#webViewSrc": "https://example.com" });++ const { $renderedContent } = await getRenderedContent(note, { interactive: true });++ const $component = $renderedContent.find(".note-detail-web-view .component");+ expect($component.prop("component")).toBe(preexisting);+ });+it("executes the search and mounts the live collection list for an interactive search note", async () => {const note = buildNote({ title: "Saved", type: "search" });vi.spyOn(note, "getBestNotePathString").mockReturnValue("root/saved");diff --git a/apps/client/src/widgets/type_widgets/canvas/useCanvasNoteDrop.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/useCanvasNoteDrop.spec.tsxnew file mode 100644index 0000000000..db3a2a4144--- /dev/null+++ b/apps/client/src/widgets/type_widgets/canvas/useCanvasNoteDrop.spec.tsx@@ -0,0 +1,161 @@+import { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";+import { type RefObject, render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import useCanvasNoteDrop from "./useCanvasNoteDrop";++const restoreElements = vi.fn((elements: unknown[]) => elements.map((el, i) => ({ ...(el as object), id: `el${i}` })));+const viewportCoordsToSceneCoords = vi.fn(() => ({ x: 100, y: 200 }));++vi.mock("@excalidraw/excalidraw", () => ({+ restoreElements: (...args: unknown[]) => restoreElements(...(args as [unknown[]])),+ viewportCoordsToSceneCoords: () => viewportCoordsToSceneCoords()+}));++type Handlers = ReturnType<typeof useCanvasNoteDrop>;++let handlers: Handlers | undefined;++function Probe({ apiRef, isReadOnly }: { apiRef: RefObject<ExcalidrawImperativeAPI>; isReadOnly: boolean }) {+ handlers = useCanvasNoteDrop(apiRef, isReadOnly);+ return null;+}++describe("useCanvasNoteDrop", () => {+ let container: HTMLElement;+ let sceneElements: unknown[];+ let api: ExcalidrawImperativeAPI;+ let updateScene: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ restoreElements.mockClear();+ viewportCoordsToSceneCoords.mockClear();+ sceneElements = [{ id: "existing" }];+ updateScene = vi.fn();+ api = {+ getAppState: vi.fn(() => ({})),+ getSceneElements: vi.fn(() => sceneElements),+ updateScene+ } as unknown as ExcalidrawImperativeAPI;+ handlers = undefined;+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ async function mountHook(isReadOnly: boolean, apiRef?: RefObject<ExcalidrawImperativeAPI>) {+ const ref = apiRef ?? ({ current: api } as RefObject<ExcalidrawImperativeAPI>);+ await act(async () => {+ render(<Probe apiRef={ref} isReadOnly={isReadOnly} />, container);+ });+ }++ function dragEvent(overrides: Partial<{ types: string[]; payload: string | undefined }> = {}) {+ const { types = ["text/plain"], payload } = overrides;+ return {+ clientX: 10,+ clientY: 20,+ dataTransfer: {+ types,+ getData: vi.fn(() => payload)+ },+ preventDefault: vi.fn(),+ stopPropagation: vi.fn()+ };+ }++ describe("onDragOverCapture", () => {+ it("accepts the drop (preventDefault + stopPropagation) when a text/plain drag is editable", async () => {+ await mountHook(false);+ const e = dragEvent();+ handlers?.onDragOverCapture(e as never);+ expect(e.preventDefault).toHaveBeenCalled();+ expect(e.stopPropagation).toHaveBeenCalled();+ });++ it("ignores the drag when read-only", async () => {+ await mountHook(true);+ const e = dragEvent();+ handlers?.onDragOverCapture(e as never);+ expect(e.preventDefault).not.toHaveBeenCalled();+ });++ it("ignores a drag that does not carry text/plain", async () => {+ await mountHook(false);+ const e = dragEvent({ types: ["Files"] });+ handlers?.onDragOverCapture(e as never);+ expect(e.preventDefault).not.toHaveBeenCalled();+ });+ });++ describe("onDropCapture", () => {+ it("inserts an embeddable per dropped note, stacked, appended to the existing scene", async () => {+ await mountHook(false);+ const e = dragEvent({ payload: JSON.stringify([{ noteId: "aaa" }, { noteId: "bbb" }]) });+ handlers?.onDropCapture(e as never);++ expect(e.preventDefault).toHaveBeenCalled();+ expect(e.stopPropagation).toHaveBeenCalled();+ expect(viewportCoordsToSceneCoords).toHaveBeenCalled();++ const partials = restoreElements.mock.calls[0][0] as Array<Record<string, unknown>>;+ expect(partials).toHaveLength(2);+ expect(partials[0]).toMatchObject({ type: "embeddable", x: 100, y: 200, link: "root/aaa" });+ // The second note is offset by STACK_OFFSET (24) from the first on both axes.+ expect(partials[1]).toMatchObject({ x: 124, y: 224, link: "root/bbb" });++ const { elements } = updateScene.mock.calls[0][0];+ expect(elements).toHaveLength(3); // 1 existing + 2 new+ expect(elements[0]).toEqual({ id: "existing" });+ });++ it("does nothing when read-only", async () => {+ await mountHook(true);+ const e = dragEvent({ payload: JSON.stringify([{ noteId: "aaa" }]) });+ handlers?.onDropCapture(e as never);+ expect(e.preventDefault).not.toHaveBeenCalled();+ expect(updateScene).not.toHaveBeenCalled();+ });++ it("does nothing when the Excalidraw API is not ready", async () => {+ await mountHook(false, { current: null } as RefObject<ExcalidrawImperativeAPI>);+ const e = dragEvent({ payload: JSON.stringify([{ noteId: "aaa" }]) });+ handlers?.onDropCapture(e as never);+ expect(e.preventDefault).not.toHaveBeenCalled();+ });++ it("ignores a drop whose payload contains no usable note IDs", async () => {+ await mountHook(false);+ const e = dragEvent({ payload: JSON.stringify([{ notANoteId: true }]) });+ handlers?.onDropCapture(e as never);+ expect(e.preventDefault).not.toHaveBeenCalled();+ expect(updateScene).not.toHaveBeenCalled();+ });+ });++ describe("dropped-payload parsing", () => {+ // Drives parseDroppedNoteIds through onDropCapture: a payload is "usable" only if it parses+ // to an array whose entries carry a string noteId. updateScene firing is the proxy for that.+ const cases: Array<{ name: string; payload: string | undefined; usable: boolean }> = [+ { name: "missing payload", payload: undefined, usable: false },+ { name: "non-array JSON", payload: JSON.stringify({ noteId: "aaa" }), usable: false },+ { name: "entries without a string noteId", payload: JSON.stringify([{ noteId: 5 }, null]), usable: false },+ { name: "invalid JSON", payload: "{not json", usable: false },+ { name: "valid note entries", payload: JSON.stringify([{ noteId: "aaa" }]), usable: true }+ ];++ for (const { name, payload, usable } of cases) {+ it(`${usable ? "accepts" : "rejects"} ${name}`, async () => {+ await mountHook(false);+ const e = dragEvent({ payload });+ handlers?.onDropCapture(e as never);+ expect(updateScene.mock.calls.length).toBe(usable ? 1 : 0);+ });+ }+ });+});diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.tsindex 36c7c4fd11..cea9675ae5 100644--- a/packages/ckeditor5/src/plugins/includenote.spec.ts+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts@@ -347,6 +347,31 @@ describe("IncludeNote", () => {expect(stop).not.toHaveBeenCalled();});+ it("treats a mousedown whose target is not an Element (e.g. a text node) as non-interactive", () => {+ insertIncludeNote(editor, "noteText", "small");++ const domRoot = editor.editing.view.getDomRoot();+ const wrapper = domRoot?.querySelector("div.include-note-wrapper");+ expect(wrapper).not.toBeNull();+ if (!wrapper) {+ return;+ }++ // A capture-phase mousedown on a bare text node makes evt.target a Text, not an Element. The+ // interactive-target guard must short-circuit and report "not interactive", so the widget's+ // normal suppression (preventDefault + stopPropagation) still runs.+ const textNode = document.createTextNode("plain text");+ wrapper.appendChild(textNode);++ const evt = new MouseEvent("mousedown", { bubbles: true, cancelable: true });+ const prevent = vi.spyOn(evt, "preventDefault");+ const stop = vi.spyOn(evt, "stopPropagation");+ textNode.dispatchEvent(evt);++ expect(prevent).toHaveBeenCalled();+ expect(stop).toHaveBeenCalled();+ });+it("stops propagation on focus and keydown inside the wrapper", () => {insertIncludeNote(editor, "noteKbd", "small");