2020-09-22 15:08:08 +08:00
|
|
|
import { Command, Node } from '@tiptap/core'
|
2020-09-10 21:10:22 +08:00
|
|
|
import { textblockTypeInputRule } from 'prosemirror-inputrules'
|
|
|
|
|
2020-09-30 22:33:13 +08:00
|
|
|
export interface CodeBlockOptions {
|
|
|
|
languageClassPrefix: string,
|
|
|
|
}
|
|
|
|
|
2020-09-22 15:08:08 +08:00
|
|
|
export type CodeBlockCommand = () => Command
|
|
|
|
|
2020-09-10 21:10:22 +08:00
|
|
|
declare module '@tiptap/core/src/Editor' {
|
2020-09-22 16:49:38 +08:00
|
|
|
interface Commands {
|
2020-09-22 15:08:08 +08:00
|
|
|
codeBlock: CodeBlockCommand,
|
2020-09-10 21:10:22 +08:00
|
|
|
}
|
|
|
|
}
|
2020-04-02 14:53:59 +08:00
|
|
|
|
2020-09-27 02:20:52 +08:00
|
|
|
export const inputRegex = /^```(?<language>[a-z]*)? $/
|
|
|
|
|
2020-09-30 22:33:13 +08:00
|
|
|
export default new Node<CodeBlockOptions>()
|
2020-09-22 15:08:08 +08:00
|
|
|
.name('code_block')
|
2020-09-30 22:33:13 +08:00
|
|
|
.defaults({
|
|
|
|
languageClassPrefix: 'language-',
|
|
|
|
})
|
|
|
|
.schema(({ options }) => ({
|
2020-09-27 02:20:52 +08:00
|
|
|
attrs: {
|
|
|
|
language: {
|
|
|
|
default: null,
|
|
|
|
},
|
|
|
|
},
|
2020-09-09 05:44:45 +08:00
|
|
|
content: 'text*',
|
|
|
|
marks: '',
|
|
|
|
group: 'block',
|
|
|
|
code: true,
|
|
|
|
defining: true,
|
|
|
|
draggable: false,
|
|
|
|
parseDOM: [
|
2020-09-30 22:25:32 +08:00
|
|
|
{
|
|
|
|
tag: 'pre',
|
|
|
|
preserveWhitespace: 'full',
|
2020-10-01 01:19:51 +08:00
|
|
|
getAttrs(node) {
|
|
|
|
const classAttribute = (node as Element).firstElementChild?.getAttribute('class')
|
2020-09-30 22:25:32 +08:00
|
|
|
|
|
|
|
if (!classAttribute) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
2020-09-30 22:33:13 +08:00
|
|
|
const regexLanguageClassPrefix = new RegExp(`^(${options.languageClassPrefix})`)
|
|
|
|
|
|
|
|
return { language: classAttribute.replace(regexLanguageClassPrefix, '') }
|
2020-09-30 22:25:32 +08:00
|
|
|
},
|
|
|
|
},
|
2020-09-09 05:44:45 +08:00
|
|
|
],
|
2020-10-01 01:19:51 +08:00
|
|
|
toDOM: node => ['pre', ['code', {
|
|
|
|
class: node.attrs.language && options.languageClassPrefix + node.attrs.language,
|
|
|
|
}, 0]],
|
2020-09-09 05:44:45 +08:00
|
|
|
}))
|
2020-09-22 15:08:08 +08:00
|
|
|
.commands(({ name }) => ({
|
|
|
|
codeBlock: attrs => ({ commands }) => {
|
2020-09-25 04:27:17 +08:00
|
|
|
return commands.toggleBlockType(name, 'paragraph', attrs)
|
2020-09-22 15:08:08 +08:00
|
|
|
},
|
|
|
|
}))
|
2020-09-10 21:10:22 +08:00
|
|
|
.keys(({ editor }) => ({
|
2020-09-24 20:46:11 +08:00
|
|
|
'Shift-Control-\\': () => editor.codeBlock(),
|
2020-09-10 21:10:22 +08:00
|
|
|
}))
|
|
|
|
.inputRules(({ type }) => [
|
2020-09-27 02:20:52 +08:00
|
|
|
textblockTypeInputRule(inputRegex, type, ({ groups }: any) => groups),
|
2020-09-10 21:10:22 +08:00
|
|
|
])
|
2020-09-09 05:44:45 +08:00
|
|
|
.create()
|