tiptap/packages/extension-code-block/index.ts

92 lines
2.0 KiB
TypeScript
Raw Normal View History

2020-10-22 18:34:49 +08:00
import { Command, createNode } from '@tiptap/core'
2020-09-10 21:10:22 +08:00
import { textblockTypeInputRule } from 'prosemirror-inputrules'
export interface CodeBlockOptions {
languageClassPrefix: string,
}
2020-10-22 18:34:49 +08:00
// export type CodeBlockCommand = () => Command
2020-09-22 15:08:08 +08:00
2020-10-22 18:34:49 +08:00
// declare module '@tiptap/core/src/Editor' {
// interface Commands {
// codeBlock: CodeBlockCommand,
// }
// }
2020-04-02 14:53:59 +08:00
export const backtickInputRegex = /^```(?<language>[a-z]*)? $/
export const tildeInputRegex = /^~~~(?<language>[a-z]*)? $/
2020-09-27 02:20:52 +08:00
2020-10-22 18:34:49 +08:00
export default createNode({
name: 'code_block',
defaultOptions: <CodeBlockOptions>{
languageClassPrefix: 'language-',
2020-10-22 18:34:49 +08:00
},
content: 'text*',
marks: '',
group: 'block',
code: true,
defining: true,
addAttributes() {
return {
2020-09-27 02:20:52 +08:00
language: {
default: null,
2020-10-22 18:34:49 +08:00
rendered: false,
2020-09-27 02:20:52 +08:00
},
2020-10-22 18:34:49 +08:00
}
},
parseHTML() {
return [
2020-09-30 22:25:32 +08:00
{
tag: 'pre',
preserveWhitespace: 'full',
2020-10-22 18:34:49 +08:00
getAttrs: node => {
2020-10-01 01:19:51 +08:00
const classAttribute = (node as Element).firstElementChild?.getAttribute('class')
2020-09-30 22:25:32 +08:00
if (!classAttribute) {
return null
}
2020-10-22 18:34:49 +08:00
const regexLanguageClassPrefix = new RegExp(`^(${this.options.languageClassPrefix})`)
return { language: classAttribute.replace(regexLanguageClassPrefix, '') }
2020-09-30 22:25:32 +08:00
},
},
2020-10-22 18:34:49 +08:00
]
},
renderHTML({ node, attributes }) {
return ['pre', attributes, ['code', {
class: node.attrs.language && this.options.languageClassPrefix + node.attrs.language,
}, 0]]
},
addCommands() {
return {
codeBlock: attrs => ({ commands }) => {
return commands.toggleBlockType('code_block', 'paragraph', attrs)
},
}
},
addKeyboardShortcuts() {
return {
'Mod-Shift-c': () => this.editor.codeBlock(),
}
},
addInputRules() {
return [
textblockTypeInputRule(backtickInputRegex, this.type, ({ groups }: any) => groups),
textblockTypeInputRule(tildeInputRegex, this.type, ({ groups }: any) => groups),
]
},
})