diff --git a/pkgs/id/web/src/image-upload.test.ts b/pkgs/id/web/src/image-upload.test.ts index 08ddc7148..00c41dc26 100644 --- a/pkgs/id/web/src/image-upload.test.ts +++ b/pkgs/id/web/src/image-upload.test.ts @@ -498,6 +498,46 @@ describe("handlePaste batch ordering (#1323)", () => { expect(imageAlts(v)).toEqual(["one.png", "three.png"]); }); }); + + it("does not dispatch or warn when a successful upload completes after view destruction", async () => { + const v = createView(); + const dispatchSpy = vi.spyOn(v, "dispatch"); + paste(v, [new File(["a"], "after-destroy.png", { type: "image/png" })]); + expect(uploads.has("after-destroy.png")).toBe(true); + + v.destroy(); + view = null; + uploads.get("after-destroy.png")!.resolve(okResponse("after-destroy.png")); + await new Promise((resolve) => setTimeout(resolve, 20)); + + // Only the synchronous placeholder insertion may dispatch. A successful + // upload settling after destroy must not try insertion or cleanup. + expect(dispatchSpy).toHaveBeenCalledTimes(1); + expect(console.warn).not.toHaveBeenCalled(); + }); + + it("does not dispatch placeholder cleanup when a failed upload completes after view destruction", async () => { + const v = createView(); + const dispatchSpy = vi.spyOn(v, "dispatch"); + const warnSpy = vi.mocked(console.warn); + paste(v, [new File(["a"], "failed-after-destroy.png", { type: "image/png" })]); + expect(uploads.has("failed-after-destroy.png")).toBe(true); + + v.destroy(); + view = null; + uploads.get("failed-after-destroy.png")!.reject(new Error("upload failed")); + await new Promise((resolve) => setTimeout(resolve, 20)); + + // The upload failure is real and may be logged, but dead-view cleanup + // must be skipped. Vitest also fails the test if the async chain rejects + // unhandled while settling. + expect(dispatchSpy).toHaveBeenCalledTimes(1); + expect(warnSpy).toHaveBeenCalledTimes(1); + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining("Upload failed for failed-after-destroy.png"), + expect.any(Error), + ); + }); }); // ============================================================================ diff --git a/pkgs/id/web/src/image-upload.ts b/pkgs/id/web/src/image-upload.ts index 58ecad68b..a64f7bb34 100644 --- a/pkgs/id/web/src/image-upload.ts +++ b/pkgs/id/web/src/image-upload.ts @@ -114,6 +114,7 @@ export async function uploadImageFile(file: File): Promise { // ============================================================================ const imageUploadKey = new PluginKey("imageUpload"); +const uploadLifetimes = new WeakMap(); interface PlaceholderAction { type: "add" | "remove"; @@ -121,6 +122,10 @@ interface PlaceholderAction { pos?: number; } +interface UploadLifetime { + active: boolean; +} + function createPlaceholderWidget(): HTMLElement { const el = document.createElement("span"); el.className = "image-upload-placeholder"; @@ -143,6 +148,18 @@ export function createImageUploadPlugin(schema: Schema): Plugin | null { return new Plugin({ key: imageUploadKey, + view(view) { + // A plugin instance can be shared by multiple EditorViews, so upload + // lifetime belongs to each individual view rather than the plugin. + const lifetime: UploadLifetime = { active: true }; + uploadLifetimes.set(view, lifetime); + return { + destroy() { + lifetime.active = false; + }, + }; + }, + state: { init(): DecorationSet { return DecorationSet.empty; @@ -185,7 +202,7 @@ export function createImageUploadPlugin(schema: Schema): Plugin | null { event.preventDefault(); - startImageUploadBatch(view, accepted, view.state.selection.from); + startImageUploadBatch(view, accepted, view.state.selection.from, uploadLifetimes.get(view)); return true; }, @@ -204,7 +221,7 @@ export function createImageUploadPlugin(schema: Schema): Plugin | null { const pos = view.posAtCoords(coords); const insertPos = pos ? pos.pos : view.state.selection.from; - startImageUploadBatch(view, accepted, insertPos); + startImageUploadBatch(view, accepted, insertPos, uploadLifetimes.get(view)); return true; }, @@ -221,10 +238,15 @@ export function createImageUploadPlugin(schema: Schema): Plugin | null { * failed upload resolves its step without inserting, so the survivors * keep their relative order. */ -function startImageUploadBatch(view: EditorView, files: File[], insertPos: number): void { +function startImageUploadBatch( + view: EditorView, + files: File[], + insertPos: number, + lifetime: UploadLifetime | undefined, +): void { let insertionGate: Promise = Promise.resolve(); for (const file of files) { - insertionGate = handleImageUpload(view, file, insertPos, insertionGate); + insertionGate = handleImageUpload(view, file, insertPos, insertionGate, lifetime); } } @@ -241,6 +263,7 @@ function handleImageUpload( file: File, insertPos: number, insertionGate: Promise, + lifetime: UploadLifetime | undefined, ): Promise { const id = `upload-${Math.random().toString(36).slice(2, 10)}`; @@ -264,6 +287,11 @@ function handleImageUpload( // Insert strictly after every earlier batch member's step (#1323). await insertionGate; + // The upload may outlive closeEditor() and EditorView.destroy(). In + // that case its placeholder disappeared with the view, so do no more + // editor work. + if (lifetime && !lifetime.active) return; + if (outcome.ok) { try { // Find where to insert (placeholder position may have shifted). @@ -286,9 +314,13 @@ function handleImageUpload( alt: outcome.result.name || fileName, }); insertTr.insert(pos, imageNode); + if (lifetime && !lifetime.active) return; view.dispatch(insertTr); return; } catch (err) { + // A dispatch that races with teardown is not an insertion failure + // worth reporting; the destroyed view no longer owns this upload. + if (lifetime && !lifetime.active) return; // Distinct from an upload failure: the upload succeeded, the // document insert failed. Never surface this as "Upload // failed" and never let it escape as an unhandled rejection @@ -298,8 +330,10 @@ function handleImageUpload( } // Upload failed or insertion failed: remove only the placeholder. + if (lifetime && !lifetime.active) return; const removeTr = view.state.tr; removeTr.setMeta(imageUploadKey, { type: "remove", id } satisfies PlaceholderAction); + if (lifetime && !lifetime.active) return; view.dispatch(removeTr); })(); }