-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathmarkdownClipboard.ts
More file actions
73 lines (63 loc) 路 2.12 KB
/
Copy pathmarkdownClipboard.ts
File metadata and controls
73 lines (63 loc) 路 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Extension, type JSONContent } from '@tiptap/core'
import { Slice } from '@tiptap/pm/model'
import { Plugin, PluginKey } from '@tiptap/pm/state'
export function createMarkdownClipboardExtension() {
return Extension.create({
name: 'markdownClipboard',
addProseMirrorPlugins() {
const { editor } = this
return [
new Plugin({
key: new PluginKey('markdownClipboard'),
props: {
handleDOMEvents: {
paste(view, event) {
// DOM event handlers run before ProseMirror's own editable check
if (!view.editable) {
return false
}
const text =
event.clipboardData?.getData('text/plain') ||
event.clipboardData?.getData('Text') ||
''
if (!text) {
return false
}
const handled = view.pasteText(text, event)
if (!handled) {
return false
}
event.preventDefault()
return true
}
},
clipboardTextSerializer(slice: Slice) {
if (!slice.content.size) {
return ''
}
return (
editor.markdown?.serialize({
type: 'doc',
content: (slice.content.toJSON() as JSONContent[] | null) ?? []
}) ?? ''
)
},
// Convert text clipboard payloads, then let ProseMirror's default
// paste flow fit the slice into the current selection.
clipboardTextParser(text, _context, _plain, view) {
try {
const markdownContent = editor.markdown?.parse(text)
if (!markdownContent?.content?.length) {
return undefined
}
return new Slice(view.state.schema.nodeFromJSON(markdownContent).content, 0, 0)
} catch {
return undefined
}
}
}
})
]
}
})
}