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
refactor(ckeditor5): remove dead inputTransformation file-upload handler
Elian Doran09e24daab8a5
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.tsindex fe0854a208..7f393f2678 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts@@ -1,5 +1,4 @@import {- ClassicEditor,Clipboard,Essentials,FileRepository,@@ -12,43 +11,20 @@ import {viewToModelPositionOutsideModelElement,_getModelData as getModelData,_setModelData as setModelData,+ type ClassicEditor,type FileLoader,type ModelItem} from "ckeditor5";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { createTestEditor } from "../../../test/editor-kit.js";import FileUploadEditing, { isHtmlIncluded } from "./fileuploadediting.js";describe("FileUploadEditing", () => {- let editorElement: HTMLDivElement;let editor: ClassicEditor;- let originalFetch: typeof globalThis.fetch;-- // The inputTransformation handler in the source passes the tree-walker VALUE- // (not value.item) to writer.setAttribute(); UpcastWriter then throws because- // a walker value has no _setAttribute(). It also kicks off fetchLocalFile()- // whose promise becomes unhandled once the handler throws. Swallow those- // unhandled rejections so they don't crash the test runner's serializer.- const swallowRejection = (event: PromiseRejectionEvent) => event.preventDefault();beforeEach(async () => {- window.addEventListener("unhandledrejection", swallowRejection);- originalFetch = globalThis.fetch;-- editorElement = document.createElement("div");- document.body.appendChild(editorElement);-- editor = await ClassicEditor.create(editorElement, {- licenseKey: "GPL",- plugins: [Essentials, Paragraph, FileRepository, Notification, Clipboard, ReferenceSchema, FileUploadEditing]- });- });-- afterEach(async () => {- globalThis.fetch = originalFetch;- editorElement.remove();- await editor.destroy();- window.removeEventListener("unhandledrejection", swallowRejection);+ editor = await createTestEditor([Essentials, Paragraph, FileRepository, Notification, Clipboard, ReferenceSchema, FileUploadEditing]);});// -----------------------------------------------------------------@@ -170,101 +146,6 @@ describe("FileUploadEditing", () => {expect(preventDefault).toHaveBeenCalled();});- // ------------------------------------------------------------------ // inputTransformation handler (local-file URL fetch)- //- // NOTE: with a local-file link present, the handler always throws because- // the source passes the tree-walker value (not value.item) to- // writer.setAttribute(); see the file-level comment. We therefore assert on- // the throw and on fetchLocalFile() having been invoked (line 63 runs before- // the throw).- // ------------------------------------------------------------------- it("invokes fetchLocalFile for local-file links (and throws on the buggy setAttribute)", () => {- globalThis.fetch = vi.fn(async () => makeBlobResponse(new Blob(["data"], { type: "text/plain" }))) as unknown as typeof globalThis.fetch;-- const content = makeViewFragmentWithLink("api/attachments/abc/download").content;-- expect(() => editor.plugins.get(Clipboard).fire("inputTransformation", { content })).toThrow();- expect(globalThis.fetch).toHaveBeenCalledWith("api/attachments/abc/download");- });-- it("ignores links that already have the uploadProcessed attribute", () => {- globalThis.fetch = vi.fn() as unknown as typeof globalThis.fetch;-- const content = makeViewFragmentWithLink("api/attachments/abc/download", { uploadProcessed: "true" }).content;-- // No fetchable files -> handler returns early, nothing thrown.- expect(() => editor.plugins.get(Clipboard).fire("inputTransformation", { content })).not.toThrow();- expect(globalThis.fetch).not.toHaveBeenCalled();- });-- it("ignores non-local content (an <a> without href)", () => {- globalThis.fetch = vi.fn() as unknown as typeof globalThis.fetch;-- const content = makeViewFragmentWithLink(null).content;-- expect(() => editor.plugins.get(Clipboard).fire("inputTransformation", { content })).not.toThrow();- expect(globalThis.fetch).not.toHaveBeenCalled();- });-- it("ignores content that is not an <a> element at all", () => {- globalThis.fetch = vi.fn() as unknown as typeof globalThis.fetch;-- const writer = new UpcastWriter(editor.editing.view.document);- const span = writer.createElement("span", { href: "api/x" });- const content = writer.createDocumentFragment([span]);-- expect(() => editor.plugins.get(Clipboard).fire("inputTransformation", { content })).not.toThrow();- expect(globalThis.fetch).not.toHaveBeenCalled();- });-- // ------------------------------------------------------------------ // fetchLocalFile() helper branches — exercised via the line-63 call.- // The handler throws right after, so we settle the dangling promise (which- // the unhandledrejection swallower keeps from crashing the runner).- // ------------------------------------------------------------------- it("fetchLocalFile resolves a File from a typed blob", async () => {- globalThis.fetch = vi.fn(async () => makeBlobResponse(new Blob(["payload"], { type: "text/plain" }))) as unknown as typeof globalThis.fetch;-- fireLocalFileTransformation("api/attachments/abc/download");-- // Let the fetch().then(...).then(...) chain settle (resolve branch).- await flushAsync();- expect(globalThis.fetch).toHaveBeenCalledWith("api/attachments/abc/download");- });-- it("fetchLocalFile derives the mime type from a base64 data URL when the blob is typeless", async () => {- globalThis.fetch = vi.fn(async () => makeBlobResponse(new Blob(["payload"]))) as unknown as typeof globalThis.fetch;-- fireLocalFileTransformation("data:image/png;base64,AAAA");-- await flushAsync();- expect(globalThis.fetch).toHaveBeenCalledWith("data:image/png;base64,AAAA");- });-- it("fetchLocalFile rejects when the mime type cannot be retrieved", async () => {- globalThis.fetch = vi.fn(async () => makeBlobResponse(new Blob(["payload"]))) as unknown as typeof globalThis.fetch;-- fireLocalFileTransformation("api/attachments/abc/download");-- // Typeless blob + non-data URL -> getFileMimeType throws -> promise rejects.- await flushAsync();- expect(globalThis.fetch).toHaveBeenCalled();- });-- it("fetchLocalFile rejects when fetch itself fails", async () => {- globalThis.fetch = vi.fn(async () => {- throw new Error("network down");- }) as unknown as typeof globalThis.fetch;-- fireLocalFileTransformation("api/attachments/abc/download");-- await flushAsync();- expect(globalThis.fetch).toHaveBeenCalled();- });-// -----------------------------------------------------------------// change post-fixer + _readAndUpload — happy path// -----------------------------------------------------------------@@ -483,26 +364,6 @@ describe("FileUploadEditing", () => {function emptyViewFragment() {return new UpcastWriter(editor.editing.view.document).createDocumentFragment([]);}-- function makeViewFragmentWithLink(href: string | null, extraAttrs: Record<string, string> = {}) {- const writer = new UpcastWriter(editor.editing.view.document);- const attrs: Record<string, string> = { ...extraAttrs };- if (href !== null) {- attrs.href = href;- }- const link = writer.createElement("a", attrs);- return { content: writer.createDocumentFragment([link]), link };- }-- function fireLocalFileTransformation(href: string) {- const content = makeViewFragmentWithLink(href).content;- try {- editor.plugins.get(Clipboard).fire("inputTransformation", { content });- } catch {- // Expected: the source's buggy setAttribute throws. fetchLocalFile()- // has already been invoked (line 63) and its promise is in flight.- }- }});/** Lets the queued microtasks / the loader.read() chain settle. */@@ -526,10 +387,6 @@ function setLoaderStatus(loader: FileLoader | null, status: string) {}}-function makeBlobResponse(blob: Blob) {- return { blob: async () => blob } as unknown as Response;-}-/** Builds a fake DataTransfer carrying the given files and optional HTML payload. */function makeDataTransfer(opts: { files?: File[]; html?: string | null } = {}): DataTransfer {const files = opts.files ?? [];diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.tsindex 90ef2b364b..efd428957f 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts@@ -1,4 +1,4 @@-import { Clipboard, FileRepository, Notification, Plugin, UpcastWriter, ViewElement, type Editor, type FileLoader, type ModelItem, type ModelNode, type ViewItem, type ViewRange } from 'ckeditor5';+import { Clipboard, FileRepository, Notification, Plugin, type Editor, type FileLoader, type ModelItem, type ViewRange } from 'ckeditor5';import FileUploadCommand from './fileuploadcommand';export default class FileUploadEditing extends Plugin {@@ -56,33 +56,6 @@ export default class FileUploadEditing extends Plugin {} );} );- this.listenTo( editor.plugins.get( Clipboard ), 'inputTransformation', ( evt, data ) => {- const fetchableFiles = Array.from( editor.editing.view.createRangeIn( data.content ) )- .filter( value => isLocalFile( value.item ) && !(value.item as unknown as ModelNode).getAttribute( 'uploadProcessed' ) )- .map( value => {- return { promise: fetchLocalFile( value.item ), fileElement: value as unknown as ViewElement };- } );-- if ( !fetchableFiles.length ) {- return;- }-- const writer = new UpcastWriter(this.editor.editing.view.document);-- for ( const fetchableFile of fetchableFiles ) {- // Set attribute marking that the file was processed already.- writer.setAttribute( 'uploadProcessed', true, fetchableFile.fileElement );-- const loader = fileRepository.createLoader( fetchableFile.promise );-- /* v8 ignore next 4 -- unreachable: line 74 calls writer.setAttribute() with `fetchableFile.fileElement`, which is the TreeWalkerValue (`value`), not `value.item`. A walker value has no `_setAttribute()`, so UpcastWriter throws there before createLoader's result is ever inspected (verified: createLoader is never invoked and this `if` body never runs). */- if ( loader ) {- writer.setAttribute( 'href', '', fetchableFile.fileElement );- writer.setAttribute( 'uploadId', loader.id, fetchableFile.fileElement );- }- }- } );-// Prevents from the browser redirecting to the dropped file.editor.editing.view.document.on( 'dragover', ( evt, data ) => {data.preventDefault();@@ -195,59 +168,6 @@ export default class FileUploadEditing extends Plugin {}}-function fetchLocalFile( link: ViewItem ) {- return new Promise<File>( ( resolve, reject ) => {- const href = (link as unknown as ModelNode).getAttribute( 'href' ) as string;-- // Fetch works asynchronously and so does not block the browser UI when processing data.- fetch( href )- .then( resource => resource.blob() )- .then( blob => {- /* v8 ignore next -- getFileMimeType() returns a non-empty string or throws; it never returns null/undefined, so the `?? ""` fallback is unreachable. */- const mimeType = getFileMimeType( blob, href ) ?? "";- const ext = mimeType?.replace( 'file/', '' );- const filename = `file.${ ext }`;- const file = createFileFromBlob( blob, filename, mimeType );-- /* v8 ignore next -- createFileFromBlob() only returns null when `new File()` throws (an Edge-only quirk); in a real browser `file` is always truthy, so the reject() branch is unreachable. */- file ? resolve( file ) : reject();- } )- .catch( reject );- } );-}--function isLocalFile( node: ViewItem ) {- if ( !node.is( 'element', 'a' ) || !node.getAttribute( 'href' ) ) {- return false;- }-- return node.getAttribute( 'href' );-}--function getFileMimeType( blob: Blob, src: string ) {- if ( blob.type ) {- return blob.type;- } else if ( src.match( /data:(image\/\w+);base64/ ) ) {- return src.match( /data:(image\/\w+);base64/ )?.[ 1 ].toLowerCase();- } else {- throw new Error( 'Could not retrieve mime type for file.' );- }-}--function createFileFromBlob( blob: BlobPart, filename: string, mimeType: string ) {- try {- return new File( [ blob ], filename, { type: mimeType } );- /* v8 ignore start -- Edge-only fallback: the `File` constructor never throws in the supported (Chromium) browsers, so this catch is unreachable. See https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9551546/ and ckeditor5-upload#247. */- } catch ( err ) {- // Edge does not support `File` constructor ATM, see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9551546/.- // However, the `File` function is present (so cannot be checked with `!window.File` or `typeof File === 'function'`), but- // calling it with `new File( ... )` throws an error. This try-catch prevents that. Also when the function will- // be implemented correctly in Edge the code will start working without any changes (see #247).- return null;- }- /* v8 ignore stop */-}-// Returns `true` if non-empty `text/html` is included in the data transfer.//// @param {module:clipboard/datatransfer~DataTransfer} dataTransfer