Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: fix some issues

Adorian Doran8febfa23d86b
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.ts
index a6391377bb..1f2827f4f4 100644
--- a/apps/client/src/menus/link_context_menu.spec.ts
+++ b/apps/client/src/menus/link_context_menu.spec.ts
@@ -14,7 +14,7 @@ const mocks = vi.hoisted(() => ({
activeNtxId: "ntx-active" as string | null,
/** False when no tab is open at all, which leaves both the hoisting and the split unresolvable. */
hasActiveContext: true,
- getAttachment: vi.fn(),
+ getAttachmentOfNote: vi.fn(),
getAttachmentActionGroups: vi.fn(),
getTextEditorContaining: vi.fn()
}));
@@ -27,7 +27,9 @@ vi.mock("../services/options", () => ({ default: { get: () => "expandable" } }))
vi.mock("./context_menu", () => ({ default: { show: mocks.show } }));
-vi.mock("../services/froca", () => ({ default: { getAttachment: mocks.getAttachment } }));
+vi.mock("../services/froca", () => ({
+ default: { getAttachmentOfNote: mocks.getAttachmentOfNote }
+}));
vi.mock("../services/attachment_actions", () => ({
getAttachmentActionGroups: mocks.getAttachmentActionGroups
@@ -80,7 +82,7 @@ beforeEach(() => {
mocks.subContexts = [ { ntxId: "ntx-first" }, { ntxId: "ntx-last" } ];
mocks.activeNtxId = "ntx-active";
mocks.hasActiveContext = true;
- mocks.getAttachment.mockResolvedValue(null);
+ mocks.getAttachmentOfNote.mockResolvedValue(null);
});
describe("getItems", () => {
@@ -225,7 +227,7 @@ describe("openContextMenu", () => {
it("appends the actions on a linked attachment, each group after a separator", async () => {
const attachment = { attachmentId: "att-1" };
const download = vi.fn();
- mocks.getAttachment.mockResolvedValue(attachment);
+ mocks.getAttachmentOfNote.mockResolvedValue(attachment);
mocks.getAttachmentActionGroups.mockReturnValue([
[ { title: "Download", icon: "bx bx-download", run: download } ],
[ {
@@ -238,7 +240,7 @@ describe("openContextMenu", () => {
await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(), VIEW_SCOPE);
- expect(mocks.getAttachment).toHaveBeenCalledWith("att-1", true);
+ expect(mocks.getAttachmentOfNote).toHaveBeenCalledWith("n1", "att-1");
expect(mocks.getAttachmentActionGroups).toHaveBeenCalledWith(attachment);
const { items } = mocks.show.mock.calls[0][0];
expect(items.slice(4)).toMatchObject([
@@ -254,7 +256,7 @@ describe("openContextMenu", () => {
it("ends with converting an attachment link to an embed, only in a note being edited", async () => {
const execute = vi.fn();
- mocks.getAttachment.mockResolvedValue({ attachmentId: "att-1" });
+ mocks.getAttachmentOfNote.mockResolvedValue({ attachmentId: "att-1" });
mocks.getAttachmentActionGroups.mockReturnValue([
[ { title: "Download", icon: "bx bx-download", run: vi.fn() } ]
]);
@@ -292,12 +294,32 @@ describe("openContextMenu", () => {
it("adds nothing for a link to a note, or to an attachment that no longer exists", async () => {
await linkContextMenu.openContextMenu("root/n1", contextMenuEvent());
- expect(mocks.getAttachment).not.toHaveBeenCalled();
+ expect(mocks.getAttachmentOfNote).not.toHaveBeenCalled();
await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(), VIEW_SCOPE);
- expect(mocks.getAttachment).toHaveBeenCalledWith("att-1", true);
+ expect(mocks.getAttachmentOfNote).toHaveBeenCalledWith("n1", "att-1");
expect(mocks.show.mock.calls.map(([ shown ]) => shown.items.length)).toEqual([ 4, 4 ]);
expect(mocks.getAttachmentActionGroups).not.toHaveBeenCalled();
});
+
+ it("drops a menu whose attachment loads after a later menu opened", async () => {
+ let resolveAttachment: (value: unknown) => void = () => {};
+ mocks.getAttachmentOfNote.mockReturnValue(new Promise((resolve) => {
+ resolveAttachment = resolve;
+ }));
+ mocks.getAttachmentActionGroups.mockReturnValue([]);
+
+ const first = linkContextMenu.openContextMenu("root/n1", contextMenuEvent(), VIEW_SCOPE);
+ await linkContextMenu.openContextMenu("root/n2", contextMenuEvent());
+ resolveAttachment({ attachmentId: "att-1" });
+ await first;
+
+ expect(mocks.show).toHaveBeenCalledOnce();
+ mocks.show.mock.calls[0][0].selectMenuItemHandler({ command: "openNoteInPopup" });
+ expect(mocks.triggerCommand).toHaveBeenCalledWith("openInPopup", {
+ noteIdOrPath: "root/n2",
+ viewScope: {}
+ });
+ });
});
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index 65b4818adb..82ffb374e7 100644
--- a/apps/client/src/menus/link_context_menu.ts
+++ b/apps/client/src/menus/link_context_menu.ts
@@ -10,13 +10,21 @@ import { getClosestNtxId } from "../widgets/widget_utils.js";
import contextMenu, { type ContextMenuEvent, type MenuItem } from "./context_menu.js";
import { getTextEditorContaining } from "./text_editor_context_menu.js";
+let lastMenuRequest = 0;
+
async function openContextMenu(
notePath: string,
e: ContextMenuEvent,
viewScope: ViewScope = {},
hoistedNoteId: string | null = null
) {
- const attachmentItems = await getAttachmentItems(viewScope, e);
+ const request = ++lastMenuRequest;
+ const noteId = notePath.split("/").at(-1) ?? notePath;
+ const attachmentItems = await getAttachmentItems(noteId, viewScope, e);
+ // A later right-click opened its own menu while this one waited for the attachment.
+ if (request !== lastMenuRequest) {
+ return;
+ }
contextMenu.show({
x: e.pageX,
@@ -91,6 +99,7 @@ function handleLinkContextMenuItem(command: string | undefined, e: ContextMenuEv
/** The actions on the attachment a link points to, each group after a separator. */
async function getAttachmentItems(
+ noteId: string,
{ viewMode, attachmentId }: ViewScope,
e: ContextMenuEvent
): Promise<MenuItem<CommandNames>[]> {
@@ -100,7 +109,7 @@ async function getAttachmentItems(
// Imported on demand: `attachment_actions` imports `link`, which imports this module.
const [ attachment, { getAttachmentActionGroups }, embedItem ] = await Promise.all([
- froca.getAttachment(attachmentId, true),
+ froca.getAttachmentOfNote(noteId, attachmentId),
import("../services/attachment_actions.js"),
getConvertToEmbedItem(e)
]);
diff --git a/apps/client/src/services/froca.spec.ts b/apps/client/src/services/froca.spec.ts
index 5bc66d6c89..a359b760b0 100644
--- a/apps/client/src/services/froca.spec.ts
+++ b/apps/client/src/services/froca.spec.ts
@@ -494,6 +494,33 @@ describe("getAttachment / getAttachmentsForNote / processAttachmentRows", () =>
expect(owner.attachments?.map((a) => a.attachmentId)).toContain("loaded-att");
});
+ it("loads an attachment whose owner note the cache has not loaded", async () => {
+ const rows = [ attRow("orphan-att", "uncached-owner") ];
+ server.getWithSilentNotFound = vi.fn(async () => rows) as
+ typeof server.getWithSilentNotFound;
+
+ expect((await froca.getAttachment("orphan-att"))?.attachmentId).toBe("orphan-att");
+ });
+
+ it("finds an attachment only among the note's own, loading the note first", async () => {
+ const owner = buildNote({ id: "scope-owner", title: "Owner" });
+ const getNote = vi.spyOn(froca, "getNote");
+ froca.attachments["owned-att"] = {
+ attachmentId: "owned-att",
+ ownerId: owner.noteId
+ } as any;
+ froca.attachments["foreign-att"] = { attachmentId: "foreign-att", ownerId: "other" } as any;
+
+ expect(await froca.getAttachmentOfNote(owner.noteId, "owned-att"))
+ .toBe(froca.attachments["owned-att"]);
+ expect(getNote).toHaveBeenCalledWith(owner.noteId, true);
+ expect(await froca.getAttachmentOfNote(owner.noteId, "foreign-att")).toBeNull();
+
+ getNote.mockResolvedValueOnce(null);
+ expect(await froca.getAttachmentOfNote("gone-note", "owned-att")).toBeNull();
+ getNote.mockRestore();
+ });
+
it("does not link attachments when the load returns nothing", async () => {
server.getWithSilentNotFound = vi.fn(async () => []) as typeof server.getWithSilentNotFound;
const att = await froca.getAttachment("empty-load-att");
diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.ts
index aeff8d4434..307b764808 100644
--- a/apps/client/src/services/froca.ts
+++ b/apps/client/src/services/froca.ts
@@ -355,14 +355,24 @@ class FrocaImpl implements Froca {
}
const attachments = this.processAttachmentRows(attachmentRows);
-
- if (attachments.length) {
- attachments[0].getNote().attachments = attachments;
+ const owner = attachments.length ? attachments[0].getNote() : undefined;
+ if (owner) {
+ owner.attachments = attachments;
}
return this.attachments[attachmentId];
}
+ /** The attachment if `noteId` owns it, otherwise `null`. Loads the note first. */
+ async getAttachmentOfNote(noteId: string, attachmentId: string) {
+ if (!await this.getNote(noteId, true)) {
+ return null;
+ }
+
+ const attachment = await this.getAttachment(attachmentId, true);
+ return attachment?.ownerId === noteId ? attachment : null;
+ }
+
async getAttachmentsForNote(noteId: string) {
const attachmentRows = await server.get<FAttachmentRow[]>(`notes/${noteId}/attachments`);
return this.processAttachmentRows(attachmentRows);
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.ts
index e3f4794683..26f34e3fa5 100644
--- a/apps/client/src/services/link.spec.ts
+++ b/apps/client/src/services/link.spec.ts
@@ -826,20 +826,27 @@ describe("getReferenceLinkTitle / getReferenceLinkTitleSync", () => {
expect(await linkService.getReferenceLinkTitle(`#root/${note.noteId}`)).toBe("Referenced");
});
- it("getReferenceLinkTitle resolves an attachment the cached list lacks", async () => {
+ it("getReferenceLinkTitle resolves an attachment among those of the linked note", async () => {
const note = buildNote({ title: "WithAtt" });
note.attachments = [];
- froca.getAttachment = vi.fn(async () => ({ title: "Att" }) as any);
- const title = await linkService.getReferenceLinkTitle(`#root/${note.noteId}?viewMode=attachments&attachmentId=a1`);
+ const getAttachmentOfNote = vi.spyOn(froca, "getAttachmentOfNote")
+ .mockResolvedValue({ title: "Att" } as any);
+ const title = await linkService.getReferenceLinkTitle(
+ `#root/${note.noteId}?viewMode=attachments&attachmentId=a1`
+ );
expect(title).toBe("Att");
- expect(froca.getAttachment).toHaveBeenCalledWith("a1", true);
+ expect(getAttachmentOfNote).toHaveBeenCalledWith(note.noteId, "a1");
+ getAttachmentOfNote.mockRestore();
});
it("getReferenceLinkTitle returns [missing attachment] when attachment not found", async () => {
const note = buildNote({ title: "WithAtt2" });
- froca.getAttachment = vi.fn(async () => null);
- const title = await linkService.getReferenceLinkTitle(`#root/${note.noteId}?viewMode=attachments&attachmentId=a2`);
+ const getAttachmentOfNote = vi.spyOn(froca, "getAttachmentOfNote").mockResolvedValue(null);
+ const title = await linkService.getReferenceLinkTitle(
+ `#root/${note.noteId}?viewMode=attachments&attachmentId=a2`
+ );
expect(title).toBe("[missing attachment]");
+ getAttachmentOfNote.mockRestore();
});
it("getReferenceLinkTitleSync covers missing note, attachments and bookmark variants", () => {
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index 91db292e3c..a231e218f4 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -718,8 +718,8 @@ async function getReferenceLinkTitle(href: string) {
}
if (viewScope?.viewMode === "attachments" && viewScope?.attachmentId) {
- // `froca.getAttachment()` reloads the attachments when the cached list lacks this one.
- const attachment = await froca.getAttachment(viewScope.attachmentId, true);
+ // `froca.getAttachmentOfNote()` reloads the attachments when the cached list lacks it.
+ const attachment = await froca.getAttachmentOfNote(noteId, viewScope.attachmentId);
return attachment ? attachment.title : "[missing attachment]";
}
diff --git a/apps/client/src/services/note_tooltip.spec.ts b/apps/client/src/services/note_tooltip.spec.ts
index 19adbe4a75..87f156d81c 100644
--- a/apps/client/src/services/note_tooltip.spec.ts
+++ b/apps/client/src/services/note_tooltip.spec.ts
@@ -447,7 +447,7 @@ describe("mouseEnterHandler", () => {
it("previews the attachment an attachment link points to, rather than its note", async () => {
vi.useFakeTimers();
froca.getNote = vi.fn(async () => null) as any;
- froca.getAttachment = vi.fn(async () => ({
+ froca.getAttachmentOfNote = vi.fn(async () => ({
attachmentId: "att1",
ownerId: "owner",
title: "report.pdf",
@@ -466,7 +466,7 @@ describe("mouseEnterHandler", () => {
await vi.advanceTimersByTimeAsync(600);
await promise;
- expect(froca.getAttachment).toHaveBeenCalledWith("att1", true);
+ expect(froca.getAttachmentOfNote).toHaveBeenCalledWith("owner", "att1");
expect(froca.getNote).not.toHaveBeenCalled();
const [ options ] = ($.fn.tooltip as unknown as ReturnType<typeof vi.fn>).mock.calls[0];
expect(options.title).toContain("attachmentId=att1");
diff --git a/apps/client/src/services/note_tooltip.ts b/apps/client/src/services/note_tooltip.ts
index 154a1a5689..514d6575b3 100644
--- a/apps/client/src/services/note_tooltip.ts
+++ b/apps/client/src/services/note_tooltip.ts
@@ -99,7 +99,8 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggere
if (url && url.startsWith("#") && !url.startsWith("#root/") && !url.includes("?")) {
renderPromise = renderFootnoteOrAnchor($link, url);
} else if (attachmentId) {
- renderPromise = renderTooltip(await froca.getAttachment(attachmentId, true), detail);
+ const attachment = await froca.getAttachmentOfNote(noteId, attachmentId);
+ renderPromise = renderTooltip(attachment, detail);
} else if ($link.attr("data-note-deleted") != null) {
// The element explicitly targets a soft-deleted note (e.g. an entry in the deleted-notes
// dialog): read it via the deleted-content route. `DeletedFNote.load` returns null once the
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
index e439206ef4..9ec8a6b140 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
@@ -7,7 +7,7 @@
* being uploaded flickered and vanished instead of a "cannot upload" toast appearing.
*/
import type { CKTextEditor, FileUploadData } from "@triliumnext/ckeditor5";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import type LoadResults from "../../../services/load_results";
@@ -28,6 +28,7 @@ vi.mock("../../../services/i18n", async (importOriginal) => ({
vi.mock("@triliumnext/ckeditor5", () => ({}));
const {
+ applyPendingAttachmentChanges,
notifyAttachmentChanges,
onNotificationInfo,
onNotificationWarning,
@@ -132,27 +133,35 @@ describe("showFileUploadProgress", () => {
describe("notifyAttachmentChanges", () => {
type Row = { attachmentId?: string; isDeleted?: boolean };
- function setUp(rows: Row[], isContentReloaded = false) {
- const updateAttachmentLinks = vi.fn();
- const editor = {
- plugins: { get: () => ({ updateAttachmentLinks }) }
- } as unknown as CKTextEditor;
- const loadResults = {
+ const updateAttachmentLinks = vi.fn();
+ const editor = {
+ plugins: { get: () => ({ updateAttachmentLinks }) }
+ } as unknown as CKTextEditor;
+
+ function loadResultsOf(rows: Row[], isContentReloaded = false) {
+ return {
getAttachmentRows: () => rows,
isNoteContentReloaded: vi.fn(() => isContentReloaded)
};
+ }
- return { editor, loadResults, updateAttachmentLinks };
+ function notify(loadResults: ReturnType<typeof loadResultsOf>, pending: PendingRef) {
+ notifyAttachmentChanges(
+ editor, loadResults as unknown as LoadResults, "note1", "component1", pending
+ );
}
+ type PendingRef = Parameters<typeof notifyAttachmentChanges>[4];
+
+ beforeEach(() => updateAttachmentLinks.mockClear());
+
it("passes the changed attachments to the editor's reference links", () => {
- const { editor, loadResults, updateAttachmentLinks } = setUp([
+ const loadResults = loadResultsOf([
{ attachmentId: "renamed" },
{ attachmentId: "deleted", isDeleted: true }
]);
- const results = loadResults as unknown as LoadResults;
- notifyAttachmentChanges(editor, results, "note1", "component1");
+ notify(loadResults, { current: undefined });
expect(loadResults.isNoteContentReloaded).toHaveBeenCalledWith("note1", "component1");
expect(updateAttachmentLinks).toHaveBeenCalledWith([
@@ -161,15 +170,39 @@ describe("notifyAttachmentChanges", () => {
]);
});
- it("leaves the links alone when no attachment changed, or the content was reloaded", () => {
- const cases: [ Row[], boolean ][] = [ [ [], false ], [ [ { attachmentId: "a" } ], true ] ];
+ it("leaves the links alone when no attachment changed", () => {
+ const pending: PendingRef = { current: undefined };
+
+ notify(loadResultsOf([]), pending);
+
+ expect(updateAttachmentLinks).not.toHaveBeenCalled();
+ expect(pending.current).toBeUndefined();
+ });
+
+ it("holds the changes while the note content reloads, until the editor takes it", () => {
+ const pending: PendingRef = { current: undefined };
+
+ notify(loadResultsOf([ { attachmentId: "renamed" } ], true), pending);
+ notify(loadResultsOf([ { attachmentId: "deleted", isDeleted: true } ], true), pending);
+ expect(updateAttachmentLinks).not.toHaveBeenCalled();
+
+ applyPendingAttachmentChanges(editor, "note1", pending);
+ expect(updateAttachmentLinks).toHaveBeenCalledExactlyOnceWith([
+ { attachmentId: "renamed", isDeleted: false },
+ { attachmentId: "deleted", isDeleted: true }
+ ]);
+
+ applyPendingAttachmentChanges(editor, "note1", pending);
+ expect(updateAttachmentLinks).toHaveBeenCalledOnce();
+ });
- for (const [ rows, isContentReloaded ] of cases) {
- const { editor, loadResults, updateAttachmentLinks } = setUp(rows, isContentReloaded);
+ it("drops the held changes when the editor takes another note's content", () => {
+ const pending: PendingRef = { current: undefined };
+ notify(loadResultsOf([ { attachmentId: "renamed" } ], true), pending);
- notifyAttachmentChanges(editor, loadResults as unknown as LoadResults, "note1");
+ applyPendingAttachmentChanges(editor, "note2", pending);
+ applyPendingAttachmentChanges(editor, "note1", pending);
- expect(updateAttachmentLinks).not.toHaveBeenCalled();
- }
+ expect(updateAttachmentLinks).not.toHaveBeenCalled();
});
});
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index fb9fe340cf..5320318fb6 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -2,6 +2,7 @@ import "./EditableText.css";
import "./LinkEmbed.css";
import {
+ type AttachmentLinkChange,
CKTextEditor,
EditorWatchdog,
type FileUploadData,
@@ -52,6 +53,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
const contentRef = useRef<string>("");
/** The note `contentRef` holds the content of, so a restarted editor can be marked as holding it. */
const contentNoteIdRef = useRef<string>();
+ const pendingAttachmentChangesRef = useRef<PendingAttachmentChanges>();
const watchdogRef = useRef<EditorWatchdog>(null);
const editorApiRef = useRef<CKEditorApi>(null);
/** The open icon picker request and its balloon container, or `null` when none is open. */
@@ -93,6 +95,10 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
setEditorNoteId(editor, note.noteId);
}
editor?.setData(newContent);
+ if (editor && note) {
+ const textEditor = editor as CKTextEditor;
+ applyPendingAttachmentChanges(textEditor, note.noteId, pendingAttachmentChangesRef);
+ }
// Jump to the first search match when navigated from search results.
consumeSearchTerms(noteContext, ntxId);
@@ -185,6 +191,9 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
loadIncludedNote,
loadIncludedAttachment,
getAttachmentHref,
+ getNoteId() {
+ return note.noteId;
+ },
// Link preview functionality. The insert flow itself lives in the editor (a balloon form),
// so the host only has to supply the metadata and the rendering.
async fetchLinkMetadata(url: string) {
@@ -280,7 +289,13 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
const editor = watchdogRef.current?.editor as CKTextEditor | null | undefined;
if (editor && note) {
- notifyAttachmentChanges(editor, loadResults, note.noteId, parentComponent?.componentId);
+ notifyAttachmentChanges(
+ editor,
+ loadResults,
+ note.noteId,
+ parentComponent?.componentId,
+ pendingAttachmentChangesRef
+ );
}
});
@@ -677,30 +692,63 @@ export function onNotificationInfo(_evt: NotificationEventInfo, data: Notificati
toast.showMessage(data.message);
}
+interface PendingAttachmentChanges {
+ noteId: string;
+ changes: AttachmentLinkChange[];
+}
+
/**
* Passes the attachments changed in `loadResults` to the editor's reference links, so a link shows
* the new title of its attachment or goes away with it.
*
+ * When `loadResults` also reloads the note's content, the changes wait in `pending` until
+ * `applyPendingAttachmentChanges()` runs on the reloaded content.
+ *
* Exported for testing.
*/
export function notifyAttachmentChanges(
editor: CKTextEditor,
loadResults: LoadResults,
noteId: string,
- componentId?: string
+ componentId: string | undefined,
+ pending: { current: PendingAttachmentChanges | undefined }
) {
const changes = loadResults.getAttachmentRows().flatMap(({ attachmentId, isDeleted }) =>
attachmentId ? [ { attachmentId, isDeleted: !!isDeleted } ] : []
);
+ if (!changes.length) {
+ return;
+ }
- // The server rewrote the links in reloaded content itself, as when converting an attachment.
- if (!changes.length || loadResults.isNoteContentReloaded(noteId, componentId)) {
+ // `useNoteBlob()` reloads the content under the same condition, and `setData()` would discard
+ // the updated links.
+ if (loadResults.isNoteContentReloaded(noteId, componentId)) {
+ const held = pending.current?.noteId === noteId ? pending.current.changes : [];
+ pending.current = { noteId, changes: [ ...held, ...changes ] };
return;
}
editor.plugins.get("ReferenceLinkEditing").updateAttachmentLinks(changes);
}
+/**
+ * Applies the changes `notifyAttachmentChanges()` held for `noteId`, once the editor holds its
+ * reloaded content. Changes held for another note are dropped.
+ *
+ * Exported for testing.
+ */
+export function applyPendingAttachmentChanges(
+ editor: CKTextEditor,
+ noteId: string,
+ pending: { current: PendingAttachmentChanges | undefined }
+) {
+ const held = pending.current;
+ pending.current = undefined;
+ if (held?.noteId === noteId) {
+ editor.plugins.get("ReferenceLinkEditing").updateAttachmentLinks(held.changes);
+ }
+}
+
/**
* Shows the progress of a file attachment upload in a toast until the upload ends.
*
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index 84c0265544..35470eee72 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -51,6 +51,8 @@ declare global {
): void;
/** The href of a reference link to the attachment, or `null` once it is deleted. */
getAttachmentHref(attachmentId: string): Promise<string | null>;
+ /** The note the editor holds. Hosts without a note of their own leave it out. */
+ getNoteId?(): string | undefined;
/**
* Reads a page's preview metadata through the host. Never rejects: any failure — network
* error, HTTP error, unparseable page — resolves as `{ unresolved: true }` with
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index ede0b95100..041f63b417 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -15,6 +15,7 @@ export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, Model
export type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";
export type { FileUploadData, FileUploadEvent } from "./plugins/file_upload/fileuploadediting.js";
export type { PasteTarget } from "./plugins/cuttonote.js";
+export type { AttachmentLinkChange } from "./plugins/referencelink.js";
export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";
export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
diff --git a/packages/ckeditor5/src/plugins/uploadimage.spec.ts b/packages/ckeditor5/src/plugins/uploadimage.spec.ts
index 44c6e65e23..0f9b4e8521 100644
--- a/packages/ckeditor5/src/plugins/uploadimage.spec.ts
+++ b/packages/ckeditor5/src/plugins/uploadimage.spec.ts
@@ -98,7 +98,9 @@ describe("UploadimagePlugin", () => {
getHeaders = vi.fn(async () => ({ Authorization: "Bearer token", "x-csrf": "abc" }));
installGlobMock({
getHeaders,
- getActiveContextNote: () => ({ noteId: "noteAbc" })
+ getActiveContextNote: () => ({ noteId: "noteAbc" }),
+ // A host whose editor does not name its note, such as the chat input.
+ getComponentByEl: () => ({})
});
originalXHR = window.XMLHttpRequest;
@@ -161,6 +163,18 @@ describe("UploadimagePlugin", () => {
await expect(uploadPromise).resolves.toEqual({ default: "http://example.com/pic.png" });
});
+ it("uploads to the note its editor holds, rather than to the active tab's", async () => {
+ installGlobMock({
+ getHeaders,
+ getActiveContextNote: () => ({ noteId: "noteAbc" }),
+ getComponentByEl: () => ({ getNoteId: () => "editorNote" })
+ });
+
+ void createAdapter(new File(["content"], "pic.png", { type: "image/png" })).upload();
+
+ expect((await awaitSentXhr()).url).toBe("api/notes/editorNote/attachments/upload");
+ });
+
it("asks for a link only for a loader marked to upload as one", async () => {
const fileRepository = editor.plugins.get(FileRepository);
const marked = createFakeLoader(new File(["content"], "pic.png", { type: "image/png" }));
diff --git a/packages/ckeditor5/src/plugins/uploadimage.ts b/packages/ckeditor5/src/plugins/uploadimage.ts
index 438560377e..1f5224f2ce 100644
--- a/packages/ckeditor5/src/plugins/uploadimage.ts
+++ b/packages/ckeditor5/src/plugins/uploadimage.ts
@@ -1,15 +1,11 @@
-import { FileRepository, Plugin, type FileLoader, type LocaleTranslate, type UploadAdapter } from "ckeditor5";
-
-const linkLoaders = new WeakSet<FileLoader>();
-
-/** Makes the upload answer with a link to the attachment, and store a picture as uploaded. */
-export function uploadAsLink(loader: FileLoader) {
- linkLoaders.add(loader);
-}
-
-export function isUploadAsLink(loader: FileLoader) {
- return linkLoaders.has(loader);
-}
+import {
+ FileRepository,
+ Plugin,
+ type Editor,
+ type FileLoader,
+ type LocaleTranslate,
+ type UploadAdapter
+} from "ckeditor5";
export default class UploadimagePlugin extends Plugin {
static get requires() {
@@ -21,25 +17,39 @@ export default class UploadimagePlugin extends Plugin {
}
init() {
- const t = this.editor.t;
- this.editor.plugins.get('FileRepository').createUploadAdapter = loader => new Adapter(loader, t);
+ const editor = this.editor;
+ const fileRepository = editor.plugins.get('FileRepository');
+ fileRepository.createUploadAdapter = loader => new Adapter(loader, editor);
}
}
+const linkLoaders = new WeakSet<FileLoader>();
+
+/** Makes the upload answer with a link to the attachment, and store a picture as uploaded. */
+export function uploadAsLink(loader: FileLoader) {
+ linkLoaders.add(loader);
+}
+
+export function isUploadAsLink(loader: FileLoader) {
+ return linkLoaders.has(loader);
+}
+
class Adapter implements UploadAdapter {
private loader: FileLoader;
+ private editor: Editor;
private t: LocaleTranslate;
private xhr?: XMLHttpRequest;
/**
* Creates a new adapter instance.
*/
- constructor(loader: FileLoader, t: LocaleTranslate) {
+ constructor(loader: FileLoader, editor: Editor) {
/**
* FileLoader instance to use during the upload.
*/
this.loader = loader;
- this.t = t;
+ this.editor = editor;
+ this.t = editor.t;
}
/**
@@ -78,7 +88,11 @@ class Adapter implements UploadAdapter {
return glob.getHeaders().then(headers => {
const xhr = this.xhr = new XMLHttpRequest();
- const {noteId} = glob.getActiveContextNote();
+ // The note the editor holds, which is not the active tab's in a split or the quick edit
+ // popup. A host that does not say falls back to the active tab's.
+ const domRoot = this.editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>( domRoot );
+ const noteId = component?.getNoteId?.() ?? glob.getActiveContextNote().noteId;
const query = isUploadAsLink(this.loader) ? "?link=true" : "";
// this must be a relative path