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(web): merge later image uploads into adjacent galleries
tianma-if9b0ad6d38340
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 31a5cbe0..156f2764 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -79,6 +79,7 @@ import {getResourceInsertionTarget,shouldSelectInsertedResources,} from "@/lib/resource-insertion-target";+import { insertUploadedResources } from "@/lib/resource-insertion";import {createSlashCommandExtension,type SlashCommandActions,@@ -112,7 +113,6 @@ import { EDITOR_CONTENT_MAX_WIDTH, EDITOR_CONTENT_MAX_WIDTH_COLLAPSED } from "@/import {countMemoCharacters,docToMarkdown,- groupConsecutiveImagesIntoGalleries,MEMO_CONTENT_STYLE,markdownToDoc,MergeDivider,@@ -1130,11 +1130,11 @@ const RichEditorPane = ({insertion.focus();}insertion- .insertContentAt(+ .command(insertUploadedResources(safeInsertionTarget,- groupConsecutiveImagesIntoGalleries(content),- { updateSelection },- )+ content,+ updateSelection,+ )).run();if (!updateSelection) {// ProseMirror can still map a cursor at the document boundary to adiff --git a/apps/web/src/lib/resource-insertion-target.ts b/apps/web/src/lib/resource-insertion-target.tsindex 8785df88..2e6c33f2 100644--- a/apps/web/src/lib/resource-insertion-target.ts+++ b/apps/web/src/lib/resource-insertion-target.ts@@ -2,6 +2,7 @@ import type { Editor } from "@tiptap/core";import { GapCursor } from "@tiptap/pm/gapcursor";import type { Selection } from "@tiptap/pm/state";import { NodeSelection, Selection as ProseMirrorSelection } from "@tiptap/pm/state";+import { IMAGE_GALLERY_NODE_TYPE } from "@edgeever/shared";export type ResourceInsertionTarget = number | { from: number; to: number };@@ -12,6 +13,11 @@ export type ResourceInsertionTarget = number | { from: number; to: number };*/export const getResourceInsertionTarget = (selection: Selection): ResourceInsertionTarget => {if (selection instanceof NodeSelection) {+ for (let depth = selection.$from.depth; depth > 0; depth -= 1) {+ if (selection.$from.node(depth).type.name === IMAGE_GALLERY_NODE_TYPE) {+ return selection.$from.after(depth);+ }+ }return selection.to;}diff --git a/apps/web/src/lib/resource-insertion.test.mjs b/apps/web/src/lib/resource-insertion.test.mjsnew file mode 100644index 00000000..6f1a7e5f--- /dev/null+++ b/apps/web/src/lib/resource-insertion.test.mjs@@ -0,0 +1,141 @@+import { describe, expect, test } from "bun:test";+import { Editor } from "@tiptap/core";+import Image from "@tiptap/extension-image";+import StarterKit from "@tiptap/starter-kit";+import { closeHistory, history, undo, redo } from "@tiptap/pm/history";+import { ImageGallery, IMAGE_GALLERY_NODE_TYPE } from "@edgeever/shared";+import { insertUploadedResources } from "./resource-insertion";+import { getResourceInsertionTarget } from "./resource-insertion-target";++const image = (src) => ({ type: "image", attrs: { src, alt: src, title: src } });+const paragraph = (text) => ({ type: "paragraph", content: text ? [{ type: "text", text }] : [] });+const gallery = (layout = "3", sources = ["one", "two"]) => ({+ type: IMAGE_GALLERY_NODE_TYPE, attrs: { layout }, content: sources.map(image),+});+const makeEditor = (content) => new Editor({+ extensions: [StarterKit, Image, ImageGallery], content: { type: "doc", content },+});+const insert = (editor, target, content, select = true) => {+ expect(editor.commands.command(insertUploadedResources(target, content, select))).toBe(true);+ editor.state.doc.check();+};++describe("uploaded resources beside an existing gallery", () => {+ test("still extends a gallery after saving and reloading the note", () => {+ const original = makeEditor([gallery("2")]);+ const saved = JSON.parse(JSON.stringify(original.getJSON()));+ original.destroy();+ const editor = makeEditor(saved.content);+ editor.commands.setNodeSelection(2);+ insert(editor, getResourceInsertionTarget(editor.state.selection), [image("three")]);+ expect(editor.getJSON().content).toHaveLength(1);+ expect(editor.getJSON().content[0].attrs.layout).toBe("2");+ expect(editor.getJSON().content[0].content.map((node) => node.attrs.src)).toEqual(["one", "two", "three"]);+ editor.destroy();+ });++ test("keeps a single upload standalone when there is no neighboring gallery", () => {+ const editor = makeEditor([image("old"), paragraph()]);+ insert(editor, 2, [image("new")]);+ expect(editor.getJSON().content.map((node) => node.type)).toEqual(["image", "image"]);+ editor.destroy();+ });++ test("preserves text replacement and does not cross the remaining paragraph", () => {+ const editor = makeEditor([gallery(), paragraph("replace keep")]);+ insert(editor, { from: 5, to: 12 }, [image("new")]);+ expect(editor.getJSON().content.map((node) => node.type)).toEqual([IMAGE_GALLERY_NODE_TYPE, "paragraph"]);+ expect(editor.getJSON().content[1].content[0].text).toBe(" keep");+ editor.destroy();+ });++ test("a separate later upload extends the first batch and preserves its layout and metadata", () => {+ const editor = makeEditor([paragraph()]);+ // Headless TipTap does not mount view plugins; install history explicitly.+ editor.view.updateState(editor.state.reconfigure({ plugins: [history()] }));+ insert(editor, 1, [image("one"), image("two")]);+ editor.commands.setNodeSelection(0);+ editor.commands.updateAttributes(IMAGE_GALLERY_NODE_TYPE, { layout: "3" });+ const before = editor.getJSON();+ editor.view.dispatch(closeHistory(editor.state.tr));+ insert(editor, getResourceInsertionTarget(editor.state.selection), [image("three")]);+ expect(editor.getJSON().content).toHaveLength(1);+ expect(editor.getJSON().content[0].attrs.layout).toBe("3");+ expect(editor.getJSON().content[0].content.map((node) => node.attrs.src)).toEqual(["one", "two", "three"]);+ expect(editor.getJSON().content[0].content[2].attrs.title).toBe("three");+ expect(undo(editor.state, editor.view.dispatch)).toBe(true);+ expect(editor.getJSON()).toEqual(before);+ expect(redo(editor.state, editor.view.dispatch)).toBe(true);+ expect(editor.getJSON().content[0].content).toHaveLength(3);+ editor.destroy();+ });++ test("uploading with a gallery child selected appends without nesting or replacing images", () => {+ const editor = makeEditor([gallery()]);+ editor.commands.setNodeSelection(1);+ expect(getResourceInsertionTarget(editor.state.selection)).toBe(4);+ insert(editor, getResourceInsertionTarget(editor.state.selection), [image("three"), image("four")]);+ expect(editor.getJSON().content).toHaveLength(1);+ expect(editor.getJSON().content[0].attrs.layout).toBe("3");+ expect(editor.getJSON().content[0].content.map((node) => node.attrs.src)).toEqual(["one", "two", "three", "four"]);+ editor.destroy();+ });++ for (const layout of ["auto", "1", "2", "3"]) {+ for (const sources of [["new"], ["new-a", "new-b"]]) {+ test(`prepends ${sources.length} images and keeps layout ${layout}`, () => {+ const editor = makeEditor([gallery(layout)]);+ insert(editor, 0, sources.map(image));+ expect(editor.getJSON().content).toHaveLength(1);+ expect(editor.getJSON().content[0].attrs.layout).toBe(layout);+ expect(editor.getJSON().content[0].content.map((node) => node.attrs.src)).toEqual([...sources, "one", "two"]);+ editor.destroy();+ });+ }+ }++ test("replaces a trailing empty insertion paragraph but never crosses other paragraphs", () => {+ for (const separator of [paragraph("keep"), paragraph()]) {+ const editor = makeEditor([gallery(), separator, paragraph()]);+ insert(editor, editor.state.doc.content.size - 1, [image("three")]);+ expect(editor.getJSON().content.map((node) => node.type)).toEqual([IMAGE_GALLERY_NODE_TYPE, "paragraph", "image"]);+ editor.destroy();+ }+ const editor = makeEditor([gallery(), paragraph()]);+ insert(editor, 5, [image("three")]);+ expect(editor.getJSON().content).toHaveLength(1);+ expect(editor.getJSON().content[0].content).toHaveLength(3);+ editor.destroy();+ });++ test("preserves mixed upload order and only merges the adjacent image run", () => {+ const editor = makeEditor([gallery()]);+ insert(editor, 4, [image("three"), paragraph("attachment"), image("four"), image("five")]);+ const content = editor.getJSON().content;+ expect(content.map((node) => node.type)).toEqual([IMAGE_GALLERY_NODE_TYPE, "paragraph", IMAGE_GALLERY_NODE_TYPE]);+ expect(content[0].content.map((node) => node.attrs.src)).toEqual(["one", "two", "three"]);+ expect(content[1].content[0].text).toBe("attachment");+ expect(content[2].content.map((node) => node.attrs.src)).toEqual(["four", "five"]);+ editor.destroy();+ });++ test("does not merge two existing galleries or unrelated occurrences of the same source", () => {+ const editor = makeEditor([gallery(), gallery("2", ["other-a", "other-b"]), image("three"), paragraph("keep")]);+ insert(editor, 4, [image("three")]);+ expect(editor.getJSON().content).toHaveLength(4);+ expect(editor.getJSON().content[0].content).toHaveLength(3);+ expect(editor.getJSON().content[1].attrs.layout).toBe("2");+ expect(editor.getJSON().content[1].content).toHaveLength(2);+ expect(editor.getJSON().content[2].attrs.src).toBe("three");+ editor.destroy();+ });++ test("preserves a newer selection inside an existing gallery when selection updates are disabled", () => {+ const editor = makeEditor([gallery()]);+ editor.commands.setNodeSelection(1);+ insert(editor, 4, [image("three")], false);+ expect(editor.state.selection.from).toBe(1);+ expect(editor.state.selection.node.attrs.src).toBe("one");+ editor.destroy();+ });+});diff --git a/apps/web/src/lib/resource-insertion.ts b/apps/web/src/lib/resource-insertion.tsnew file mode 100644index 00000000..1a198d58--- /dev/null+++ b/apps/web/src/lib/resource-insertion.ts@@ -0,0 +1,54 @@+import type { Command } from "@tiptap/core";+import { Fragment, type Node as ProseMirrorNode } from "@tiptap/pm/model";+import { canJoin } from "@tiptap/pm/transform";+import {+ groupConsecutiveImagesIntoGalleries,+ IMAGE_GALLERY_NODE_TYPE,+ type TiptapNode,+} from "@edgeever/shared";+import type { ResourceInsertionTarget } from "./resource-insertion-target";++/** Insert a batch and extend only galleries immediately beside the new media. */+export const insertUploadedResources = (+ target: ResourceInsertionTarget,+ content: TiptapNode[],+ updateSelection: boolean,+): Command => ({ tr, commands, dispatch }) => {+ const nodes = groupConsecutiveImagesIntoGalleries(content).map((node) => tr.doc.type.schema.nodeFromJSON(node));+ if (!commands.insertContentAt(target, Fragment.from(nodes), { updateSelection })) return false;+ if (!dispatch) return true;++ // Track the actual inserted nodes, not URLs: an older occurrence of the same+ // image elsewhere in the note must never be regrouped by this upload.+ const inserted = new Set(nodes);+ const candidates: Array<{ node: ProseMirrorNode; pos: number }> = [];+ tr.doc.forEach((node, pos) => {+ if (inserted.has(node) && (node.type.name === "image" || node.type.name === IMAGE_GALLERY_NODE_TYPE)) {+ candidates.push({ node, pos });+ }+ });++ // Work backwards so later joins do not invalidate earlier positions. Never+ // cross paragraphs/attachments or combine two pre-existing galleries.+ for (const { node, pos } of candidates.reverse()) {+ const before = tr.doc.resolve(pos).nodeBefore;+ const after = tr.doc.resolve(pos + node.nodeSize).nodeAfter;+ const previousGallery = before?.type.name === IMAGE_GALLERY_NODE_TYPE && !inserted.has(before) ? before : null;+ const nextGallery = after?.type.name === IMAGE_GALLERY_NODE_TYPE && !inserted.has(after) ? after : null;+ const neighbor = previousGallery ?? nextGallery;+ if (!neighbor) continue;++ // Wrap only the new singleton, then join containers. Unlike replacing the+ // entire old gallery, joining maps existing selections within it correctly.+ if (node.type.name === "image") {+ const range = tr.doc.resolve(pos).blockRange(tr.doc.resolve(pos + node.nodeSize));+ if (!range) continue;+ tr.wrap(range, [{ type: neighbor.type, attrs: neighbor.attrs }]);+ } else if (!previousGallery) {+ tr.setNodeMarkup(pos, undefined, neighbor.attrs);+ }+ const joinAt = previousGallery ? pos : pos + tr.doc.nodeAt(pos)!.nodeSize;+ if (canJoin(tr.doc, joinAt)) tr.join(joinAt);+ }+ return true;+};