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

115 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-10-02 21:28:00 +08:00
import {
2020-11-06 20:42:40 +08:00
Command,
Mark,
2020-11-06 20:42:40 +08:00
markInputRule,
markPasteRule,
2020-11-25 16:50:54 +08:00
mergeAttributes,
2020-10-02 21:28:00 +08:00
} from '@tiptap/core'
2020-11-13 23:44:22 +08:00
export interface HighlightOptions {
2020-12-04 06:32:11 +08:00
multicolor: boolean,
2021-04-21 15:43:31 +08:00
HTMLAttributes: Record<string, any>,
2020-11-13 23:44:22 +08:00
}
2021-02-10 16:59:35 +08:00
declare module '@tiptap/core' {
2021-02-17 01:39:37 +08:00
interface Commands {
2021-02-16 18:27:58 +08:00
highlight: {
/**
* Set a highlight mark
*/
setHighlight: (attributes?: { color: string }) => Command,
/**
* Toggle a highlight mark
*/
toggleHighlight: (attributes?: { color: string }) => Command,
/**
* Unset a highlight mark
*/
unsetHighlight: () => Command,
}
2021-02-10 16:59:35 +08:00
}
}
export const inputRegex = /(?:^|\s)((?:==)((?:[^~]+))(?:==))$/gm
export const pasteRegex = /(?:^|\s)((?:==)((?:[^~]+))(?:==))/gm
2021-02-11 01:25:08 +08:00
export const Highlight = Mark.create<HighlightOptions>({
name: 'highlight',
2021-02-11 01:25:08 +08:00
defaultOptions: {
2020-12-04 06:32:11 +08:00
multicolor: false,
2020-11-13 23:44:22 +08:00
HTMLAttributes: {},
},
addAttributes() {
2020-12-04 06:32:11 +08:00
if (!this.options.multicolor) {
return {}
}
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 }) {
2020-11-25 16:50:54 +08:00
return ['mark', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]
},
addCommands() {
return {
2021-02-10 16:59:35 +08:00
setHighlight: attributes => ({ commands }) => {
2020-11-19 00:36:00 +08:00
return commands.setMark('highlight', attributes)
2020-11-18 04:59:04 +08:00
},
2021-02-10 16:59:35 +08:00
toggleHighlight: attributes => ({ commands }) => {
2020-11-06 07:13:18 +08:00
return commands.toggleMark('highlight', attributes)
},
2021-02-10 16:59:35 +08:00
unsetHighlight: () => ({ commands }) => {
2020-11-19 00:38:16 +08:00
return commands.unsetMark('highlight')
2020-11-18 04:59:04 +08:00
},
}
},
addKeyboardShortcuts() {
return {
2020-11-19 08:16:10 +08:00
'Mod-Shift-h': () => this.editor.commands.toggleHighlight(),
}
},
addInputRules() {
return [
markInputRule(inputRegex, this.type),
]
},
addPasteRules() {
return [
markPasteRule(inputRegex, this.type),
]
},
})