fix: add support for pasted content from VS Code, fix #2022

This commit is contained in:
Philipp Kühn 2021-10-12 10:20:13 +02:00
parent 7aef884612
commit 0e0b0b6a8c
2 changed files with 52 additions and 0 deletions

View File

@ -23,6 +23,9 @@
"peerDependencies": {
"@tiptap/core": "^2.0.0-beta.1"
},
"dependencies": {
"prosemirror-state": "^1.3.4"
},
"repository": {
"type": "git",
"url": "https://github.com/ueberdosis/tiptap",

View File

@ -1,4 +1,5 @@
import { Node, textblockTypeInputRule } from '@tiptap/core'
import { Plugin, PluginKey, TextSelection } from 'prosemirror-state'
export interface CodeBlockOptions {
languageClassPrefix: string,
@ -132,4 +133,52 @@ export const CodeBlock = Node.create<CodeBlockOptions>({
}),
]
},
addProseMirrorPlugins() {
return [
// this plugin creates a code block for pasted content from VS Code
// we can also detect the copied code language
new Plugin({
key: new PluginKey('codeBlockVSCodeHandler'),
props: {
handlePaste: (view, event) => {
if (!event.clipboardData) {
return false
}
// dont create a new code block within code blocks
if (this.editor.isActive(this.type.name)) {
return false
}
const text = event.clipboardData.getData('text/plain')
const vscode = event.clipboardData.getData('vscode-editor-data')
const vscodeData = vscode
? JSON.parse(vscode)
: undefined
const language = vscodeData.mode
if (!text || !language) {
return false
}
const { tr } = view.state
// create an empty code block
tr.replaceSelectionWith(this.type.create({ language }))
// put cursor inside the newly created code block
tr.setSelection(TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))))
// add text to code block
tr.insertText(text)
view.dispatch(tr)
return true
},
},
}),
]
},
})