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

96 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-10-02 21:28:00 +08:00
import {
2020-11-06 20:42:40 +08:00
Command,
2020-11-16 06:25:25 +08:00
MarkExtension,
2020-11-06 20:42:40 +08:00
markInputRule,
markPasteRule,
2020-10-02 21:28:00 +08:00
} from '@tiptap/core'
2020-11-13 23:44:22 +08:00
export interface HighlightOptions {
HTMLAttributes: {
[key: string]: any
},
}
export const inputRegex = /(?:^|\s)((?:==)((?:[^~]+))(?:==))$/gm
export const pasteRegex = /(?:^|\s)((?:==)((?:[^~]+))(?:==))/gm
2020-11-16 06:25:25 +08:00
const Highlight = MarkExtension.create({
name: 'highlight',
2020-11-13 23:44:22 +08:00
defaultOptions: <HighlightOptions>{
HTMLAttributes: {},
},
addAttributes() {
return {
2020-10-03 03:39:16 +08:00
color: {
default: null,
parseHTML: element => {
2020-10-03 03:39:16 +08:00
return {
2020-11-06 20:42:40 +08:00
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',
},
]
},
2020-11-13 23:07:20 +08:00
renderHTML({ HTMLAttributes }) {
return ['mark', HTMLAttributes, 0]
},
addCommands() {
return {
2020-11-13 22:08:30 +08:00
/**
* Toggle a highlight mark
*/
2020-11-06 07:13:18 +08:00
highlight: (attributes?: { color: string }): Command => ({ commands }) => {
return commands.toggleMark('highlight', attributes)
},
}
},
addKeyboardShortcuts() {
return {
'Mod-e': () => this.editor.commands.highlight(),
}
},
addInputRules() {
return [
markInputRule(inputRegex, this.type),
]
},
addPasteRules() {
return [
markPasteRule(inputRegex, this.type),
]
},
})
export default Highlight
2020-11-11 04:18:22 +08:00
declare module '@tiptap/core' {
interface AllExtensions {
Highlight: typeof Highlight,
}
}