Skip to content

Build your personal knowledge base with Trilium Notes

link previews: fix some issues, improve coverage

Adorian Doran910c490c07a4
diff --git a/apps/client/src/services/media_playback.spec.ts b/apps/client/src/services/media_playback.spec.ts
index b9a161b094..48bc2d6072 100644
--- a/apps/client/src/services/media_playback.spec.ts
+++ b/apps/client/src/services/media_playback.spec.ts
@@ -28,8 +28,8 @@ describe("stopBackgroundMedia", () => {
<iframe class="pdf" src="blob:pdf"></iframe>
`;
- const video = container.querySelector("video")!;
- const audio = container.querySelector("audio")!;
+ const video = container.querySelector("video") as HTMLVideoElement;
+ const audio = container.querySelector("audio") as HTMLAudioElement;
video.pause = vi.fn();
audio.pause = vi.fn();
diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsx
index 79d4930a14..66a00c05d8 100644
--- a/apps/client/src/widgets/NoteDetail.tsx
+++ b/apps/client/src/widgets/NoteDetail.tsx
@@ -275,13 +275,14 @@ function NoteDetailWrapper({ Element, type, isVisible, isFullHeight, props }: {
}, [ props, isVisible ]);
// This widget stays mounted (just hidden) when the user switches note type —
- // e.g. read-only ↔ editable text. A hidden but still-mounted embedded player
- // keeps playing audio/video in the background, so stop it whenever it's hidden.
+ // e.g. read-only ↔ editable text — and also when an enclosing dialog such as the quick-edit
+ // popup is closed but kept in the DOM. A hidden but still-mounted embedded player keeps playing
+ // audio/video in the background, so stop it in either case.
useEffect(() => {
- if (!isVisible) {
+ if (!isVisible || !containerVisible) {
stopBackgroundMedia(wrapperRef.current);
}
- }, [ isVisible ]);
+ }, [ isVisible, containerVisible ]);
const typeMapping = TYPE_MAPPINGS[type];
return (
diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.ts
index 6999ca8fa6..8929b9678d 100644
--- a/apps/desktop/src/main.spec.ts
+++ b/apps/desktop/src/main.spec.ts
@@ -39,6 +39,7 @@ const h = vi.hoisted(() => ({
streamErrorHandlers: [] as Handler[],
// Captured commandLine.appendSwitch calls.
appendSwitch: vi.fn(),
+ onBeforeSendHeaders: vi.fn(),
setName: vi.fn(),
quit: vi.fn(),
exit: vi.fn(),
@@ -102,12 +103,22 @@ vi.mock("electron", () => {
on: (channel: string, fn: Handler) => h.ipcOn.set(channel, fn),
handle: (channel: string, fn: Handler) => h.ipcHandle.set(channel, fn)
};
+ // onReady() installs the embed-Referer hook, whose default argument reads
+ // `electron.session.defaultSession` (see services/embed_referer.ts).
+ const session = {
+ defaultSession: {
+ webRequest: {
+ onBeforeSendHeaders: (...a: unknown[]) => h.onBeforeSendHeaders(...a)
+ }
+ }
+ };
return {
app: appObj,
BrowserWindow,
globalShortcut,
ipcMain,
- default: { app: appObj, BrowserWindow, globalShortcut, ipcMain }
+ session,
+ default: { app: appObj, BrowserWindow, globalShortcut, ipcMain, session }
};
});
diff --git a/apps/desktop/src/services/embed_referer.spec.ts b/apps/desktop/src/services/embed_referer.spec.ts
index f5570037e3..97f539ff4b 100644
--- a/apps/desktop/src/services/embed_referer.spec.ts
+++ b/apps/desktop/src/services/embed_referer.spec.ts
@@ -1,3 +1,4 @@
+import type { Session } from "electron";
import { describe, expect, it, vi } from "vitest";
vi.mock("electron", () => ({
@@ -8,31 +9,86 @@ vi.mock("electron", () => ({
const { setupEmbedReferer } = await import("./embed_referer.js");
+type RequestHeaders = Record<string, string>;
+type Filter = { urls: string[] };
+type Handler = (
+ details: { url: string; requestHeaders: RequestHeaders },
+ callback: (response: { requestHeaders: RequestHeaders }) => void
+) => void;
+
+/** A stand-in Electron session that records the hook registered on it. */
+function fakeSession() {
+ let captured: Handler | undefined;
+ const session = {
+ webRequest: {
+ onBeforeSendHeaders: vi.fn((_filter: Filter, handler: Handler) => {
+ captured = handler;
+ })
+ }
+ };
+
+ return {
+ session: session as unknown as Session,
+ registrations: () => session.webRequest.onBeforeSendHeaders.mock.calls.length,
+ filter: () => session.webRequest.onBeforeSendHeaders.mock.calls[0]?.[0],
+ /** Runs the registered hook over `requestHeaders` and returns what it forwards. */
+ run(requestHeaders: RequestHeaders) {
+ expect(captured).toBeDefined();
+
+ let forwarded: RequestHeaders | undefined;
+ captured?.(
+ { url: "https://www.youtube.com/embed/abc", requestHeaders },
+ (response) => (forwarded = response.requestHeaders)
+ );
+
+ if (!forwarded) {
+ throw new Error("The hook did not forward any headers.");
+ }
+ return forwarded;
+ }
+ };
+}
+
describe("setupEmbedReferer", () => {
it("registers a header hook scoped to the embed providers that injects the given Referer", () => {
- let captured: ((details: any, cb: (r: any) => void) => void) | undefined;
- const session = {
- webRequest: {
- onBeforeSendHeaders: vi.fn((_filter: any, handler: any) => {
- captured = handler;
- })
- }
- };
+ const { session, registrations, filter, run } = fakeSession();
- setupEmbedReferer("http://localhost:37840/", session as any);
+ setupEmbedReferer("http://localhost:37840/", session);
- expect(session.webRequest.onBeforeSendHeaders).toHaveBeenCalledTimes(1);
- const [filter] = session.webRequest.onBeforeSendHeaders.mock.calls[0];
+ expect(registrations()).toBe(1);
// Scoped to the embed providers (Electron does the actual URL matching),
// and notably NOT a catch-all.
- expect(filter.urls).toContain("*://*.youtube.com/*");
- expect(filter.urls).toContain("*://*.youtube-nocookie.com/*");
- expect(filter.urls).not.toContain("*://*/*");
+ expect(filter()?.urls).toContain("*://*.youtube.com/*");
+ expect(filter()?.urls).toContain("*://*.youtube-nocookie.com/*");
+ expect(filter()?.urls).not.toContain("*://*/*");
// The handler sets the supplied origin as the Referer and forwards the headers.
- let result: any;
- captured!({ url: "https://www.youtube.com/embed/abc", requestHeaders: { "X-Foo": "bar" } }, (r) => (result = r));
- expect(result.requestHeaders["Referer"]).toBe("http://localhost:37840/");
- expect(result.requestHeaders["X-Foo"]).toBe("bar");
+ const headers = run({ "X-Foo": "bar" });
+ expect(headers["Referer"]).toBe("http://localhost:37840/");
+ expect(headers["X-Foo"]).toBe("bar");
+ });
+
+ it("replaces an existing Referer whatever its casing, so the header is never sent twice", () => {
+ const { session, run } = fakeSession();
+
+ setupEmbedReferer("http://localhost:37840/", session);
+
+ const headers = run({ "referer": "https://elsewhere.example.com/", "X-Foo": "bar" });
+ expect(Object.keys(headers).filter((name) => name.toLowerCase() === "referer")).toEqual(["Referer"]);
+ expect(headers["Referer"]).toBe("http://localhost:37840/");
+ expect(headers["X-Foo"]).toBe("bar");
+ });
+
+ it("installs once per session, but does install on a second session", () => {
+ const first = fakeSession();
+ const second = fakeSession();
+
+ setupEmbedReferer("http://localhost:37840/", first.session);
+ setupEmbedReferer("http://localhost:37840/", first.session);
+ setupEmbedReferer("http://localhost:37840/", second.session);
+
+ // Electron allows one listener per session — not one per process.
+ expect(first.registrations()).toBe(1);
+ expect(second.registrations()).toBe(1);
});
});
diff --git a/apps/desktop/src/services/embed_referer.ts b/apps/desktop/src/services/embed_referer.ts
index 47d8b57dd9..e5cba03419 100644
--- a/apps/desktop/src/services/embed_referer.ts
+++ b/apps/desktop/src/services/embed_referer.ts
@@ -20,7 +20,12 @@ const EMBED_PROVIDER_URLS = [
"*://*.youtube-nocookie.com/*"
];
-let installed = false;
+/**
+ * Sessions already carrying the hook. Keyed on the session rather than a module-wide flag so that a
+ * second session (and each test) can install its own — Electron allows one `onBeforeSendHeaders`
+ * listener per session, not one per process.
+ */
+const installedSessions = new WeakSet<Session>();
/**
* Installs a single `onBeforeSendHeaders` hook on the session (default: the
@@ -33,17 +38,26 @@ let installed = false;
* provider's own domain (`https://www.youtube.com`): YouTube rejects that as an
* invalid embed host (Error 152).
*
- * Must be called after `app.ready`. Idempotent — only the first call registers
- * the hook (Electron allows a single `onBeforeSendHeaders` listener per session).
+ * Must be called after `app.ready`. Idempotent per session — a repeat call for a session that
+ * already has the hook does nothing.
*/
export function setupEmbedReferer(appOrigin: string, session: Session = electron.session.defaultSession) {
- if (installed) {
+ if (installedSessions.has(session)) {
return;
}
- installed = true;
+ installedSessions.add(session);
session.webRequest.onBeforeSendHeaders({ urls: EMBED_PROVIDER_URLS }, (details, callback) => {
+ // Header names are case-insensitive, but `requestHeaders` is a plain object with
+ // case-sensitive keys: assigning "Referer" alongside an existing "referer" would send the
+ // header twice, and YouTube rejects a request whose embed host it cannot pin down.
+ for (const name of Object.keys(details.requestHeaders)) {
+ if (name.toLowerCase() === "referer") {
+ delete details.requestHeaders[name];
+ }
+ }
details.requestHeaders["Referer"] = appOrigin;
+
callback({ requestHeaders: details.requestHeaders });
});
}
diff --git a/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
index 4ff3cd105a..38d57880d3 100644
--- a/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
@@ -600,4 +600,92 @@ describe("LinkEmbedToolbar", () => {
// undefined, so `mode?.label ?? value` returns "custom-unknown-mode".
expect(dropdown.buttonView.label).toBe("custom-unknown-mode");
});
+
+ // -----------------------------------------------------------------------
+ // The balloon's other items: open-link, copy-URL and unlink
+ // -----------------------------------------------------------------------
+
+ describe("link, copy and unlink buttons", () => {
+ const URL = "https://example.com/page";
+ let copy: ReturnType<typeof vi.fn>;
+
+ beforeEach(async () => {
+ copy = vi.fn();
+ // The copy button reaches the host through these two config entries, which the editor
+ // config type does not declare (the host sets them the same way, via a cast).
+ const hostConfig = {
+ clipboard: { copy },
+ translate: (key: string) => `translated:${key}`
+ } as unknown as Parameters<typeof createTestEditor>[1];
+
+ editor = await createTestEditor([Essentials, Paragraph, LinkEmbed, LinkEmbedToolbar], hostConfig);
+ });
+
+ function selectLinkMention() {
+ setModelData(editor.model, `<paragraph>[<linkMention url="${URL}" title="T"></linkMention>]</paragraph>`);
+ }
+
+ function createButton(name: string) {
+ return editor.ui.componentFactory.create(name) as unknown as ToolbarButton;
+ }
+
+ it("linkEmbedLink is an <a target=_blank> bound to the selected widget's URL", () => {
+ const button = createButton("linkEmbedLink");
+ button.render();
+
+ // Nothing selected: the command exposes no URL, so the button is inert.
+ expect(button.isEnabled).toBe(false);
+ expect(button.label).toBeUndefined();
+ expect(button.href).toBeUndefined();
+
+ selectLinkMention();
+
+ expect(button.isEnabled).toBe(true);
+ expect(button.label).toBe(URL);
+ expect(button.href).toBe(URL);
+
+ // Rendered as a real anchor so a click opens the page in a new tab, reusing
+ // CKEditor's own link-toolbar styling.
+ expect(button.element?.tagName).toBe("A");
+ expect(button.element?.getAttribute("href")).toBe(URL);
+ expect(button.element?.getAttribute("target")).toBe("_blank");
+ expect(button.element?.getAttribute("rel")).toBe("noopener noreferrer");
+ expect(button.element?.classList.contains("ck-link-toolbar__preview")).toBe(true);
+ });
+
+ it("linkEmbedCopyUrl copies the selected widget's URL through the host clipboard", () => {
+ const button = createButton("linkEmbedCopyUrl");
+ expect(button.label).toBe("translated:link.copy_url");
+
+ // With nothing selected there is no URL, so nothing is copied.
+ button.fire("execute");
+ expect(copy).not.toHaveBeenCalled();
+
+ selectLinkMention();
+ button.fire("execute");
+ expect(copy).toHaveBeenCalledWith(URL);
+ });
+
+ it("linkEmbedUnlink is enabled only for a selected widget and unlinks it", () => {
+ const button = createButton("linkEmbedUnlink");
+ expect(button.isEnabled).toBe(false);
+
+ selectLinkMention();
+ expect(button.isEnabled).toBe(true);
+
+ button.fire("execute");
+
+ // The widget is gone, leaving the bare URL as plain text.
+ expect(editor.getData()).toBe(`<p>${URL}</p>`);
+ });
+ });
});
+
+type ToolbarButton = {
+ isEnabled: boolean;
+ label?: string;
+ href?: string;
+ element?: HTMLElement | null;
+ render(): void;
+ fire(evt: string): void;
+};
diff --git a/packages/ckeditor5/src/plugins/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
index 529738d3e8..ddcfbb3e1c 100644
--- a/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
+++ b/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
@@ -146,15 +146,19 @@ class LinkEmbedLinkButton extends Plugin {
public init() {
const editor = this.editor;
- const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND) as Command & { url: string | null };
+ const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND) as (Command & { url: string | null }) | undefined;
editor.ui.componentFactory.add("linkEmbedLink", locale => {
const button = new LinkEmbedPreviewButtonView(locale);
button.set("tooltip", locale.t("Open link in new tab"));
- button.bind("isEnabled").to(command, "url", url => !!url);
- button.bind("label").to(command, "url", url => url ?? undefined);
- button.bind("href").to(command, "url", url => url ?? undefined);
+
+ /* v8 ignore next -- LinkEmbedEditing always registers CHANGE_LINK_DISPLAY_COMMAND (this plugin requires LinkEmbed), so the no-command branch is unreachable */
+ if (command) {
+ button.bind("isEnabled").to(command, "url", url => !!url);
+ button.bind("label").to(command, "url", url => url ?? undefined);
+ button.bind("href").to(command, "url", url => url ?? undefined);
+ }
return button;
});
@@ -173,10 +177,10 @@ class LinkEmbedCopyUrlButton extends Plugin {
public init() {
const editor = this.editor;
- const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND) as Command & { url: string | null };
+ const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND) as (Command & { url: string | null }) | undefined;
editor.ui.componentFactory.add("linkEmbedCopyUrl", locale =>
- createCopyUrlButton(editor, locale, () => command.url)
+ createCopyUrlButton(editor, locale, () => command?.url)
);
}
}
@@ -204,6 +208,7 @@ class LinkEmbedUnlinkButton extends Plugin {
tooltip: true
});
+ /* v8 ignore next -- LinkEmbedEditing always registers REMOVE_LINK_EMBED_COMMAND (this plugin requires LinkEmbed), so the no-command branch is unreachable */
if (command) {
button.bind("isEnabled").to(command, "isEnabled");
}
@@ -242,6 +247,7 @@ class LinkEmbedPreviewButtonView extends ButtonView {
}
});
+ /* v8 ignore next -- ButtonView always builds a template, and extendTemplate() above would have thrown otherwise, so the no-template branch is unreachable */
if (this.template) {
this.template.tag = "a";
}
diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.ts
index a5168f957b..0db38b9e5f 100644
--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.spec.ts
@@ -14,7 +14,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
import { installGlobMock } from "../../test/globals-test-kit.js";
-import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND } from "./linkembed.js";
+import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./linkembed.js";
const META = {
url: "https://example.com/",
@@ -382,6 +382,45 @@ describe("LinkEmbed", () => {
expect(editor.getData()).toBe(before);
});
+ // -----------------------------------------------------------------------
+ // RemoveLinkEmbedCommand (the toolbar's unlink button)
+ // -----------------------------------------------------------------------
+
+ it("unlinks a selected linkMention, leaving the bare URL as plain text", () => {
+ setModelData(editor.model, '<paragraph>[<linkMention url="https://e.com/" title="T"></linkMention>]</paragraph>');
+
+ editor.execute(REMOVE_LINK_EMBED_COMMAND);
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ // Mirrors the default link's unlink: the URL survives as plain, non-linked text.
+ expect(editor.getData()).toBe("<p>https://e.com/</p>");
+ });
+
+ it("unlinks a selected block linkEmbed the same way", () => {
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="youtube"></linkEmbed>]');
+
+ editor.execute(REMOVE_LINK_EMBED_COMMAND);
+
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(editor.getData()).toBe("<p>https://e.com/</p>");
+ });
+
+ it("is disabled with no link widget selected, and does nothing if executed anyway", () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const before = editor.getData();
+
+ const command = editor.commands.get(REMOVE_LINK_EMBED_COMMAND);
+ expect(command?.isEnabled).toBe(false);
+
+ // Command swallows execute() while disabled, so force it enabled to exercise the early return.
+ if (command) {
+ command.isEnabled = true;
+ }
+ command?.execute();
+
+ expect(editor.getData()).toBe(before);
+ });
+
// -----------------------------------------------------------------------
// AutoLinkToMention
// -----------------------------------------------------------------------
@@ -421,7 +460,7 @@ describe("LinkEmbed", () => {
const url = "https://example.com/article";
editor = await createTestEditor(
[Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed],
- { autoLinkPreviewsEnabled: false }
+ hostConfig({ autoLinkPreviewsEnabled: false })
);
addLinkedText(editor, url);
@@ -441,7 +480,7 @@ describe("LinkEmbed", () => {
let enabled = false;
editor = await createTestEditor(
[Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed],
- { autoLinkPreviewsEnabled: () => enabled }
+ hostConfig({ autoLinkPreviewsEnabled: () => enabled })
);
addLinkedText(editor, "https://example.com/off");
@@ -455,6 +494,20 @@ describe("LinkEmbed", () => {
expect(findElement(editor, "linkMention")).toBeDefined();
});
+ it("converts an embeddable URL standing alone in its block into a block linkEmbed", async () => {
+ const url = "https://youtube.com/watch?v=abc12345678";
+ fetchLinkMetadata.mockResolvedValueOnce({ ...META, url, embedType: "youtube" });
+
+ addLinkedText(editor, url);
+ await flushFetch();
+
+ // Embeddable + alone in its block => the player, not an inline pill.
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ const embed = findElement(editor, "linkEmbed");
+ expect(embed?.getAttribute("url")).toBe(url);
+ expect(embed?.getAttribute("embedType")).toBe("youtube");
+ });
+
it("ignores a labeled link whose text differs from the href", async () => {
addLinkedText(editor, "https://example.com/article", "click here");
@@ -697,6 +750,14 @@ function changeCommand(editor: ClassicEditor): {
return command as unknown as { isEnabled: boolean; value: string | null; embedAvailable: boolean };
}
+/**
+ * Editor config entries the host supplies but the CKEditor config type does not declare — the host
+ * sets them through the same kind of cast (see the client's `buildConfig`).
+ */
+function hostConfig(entries: Record<string, unknown>): Parameters<typeof createTestEditor>[1] {
+ return entries as Parameters<typeof createTestEditor>[1];
+}
+
function findElement(editor: ClassicEditor, name: string) {
const root = editor.model.document.getRoot();
if (!root) {