tiptap/packages/extension-highlight/index.ts

89 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-10-02 21:28:00 +08:00
import {
Command, createMark, markInputRule, markPasteRule,
2020-10-02 21:28:00 +08:00
} from '@tiptap/core'
export interface HighlightOptions {
color: string,
2020-10-02 21:28:00 +08:00
}
export const inputRegex = /(?:^|\s)((?:==)((?:[^~]+))(?:==))$/gm
export const pasteRegex = /(?:^|\s)((?:==)((?:[^~]+))(?:==))/gm
const Highlight = createMark({
name: 'highlight',
addAttributes() {
return {
2020-10-03 03:39:16 +08:00
color: {
default: null,
parseHTML: element => {
2020-10-03 03:39:16 +08:00
return {
color:
element.getAttribute('data-color')
|| element.style.backgroundColor,
}
},
renderHTML: attributes => {
if (!attributes.color) {
return {}
}
return {
'data-color': attributes.color,
style: `background-color: ${attributes.color}`,
2020-10-03 03:39:16 +08:00
}
},
2020-10-02 21:28:00 +08:00
},
}
},
parseHTML() {
return [
{
tag: 'mark',
},
{
style: 'background-color',
},
]
},
renderHTML({ attributes }) {
return ['mark', attributes, 0]
},
addCommands() {
return {
highlight: (attrs?: HighlightOptions): Command => ({ commands }) => {
return commands.toggleMark('highlight', attrs)
},
}
},
addKeyboardShortcuts() {
return {
'Mod-e': () => this.editor.highlight(),
}
},
addInputRules() {
return [
markInputRule(inputRegex, this.type),
]
},
addPasteRules() {
return [
markPasteRule(inputRegex, this.type),
]
},
})
export default Highlight
declare module '@tiptap/core/src/Editor' {
interface AllExtensions {
Highlight: typeof Highlight,
}
}