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
chore(text): pass upload services through editor config
Elian Doranf2baa7aef8ef
diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.mdindex fb909729b6..cbe8ce6b39 100644--- a/.claude/skills/ckeditor5-testing/references/patterns.md+++ b/.claude/skills/ckeditor5-testing/references/patterns.md@@ -37,14 +37,16 @@ standalone packages (and legacy specs mid-migration) still hand-roll the scaffolHost services that need no component come through the editor config, so a spec passes them to`createTestEditor( plugins, { … } )` instead of mocking `glob`: `formatDateTime` (date/time),-`referenceLink: { getTitle, getTitleSync }` (reference links) and `linkEmbed` (link previews —-`createLinkEmbedHost()` in `test/link-embed-kit.ts` builds the mocked entry). Each falls back to a-placeholder when left out, so a spec that does not assert on it can omit it.+`referenceLink: { getTitle, getTitleSync }` (reference links), `linkEmbed` (link previews —+`createLinkEmbedHost()` in `test/link-embed-kit.ts` builds the mocked entry), and `getNoteId` plus+`attachmentUpload: { getHeaders, getLocalUpload, getEmbedBoxSize }` (uploads). Each falls back to a+placeholder when left out (an upload without `getNoteId` is rejected), so a spec that does not+assert on it can omit it. A spec sharing one editor across tests can swap an entry with+`editor.config.set()`, which the plugins read at call time.Many in-aggregate plugins still reach for a global `glob` (the Trilium bridge — typed in-`packages/ckeditor5/src/augmentation.ts` with `getComponentByEl`, `getActiveContextNote`,-`getHeaders`, `getLocalUpload`), some buttons hit-`navigator.clipboard`, and some converters call jQuery `$(...)` (e.g. the `editingDowncast`+`packages/ckeditor5/src/augmentation.ts` with `getComponentByEl` and `getActiveContextNote`), some+buttons hit `navigator.clipboard`, and some converters call jQuery `$(...)` (e.g. the `editingDowncast`converter in `packages/ckeditor5/src/plugins/referencelink.ts`). Use the globals kit(`test/globals-test-kit.ts`) so each stub **tears itself down** after the test — never hand-roll`globalThis.glob = …` plus a manual `delete`:diff --git a/apps/client/src/services/glob.ts b/apps/client/src/services/glob.tsindex 92c0337726..de9b8c87e4 100644--- a/apps/client/src/services/glob.ts+++ b/apps/client/src/services/glob.ts@@ -11,7 +11,6 @@ function setupGlobs() {window.glob.getComponentByEl = (el) => appContext.getComponentByEl(el);window.glob.getHeaders = server.getHeaders;- window.glob.getLocalUpload = server.getLocalUpload;window.glob.getReferenceLinkTitle = (href) => linkService.getReferenceLinkTitle(href);window.glob.getReferenceLinkTitleSync = (href, storedTitle) =>linkService.getReferenceLinkTitleSync(href, storedTitle);diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.tsindex 79f99a5510..8d65072d00 100644--- a/apps/client/src/types.d.ts+++ b/apps/client/src/types.d.ts@@ -20,7 +20,6 @@ interface CustomGlobals extends BootstrapDefinition {isMobile: typeof utils.isMobile;getComponentByEl: typeof appContext.getComponentByEl;getHeaders: typeof server.getHeaders;- getLocalUpload: typeof server.getLocalUpload;getReferenceLinkTitle: (href: string) => Promise<string>;getReferenceLinkTitleSync: (href: string, storedTitle?: string) => string;getActiveContextNote: () => FNote | null;diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex 8dad20d8f9..5400d42b58 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -285,7 +285,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLacontentLanguage: contentLanguage ?? null,templates: templatesRef.current,getNoteLocation: () => noteLocationRef.current,- getNoteId: () => noteIdRef.current+ getNoteId: () => noteIdRef.current,+ getComponentId: () => parentComponent?.componentId});if (isStale) {diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 6fd9b10ab5..9f196aec23 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -20,7 +20,6 @@ import {openBlockHandleMenu} from "../../../services/block_reference";import { consumeBookmark } from "../../../services/bookmark_jump";-import { getUploadBoxSize } from "../../../services/content_renderer";import dialog from "../../../services/dialog";import froca from "../../../services/froca";import { t } from "../../../services/i18n";@@ -323,7 +322,6 @@ export default function EditableText({getNoteId() {return note.noteId;},- getEmbedBoxSize: getUploadBoxSize,openContentEmbedMenu,openBlockHandleMenu(event: MouseEvent, count: number) {const shareLink = getNoteShareLink(note);diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex e8134f4cef..4bf19888cb 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -94,6 +94,22 @@ vi.mock("../../../services/dialog.js", () => ({}));vi.mock("@triliumnext/highlightjs", () => ({ default: { name: "hljs-stub" } }));vi.mock("../../../services/math.js", () => ({ default: { name: "katex-stub" } }));+vi.mock("../../../services/content_renderer.js", () => ({ getUploadBoxSize: vi.fn(() => "medium") }));+vi.mock("../../../services/server.js", async (importOriginal) => {+ const original = await importOriginal<typeof import("../../../services/server.js")>();+ return {+ default: {+ ...original.default,+ // `keyboard_actions` loads its actions through `get` on import.+ get: vi.fn(async () => []),+ getHeaders: vi.fn(async (headers?: Record<string, string | null | undefined>) => ({+ "x-csrf-token": "csrf",+ "trilium-hoisted-note-id": null,+ ...headers+ }))+ }+ };+});vi.mock("../../../services/link_embed.js", async (importOriginal) => ({...(await importOriginal<typeof import("../../../services/link_embed.js")>()),fetchMetadata: vi.fn(async (url: string, ownerNoteId: string) => ({ url, embedType: "opengraph", title: ownerNoteId }))@@ -363,6 +379,16 @@ describe("CK config - tables", () => {expect(linkEmbed?.detectEmbedType?.("https://youtube.com/watch?v=abc12345678")).toBe("youtube");});+ it("uploads to the open note, as a change of the editor's component", async () => {+ const config = await buildConfig(baseOpts({ getNoteId: () => "noteAbc", getComponentId: () => "editor1" }));++ expect(config.getNoteId?.()).toBe("noteAbc");+ // Headers without a value are left out rather than sent as the text "null".+ expect(await config.attachmentUpload?.getHeaders?.())+ .toStrictEqual({ "x-csrf-token": "csrf", "trilium-component-id": "editor1" });+ expect(config.attachmentUpload?.getEmbedBoxSize?.("image/png", 1)).toBe("medium");+ });+it("titles reference links through the link service", async () => {expect((await buildConfig(baseOpts())).referenceLink).toStrictEqual({getTitle: linkService.getReferenceLinkTitle,diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex f2752ed29b..209d24df37 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -1,9 +1,10 @@-import { type EditorConfig, getCkLocale, type LinkEmbedHost, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";+import { type AttachmentUploadHost, type EditorConfig, getCkLocale, type LinkEmbedHost, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import i18next from "i18next";import { copyHtmlWithToast, copyTextWithToast } from "../../../services/clipboard_ext.js";+import { getUploadBoxSize } from "../../../services/content_renderer.js";import { prompt } from "../../../services/dialog.js";import { t } from "../../../services/i18n.js";import imageService from "../../../services/image.js";@@ -13,6 +14,7 @@ import { detectEmbedType, fetchMetadata, renderEmbedPreview, renderMentionPrevieimport { default as mimeTypesService, getHighlightJsNameForMime } from "../../../services/mime_types.js";import options from "../../../services/options.js";import { sanitizeNoteContentHtml } from "../../../services/sanitize_content.js";+import server from "../../../services/server.js";import { getSourceEmbedTypeByLanguage, SOURCE_EMBED_TYPES } from "../../../services/source_embeds.js";import { ensureMimeTypesForHighlighting, isSyntaxHighlightEnabled } from "../../../services/syntax_highlight.js";import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../services/task_states.js";@@ -50,6 +52,8 @@ export interface BuildEditorOptions {getNoteLocation?: AiNoteLocationProvider;/** The ID of the note the editor is open on. A getter for the same reason as `getNoteLocation`. */getNoteId?: () => string | undefined;+ /** The ID of the component that hosts the editor, which changes the editor makes are sent as. */+ getComponentId?: () => string | undefined;}export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfig> {@@ -207,6 +211,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfigetTitleSync: linkService.getReferenceLinkTitleSync},linkEmbed: buildLinkEmbedHost(opts.getNoteId),+ getNoteId: opts.getNoteId,+ attachmentUpload: buildAttachmentUploadHost(opts.getComponentId),slashCommand: {// Drop CKEditor's built-in list slash commands, whose Title Case titles the palette// re-defines in sentence case.@@ -344,6 +350,25 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi};}+/** The upload services of the editor, sending its uploads as changes of `getComponentId()`. */+function buildAttachmentUploadHost(getComponentId?: () => string | undefined): AttachmentUploadHost {+ return {+ async getHeaders() {+ // Sent as a change of the host, which then does not redraw the links and embeds it shows.+ const headers = await server.getHeaders({ "trilium-component-id": getComponentId?.() });+ const sent: Record<string, string> = {};+ for (const [ name, value ] of Object.entries(headers)) {+ if (value) {+ sent[name] = value;+ }+ }+ return sent;+ },+ getLocalUpload: server.getLocalUpload,+ getEmbedBoxSize: getUploadBoxSize+ };+}+/** The link preview services of the editor, for the note `getNoteId()` names. */function buildLinkEmbedHost(getNoteId?: () => string | undefined): LinkEmbedHost {return {diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 33a4d92901..5b8e93f4e7 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -1,7 +1,5 @@import "ckeditor5";-import type { StandaloneApi } from "@triliumnext/commons";-import type { InlineEmbedSource } from "./plugins/content_embed/inline_source.js";declare global {@@ -141,11 +139,6 @@ declare global {getAttachmentHref(attachmentId: string): Promise<string | null>;/** The note the editor holds. Hosts without a note of their own leave it out. */getNoteId?(): string | undefined;- /**- * The box size of a new embed of a file being uploaded, from its media type. Hosts without- * embeds leave it out.- */- getEmbedBoxSize?(mime: string, size: number): string;/*** Opens the context menu of what `embed` shows, below `anchor`. Hosts without embeds* leave it out.@@ -183,19 +176,11 @@ declare global {convertImageToDrawing?(src: string): Promise<string | null>;}- type LocalUpload = NonNullable<StandaloneApi["localUpload"]>;-var glob: {getComponentByEl<T extends Component>(el: unknown): T;getActiveContextNote(): {noteId: string;};- /** The headers of a request to the server, with `headers` added to them. */- getHeaders(headers?: Record<string, string | undefined>): Promise<Record<string, string>>;- /**- * The host's in-page upload to its local server, when it has one. Uploads go through it- * because a raw request with a body cannot reach that server from every platform.- */- getLocalUpload?(): LocalUpload | undefined;};}+diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 1acd03cc56..624371bc0a 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -37,6 +37,7 @@ export type { default as TextFormattingToolbar } from "./plugins/text_formattingexport type { default as ContextToolbar } from "./plugins/context_toolbar.js";export type { default as MobileToolbarItems } from "./plugins/mobile_toolbar_items.js";export type { LinkEmbedHost } from "./plugins/link_embed/link_embed_commands.js";+export type { AttachmentUploadHost } from "./plugins/uploadimage.js";export type { ColorMenuHost, ColorMenuRequest, ColorMenuTarget } from "./plugins/color_menu.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.tsindex f5febb56fd..e31f149e49 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts@@ -14,7 +14,6 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";-import { installGlobMock } from "../../../test/globals-test-kit.js";import ContentEmbed from "../content_embed/content_embed.js";import { isUploadAsLink } from "../uploadimage.js";import FileUploadCommand, { isFocusUpload, isQuietUpload } from "./fileuploadcommand.js";@@ -149,7 +148,7 @@ describe("FileUploadCommand", () => {it("inserts an embed placeholder per file, in the size the host gives its type and size", () => {const getEmbedBoxSize = vi.fn((mime: string, _size: number) =>(mime === "image/png" || mime === "application/vnd.excalidraw+json" ? "medium" : "tiny"));- installGlobMock({ getComponentByEl: () => ({ getEmbedBoxSize }) });+ editor.config.set("attachmentUpload", { getEmbedBoxSize });setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");editor.execute("fileUpload", {@@ -178,7 +177,6 @@ describe("FileUploadCommand", () => {});it("sizes the embeds medium for a host that names no size", () => {- installGlobMock({ getComponentByEl: () => ({}) });setModelData(editor.model, "<paragraph>[]</paragraph>");editor.execute("fileUpload", {@@ -192,7 +190,7 @@ describe("FileUploadCommand", () => {it("gives the embeds the box size, hidden title and editing the caller asks for", () => {const getEmbedBoxSize = vi.fn(() => "tiny");- installGlobMock({ getComponentByEl: () => ({ getEmbedBoxSize }) });+ editor.config.set("attachmentUpload", { getEmbedBoxSize });setModelData(editor.model, "<paragraph>[]</paragraph>");editor.execute("fileUpload", {@@ -213,7 +211,6 @@ describe("FileUploadCommand", () => {});it("places an embed that takes the focus as an image, keeping the text and the cursor", () => {- installGlobMock({ getComponentByEl: () => ({}) });const insert = (data: string, focusEmbed: boolean) => {setModelData(editor.model, data);editor.execute("fileUpload", {@@ -250,7 +247,6 @@ describe("FileUploadCommand", () => {});it("marks the loaders of a quiet upload and of a focus upload, and only those", () => {- installGlobMock({ getComponentByEl: () => ({}) });setModelData(editor.model, "<paragraph>[]</paragraph>");const createLoaderSpy = vi.spyOn(editor.plugins.get(FileRepository), "createLoader");@@ -264,7 +260,6 @@ describe("FileUploadCommand", () => {});it("marks the loader of every file to upload as a link, for an embed too", () => {- installGlobMock({ getComponentByEl: () => ({}) });setModelData(editor.model, "<paragraph>[]</paragraph>");const createLoaderSpy = vi.spyOn(editor.plugins.get(FileRepository), "createLoader");diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.tsindex fa0b2e0a66..3e8e24cddc 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts@@ -141,7 +141,6 @@ interface EmbedPlaceholderOptions {/** The box size the host gives an embed of `file`, `medium` when the host does not say. */function getEmbedBoxSize(editor: Editor, file: File) {- const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());const mime = getAttachedFileMime(file.name, file.type);- return component.getEmbedBoxSize?.(mime, file.size) ?? "medium";+ return editor.config.get("attachmentUpload")?.getEmbedBoxSize?.(mime, file.size) ?? "medium";}diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.tsindex ea0d89ce70..75e98f942f 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts@@ -607,7 +607,6 @@ describe("FileUploadEditing with embeds", () => {const focusContentEmbed = vi.fn();installGlobMock({getComponentByEl: () => ({- getEmbedBoxSize: () => "small",loadEmbeddedAttachment,focusContentEmbed})@@ -615,7 +614,7 @@ describe("FileUploadEditing with embeds", () => {const editor = await createTestEditor([Essentials, Paragraph, FileRepository, Notification, Clipboard, ReferenceSchema,ContentEmbed, FileUploadEditing- ]);+ ], { attachmentUpload: { getEmbedBoxSize: () => "small" } });const controls = installUploadAdapter(editor);setModelData(editor.model, "<paragraph>[]</paragraph>");diff --git a/packages/ckeditor5/src/plugins/uploadimage.spec.ts b/packages/ckeditor5/src/plugins/uploadimage.spec.tsindex 3bf6ce8302..8dc900a618 100644--- a/packages/ckeditor5/src/plugins/uploadimage.spec.ts+++ b/packages/ckeditor5/src/plugins/uploadimage.spec.ts@@ -2,7 +2,6 @@ import { ClassicEditor, Essentials, FileRepository, Paragraph, type FileLoader,import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";-import { installGlobMock } from "../../test/globals-test-kit.js";import UploadimagePlugin, {isUploadAsLink,uploadAsLink@@ -92,22 +91,23 @@ function createFakeLoader(file: File | null): FileLoader {describe("UploadimagePlugin", () => {let editor: ClassicEditor;let getHeaders: ReturnType<typeof vi.fn>;+ let noteId: string | undefined;+ let localUpload: ReturnType<typeof vi.fn> | undefined;let originalXHR: typeof window.XMLHttpRequest;beforeEach(async () => {getHeaders = vi.fn(async () => ({ Authorization: "Bearer token", "x-csrf": "abc" }));- installGlobMock({- getHeaders,- getActiveContextNote: () => ({ noteId: "noteAbc" }),- // A host whose editor does not name its note, such as the chat input.- getComponentByEl: () => ({})- });+ noteId = "noteAbc";+ localUpload = undefined;originalXHR = window.XMLHttpRequest;window.XMLHttpRequest = FakeXHR as unknown as typeof window.XMLHttpRequest;FakeXHR.last = undefined;- editor = await createTestEditor([Essentials, Paragraph, FileRepository, UploadimagePlugin]);+ editor = await createTestEditor([Essentials, Paragraph, FileRepository, UploadimagePlugin], {+ getNoteId: () => noteId,+ attachmentUpload: { getHeaders, getLocalUpload: () => localUpload }+ });});afterEach(() => {@@ -163,18 +163,24 @@ 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: () => ({ componentId: "editor1", getNoteId: () => "editorNote" })- });-+ it("uploads to the note the host names when the upload starts, and nowhere without one", async () => {+ noteId = "otherNote";void createAdapter(new File(["content"], "pic.png", { type: "image/png" })).upload();+ expect((await awaitSentXhr()).url).toBe("api/notes/otherNote/attachments/upload");++ FakeXHR.last = undefined;+ noteId = undefined;+ await expect(createAdapter(new File(["content"], "pic.png", { type: "image/png" })).upload())+ .rejects.toBe("Cannot upload file: pic.png.");+ expect(FakeXHR.last).toBeUndefined();+ });++ it("cannot upload without the getNoteId config entry", async () => {+ const plainEditor = await createTestEditor([Essentials, Paragraph, FileRepository, UploadimagePlugin]);+ const adapter = plainEditor.plugins.get(FileRepository)+ .createUploadAdapter?.(createFakeLoader(new File(["content"], "pic.png", { type: "image/png" })));- expect((await awaitSentXhr()).url).toBe("api/notes/editorNote/attachments/upload");- // As a change of the editor, which then does not redraw the embed it completes.- expect(getHeaders).toHaveBeenCalledWith({ "trilium-component-id": "editor1" });+ await expect(adapter?.upload()).rejects.toBe("Cannot upload file: pic.png.");});it("asks for a link only for a loader marked to upload as one", async () => {@@ -339,20 +345,12 @@ describe("UploadimagePlugin", () => {});describe("with a local server", () => {- let localUpload: ReturnType<typeof vi.fn>;-function answerWith(body: string, status = 200, contentType = "application/json") {- localUpload.mockResolvedValue(new Response(body, { status, headers: { "content-type": contentType } }));+ localUpload?.mockResolvedValue(new Response(body, { status, headers: { "content-type": contentType } }));}beforeEach(() => {localUpload = vi.fn();- installGlobMock({- getHeaders,- getActiveContextNote: () => ({ noteId: "noteAbc" }),- getComponentByEl: () => ({}),- getLocalUpload: () => localUpload- });});it("hands the file to the local server instead of sending a request", async () => {@@ -380,13 +378,13 @@ describe("UploadimagePlugin", () => {await expect(createAdapter(file).upload()).rejects.toBe("Cannot upload file: pic.png. The file is too large to be uploaded (HTTP 413). If Trilium is behind a reverse proxy, raise its request body size limit.");- localUpload.mockRejectedValue(new Error("Worker gone"));+ localUpload?.mockRejectedValue(new Error("Worker gone"));await expect(createAdapter(file).upload()).rejects.toBe("Cannot upload file: pic.png.");});it("rejects with no reason when aborted, and ignores the late answer", async () => {let answer: (response: Response) => void = () => {};- localUpload.mockReturnValue(new Promise<Response>(resolve => {+ localUpload?.mockReturnValue(new Promise<Response>(resolve => {answer = resolve;}));const adapter = createAdapter(new File(["content"], "pic.png", { type: "image/png" }));diff --git a/packages/ckeditor5/src/plugins/uploadimage.ts b/packages/ckeditor5/src/plugins/uploadimage.tsindex 8e01f57ad0..85d5e26a05 100644--- a/packages/ckeditor5/src/plugins/uploadimage.ts+++ b/packages/ckeditor5/src/plugins/uploadimage.ts@@ -1,3 +1,4 @@+import type { StandaloneApi } from "@triliumnext/commons";import {FileRepository,Plugin,@@ -59,18 +60,23 @@ class Adapter implements UploadAdapter {* @see module:upload/filerepository~Adapter#upload*/upload() {- const localUpload = glob.getLocalUpload?.();- if (localUpload) {- return this._uploadLocally(localUpload) as Promise<any>;- }+ return this.loader.file.then((file): Promise<unknown> => {+ if (!file) {+ throw "Missing file";+ }++ const localUpload = this.editor.config.get('attachmentUpload')?.getLocalUpload?.();+ if (localUpload) {+ return this._uploadLocally(localUpload, file);+ }- return this.loader.file- .then( file => new Promise<File | null>( ( resolve, reject ) => {- this._initRequest().then(() => {- this._initListeners(resolve, reject);- this._sendRequest();- });- } ) ) as Promise<any>;+ return new Promise<File | null>((resolve, reject) => {+ this._initRequest(file).then(() => {+ this._initListeners(file, resolve, reject);+ this._sendRequest(file);+ }, reject);+ });+ }) as Promise<any>;}/**@@ -90,14 +96,9 @@ class Adapter implements UploadAdapter {* Hands the file to the host's local server. A raw request with a body cannot reach it: the* mobile app's native request bridges answer GET and HEAD only.*/- private async _uploadLocally(localUpload: LocalUpload) {- const file = await this.loader.file;- if (!file) {- throw "Missing file";- }-+ private async _uploadLocally(localUpload: LocalUpload, file: File) {const genericError = this.t('Cannot upload file:') + ` ${file.name}.`;- const { url, headers } = await this._getRequestTarget();+ const { url, headers } = await this._getRequestTarget(file);const aborted = new Promise<never>((_, reject) => {this.rejectLocal = () => reject();});@@ -129,8 +130,8 @@ class Adapter implements UploadAdapter {** @private*/- _initRequest() {- return this._getRequestTarget().then(({ url, headers }) => {+ _initRequest(file: File) {+ return this._getRequestTarget(file).then(({ url, headers }) => {const xhr = this.xhr = new XMLHttpRequest();xhr.open('POST', url, true);@@ -142,17 +143,18 @@ class Adapter implements UploadAdapter {});}- /** The relative URL of the upload route for the editor's note, and the request headers. */- private async _getRequestTarget() {- const domRoot = this.editor.editing.view.getDomRoot();- const component = glob.getComponentByEl<EditorComponent>( domRoot );-- // Sent as a change of the host, which then does not redraw the links and embeds it shows.- const headers = await glob.getHeaders({ "trilium-component-id": component?.componentId });+ /**+ * The relative URL of the upload route for the note `getNoteId` names, and the request headers.+ * Rejects when the editor names no note to attach `file` to.+ */+ private async _getRequestTarget(file: File) {+ const config = this.editor.config;+ const noteId = config.get('getNoteId')?.();+ if (!noteId) {+ throw this.t('Cannot upload file:') + ` ${file.name}.`;+ }- // 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 noteId = component?.getNoteId?.() ?? glob.getActiveContextNote().noteId;+ const headers = await config.get('attachmentUpload')?.getHeaders?.() ?? {};const query = isUploadAsLink(this.loader) ? "?link=true" : "";// this must be a relative path@@ -166,7 +168,7 @@ class Adapter implements UploadAdapter {* @param resolve Callback function to be called when the request is successful.* @param reject Callback function to be called when the request cannot be completed.*/- async _initListeners(resolve: (value: File | PromiseLike<File | null> | null) => void, reject: (reason?: any) => void) {+ _initListeners(file: File, resolve: (value: File | PromiseLike<File | null> | null) => void, reject: (reason?: any) => void) {const xhr = this.xhr;/* v8 ignore next 4 -- unreachable: _initListeners runs only after _initRequest() resolves, which always assigns this.xhr */if (!xhr) {@@ -175,12 +177,6 @@ class Adapter implements UploadAdapter {}const loader = this.loader;- const file = await loader.file;- if (!file) {- reject("Missing file");- return;- }-const t = this.t;const genericError = t('Cannot upload file:') + ` ${file.name}.`;@@ -215,17 +211,10 @@ class Adapter implements UploadAdapter {** @private*/- async _sendRequest() {- // Prepare form data.+ _sendRequest(file: File) {const data = new FormData();-- const file = await this.loader.file;- if (file) {- data.append('upload', file);-- // Send request.- this.xhr?.send(data);- }+ data.append('upload', file);+ this.xhr?.send(data);}}@@ -258,3 +247,26 @@ function describeUploadFailure(t: LocaleTranslate, status: number, response: { ereturn '';}++type LocalUpload = NonNullable<StandaloneApi["localUpload"]>;++/** The services the host provides for uploading attachments, through the `attachmentUpload` config entry. */+export interface AttachmentUploadHost {+ /** The headers of an upload request. */+ getHeaders(): Promise<Record<string, string>>;+ /**+ * The host's in-page upload to its local server, when it has one. Uploads go through it+ * because a raw request with a body cannot reach that server from every platform.+ */+ getLocalUpload(): LocalUpload | undefined;+ /** The box size a new embed of an uploaded file starts at, from its media type and size. */+ getEmbedBoxSize(mime: string, size: number): string;+}++declare module "ckeditor5" {+ interface EditorConfig {+ /** The ID of the note the editor holds, which uploads attach to. */+ getNoteId?(): string | undefined;+ attachmentUpload?: Partial<AttachmentUploadHost>;+ }+}