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,
2020-11-13 23:44:22 +08:00
HTMLAttributes: {
[key: string]: any
},
}
2021-02-10 16:59:35 +08:00
declare module '@tiptap/core' {
interface Commands {
2021-02-11 01:05:02 +08:00
/**
* Set a highlight mark
*/
2021-02-10 16:59:35 +08:00
setHighlight: (attributes?: { color: string }) => Command,
2021-02-11 01:05:02 +08:00
/**
* Toggle a highlight mark
*/
2021-02-10 16:59:35 +08:00
toggleHighlight: (attributes?: { color: string }) => Command,
2021-02-11 01:05:02 +08:00
/**
* Unset a highlight mark
*/
2021-02-10 16:59:35 +08:00
unsetHighlight: () => Command,
}
}
export const inputRegex = /(?:^|\s)((?:==)((?:[^~]+))(?:==))$/gm
export const pasteRegex = /(?:^|\s)((?:==)((?:[^~]+))(?:==))/gm
2020-12-08 04:32:50 +08:00
export const Highlight = Mark.create({
name: 'highlight',
2020-11-13 23:44:22 +08:00
defaultOptions: <HighlightOptions>{
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),
]
},
})