Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions pkgs/id/web/src/image-upload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
);
});
});

// ============================================================================
Expand Down
42 changes: 38 additions & 4 deletions pkgs/id/web/src/image-upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,18 @@ export async function uploadImageFile(file: File): Promise<UploadResponse> {
// ============================================================================

const imageUploadKey = new PluginKey<DecorationSet>("imageUpload");
const uploadLifetimes = new WeakMap<EditorView, UploadLifetime>();

interface PlaceholderAction {
type: "add" | "remove";
id: string;
pos?: number;
}

interface UploadLifetime {
active: boolean;
}

function createPlaceholderWidget(): HTMLElement {
const el = document.createElement("span");
el.className = "image-upload-placeholder";
Expand All @@ -143,6 +148,18 @@ export function createImageUploadPlugin(schema: Schema): Plugin | null {
return new Plugin<DecorationSet>({
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;
Expand Down Expand Up @@ -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;
},
Expand All @@ -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;
},
Expand All @@ -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<void> = Promise.resolve();
for (const file of files) {
insertionGate = handleImageUpload(view, file, insertPos, insertionGate);
insertionGate = handleImageUpload(view, file, insertPos, insertionGate, lifetime);
}
}

Expand All @@ -241,6 +263,7 @@ function handleImageUpload(
file: File,
insertPos: number,
insertionGate: Promise<void>,
lifetime: UploadLifetime | undefined,
): Promise<void> {
const id = `upload-${Math.random().toString(36).slice(2, 10)}`;

Expand All @@ -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).
Expand All @@ -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
Expand All @@ -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);
})();
}
Loading