mirror of
https://github.com/ueberdosis/tiptap.git
synced 2025-06-07 09:25:29 +08:00
fix: add support for pasted content from VS Code, fix #2022
This commit is contained in:
parent
7aef884612
commit
0e0b0b6a8c
@ -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",
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
// don’t 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
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
},
|
||||
})
|
||||
|
Loading…
Reference in New Issue
Block a user