diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index f58155ae4559e..5047c88556353 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -555,6 +555,7 @@ it("keeps unknown dollar names editable when restoring and pasting a draft", asy it.each([ "Read https://example.com/_handle_/status/1 and open src/__test__.tsx", "see `**x**` now", + "signal = (7 * 2**3 * 5)**4", ])("sends pasted %s as pasted", async (pasted) => { await using screen = await mountEditor(""); const { editor } = screen; @@ -566,6 +567,127 @@ it.each([ expect(serializeEditorDoc(editor.state.doc).value).toBe(pasted); }); +// regression: #31079 paste rules restyled dropped text, and dropped Markdown skipped the composer's parser +it.each([ + // Shown bold like the same paste; the sent text stays verbatim. + ["signal = (7 * 2**3 * 5)**4", "signal = (7 * 23 * 5)4"], + ["a **bold** and *soft* word", "a bold and soft word"], +])("drops %s like a paste", async (dropped, shown) => { + await using screen = await mountEditor(""); + const { editor } = screen; + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", dropped); + const { left, top } = editor.view.coordsAtPos(1); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: left, + clientY: top + 1, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe(dropped); + expect(editor.state.doc.textContent).toBe(shown); + expect(editor.view.hasFocus()).toBe(true); +}); + +it("parses markdown dropped below the first line of an empty composer", async () => { + await using screen = await mountEditor(""); + const { editor } = screen; + const box = editor.view.dom.getBoundingClientRect(); + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", "a **bold** word"); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: box.left + 4, + clientY: box.bottom - 1, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe("a **bold** word"); + expect(editor.state.doc.textContent).toBe("a bold word"); +}); + +it("drops plain text on a new line below the last line", async () => { + await using screen = await mountEditor("before"); + const { editor } = screen; + const box = editor.view.dom.getBoundingClientRect(); + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", "Docs https://example.com/document\n\nsecond"); + dataTransfer.setData("text/html", 'Docs'); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: box.left + 4, + clientY: box.bottom - 1, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe( + "before\nDocs https://example.com/document\n\nsecond", + ); + await act(async () => { + editor.commands.undo(); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe("before"); +}); + +it("drops text on a list marker inside the list", async () => { + await using screen = await mountEditor("- one\n- two"); + const { editor } = screen; + const item = editor.view.dom.querySelectorAll("li")[1]!.getBoundingClientRect(); + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", "added"); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: item.left - 8, + clientY: item.top + item.height / 2, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(serializeEditorDoc(editor.state.doc).value).toMatch(/^- one\n.*added[\s\S]*- two$/); +}); + +it("drops text on a rule's edge without replacing the rule", async () => { + await using screen = await mountEditor("before\n\n---\n\nafter"); + const { editor } = screen; + let rulePos = -1; + editor.state.doc.forEach((node, offset) => { + if (node.type.name === "horizontalRule") rulePos = offset; + }); + const rule = (editor.view.nodeDOM(rulePos) as HTMLElement).getBoundingClientRect(); + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", "dropped"); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: rule.left + rule.width / 2, + clientY: rule.top, + bubbles: true, + cancelable: true, + }), + ); + }); + const value = serializeEditorDoc(editor.state.doc).value; + expect(value).toContain("---"); + expect(value).toContain("dropped"); +}); + it.each([ ["**DEV**", "**DEV**!"], ["*DEV*", "*DEV*!"], diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 8ce568c117dce..1088e27f2a05d 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1160,6 +1160,114 @@ function ComposerPromptEditorTiptapInner( "aria-placeholder": placeholder, }; + /** `newLineAt` inserts on a fresh line created at that block boundary, in the same undo step. */ + const insertClipboardText = ( + view: EditorView, + clipboardData: DataTransfer, + newLineAt?: number, + ): boolean => { + const pastedText = readPastedPlainText(clipboardData); + if (!pastedText) return false; + const onNewLine = newLineAt !== undefined; + // Paste verbatim inside fences; markdown parsing would split blocks and create unsupported chips. + if (!onNewLine && isInCodeBlock(view)) { + const { from, to } = view.state.selection; + view.dispatch( + markAsClipboardEdit( + view.state.tr.insertText(pastedText, from, to), + "paste", + ).scrollIntoView(), + ); + return true; + } + // Shown Markdown source is parsed when the caret leaves, so paste one line into it as text. + const sourceType = view.state.schema.marks[MARKDOWN_SOURCE_MARK]; + const { from: pasteFrom, to: pasteTo, $from: $pasteFrom } = view.state.selection; + if ( + !onNewLine && + sourceType?.isInSet($pasteFrom.marks()) && + !pastedText.includes("\n") && + collectComposerPromptInlineTokens(`${pastedText}\n`).length === 0 + ) { + view.dispatch( + markAsClipboardEdit( + view.state.tr.insertText(pastedText, pasteFrom, pasteTo), + "paste", + ).scrollIntoView(), + ); + return true; + } + const importFragment = readCallbacks().importContextFragment; + let text = + !literalText && importFragment + ? importPastedComposerText(clipboardData, importFragment) + : pastedText; + const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`); + const isChip = (token: (typeof tokens)[number] | undefined) => + token?.type === "mention" || + (token?.type === "skill" && skillLabelFor(token.value) !== null) || + (token?.type === "model" && isKnownModel(token.instanceId, token.model)); + const lastToken = tokens.at(-1); + if (isChip(lastToken) && lastToken?.end === text.length) { + text += " "; + } + if (!onNewLine && isChip(tokens[0]) && tokens[0]?.start === 0) { + const map = serializeEditorDoc(view.state.doc); + const offset = flatToMarkdown(map, pmToFlat(map, view.state.selection.from)); + if (offset > 0 && !/\s/.test(map.value[offset - 1]!)) text = ` ${text}`; + } + const { $from } = view.state.selection; + const lineBefore = onNewLine + ? "" + : $from.parent.textBetween(0, $from.parentOffset, undefined, "\uFFFC"); + const literalLength = literalText + ? 0 + : pastedPathQueryLength(lineBefore, text, readCallbacks().isPathQueryActive?.()); + const editorInstance = (view.dom as TiptapEditorHTMLElement).editor; + if (editorInstance) { + const $paste = onNewLine ? view.state.doc.resolve(newLineAt) : view.state.selection.$from; + const nested = ["listItem", "taskItem", "blockquote"].some((name) => + hasAncestor($paste, name), + ); + insertMarkdownParagraphs( + text, + skillLabelFor, + { styling: richText, blocks: !nested, literalText, literalLength, isKnownModel }, + (content) => { + editorInstance + .chain() + .command(({ tr }) => { + markAsClipboardEdit(tr, "paste"); + if (onNewLine) { + tr.insert(newLineAt, tr.doc.type.schema.nodes.paragraph!.create()); + tr.setSelection(TextSelection.create(tr.doc, newLineAt + 1)); + } + return true; + }) + // Pasted chips and lines would split shown Markdown, so parse it first. + .command(collapseShownMarkdownSource) + .insertContent(content) + .command(({ tr }) => { + // Move after a pasted rule so the next keystroke cannot replace it; add a trailing line + // if needed. + const { selection } = tr; + if (!(selection instanceof NodeSelection) || !selection.node.isBlock) { + return true; + } + if (!tr.doc.resolve(selection.to).nodeAfter?.isTextblock) { + tr.insert(selection.to, tr.doc.type.schema.nodes.paragraph!.create()); + } + tr.setSelection(TextSelection.create(tr.doc, selection.to + 1)); + return true; + }) + .run(); + }, + ); + scrollTiptapCaretIntoView(editorInstance); + } + return true; + }; + const editor = useEditor( { extensions: richText ? RICH_TEXT_EXTENSIONS : PLAIN_TEXT_EXTENSIONS, @@ -1169,6 +1277,8 @@ function ComposerPromptEditorTiptapInner( isKnownModel: (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)), }), editable: !disabled, + // The composer parses pasted and dropped text itself; paste rules would restyle literal `*`. + enablePasteRules: false, editorProps: { attributes: editorAttributes, handleDOMEvents: { @@ -1456,100 +1566,39 @@ function ComposerPromptEditorTiptapInner( (literalText || !readPastedComposerContext(clipboardData)?.records.length) ) return false; - const pastedText = readPastedPlainText(clipboardData); - if (!pastedText) return false; + if (!insertClipboardText(view, clipboardData)) return false; event.preventDefault(); - // Paste verbatim inside fences; markdown parsing would split blocks and create unsupported chips. - if (isInCodeBlock(view)) { - const { from, to } = view.state.selection; - view.dispatch( - markAsClipboardEdit( - view.state.tr.insertText(pastedText, from, to), - "paste", - ).scrollIntoView(), - ); - return true; - } - // Shown Markdown source is parsed when the caret leaves, so paste one line into it as text. - const sourceType = view.state.schema.marks[MARKDOWN_SOURCE_MARK]; - const { from: pasteFrom, to: pasteTo, $from: $pasteFrom } = view.state.selection; - if ( - sourceType?.isInSet($pasteFrom.marks()) && - !pastedText.includes("\n") && - collectComposerPromptInlineTokens(`${pastedText}\n`).length === 0 - ) { - view.dispatch( - markAsClipboardEdit( - view.state.tr.insertText(pastedText, pasteFrom, pasteTo), - "paste", - ).scrollIntoView(), - ); - return true; - } - const importFragment = readCallbacks().importContextFragment; - let text = - !literalText && importFragment - ? importPastedComposerText(clipboardData, importFragment) - : pastedText; - const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`); - const isChip = (token: (typeof tokens)[number] | undefined) => - token?.type === "mention" || - (token?.type === "skill" && skillLabelFor(token.value) !== null) || - (token?.type === "model" && isKnownModel(token.instanceId, token.model)); - const lastToken = tokens.at(-1); - if (isChip(lastToken) && lastToken?.end === text.length) { - text += " "; - } - if (isChip(tokens[0]) && tokens[0]?.start === 0) { - const map = serializeEditorDoc(view.state.doc); - const offset = flatToMarkdown(map, pmToFlat(map, view.state.selection.from)); - if (offset > 0 && !/\s/.test(map.value[offset - 1]!)) text = ` ${text}`; - } - const { $from } = view.state.selection; - const lineBefore = $from.parent.textBetween(0, $from.parentOffset, undefined, "\uFFFC"); - const literalLength = literalText - ? 0 - : pastedPathQueryLength(lineBefore, text, readCallbacks().isPathQueryActive?.()); - const editorInstance = (view.dom as TiptapEditorHTMLElement).editor; - if (editorInstance) { - const $paste = view.state.selection.$from; - const nested = ["listItem", "taskItem", "blockquote"].some((name) => - hasAncestor($paste, name), - ); - insertMarkdownParagraphs( - text, - skillLabelFor, - { styling: richText, blocks: !nested, literalText, literalLength, isKnownModel }, - (content) => { - editorInstance - .chain() - .command(({ tr }) => { - markAsClipboardEdit(tr, "paste"); - return true; - }) - // Pasted chips and lines would split shown Markdown, so parse it first. - .command(collapseShownMarkdownSource) - .insertContent(content) - .command(({ tr }) => { - // Move after a pasted rule so the next keystroke cannot replace it; add a trailing line - // if needed. - const { selection } = tr; - if (!(selection instanceof NodeSelection) || !selection.node.isBlock) { - return true; - } - if (!tr.doc.resolve(selection.to).nodeAfter?.isTextblock) { - tr.insert(selection.to, tr.doc.type.schema.nodes.paragraph!.create()); - } - tr.setSelection(TextSelection.create(tr.doc, selection.to + 1)); - return true; - }) - .run(); - }, - ); - scrollTiptapCaretIntoView(editorInstance); - } return true; }, + handleDrop: (view, event, _slice, moved) => { + const data = event.dataTransfer; + // Files and drags that start inside the editor keep ProseMirror's own drop. + if (moved || view.dragging || !data || data.files.length > 0) return false; + const target = view.posAtCoords({ left: event.clientX, top: event.clientY }); + if (!target || !readPastedPlainText(data)) return false; + let pos = target.pos; + const $target = view.state.doc.resolve(pos); + if (!$target.parent.inlineContent) { + // Between blocks, fill an adjacent empty paragraph (the padding of an empty composer) or start + // a new line at the drop point; a nearby selection would replace or join a block. + const isEmptyParagraph = (node: typeof $target.nodeAfter) => + node?.type.name === "paragraph" && node.content.size === 0; + if (isEmptyParagraph($target.nodeAfter)) pos += 1; + else if (isEmptyParagraph($target.nodeBefore)) pos -= 1; + else { + const index = $target.index(); + const paragraph = view.state.schema.nodes.paragraph!; + // Between list items a paragraph does not fit; ProseMirror's drop adds an item there. + if (!$target.parent.canReplaceWith(index, index, paragraph)) return false; + view.focus(); + return insertClipboardText(view, data, pos); + } + } + view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, pos))); + // Handling the drop skips ProseMirror's own focus call. + view.focus(); + return insertClipboardText(view, data); + }, }, onUpdate: ({ editor: updated, transaction }) => { // Undo can restore a chip for a skill or model the environment no longer offers. diff --git a/apps/web/src/composer-rich-text-doc.ts b/apps/web/src/composer-rich-text-doc.ts index f99337382f0b1..428b6185336d7 100644 --- a/apps/web/src/composer-rich-text-doc.ts +++ b/apps/web/src/composer-rich-text-doc.ts @@ -16,7 +16,7 @@ import { Blockquote } from "@tiptap/extension-blockquote"; import { CodeBlock } from "@tiptap/extension-code-block"; import { Heading } from "@tiptap/extension-heading"; import { HorizontalRule } from "@tiptap/extension-horizontal-rule"; -import { Italic, starInputRegex, starPasteRegex } from "@tiptap/extension-italic"; +import { Italic, starInputRegex } from "@tiptap/extension-italic"; import { combineTransactionSteps, getChangedRanges, @@ -24,7 +24,6 @@ import { type Editor, InputRule, markInputRule, - markPasteRule, mergeAttributes, } from "@tiptap/core"; import { isHistoryTransaction } from "@tiptap/pm/history"; @@ -352,9 +351,6 @@ export const ComposerItalicExtension = Italic.extend({ addInputRules() { return [markInputRuleOutsideCode(starInputRegex, this.type)]; }, - addPasteRules() { - return [markPasteRule({ find: starPasteRegex, type: this.type })]; - }, }); export const ComposerBoldExtension = Bold.extend({ diff --git a/apps/web/src/composer-undo-grouping.ts b/apps/web/src/composer-undo-grouping.ts index 2a7a5a94028e7..5d33ee4c62762 100644 --- a/apps/web/src/composer-undo-grouping.ts +++ b/apps/web/src/composer-undo-grouping.ts @@ -10,10 +10,7 @@ export type ComposerChangeKind = "insert" | "delete" | "other"; const CLIPBOARD_EDIT_META = "composerClipboardEdit"; const COMPOSITION_REPLACE_META = "composerCompositionReplace"; -/** - * Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths. - * Not `uiEvent`: Tiptap's paste rules would style the already parsed paste a second time. - */ +/** Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths. */ export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Transaction { return tr.setMeta(CLIPBOARD_EDIT_META, event); }