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

73 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-09-24 06:29:05 +08:00
import {
2020-11-13 23:44:22 +08:00
Command,
2020-11-16 06:25:25 +08:00
MarkExtension,
2020-11-13 23:44:22 +08:00
markInputRule,
markPasteRule,
2020-09-24 06:29:05 +08:00
} from '@tiptap/core'
2020-09-22 15:08:08 +08:00
2020-11-13 23:44:22 +08:00
export interface CodeOptions {
HTMLAttributes: {
[key: string]: any
},
}
2020-09-10 00:47:47 +08:00
export const inputRegex = /(?:^|\s)((?:`)((?:[^`]+))(?:`))$/gm
export const pasteRegex = /(?:^|\s)((?:`)((?:[^`]+))(?:`))/gm
2020-11-16 06:25:25 +08:00
const Code = MarkExtension.create({
2020-10-22 18:34:49 +08:00
name: 'code',
2020-11-13 23:44:22 +08:00
defaultOptions: <CodeOptions>{
HTMLAttributes: {},
},
2020-10-22 18:34:49 +08:00
excludes: '_',
parseHTML() {
return [
2020-09-09 05:44:45 +08:00
{ tag: 'code' },
2020-10-22 18:34:49 +08:00
]
},
2020-11-13 23:07:20 +08:00
renderHTML({ HTMLAttributes }) {
return ['code', HTMLAttributes, 0]
2020-10-22 18:34:49 +08:00
},
addCommands() {
return {
2020-11-13 22:08:30 +08:00
/**
* Toggle inline code
*/
2020-10-23 04:40:40 +08:00
code: (): Command => ({ commands }) => {
2020-10-22 18:34:49 +08:00
return commands.toggleMark('code')
},
}
},
addKeyboardShortcuts() {
return {
'Mod-`': () => this.editor.commands.code(),
2020-10-22 18:34:49 +08:00
}
},
addInputRules() {
return [
markInputRule(inputRegex, this.type),
]
},
addPasteRules() {
return [
markPasteRule(inputRegex, this.type),
]
},
})
2020-10-23 04:40:40 +08:00
export default Code
2020-11-11 04:18:22 +08:00
declare module '@tiptap/core' {
2020-10-23 04:40:40 +08:00
interface AllExtensions {
Code: typeof Code,
}
}