Skip to content

Commit c12a669

Browse files
committed
fix(markdown): align clipboard parsing with file rendering
1 parent 2689d4e commit c12a669

6 files changed

Lines changed: 305 additions & 63 deletions

File tree

‎apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/markdown-parse.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,23 @@ export function splitMarkdownBlocks(body: string): string[] {
216216
return blocks
217217
}
218218

219+
/** Detect clipboard formatting with the same grammar and bounded blocks used to open files. */
220+
export function hasMarkdownFormatting(body: string): boolean {
221+
const markdown = markdownManager().instance
222+
const normalized = body.replace(/\r\n?/g, '\n')
223+
const blocks = NON_CHUNKABLE.test(normalized) ? [normalized] : splitMarkdownBlocks(normalized)
224+
for (const block of blocks) {
225+
let formatted = false
226+
markdown.walkTokens(markdown.lexer(block), (token) => {
227+
// Native paste can add autolinks separately, retaining the text if formatting exceeds its budget.
228+
if (token.type === 'link' && token.raw === token.text) return
229+
if (!['paragraph', 'text', 'space', 'escape', 'def'].includes(token.type)) formatted = true
230+
})
231+
if (formatted) return true
232+
}
233+
return false
234+
}
235+
219236
/**
220237
* Parse a markdown body into a ProseMirror doc by splitting it into top-level blocks and parsing each
221238
* independently, then assembling the results.

‎apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/markdown-paste.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,40 @@ describe('markdown paste', () => {
115115
expect(structural).toEqual(['heading', 'bulletList', 'blockquote'])
116116
})
117117

118+
it.each([
119+
['setext heading', 'Paste title\n===========', 'heading', 'Paste title'],
120+
['tilde fence', '~~~js\nconst answer = 42\n~~~', 'codeBlock', 'const answer = 42'],
121+
['indented code', ' const answer = 42', 'codeBlock', 'const answer = 42'],
122+
['parenthesized ordered list', '1) one\n2) two', 'orderedList', 'onetwo'],
123+
['thematic break', '---', 'horizontalRule', ''],
124+
['reference link', '[Guide][ref]\n\n[ref]: https://example.com', 'paragraph', 'Guide'],
125+
])(
126+
'renders pasted %s as Markdown and preserves it after reopening',
127+
(_, text, type, expectedText) => {
128+
const editor = mount()
129+
dispatchPaste(editor, text)
130+
const first = editor.state.doc.firstChild
131+
expect(first?.type.name).toBe(type)
132+
if (type === 'paragraph') expect(editor.getHTML()).toContain('href="https://example.com"')
133+
expect(first?.textContent).toBe(expectedText)
134+
const reopened = mount()
135+
reopened.commands.setContent(editor.getMarkdown(), { contentType: 'markdown' })
136+
expect(reopened.getJSON()).toEqual(editor.getJSON())
137+
}
138+
)
139+
140+
it.each(['Paste title', ''])(
141+
'honors explicit Markdown provenance with plain fallback %j',
142+
(fallback) => {
143+
const editor = mount()
144+
dispatchPaste(editor, fallback, '<b>Wrong representation</b>', {
145+
'text/markdown': 'Paste title\n===========',
146+
})
147+
expect(editor.getHTML()).toContain('<h1>Paste title</h1>')
148+
expect(editor.getText()).not.toContain('Wrong representation')
149+
}
150+
)
151+
118152
it('strips <style>/<script> from pasted HTML so their text never leaks into the doc', () => {
119153
const editor = mount()
120154
const gsheets =

‎apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/markdown-paste.ts‎

Lines changed: 11 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import { type Editor, Extension } from '@tiptap/core'
22
import { Plugin } from '@tiptap/pm/state'
33
import { normalizeLinkHref } from '@/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/markdown-fidelity'
4-
import { parseMarkdownToDoc } from '@/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/markdown-parse'
4+
import {
5+
hasMarkdownFormatting,
6+
parseMarkdownToDoc,
7+
} from '@/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/markdown-parse'
58

69
interface MarkdownPasteStorage {
710
pasteWithoutFormatting: boolean
@@ -40,41 +43,6 @@ function pastedLinkHref(text: string): string | null {
4043
return null
4144
}
4245

43-
/**
44-
* Structural markdown — strong signals the plain text is genuinely markdown (a link, image, badge,
45-
* list, heading, blockquote, fenced block, or GFM table). Only used after clipboard provenance has
46-
* established that the source is plain text or explicitly Markdown.
47-
*/
48-
const STRUCTURAL_MARKDOWN_HINTS: ReadonlyArray<RegExp> = [
49-
/^#{1,6}\s/m,
50-
/\*\*[^*]+\*\*/,
51-
/\[[^\]]*]\([^)]+\)/,
52-
/^\s*[-*+]\s/m,
53-
/^\s*\d+\.\s/m,
54-
/^>\s/m,
55-
/```/,
56-
/^\|.*\|.*\|/m,
57-
]
58-
59-
/**
60-
* Inline marks — weaker markdown signals (`*italic*` / `_italic_`, `~~strike~~`, `` `code` ``) that a
61-
* rich HTML sibling encodes just as well. Parsed for a plain-text-only paste (so markdown copied from a
62-
* terminal or `.md` source renders), but deferred to an HTML sibling: its presence means the source was
63-
* rich, and it may carry structure the plain text can't (a copied table's plain form is tab-separated,
64-
* not a `| … |` grid, so parsing it would flatten the table).
65-
*/
66-
const INLINE_MARK_HINTS: ReadonlyArray<RegExp> = [
67-
/\*[^*\n]+\*/,
68-
/_[^_\n]+_/,
69-
/~~[^~\n]+~~/,
70-
/`[^`\n]+`/,
71-
/==(?:[^=\n]|=(?!=))+==/,
72-
]
73-
74-
function hasAny(hints: ReadonlyArray<RegExp>, text: string): boolean {
75-
return hints.some((hint) => hint.test(text))
76-
}
77-
7846
/**
7947
* VSCode language ids that differ from our code-block language values. `markdown`/`plaintext` map to
8048
* the empty string so they are NOT forced into a code block — markdown copied from VSCode should parse
@@ -157,8 +125,8 @@ function stripNonContentHtml(html: string): string {
157125
*
158126
* Provenance decides plain-text-vs-HTML: a `text/html` sibling (copied from a browser, Slack, Notion,
159127
* GitHub, or this editor) is the signal the source was rich. Defer to that structure even when literal
160-
* cell text resembles Markdown. VSCode's explicit Markdown mode is the exception: its colored-span
161-
* HTML represents source, not a rendered document. Explicit paste-without-formatting bypasses every
128+
* cell text resembles Markdown. Explicit `text/markdown` and VSCode's Markdown mode prefer source
129+
* over the HTML representation. Explicit paste-without-formatting bypasses every
162130
* transformation, including link wrapping and source-language code blocks.
163131
*
164132
* The strictness of the parse matters: `marked` follows CommonMark flanking rules, so `*text*` becomes
@@ -221,7 +189,8 @@ export const MarkdownPaste = Extension.create<Record<string, never>, MarkdownPas
221189
return true
222190
}
223191
if (editor.isActive('codeBlock') || editor.isActive('code')) return false
224-
const text = event.clipboardData?.getData('text/plain')
192+
const markdown = event.clipboardData?.getData('text/markdown')
193+
const text = markdown || event.clipboardData?.getData('text/plain')
225194
if (!text) return false
226195
const { selection } = view.state
227196
if (
@@ -242,10 +211,10 @@ export const MarkdownPaste = Extension.create<Record<string, never>, MarkdownPas
242211
content: [{ type: 'text', text }],
243212
})
244213
}
245-
const isMarkdownSource = mode === 'markdown' || mode === 'md' || mode === 'mdx'
214+
const isMarkdownSource =
215+
Boolean(markdown) || mode === 'markdown' || mode === 'md' || mode === 'mdx'
246216
if (event.clipboardData?.getData('text/html') && !isMarkdownSource) return false
247-
if (!hasAny(STRUCTURAL_MARKDOWN_HINTS, text) && !hasAny(INLINE_MARK_HINTS, text))
248-
return false
217+
if (!isMarkdownSource && !hasMarkdownFormatting(text)) return false
249218
const doc = parseMarkdownToDoc(text)
250219
if (!doc.content?.length) return false
251220
return editor.commands.insertContent(doc)

‎apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/paste-admission.test.ts‎

Lines changed: 64 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,19 @@ afterEach(() => {
1616
editor = null
1717
})
1818

19-
function runPaste(ed: Editor, text: string, html = ''): { handled: boolean; prevented: boolean } {
19+
function runPaste(
20+
ed: Editor,
21+
text: string,
22+
html = '',
23+
extra: Record<string, string> = {}
24+
): { handled: boolean; prevented: boolean } {
2025
let prevented = false
2126
const event = {
2227
clipboardData: {
2328
getData: (type: string) => {
2429
if (type === 'text/plain') return text
2530
if (type === 'text/html') return html
26-
return ''
31+
return extra[type] ?? ''
2732
},
2833
},
2934
preventDefault: () => {
@@ -38,11 +43,11 @@ function runPaste(ed: Editor, text: string, html = ''): { handled: boolean; prev
3843
return { handled: false, prevented }
3944
}
4045

41-
function dispatchPaste(ed: Editor, text: string) {
46+
function dispatchPaste(ed: Editor, text: string, extra: Record<string, string> = {}) {
4247
const event = new Event('paste', { bubbles: true, cancelable: true })
4348
Object.defineProperty(event, 'clipboardData', {
4449
value: {
45-
getData: (type: string) => (type === 'text/plain' ? text : ''),
50+
getData: (type: string) => (type === 'text/plain' ? text : (extra[type] ?? '')),
4651
files: [],
4752
items: [],
4853
},
@@ -136,23 +141,62 @@ describe('rich Markdown paste admission', () => {
136141
expect(onRejected).toHaveBeenCalledOnce()
137142
})
138143

139-
it('rejects before downstream paste parsing when projected bytes exceed the document limit', () => {
140-
const onRejected = vi.fn()
141-
editor = new Editor({
142-
extensions: [
143-
...createMarkdownContentExtensions(),
144-
createRichMarkdownPasteAdmission({
145-
maxResultBytes: 10,
146-
getCurrentText: () => '123456',
147-
onRejected,
148-
}),
149-
],
150-
content: '<p>123456</p>',
151-
})
144+
it.each(['text/plain', 'text/markdown'])(
145+
'rejects oversized %s before downstream paste parsing',
146+
(type) => {
147+
const onRejected = vi.fn()
148+
editor = new Editor({
149+
extensions: [
150+
...createMarkdownContentExtensions(),
151+
createRichMarkdownPasteAdmission({
152+
maxResultBytes: 10,
153+
getCurrentText: () => '123456',
154+
onRejected,
155+
}),
156+
],
157+
content: '<p>123456</p>',
158+
})
152159

153-
expect(runPaste(editor, 'abcde')).toEqual({ handled: true, prevented: true })
154-
expect(onRejected).toHaveBeenCalledOnce()
155-
})
160+
expect(
161+
runPaste(editor, type === 'text/plain' ? 'abcde' : 'x', '', { [type]: 'abcde' })
162+
).toEqual({ handled: true, prevented: true })
163+
expect(onRejected).toHaveBeenCalledOnce()
164+
}
165+
)
166+
167+
it.each(['plain shortcut', 'code block', 'inline code'])(
168+
'budgets the consumed plain representation for %s',
169+
(context) => {
170+
const onRejected = vi.fn()
171+
editor = new Editor({
172+
extensions: [
173+
...createMarkdownContentExtensions(),
174+
MarkdownPaste,
175+
createRichMarkdownPasteAdmission({
176+
maxResultBytes: 64,
177+
getCurrentText: () => editor?.getMarkdown() ?? '',
178+
onRejected,
179+
}),
180+
],
181+
enablePasteRules: false,
182+
})
183+
if (context === 'code block') editor.commands.setCodeBlock()
184+
else if (context === 'inline code') editor.commands.setCode()
185+
else
186+
editor.view.dom.dispatchEvent(
187+
new KeyboardEvent('keydown', {
188+
key: 'v',
189+
keyCode: 86,
190+
ctrlKey: true,
191+
shiftKey: true,
192+
bubbles: true,
193+
})
194+
)
195+
dispatchPaste(editor, 'x', { 'text/markdown': '# '.repeat(100) })
196+
expect(editor.state.doc.textContent).toBe('x')
197+
expect(onRejected).not.toHaveBeenCalled()
198+
}
199+
)
156200

157201
it('rejects oversized rich HTML before downstream parsing', () => {
158202
const onRejected = vi.fn()

‎apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/paste-admission.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
import { Extension } from '@tiptap/core'
99
import { Plugin, type Transaction } from '@tiptap/pm/state'
1010
import { postProcessSerializedMarkdown } from '@/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/markdown-fidelity'
11+
import { isPlainTextPaste } from '@/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/markdown-paste'
1112

1213
export interface RichMarkdownPasteAdmissionOptions {
1314
maxResultBytes: number
@@ -101,7 +102,14 @@ export function createRichMarkdownPasteAdmission({
101102
props: {
102103
handleDOMEvents: {
103104
paste: (view, event) => {
104-
const pastedText = event.clipboardData?.getData('text/plain') ?? ''
105+
const literal =
106+
isPlainTextPaste(editor) ||
107+
editor.isActive('codeBlock') ||
108+
editor.isActive('code')
109+
const pastedText =
110+
(!literal && event.clipboardData?.getData('text/markdown')) ||
111+
event.clipboardData?.getData('text/plain') ||
112+
''
105113
const pastedHtml = event.clipboardData?.getData('text/html') ?? ''
106114
if (!pastedText && !pastedHtml) return false
107115

0 commit comments

Comments
 (0)