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): remove empty galleries after image deletion (#707)
tianma-if3b458077537d
diff --git a/packages/shared/src/image-gallery-deletion.test.mjs b/packages/shared/src/image-gallery-deletion.test.mjsnew file mode 100644index 00000000..8a8ce207--- /dev/null+++ b/packages/shared/src/image-gallery-deletion.test.mjs@@ -0,0 +1,98 @@+import { describe, expect, test } from "bun:test";+import { getSchema } from "@tiptap/core";+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 { docToMarkdown, markdownToDoc } from "./content";++const schema = getSchema([StarterKit, Image, ImageGallery]);+const image = (src) => schema.nodes.image.create({ src });+const paragraph = (text) => schema.nodes.paragraph.create(null, text ? schema.text(text) : null);+const gallery = (...sources) => schema.nodes.edgeeverImageGallery.create({ layout: "3", fit: "height" }, sources.map(image));+const editor = (nodes) => {+ let state = EditorState.create({ schema, doc: schema.nodes.doc.create(null, nodes), plugins: [history(), createImageGalleryCleanupPlugin()] });+ return {+ get state() { return state; },+ dispatch(transaction) {+ state = state.applyTransaction(transaction).state;+ state.doc.check();+ },+ };+};++// NodeView.deleteNode() uses deleteRange(), which dispatches tr.delete(from,to).+const deleteImage = (editor, position) => editor.dispatch(editor.state.tr.delete(position, position + 1));++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);+ expect(e.state.doc.toJSON()).toEqual({ type: "doc", content: [{ type: "paragraph" }] });+ expect(e.state.selection).toBeInstanceOf(TextSelection);+ expect(docToMarkdown(e.state.doc.toJSON())).toBe("");+ expect(markdownToDoc(docToMarkdown(e.state.doc.toJSON()))).toEqual(e.state.doc.toJSON());+ e.dispatch(e.state.tr.insertText("still editable"));+ expect(e.state.doc.textContent).toBe("still editable");+ });++ 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 before = e.state.doc.toJSON();+ deleteImage(e, 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("");+ });++ test("keyboard node-selection deletion preserves neighboring prose", () => {+ const e = editor([paragraph("before"), gallery("/one.jpg"), paragraph("after")]);+ const position = e.state.doc.firstChild.nodeSize + 1;+ e.dispatch(e.state.tr.setSelection(NodeSelection.create(e.state.doc, position)));+ e.dispatch(e.state.tr.deleteSelection());+ expect(e.state.doc.toJSON()).toEqual(schema.nodes.doc.create(null, [paragraph("before"), paragraph("after")]).toJSON());+ });++ test("range deletion of all gallery children removes the shell", () => {+ const e = editor([gallery("/one.jpg", "/two.jpg")]);+ e.dispatch(e.state.tr.delete(1, 3));+ expect(e.state.doc.firstChild.type.name).toBe("paragraph");+ expect(docToMarkdown(e.state.doc.toJSON())).toBe("");+ });++ test("nested gallery deletion leaves its container editable", () => {+ const e = editor([schema.nodes.blockquote.create(null, gallery("/one.jpg")), paragraph("outside")]);+ deleteImage(e, 2);+ expect(e.state.doc.firstChild.type.name).toBe("blockquote");+ expect(e.state.doc.firstChild.firstChild.type.name).toBe("paragraph");+ expect(e.state.doc.lastChild.textContent).toBe("outside");+ });++ test("multiple emptied galleries are removed without shifting other deletions", () => {+ const e = editor([gallery("/one.jpg"), paragraph("keep"), gallery("/two.jpg")]);+ const secondPosition = e.state.doc.child(0).nodeSize + e.state.doc.child(1).nodeSize + 1;+ e.dispatch(e.state.tr.delete(secondPosition, secondPosition + 1).delete(1, 2));+ expect(e.state.doc.toJSON()).toEqual(schema.nodes.doc.create(null, paragraph("keep")).toJSON());+ });++ test("pending upload sources survive removal of another image", () => {+ 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");+ expect(e.state.doc.firstChild.firstChild.attrs.src).toBe(pending);+ });++ test("standalone image deletion keeps its normal behavior", () => {+ const e = editor([image("/one.jpg")]);+ deleteImage(e, 0);+ expect(e.state.doc.toJSON()).toEqual({ type: "doc", content: [{ type: "paragraph" }] });+ });+});diff --git a/packages/shared/src/image-gallery.ts b/packages/shared/src/image-gallery.tsindex 8af7b6fd..666ac97c 100644--- a/packages/shared/src/image-gallery.ts+++ b/packages/shared/src/image-gallery.ts@@ -1,4 +1,5 @@import { mergeAttributes, Node } from "@tiptap/core";+import { Plugin, PluginKey } from "@tiptap/pm/state";import { openBlockSource } from "./markdown-block-start";import type { TiptapDoc, TiptapNode, TiptapTextNode } from "./content";import { parseImageAlignment } from "./image-alignment";@@ -33,6 +34,10 @@ export const ImageGallery = Node.create({defining: true,isolating: true,+ addProseMirrorPlugins() {+ return [createImageGalleryCleanupPlugin()];+ },+addAttributes() {return {fit: {@@ -154,6 +159,33 @@ 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. */+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 }> = [];+ 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) =>+ typeof image.attrs.src === "string" && image.attrs.src.trim().length > 0+ )) {+ emptyGalleries.push({ from: position, to: position + node.nodeSize });+ }+ return false;+ });+ if (!emptyGalleries.length) return null;++ const transaction = state.tr;+ for (const { from, to } of emptyGalleries.reverse()) transaction.delete(from, to);+ return transaction;+ },+});+type NormalizedNodes = {changed: boolean;nodes: Array<TiptapNode | TiptapTextNode>;diff --git a/tests/e2e/fixtures/image-gallery-deletion.html b/tests/e2e/fixtures/image-gallery-deletion.htmlnew file mode 100644index 00000000..d5dbc881--- /dev/null+++ b/tests/e2e/fixtures/image-gallery-deletion.html@@ -0,0 +1,17 @@+<!doctype html>+<meta charset="utf-8">+<title>Image gallery deletion regression #707</title>+<h1>Image gallery deletion regression #707</h1>+<div id="editor"></div>+<button id="undo">Undo</button>+<button id="redo">Redo</button>+<pre id="document"></pre>+<pre id="markdown"></pre>+<script type="module">+ import RefreshRuntime from "/@react-refresh";+ RefreshRuntime.injectIntoGlobalHook(window);+ window.$RefreshReg$ = () => {};+ window.$RefreshSig$ = () => (type) => type;+ window.__vite_plugin_react_preamble_installed__ = true;+</script>+<script type="module" src="./image-gallery-deletion.js"></script>diff --git a/tests/e2e/fixtures/image-gallery-deletion.js b/tests/e2e/fixtures/image-gallery-deletion.jsnew file mode 100644index 00000000..e2cd84f2--- /dev/null+++ b/tests/e2e/fixtures/image-gallery-deletion.js@@ -0,0 +1,43 @@+import React from "react";+import { createRoot } from "react-dom/client";+import { EditorContent, useEditor, NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";+import StarterKit from "@tiptap/starter-kit";+import Image from "@tiptap/extension-image";+import { docToMarkdown } from "@edgeever/shared";+import { EditableImageGallery } from "/src/components/editor/ImageGallery.tsx";+import "/src/i18n/index.ts";++// Exercise Tiptap's actual node-view deleteNode callback used by the resource+// menu without deleting external resources or depending on a logged-in API.+const DeletableImage = Image.extend({+ addNodeView() {+ return ReactNodeViewRenderer(({ node, deleteNode }) => React.createElement(+ NodeViewWrapper, null,+ React.createElement("span", null, node.attrs.src),+ React.createElement("button", { contentEditable: false, onClick: deleteNode }, "Delete image"),+ ));+ },+});++function Fixture() {+ const editor = useEditor({+ extensions: [StarterKit, DeletableImage, EditableImageGallery],+ content: { type: "doc", content: [{+ type: "edgeeverImageGallery", attrs: { layout: "2" },+ content: ["/one.jpg", "/two.jpg"].map((src) => ({ type: "image", attrs: { src } })),+ }] },+ onCreate: ({ editor }) => renderState(editor),+ onTransaction: ({ editor }) => renderState(editor),+ });+ React.useEffect(() => {+ if (!editor) return;+ document.querySelector("#undo").onclick = () => editor.commands.undo();+ document.querySelector("#redo").onclick = () => editor.commands.redo();+ }, [editor]);+ return React.createElement(EditorContent, { editor });+}+function renderState(editor) {+ document.querySelector("#document").textContent = JSON.stringify(editor.getJSON());+ document.querySelector("#markdown").textContent = docToMarkdown(editor.getJSON());+}+createRoot(document.querySelector("#editor")).render(React.createElement(Fixture));diff --git a/tests/e2e/image-gallery-deletion.spec.ts b/tests/e2e/image-gallery-deletion.spec.tsnew file mode 100644index 00000000..a4403664--- /dev/null+++ b/tests/e2e/image-gallery-deletion.spec.ts@@ -0,0 +1,27 @@+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 }) => {+ 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 });+ const gallery = page.locator("[data-edgeever-image-gallery]");+ await expect(images).toHaveCount(2);+ await images.first().click();+ await expect(images).toHaveCount(1);+ // Separate deliberate deletion actions into individual history events.+ await page.waitForTimeout(550);+ await images.click();+ await expect(gallery).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).toHaveAttribute("data-image-gallery-layout", "2");+ await expect(page.locator("#markdown")).toContainText("");+ await page.getByRole("button", { name: "Redo", exact: true }).click();+ await expect(gallery).toHaveCount(0);+ await expect(page.locator("#markdown")).toHaveText("");+ await page.locator(".tiptap").fill("still editable");+ await expect(page.locator("#markdown")).toHaveText("still editable");+});