Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ’„ style(chat-input): stop inserting inline image references on paste (#23111)

YuTengjing2c63f34fa9a7
diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.test.ts b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.test.ts
index 2d638e4eb5e..d53155010de 100644
--- a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.test.ts
+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.test.ts
@@ -1,11 +1,21 @@
import { $dfs } from '@lexical/utils';
import type { IEditor } from '@lobehub/editor';
import { CommonPlugin, Kernel, MarkdownPlugin, moment } from '@lobehub/editor';
-import { $createParagraphNode, $createTextNode, $getRoot, HISTORIC_TAG } from 'lexical';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ type ElementNode,
+ HISTORIC_TAG,
+} from 'lexical';
import { describe, expect, it, vi } from 'vitest';
import type { ImageUploadRef } from '../../utils/imageUploads';
-import { $isImageRefTagNode, type ImageRefTagNode } from './ImageRefTagNode';
+import {
+ $createImageRefTagNode,
+ $isImageRefTagNode,
+ type ImageRefTagNode,
+} from './ImageRefTagNode';
import {
ImageRefTagPlugin,
PRUNE_UNATTACHED_IMAGE_REFS_COMMAND,
@@ -26,12 +36,26 @@ const refsOf = (...srcs: string[]) =>
const sync = async (
editor: IEditor,
refs: Map<string, ImageUploadRef>,
- { insert, removed }: { insert?: string[]; removed?: string[] } = {},
+ { removed }: { removed?: string[] } = {},
) => {
- editor.dispatchCommand(SYNC_IMAGE_REF_TAGS_COMMAND, { insert, refs, removed });
+ editor.dispatchCommand(SYNC_IMAGE_REF_TAGS_COMMAND, { refs, removed });
await moment();
};
+/**
+ * Adds references at the end of the text, as editor data saved before references stopped
+ * being inserted brings them back, then syncs them with the attachment list.
+ */
+const addReferences = async (editor: IEditor, refs: Map<string, ImageUploadRef>) => {
+ editor.getLexicalEditor()!.update(() => {
+ const paragraph = $getRoot().getLastChild() as ElementNode;
+ for (const ref of refs.values()) {
+ paragraph.append($createImageRefTagNode(ref.src, ref.number), $createTextNode(' '));
+ }
+ });
+ await sync(editor, refs);
+};
+
// The exported markdown escapes `[`, which still reads as the literal text `[Image #N]`.
const markdown = (editor: IEditor) =>
String(editor.getDocument('markdown')).trim().replaceAll('\\[', '[');
@@ -71,7 +95,7 @@ describe('ImageRefTagPlugin', () => {
const decorator = vi.fn((node: ImageRefTagNode) => `chip ${node.number}`);
const editor = createEditor(decorator);
await setText(editor, '');
- await sync(editor, refsOf('blob:a'), { insert: ['blob:a'] });
+ await addReferences(editor, refsOf('blob:a'));
const lexical = editor.getLexicalEditor()!;
const rendered = lexical.getEditorState().read(() =>
@@ -84,19 +108,28 @@ describe('ImageRefTagPlugin', () => {
expect(rendered).toEqual(['chip 1']);
});
- it('references newly attached images at the caret as [Image #N]', async () => {
+ it('writes references as [Image #N]', async () => {
const editor = createEditor();
- await setText(editor, 'compare');
+ await setText(editor, 'compare ');
- await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });
+ await addReferences(editor, refsOf('blob:a', 'blob:b'));
+
+ expect(markdown(editor)).toBe('compare [Image #1] [Image #2]');
+ });
+
+ it('adds no reference when an image is attached', async () => {
+ const editor = createEditor();
+ await setText(editor, 'hi');
+
+ await sync(editor, refsOf('blob:a'));
- expect(markdown(editor)).toBe('compare[Image #1] [Image #2]');
+ expect(referencesOf(editor)).toEqual([]);
});
it('renumbers references when an earlier image is removed', async () => {
const editor = createEditor();
await setText(editor, 'see ');
- await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });
+ await addReferences(editor, refsOf('blob:a', 'blob:b'));
await sync(editor, refsOf('blob:b'), { removed: ['blob:a'] });
@@ -106,7 +139,7 @@ describe('ImageRefTagPlugin', () => {
it('removes references to images that are no longer attached', async () => {
const editor = createEditor();
await setText(editor, 'look ');
- await sync(editor, refsOf('blob:a'), { insert: ['blob:a'] });
+ await addReferences(editor, refsOf('blob:a'));
await sync(editor, refsOf(), { removed: ['blob:a'] });
@@ -116,7 +149,7 @@ describe('ImageRefTagPlugin', () => {
it('leaves references to unlisted images out of the text, even after undo', async () => {
const editor = createEditor();
await setText(editor, 'a ');
- await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });
+ await addReferences(editor, refsOf('blob:a', 'blob:b'));
const beforeRemoval = editor.getDocument('json');
// Removing image #1 and then undoing brings its reference and the old numbers back.
@@ -131,7 +164,7 @@ describe('ImageRefTagPlugin', () => {
it('stores the current numbers in the editor data after undo brings old ones back', async () => {
const editor = createEditor();
await setText(editor, 'a ');
- await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });
+ await addReferences(editor, refsOf('blob:a', 'blob:b'));
const beforeRemoval = editor.getDocument('json');
await sync(editor, refsOf('blob:b'), { removed: ['blob:a'] });
@@ -144,7 +177,7 @@ describe('ImageRefTagPlugin', () => {
it('binds a reference restored from a sent message to its image by file id', async () => {
const editor = createEditor();
await setText(editor, 'what is ');
- await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });
+ await addReferences(editor, refsOf('blob:a', 'blob:b'));
// Both uploads finish, so the references record the uploaded files' ids.
await sync(
editor,
@@ -177,7 +210,7 @@ describe('ImageRefTagPlugin', () => {
it('keeps a restored reference whose image is not listed yet', async () => {
const editor = createEditor();
await setText(editor, 'old ');
- await sync(editor, refsOf('blob:a'), { insert: ['blob:a'] });
+ await addReferences(editor, refsOf('blob:a'));
const restored = editor.getDocument('json');
// Another conversation's list, then the draft comes back before its uploads.
@@ -193,7 +226,7 @@ describe('ImageRefTagPlugin', () => {
it('drops references to unattached images before sending', async () => {
const editor = createEditor();
await setText(editor, 'see ');
- await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });
+ await addReferences(editor, refsOf('blob:a', 'blob:b'));
const restored = editor.getDocument('json');
// After a reload only image b came back; the draft still references both.
diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.ts b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.ts
index 01bb16fef8f..72035e3e141 100644
--- a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.ts
+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.ts
@@ -1,32 +1,18 @@
import { $dfs } from '@lexical/utils';
import { type getKernelFromEditor, IMarkdownShortCutService } from '@lobehub/editor';
import {
- $createParagraphNode,
- $createTextNode,
- $getRoot,
- $getSelection,
- $isElementNode,
- $isRangeSelection,
$isTextNode,
COMMAND_PRIORITY_HIGH,
createCommand,
HISTORIC_TAG,
HISTORY_MERGE_TAG,
type LexicalEditor,
- type LexicalNode,
} from 'lexical';
import type { ImageUploadRef } from '../../utils/imageUploads';
-import {
- $createImageRefTagNode,
- $isImageRefTagNode,
- formatImageRef,
- ImageRefTagNode,
-} from './ImageRefTagNode';
+import { $isImageRefTagNode, formatImageRef, ImageRefTagNode } from './ImageRefTagNode';
export interface SyncImageRefTagsPayload {
- /** Preview URLs of newly attached images to reference at the caret, in attachment order. */
- insert?: string[];
/** The draft's current image uploads, keyed by preview URL. */
refs: Map<string, ImageUploadRef>;
/** Preview URLs of images the user just removed from the attachment list. */
@@ -35,8 +21,10 @@ export interface SyncImageRefTagsPayload {
/**
* Brings the inline references in line with the attachment list: references to `removed`
- * images are deleted, references to attached images take the image's current number, and
- * `insert` adds references for newly attached images at the caret.
+ * images are deleted, and references to attached images take the image's current number.
+ *
+ * New references are no longer created; these come from editor data saved before that
+ * (drafts and sent messages), so they stay readable and numbered like their images.
*
* A reference to an image that is neither attached nor removed β€” a draft restored before
* its uploads, or after a reload β€” is left in place, since its image may still be listed
@@ -63,7 +51,7 @@ export interface ImageRefTagPluginOptions {
theme?: { imageRefTag?: string };
}
-/** Removes a reference together with the space inserted after it. */
+/** Removes a reference together with the space that followed it. */
const $removeImageRefTag = (node: ImageRefTagNode) => {
const next = node.getNextSibling();
if ($isTextNode(next) && next.getTextContent().startsWith(' ')) {
@@ -124,27 +112,6 @@ const $syncImageRefTags = (refs: Map<string, ImageUploadRef>, removed: RemovedSr
/** Marks the follow-up update that re-syncs references, so it does not trigger itself. */
const IMAGE_REF_RESYNC_TAG = 'image-ref-resync';
-const $insertImageRefTags = (refs: ImageUploadRef[]) => {
- const nodes: LexicalNode[] = refs.flatMap((ref) => [
- $createImageRefTagNode(ref.src, ref.number),
- // Trailing space so the user can keep typing without adding one manually.
- $createTextNode(' '),
- ]);
-
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertNodes(nodes);
- return;
- }
-
- const root = $getRoot();
- const last = root.getLastChild();
- const paragraph = $isElementNode(last) && last.canBeEmpty() ? last : $createParagraphNode();
- if (paragraph !== last) root.append(paragraph);
- paragraph.append(...nodes);
- nodes.at(-1)?.selectEnd();
-};
-
/**
* Owns the `image-ref-tag` node: its decorator, its `[Image #N]` markdown writer, and
* keeping references in sync with the draft's image uploads.
@@ -197,20 +164,13 @@ export class ImageRefTagPlugin {
private registerSync(editor: LexicalEditor): void {
editor.registerCommand(
SYNC_IMAGE_REF_TAGS_COMMAND,
- ({ insert, refs, removed }) => {
+ ({ refs, removed }) => {
this.refs = refs;
for (const src of refs.keys()) this.removed.delete(src);
for (const src of removed ?? []) this.removed.add(src);
- const inserted = (insert ?? []).flatMap((src) => refs.get(src) ?? []);
- editor.update(
- () => {
- $syncImageRefTags(refs, this.removed);
- if (inserted.length > 0) $insertImageRefTags(inserted);
- },
- // Renumbering after a removal belongs to that removal, not to its own undo step.
- inserted.length > 0 ? undefined : { tag: HISTORY_MERGE_TAG },
- );
+ // Renumbering after a removal belongs to that removal, not to its own undo step.
+ editor.update(() => $syncImageRefTags(refs, this.removed), { tag: HISTORY_MERGE_TAG });
return true;
},
COMMAND_PRIORITY_HIGH,
diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.test.ts b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.test.ts
index c7c8991ec23..eb26cf32f7e 100644
--- a/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.test.ts
+++ b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { UploadFileItem } from '@/types/files/upload';
+import { getImageUploadRefs } from '../../utils/imageUploads';
import { planImageRefSync } from './useImageRefTagSync';
vi.mock('@/features/ChatInput/hooks/useChatInputUpload', () => ({
@@ -24,43 +25,18 @@ describe('planImageRefSync', () => {
it('adopts the images already attached when the composer mounts', () => {
const { payload } = planImageRefSync([upload('blob:a', 'pending')], 'topic-a', null);
- expect(payload.insert).toBeUndefined();
expect(payload.removed).toBeUndefined();
});
- it('inserts references for images that just started uploading, in attachment order', () => {
+ it('adds no reference for an image that just started uploading', () => {
+ // Pasting an image used to insert an inline [Image #N] reference at the caret.
const { state } = planImageRefSync([], 'topic-a', null);
const files = [upload('blob:a', 'pending'), upload('blob:b', 'uploading')];
- expect(planImageRefSync(files, 'topic-a', state).payload.insert).toEqual(['blob:a', 'blob:b']);
- });
-
- it('still removes and renumbers references when new ones are not inserted (mobile)', () => {
- const mobile = { insertNew: false };
- const { state } = planImageRefSync(
- [upload('blob:a', 'success'), upload('blob:b', 'success')],
- 'topic-a',
- null,
- mobile,
- );
- const files = [upload('blob:b', 'success'), upload('blob:new', 'pending')];
-
- const { payload } = planImageRefSync(files, 'topic-a', state, mobile);
-
- expect(payload.insert).toEqual([]);
- expect(payload.removed).toEqual(['blob:a']);
- expect(payload.refs.get('blob:b')?.number).toBe(1);
- });
-
- it('does not reference attachments restored from a message or seen before', () => {
- const { state } = planImageRefSync([upload('blob:seen', 'pending')], 'topic-a', null);
- const files = [
- upload('blob:seen', 'success'),
- upload('blob:restored', 'success'),
- upload('blob:new', 'pending'),
- ];
-
- expect(planImageRefSync(files, 'topic-a', state).payload.insert).toEqual(['blob:new']);
+ expect(planImageRefSync(files, 'topic-a', state).payload).toEqual({
+ refs: getImageUploadRefs(files),
+ removed: [],
+ });
});
it('removes references only for images removed from the same list', () => {
diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.ts b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.ts
index d036524e5c8..e82a212ea58 100644
--- a/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.ts
+++ b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.ts
@@ -9,71 +9,44 @@ import { getImageUploadRefs } from '../../utils/imageUploads';
import type { SyncImageRefTagsPayload } from './ImageRefTagPlugin';
import { SYNC_IMAGE_REF_TAGS_COMMAND } from './ImageRefTagPlugin';
-/** Uploads that started in this composer, as opposed to attachments restored from a message. */
-const isNewUpload = (item: UploadFileItem | undefined) =>
- item?.status === 'pending' || item?.status === 'uploading' || item?.status === 'processing';
-
-export interface ImageRefSyncOptions {
- /**
- * Whether newly attached images are referenced at the caret. Off on mobile, which has no
- * numbered image cards; existing references (e.g. from a restored message) still follow
- * removals and renumbering there.
- */
- insertNew?: boolean;
-}
-
export interface ImageRefSyncState {
/** Preview URLs of the images attached at the last sync. */
attached: Set<string>;
/** Upload list the state belongs to. */
key?: string;
- /** Preview URLs ever attached to this list, so a reference is inserted at most once. */
- seen: Set<string>;
}
/**
* What to change after the attachment list changed from `previous` to `files`.
*
- * Only a change within the same upload list inserts or removes references. Moving to
- * another list (switching conversations) only adopts its images: the draft restored there
- * keeps its references, and they are renumbered once those images are listed.
+ * Only a change within the same upload list removes references. Moving to another list
+ * (switching conversations) only adopts its images: the draft restored there keeps its
+ * references, and they are renumbered once those images are listed.
*/
export const planImageRefSync = (
files: UploadFileItem[],
key: string | undefined,
previous: ImageRefSyncState | null,
- { insertNew = true }: ImageRefSyncOptions = {},
): { payload: SyncImageRefTagsPayload; state: ImageRefSyncState } => {
const refs = getImageUploadRefs(files);
const attached = new Set(refs.keys());
if (!previous || previous.key !== key) {
- return { payload: { refs }, state: { attached, key, seen: new Set(attached) } };
+ return { payload: { refs }, state: { attached, key } };
}
const removed = [...previous.attached].filter((src) => !attached.has(src));
- const insert = [...attached].filter(
- (src) =>
- insertNew &&
- !previous.seen.has(src) &&
- isNewUpload(files.find((file) => file.previewUrl === src)),
- );
- return {
- payload: { insert, refs, removed },
- state: { attached, key, seen: new Set([...previous.seen, ...attached]) },
- };
+ return { payload: { refs, removed }, state: { attached, key } };
};
/**
- * Keeps the editor's inline image references in step with the draft's image uploads: a
- * newly attached image is referenced at the caret, a removed image takes its references
- * with it, and the remaining references follow the images' new numbers.
+ * Keeps inline image references already in the draft (from editor data saved before new
+ * references stopped being inserted) in step with the draft's image uploads: a removed image
+ * takes its references with it, and the remaining references follow the images' new numbers.
+ * Attaching an image adds no reference; the numbered image cards identify it.
*/
-export const useImageRefTagSync = (
- editor: IEditor | undefined,
- { insertNew = true }: ImageRefSyncOptions = {},
-) => {
+export const useImageRefTagSync = (editor: IEditor | undefined) => {
const key = useChatInputUploadKey();
const files = useFileStore(fileChatSelectors.chatUploadFileList(key));
const stateRef = useRef<ImageRefSyncState | null>(null);
@@ -81,10 +54,8 @@ export const useImageRefTagSync = (
useEffect(() => {
if (!editor) return;
- const { payload, state } = planImageRefSync(files, key, stateRef.current, {
- insertNew,
- });
+ const { payload, state } = planImageRefSync(files, key, stateRef.current);
stateRef.current = state;
editor.dispatchCommand(SYNC_IMAGE_REF_TAGS_COMMAND, payload);
- }, [editor, files, insertNew, key]);
+ }, [editor, files, key]);
};
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
index e065871959c..37c0b01df39 100644
--- a/src/features/ChatInput/InputEditor/index.test.tsx
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -1,5 +1,5 @@
import { RequestTrigger } from '@lobechat/types';
-import { render, screen, waitFor } from '@testing-library/react';
+import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import InputEditor from './index';
@@ -364,17 +364,6 @@ describe('ChatInput InputEditor', () => {
expect((await getEditorStyle())?.fontSize).toBe(16);
});
- it('keeps restored image references in sync on mobile without inserting new ones', async () => {
- const { useImageRefTagSync } = await import('./ImageRefTag');
- platform.isMobile = true;
-
- render(<InputEditor />);
-
- await waitFor(() =>
- expect(useImageRefTagSync).toHaveBeenLastCalledWith(expect.anything(), { insertNew: false }),
- );
- });
-
it('keeps the editor font size unchanged on desktop', async () => {
permission.allowed = true;
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index 0ed97806f3d..17e9578de23 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -293,10 +293,9 @@ const InputEditor = memo<{
// Listen to editor's paste event for file uploads
usePasteFile(editor, handlePasteFiles);
- // Reference each attached image inline and keep the references numbered like the images.
- // New references are desktop only, since the numbered image cards are a desktop composer UI;
- // references restored from a message still follow removals and renumbering on mobile.
- useImageRefTagSync(editor, { insertNew: !mobile });
+ // Attaching an image inserts no inline reference; references saved in older drafts and
+ // messages still follow removals and renumbering.
+ useImageRefTagSync(editor);
useEffect(() => {
const fn = (e: BeforeUnloadEvent) => {