AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(editor): unwrap a gallery left with one image after a move or deletion
Dariusz Koryto0c2e3ed02687
diff --git a/apps/web/src/components/editor/image-drag.test.mjs b/apps/web/src/components/editor/image-drag.test.mjsindex d2275669..c882881f 100644--- a/apps/web/src/components/editor/image-drag.test.mjs+++ b/apps/web/src/components/editor/image-drag.test.mjs@@ -4,7 +4,7 @@ import StarterKit from "@tiptap/starter-kit";import Image from "@tiptap/extension-image";import { EditorState } from "@tiptap/pm/state";import { history, undo, redo } from "@tiptap/pm/history";-import { ImageGallery } from "@edgeever/shared";+import { ImageGallery, createImageGalleryCleanupPlugin } from "@edgeever/shared";import { createImageDragPlugin, imageDragKey, moveImage } from "./image-drag";const schema = getSchema([StarterKit, Image.extend({ addAttributes() {@@ -52,6 +52,22 @@ describe("existing image dragging (#708)", () => {expect(next.doc.childCount).toBe(1);expect(sources(next.doc)).toEqual(["B", "A", "C"]);});+ test("moving one image out of a two-image gallery leaves the other standalone (#728)", () => {+ // The editor runs the gallery cleanup plugin alongside dragging.+ const before = EditorState.create({+ doc: schema.nodes.doc.create(null, [gallery("A", "B"), paragraph("text")]),+ plugins: [history(), createImageDragPlugin(), createImageGalleryCleanupPlugin()],+ });+ let next = move(before, 2, before.doc.content.size);+ const moved = next.doc.toJSON();+ expect(moved).toEqual(schema.nodes.doc.create(null, [image("A"), paragraph("text"), image("B")]).toJSON());+ expect(next.doc.firstChild).toBe(before.doc.firstChild.firstChild);+ expect(next.selection.node.attrs.src).toBe("B");+ expect(undo(next, (tr) => { next = next.applyTransaction(tr).state; })).toBe(true);+ expect(next.doc.toJSON()).toEqual(before.doc.toJSON());+ expect(redo(next, (tr) => { next = next.applyTransaction(tr).state; })).toBe(true);+ expect(next.doc.toJSON()).toEqual(moved);+ });test("one undo restores the original document; redo repeats the move", () => {const before = state(gallery("A"), paragraph("text"), gallery("B", "C"));let next = move(before, 1, 11);diff --git a/packages/shared/src/image-gallery-deletion.test.mjs b/packages/shared/src/image-gallery-deletion.test.mjsindex 8a8ce207..a513a44a 100644--- a/packages/shared/src/image-gallery-deletion.test.mjs+++ b/packages/shared/src/image-gallery-deletion.test.mjs@@ -4,7 +4,7 @@ import StarterKit from "@tiptap/starter-kit";import Image from "@tiptap/extension-image";import { EditorState, NodeSelection, TextSelection } from "@tiptap/pm/state";import { closeHistory, history, undo, redo } from "@tiptap/pm/history";-import { ImageGallery, createImageGalleryCleanupPlugin, TRANSIENT_IMAGE_UPLOAD_PREFIX } from "./image-gallery";+import { ImageGallery, createImageGalleryCleanupPlugin, normalizeImageGalleries, TRANSIENT_IMAGE_UPLOAD_PREFIX } from "./image-gallery";import { docToMarkdown, markdownToDoc } from "./content";const schema = getSchema([StarterKit, Image, ImageGallery]);@@ -29,9 +29,10 @@ describe("live gallery deletion (#707)", () => {test("deleting both images leaves editable empty content and empty Markdown", () => {const e = editor([gallery("/one.jpg", "/two.jpg")]);deleteImage(e, 1);- expect(e.state.doc.firstChild.firstChild.attrs.src).toBe("/two.jpg");- expect(e.state.doc.firstChild.attrs).toMatchObject({ layout: "3", fit: "height" });- deleteImage(e, 1);+ // The remaining image becomes standalone (#728).+ expect(e.state.doc.firstChild.type.name).toBe("image");+ expect(e.state.doc.firstChild.attrs.src).toBe("/two.jpg");+ deleteImage(e, 0);expect(e.state.doc.toJSON()).toEqual({ type: "doc", content: [{ type: "paragraph" }] });expect(e.state.selection).toBeInstanceOf(TextSelection);expect(docToMarkdown(e.state.doc.toJSON())).toBe("");@@ -41,15 +42,15 @@ describe("live gallery deletion (#707)", () => {});test("last-image deletion and cleanup undo and redo as one edit", () => {- const e = editor([gallery("/one.jpg", "/two.jpg")]);- deleteImage(e, 1);- e.dispatch(closeHistory(e.state.tr));+ const e = editor([paragraph("before"), gallery("/one.jpg", "/two.jpg")]);const before = e.state.doc.toJSON();- deleteImage(e, 1);+ const start = e.state.doc.firstChild.nodeSize + 1;+ e.dispatch(e.state.tr.delete(start, start + 2));+ expect(e.state.doc.childCount).toBe(1);expect(undo(e.state, e.dispatch)).toBe(true);expect(e.state.doc.toJSON()).toEqual(before);expect(redo(e.state, e.dispatch)).toBe(true);- expect(docToMarkdown(e.state.doc.toJSON())).toBe("");+ expect(docToMarkdown(e.state.doc.toJSON())).toBe("before");});test("keyboard node-selection deletion preserves neighboring prose", () => {@@ -90,6 +91,62 @@ describe("live gallery deletion (#707)", () => {expect(e.state.doc.firstChild.firstChild.attrs.src).toBe(pending);});+ test("a gallery left with one image unwraps it with its attributes (#728)", () => {+ const e = editor([paragraph("before"), gallery("/one.jpg", "/two.jpg"), paragraph("after")]);+ const remaining = e.state.doc.child(1).lastChild;+ deleteImage(e, e.state.doc.firstChild.nodeSize + 1);+ expect(e.state.doc.childCount).toBe(3);+ expect(e.state.doc.child(1)).toBe(remaining);+ expect(e.state.doc.toJSON()).toEqual(normalizeImageGalleries(e.state.doc.toJSON()));+ });++ test("deletion and unwrapping undo and redo as one edit (#728)", () => {+ const e = editor([gallery("/one.jpg", "/two.jpg")]);+ e.dispatch(closeHistory(e.state.tr));+ const before = e.state.doc.toJSON();+ deleteImage(e, 2);+ const after = e.state.doc.toJSON();+ expect(after).toEqual({ type: "doc", content: [image("/one.jpg").toJSON()] });+ expect(undo(e.state, e.dispatch)).toBe(true);+ expect(e.state.doc.toJSON()).toEqual(before);+ expect(redo(e.state, e.dispatch)).toBe(true);+ expect(e.state.doc.toJSON()).toEqual(after);+ });++ test("keeps a selection on the remaining image when it is unwrapped (#728)", () => {+ const e = editor([gallery("/one.jpg", "/two.jpg")]);+ e.dispatch(e.state.tr.setSelection(NodeSelection.create(e.state.doc, 1)));+ deleteImage(e, 2);+ expect(e.state.selection).toBeInstanceOf(NodeSelection);+ expect(e.state.selection.node.attrs.src).toBe("/one.jpg");+ });++ test("unwraps a nested gallery inside its container (#728)", () => {+ const e = editor([schema.nodes.blockquote.create(null, gallery("/one.jpg", "/two.jpg"))]);+ deleteImage(e, 2);+ expect(e.state.doc.firstChild.type.name).toBe("blockquote");+ expect(e.state.doc.firstChild.firstChild.type.name).toBe("image");+ expect(e.state.doc.firstChild.firstChild.attrs.src).toBe("/two.jpg");+ });++ test("a pending upload left alone stays in its gallery until it finishes", () => {+ const pending = `${TRANSIENT_IMAGE_UPLOAD_PREFIX}pending`;+ const e = editor([gallery("/one.jpg", pending)]);+ deleteImage(e, 1);+ expect(e.state.doc.firstChild.type.name).toBe("edgeeverImageGallery");+ e.dispatch(e.state.tr.setNodeMarkup(1, undefined, { ...e.state.doc.firstChild.firstChild.attrs, src: "/uploaded.jpg" }));+ expect(e.state.doc.firstChild.type.name).toBe("image");+ expect(e.state.doc.firstChild.attrs.src).toBe("/uploaded.jpg");+ });++ test("galleries with two or more images are left unchanged", () => {+ const e = editor([gallery("/one.jpg", "/two.jpg", "/three.jpg")]);+ deleteImage(e, 1);+ expect(e.state.doc.firstChild.type.name).toBe("edgeeverImageGallery");+ expect(e.state.doc.firstChild.childCount).toBe(2);+ expect(e.state.doc.firstChild.attrs).toMatchObject({ layout: "3", fit: "height" });+ });+test("standalone image deletion keeps its normal behavior", () => {const e = editor([image("/one.jpg")]);deleteImage(e, 0);diff --git a/packages/shared/src/image-gallery.ts b/packages/shared/src/image-gallery.tsindex 666ac97c..c0ce79fe 100644--- a/packages/shared/src/image-gallery.ts+++ b/packages/shared/src/image-gallery.ts@@ -1,5 +1,7 @@import { mergeAttributes, Node } from "@tiptap/core";import { Plugin, PluginKey } from "@tiptap/pm/state";+import { Slice } from "@tiptap/pm/model";+import { ReplaceAroundStep } from "@tiptap/pm/transform";import { openBlockSource } from "./markdown-block-start";import type { TiptapDoc, TiptapNode, TiptapTextNode } from "./content";import { parseImageAlignment } from "./image-alignment";@@ -159,30 +161,47 @@ const hasUsableImageSource = (node: TiptapNode | TiptapTextNode) =>typeof node.attrs?.src === "string" &&node.attrs.src.trim().length > 0;-/** Keep node-view, keyboard and range deletions in the same undoable edit. */+/**+ * Repair galleries emptied or left with one image by a move or deletion, in+ * the same undoable edit as the node-view, keyboard or range change.+ */export const createImageGalleryCleanupPlugin = () => new Plugin({key: new PluginKey("edgeever-image-gallery-cleanup"),appendTransaction(transactions, _oldState, state) {if (!transactions.some((transaction) => transaction.docChanged)) return null;- const emptyGalleries: Array<{ from: number; to: number }> = [];+ const repairs: Array<{ from: number; to: number; unwrap: boolean }> = [];state.doc.descendants((node, position) => {if (node.type.name !== IMAGE_GALLERY_NODE_TYPE) return;// image+ makes ProseMirror insert an image with src=null when its last// child is deleted. Remove that shell from the live document as well as// saved snapshots. Pending uploads have a nonempty src and stay intact.- if (!node.content.content.some((image) =>+ const images = node.content.content.filter((image) =>typeof image.attrs.src === "string" && image.attrs.src.trim().length > 0- )) {- emptyGalleries.push({ from: position, to: position + node.nodeSize });+ );+ if (!images.length) {+ repairs.push({ from: position, to: position + node.nodeSize, unwrap: false });+ } else if (node.childCount === 1 && !isTransientImageUploadSource(images[0]!.attrs.src)) {+ // A gallery left with one image after a move or deletion would crop it+ // to the gallery cell. Unwrap it as normalizeImageGalleries() does for+ // snapshots, so the editor shows the standalone image that is saved.+ repairs.push({ from: position, to: position + node.nodeSize, unwrap: true });}return false;});- if (!emptyGalleries.length) return null;+ if (!repairs.length) return null;const transaction = state.tr;- for (const { from, to } of emptyGalleries.reverse()) transaction.delete(from, to);- return transaction;+ for (const { from, to, unwrap } of repairs.reverse()) {+ if (!unwrap) {+ transaction.delete(from, to);+ continue;+ }+ // Remove only the wrapper, as lift() would if the gallery were not+ // isolating, so the image and a selection on it keep their identity.+ transaction.maybeStep(new ReplaceAroundStep(from, to, from + 1, to - 1, Slice.empty, 0, true));+ }+ return transaction.docChanged ? transaction : null;},});diff --git a/tests/e2e/image-gallery-deletion.spec.ts b/tests/e2e/image-gallery-deletion.spec.tsindex a4403664..35dd2fae 100644--- a/tests/e2e/image-gallery-deletion.spec.ts+++ b/tests/e2e/image-gallery-deletion.spec.ts@@ -1,7 +1,7 @@import { expect, test } from "@playwright/test";import { fileURLToPath } from "node:url";-test("deleting the last gallery image removes its node view and Markdown (#707)", async ({ page }) => {+test("deleting gallery images unwraps the last one and then removes it (#707, #728)", async ({ page }) => {const fixturePath = fileURLToPath(new URL("./fixtures/image-gallery-deletion.html", import.meta.url));await page.goto(`/@fs${fixturePath}`);const images = page.getByRole("button", { name: "Delete image", exact: true });@@ -9,18 +9,28 @@ test("deleting the last gallery image removes its node view and Markdown (#707)"await expect(images).toHaveCount(2);await images.first().click();await expect(images).toHaveCount(1);+ // The remaining image is unwrapped instead of staying in a one-image gallery (#728).+ await expect(gallery).toHaveCount(0);+ await expect(page.locator("#markdown")).toHaveText("");// Separate deliberate deletion actions into individual history events.await page.waitForTimeout(550);await images.click();- await expect(gallery).toHaveCount(0);+ await expect(images).toHaveCount(0);await expect(page.locator("#markdown")).toHaveText("");await expect(page.locator("#document")).toHaveText('{"type":"doc","content":[{"type":"paragraph"}]}');await page.getByRole("button", { name: "Undo", exact: true }).click();await expect(images).toHaveCount(1);+ await expect(gallery).toHaveCount(0);+ await expect(page.locator("#markdown")).toHaveText("");+ // One more undo restores the gallery together with the deleted image.+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ await expect(images).toHaveCount(2);await expect(gallery).toHaveAttribute("data-image-gallery-layout", "2");- await expect(page.locator("#markdown")).toContainText("");await page.getByRole("button", { name: "Redo", exact: true }).click();+ await expect(images).toHaveCount(1);await expect(gallery).toHaveCount(0);+ await page.getByRole("button", { name: "Redo", exact: true }).click();+ await expect(images).toHaveCount(0);await expect(page.locator("#markdown")).toHaveText("");await page.locator(".tiptap").fill("still editable");await expect(page.locator("#markdown")).toHaveText("still editable");