Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Move caret after inserted image uploads (#3796)
Naiyuan Qing0dbe9f0a8f46
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsxindex f0e348d402..8114a62b36 100644--- a/packages/views/editor/attachment.tsx+++ b/packages/views/editor/attachment.tsx@@ -60,6 +60,13 @@ export type AttachmentInput =contentType?: string;/** Editor in-flight state. Renders a loader placeholder. */uploading?: boolean;+ /**+ * Intrinsic pixel dimensions. Rendered as `<img width height>` so the+ * browser reserves the box before the image decodes — prevents the+ * layout shift that would otherwise push the caret out of view on paste.+ */+ width?: number;+ height?: number;/*** Structural hint from the call site: "this slot is definitionally an* image / file / ...". Bypasses `getPreviewKind` autodetect, which@@ -90,6 +97,8 @@ interface Normalized {attachmentId?: string;record?: AttachmentRecord;uploading: boolean;+ width?: number;+ height?: number;}function normalize(@@ -114,6 +123,8 @@ function normalize(attachmentId: record?.id,record,uploading: !!input.uploading,+ width: input.width,+ height: input.height,};}@@ -170,6 +181,8 @@ export function Attachment({src={state.url}alt={state.filename}uploading={state.uploading}+ width={state.width}+ height={state.height}editable={editable}selected={selected}onView={openPreview}@@ -228,6 +241,8 @@ interface ImageAttachmentViewProps {src: string;alt: string;uploading: boolean;+ width?: number;+ height?: number;editable?: boolean;selected?: boolean;onView: () => void;@@ -240,6 +255,8 @@ function ImageAttachmentView({src,alt,uploading,+ width,+ height,editable,selected,onView,@@ -284,6 +301,8 @@ function ImageAttachmentView({<imgsrc={src || undefined}alt={alt}+ width={width}+ height={height}className={cn("image-content", uploading && "image-uploading")}draggable={false}/>diff --git a/packages/views/editor/extensions/file-upload.test.ts b/packages/views/editor/extensions/file-upload.test.tsnew file mode 100644index 0000000000..b27998ea8c--- /dev/null+++ b/packages/views/editor/extensions/file-upload.test.ts@@ -0,0 +1,189 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Editor } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import { Markdown } from "@tiptap/markdown";+import type { UploadResult } from "@multica/core/hooks/use-file-upload";+import { ImageExtension } from "./index";+import { uploadAndInsertFile } from "./file-upload";++const BLOB_URL = "blob:test-image";+const FINAL_URL = "https://cdn.example.com/photo.png";++let editors: Editor[] = [];+let originalCreateObjectURL: typeof URL.createObjectURL | undefined;+let originalRevokeObjectURL: typeof URL.revokeObjectURL | undefined;++function makeEditor() {+ const element = document.createElement("div");+ document.body.appendChild(element);+ const editor = new Editor({+ element,+ extensions: [+ StarterKit,+ ImageExtension,+ Markdown.configure({ indentation: { style: "space", size: 3 } }),+ ],+ });+ editors.push(editor);+ return editor;+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++function makeUpload(+ overrides: Partial<UploadResult> & {+ id: string;+ link: string;+ filename: string;+ },+): UploadResult {+ return {+ workspace_id: "ws-1",+ issue_id: null,+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "user-1",+ url: overrides.link,+ download_url: overrides.link,+ content_type: "image/png",+ size_bytes: 1,+ created_at: new Date(0).toISOString(),+ ...overrides,+ };+}++beforeEach(() => {+ originalCreateObjectURL = URL.createObjectURL;+ originalRevokeObjectURL = URL.revokeObjectURL;+ Object.defineProperty(URL, "createObjectURL", {+ configurable: true,+ value: vi.fn(() => BLOB_URL),+ });+ Object.defineProperty(URL, "revokeObjectURL", {+ configurable: true,+ value: vi.fn(),+ });+});++afterEach(() => {+ for (const editor of editors) editor.destroy();+ editors = [];+ document.body.innerHTML = "";++ if (originalCreateObjectURL) {+ Object.defineProperty(URL, "createObjectURL", {+ configurable: true,+ value: originalCreateObjectURL,+ });+ } else {+ delete (URL as Partial<typeof URL>).createObjectURL;+ }++ if (originalRevokeObjectURL) {+ Object.defineProperty(URL, "revokeObjectURL", {+ configurable: true,+ value: originalRevokeObjectURL,+ });+ } else {+ delete (URL as Partial<typeof URL>).revokeObjectURL;+ }+});++function firstImageAttrs(editor: Editor): Record<string, unknown> | null {+ let attrs: Record<string, unknown> | null = null;+ editor.state.doc.descendants((node) => {+ if (attrs) return false;+ if (node.type.name === "image") {+ attrs = node.attrs;+ return false;+ }+ return undefined;+ });+ return attrs;+}++describe("uploadAndInsertFile", () => {+ it("lets typing continue in the trailing paragraph after pasted image upload preview", async () => {+ const editor = makeEditor();+ const upload = deferred<UploadResult | null>();+ const handler = vi.fn(() => upload.promise);+ const file = new File(["image"], "photo.png", { type: "image/png" });++ const uploadTask = uploadAndInsertFile(editor, file, handler);++ expect(handler).toHaveBeenCalledWith(file);+ expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");++ editor.commands.insertContent("after");+ expect(editor.getMarkdown().trimEnd()).toBe(+ [``, "", "after"].join("\n"),+ );++ upload.resolve(+ makeUpload({ id: "attachment-1", link: FINAL_URL, filename: "photo.png" }),+ );+ await uploadTask;++ const saved = editor.getMarkdown().trimEnd();+ expect(saved).toBe([``, "", "after"].join("\n"));++ const reparsed = makeEditor();+ reparsed.commands.setContent(saved, { contentType: "markdown" });+ expect(reparsed.getMarkdown().trimEnd()).toBe(saved);+ });++ it("reserves the image box by capturing intrinsic dimensions, kept through the URL swap", async () => {+ const close = vi.fn();+ const createImageBitmap = vi.fn(async () => ({+ width: 800,+ height: 600,+ close,+ }));+ vi.stubGlobal("createImageBitmap", createImageBitmap);++ try {+ const editor = makeEditor();+ const upload = deferred<UploadResult | null>();+ const handler = vi.fn(() => upload.promise);+ const file = new File(["image"], "photo.png", { type: "image/png" });++ const uploadTask = uploadAndInsertFile(editor, file, handler);++ // Dimensions are measured off-thread and patched onto the node before the+ // upload resolves, so the blob preview already reserves its box.+ await vi.waitFor(() => {+ const attrs = firstImageAttrs(editor);+ expect(attrs?.width).toBe(800);+ expect(attrs?.height).toBe(600);+ });+ expect(createImageBitmap).toHaveBeenCalledWith(file);+ expect(close).toHaveBeenCalled();++ upload.resolve(+ makeUpload({ id: "attachment-1", link: FINAL_URL, filename: "photo.png" }),+ );+ await uploadTask;++ // The src swap preserves width/height (spread of existing attrs).+ const finalAttrs = firstImageAttrs(editor);+ expect(finalAttrs?.src).toBe(FINAL_URL);+ expect(finalAttrs?.width).toBe(800);+ expect(finalAttrs?.height).toBe(600);++ // width/height are render-only — they never reach the markdown.+ expect(editor.getMarkdown().trimEnd()).toBe(``);+ } finally {+ vi.unstubAllGlobals();+ }+ });+});diff --git a/packages/views/editor/extensions/file-upload.ts b/packages/views/editor/extensions/file-upload.tsindex f46c8ab0f2..f6cc25174c 100644--- a/packages/views/editor/extensions/file-upload.ts+++ b/packages/views/editor/extensions/file-upload.ts@@ -1,5 +1,5 @@import { Extension } from "@tiptap/core";-import { Plugin, PluginKey } from "@tiptap/pm/state";+import { Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";import type { UploadResult } from "@multica/core/hooks/use-file-upload";import { createSafeId } from "@multica/core/utils";@@ -41,21 +41,91 @@ function finalizeFileCard(editor: any, uploadId: string, href: string) {if (updated) editor.view.dispatch(tr);}--function removeImageBySrc(editor: any, src: string) {- if (!editor) return;- const { tr } = editor.state;- let deleted = false;+export function findImagePosBySrc(editor: any, src: string): number | null {+ if (!editor) return null;+ let imagePos: number | null = null;editor.state.doc.descendants((node: any, pos: number) => {- if (deleted) return false;+ if (imagePos !== null) return false;if (node.type.name === "image" && node.attrs.src === src) {- tr.delete(pos, pos + node.nodeSize);- deleted = true;+ imagePos = pos;return false;}return undefined;});- if (deleted) editor.view.dispatch(tr);+ return imagePos;+}++function removeImageBySrc(editor: any, src: string) {+ const imagePos = findImagePosBySrc(editor, src);+ if (imagePos === null) return;++ const imageNode = editor.state.doc.nodeAt(imagePos);+ if (!imageNode) return;++ const tr = editor.state.tr.delete(imagePos, imagePos + imageNode.nodeSize);+ editor.view.dispatch(tr);+}++/**+ * Read an image's intrinsic pixel dimensions off-thread. Returns null when the+ * decode fails or the API is unavailable (e.g. jsdom in tests, where+ * `createImageBitmap` is undefined) — callers degrade to no reserved box.+ */+async function readImageDimensions(+ file: File,+): Promise<{ width: number; height: number } | null> {+ if (typeof createImageBitmap !== "function") return null;+ try {+ const bitmap = await createImageBitmap(file);+ const dims = { width: bitmap.width, height: bitmap.height };+ bitmap.close();+ return dims.width > 0 && dims.height > 0 ? dims : null;+ } catch {+ return null;+ }+}++/**+ * Measure the file's intrinsic size and write it onto the freshly-inserted+ * image node so the browser reserves the box before decode (no layout shift).+ * Fire-and-forget after insert: keyed on the blob `src`, so if the upload swap+ * already replaced it we simply skip — the swap preserves any width/height we+ * managed to set via `...imageNode.attrs`.+ */+async function applyImageDimensions(editor: any, file: File, src: string) {+ const dims = await readImageDimensions(file);+ if (!dims) return;++ const imagePos = findImagePosBySrc(editor, src);+ if (imagePos === null) return;++ const imageNode = editor.state.doc.nodeAt(imagePos);+ if (!imageNode || imageNode.attrs.width) return;++ const tr = editor.state.tr.setNodeMarkup(imagePos, undefined, {+ ...imageNode.attrs,+ width: dims.width,+ height: dims.height,+ });+ editor.view.dispatch(tr);+}++function moveSelectionToParagraphAfterImage(editor: any, src: string) {+ const imagePos = findImagePosBySrc(editor, src);+ if (imagePos === null) return;++ const imageNode = editor.state.doc.nodeAt(imagePos);+ if (!imageNode) return;++ const afterImagePos = imagePos + imageNode.nodeSize;+ const $afterImage = editor.state.doc.resolve(afterImagePos);+ if ($afterImage.nodeAfter?.type.name !== "paragraph") return;++ const paragraphStart = afterImagePos + 1;+ const tr = editor.state.tr+ .setSelection(TextSelection.create(editor.state.doc, paragraphStart))+ .scrollIntoView();+ editor.view.dispatch(tr);}/**@@ -78,28 +148,28 @@ export async function uploadAndInsertFile(editor.chain().focus().insertContentAt(pos, { type: "image", attrs: imgAttrs }).run();} else {editor.chain().focus().setImage(imgAttrs).run();+ moveSelectionToParagraphAfterImage(editor, blobUrl);}+ // Reserve the image box ASAP so the async decode doesn't shift layout.+ // Fire-and-forget: must not delay the handler() call below, which the+ // synchronous-insert contract (instant preview) depends on.+ void applyImageDimensions(editor, file, blobUrl);+try {const result = await handler(file);if (result) {- const { tr } = editor.state;- let found = false;- editor.state.doc.descendants((node: { type: { name: string }; attrs: { src: string } }, nodePos: number) => {- if (found) return false;- if (node.type.name === "image" && node.attrs.src === blobUrl) {- tr.setNodeMarkup(nodePos, undefined, {- ...node.attrs,- src: result.link,- alt: result.filename,- uploading: false,- });- found = true;- return false;- }- return undefined;- });- if (found) editor.view.dispatch(tr);+ const imagePos = findImagePosBySrc(editor, blobUrl);+ const imageNode = imagePos === null ? null : editor.state.doc.nodeAt(imagePos);+ if (imagePos !== null && imageNode) {+ const tr = editor.state.tr.setNodeMarkup(imagePos, undefined, {+ ...imageNode.attrs,+ src: result.link,+ alt: result.filename,+ uploading: false,+ });+ editor.view.dispatch(tr);+ }} else {removeImageBySrc(editor, blobUrl);}diff --git a/packages/views/editor/extensions/image-view.tsx b/packages/views/editor/extensions/image-view.tsxindex 0df143e072..39977b077b 100644--- a/packages/views/editor/extensions/image-view.tsx+++ b/packages/views/editor/extensions/image-view.tsx@@ -16,6 +16,8 @@ function ImageView({ node, editor, selected, deleteNode }: NodeViewProps) {const src = (node.attrs.src as string) || "";const alt = (node.attrs.alt as string) || "";const uploading = node.attrs.uploading as boolean;+ const width = (node.attrs.width as number | null) ?? undefined;+ const height = (node.attrs.height as number | null) ?? undefined;// <Attachment> emits its own .image-node wrapper, so the NodeViewWrapper// stays unclassed — no double image-node.@@ -27,6 +29,9 @@ function ImageView({ node, editor, selected, deleteNode }: NodeViewProps) {url: src,filename: alt,uploading,+ // Intrinsic dimensions reserve the <img> box pre-decode (no shift).+ width,+ height,// Tiptap image node is structurally an image regardless of alt.forceKind: "image",}}diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.tsindex 82a5a9ea89..4506856286 100644--- a/packages/views/editor/extensions/index.ts+++ b/packages/views/editor/extensions/index.ts@@ -72,6 +72,30 @@ export const ImageExtension = Image.extend({attrs.uploading ? { "data-uploading": "" } : {},parseHTML: (el: HTMLElement) => el.hasAttribute("data-uploading"),},+ // Intrinsic pixel dimensions, captured on upload (file-upload.ts). The+ // browser uses width/height on <img> to compute aspect-ratio and reserve+ // the box before the image decodes, so inserting an image causes no+ // layout shift (and the post-insert scrollIntoView stays correct). Not+ // serialized to markdown — `renderMarkdown` only emits src/alt/title — so+ // round-trips stay clean.+ width: {+ default: null,+ renderHTML: (attrs: Record<string, unknown>) =>+ attrs.width ? { width: attrs.width as number } : {},+ parseHTML: (el: HTMLElement) => {+ const w = parseInt(el.getAttribute("width") || "", 10);+ return Number.isFinite(w) ? w : null;+ },+ },+ height: {+ default: null,+ renderHTML: (attrs: Record<string, unknown>) =>+ attrs.height ? { height: attrs.height as number } : {},+ parseHTML: (el: HTMLElement) => {+ const h = parseInt(el.getAttribute("height") || "", 10);+ return Number.isFinite(h) ? h : null;+ },+ },};},addNodeView() {