tiptap/packages/extension-strike/src/strike.ts
2021-05-26 16:56:41 +08:00

97 lines
1.8 KiB
TypeScript

import {
Command,
Mark,
markInputRule,
markPasteRule,
mergeAttributes,
} from '@tiptap/core'
export interface StrikeOptions {
HTMLAttributes: Record<string, any>,
}
declare module '@tiptap/core' {
interface Commands {
strike: {
/**
* Set a strike mark
*/
setStrike: () => Command,
/**
* Toggle a strike mark
*/
toggleStrike: () => Command,
/**
* Unset a strike mark
*/
unsetStrike: () => Command,
}
}
}
export const inputRegex = /(?:^|\s)((?:~~)((?:[^~]+))(?:~~))$/gm
export const pasteRegex = /(?:^|\s)((?:~~)((?:[^~]+))(?:~~))/gm
export const Strike = Mark.create<StrikeOptions>({
name: 'strike',
defaultOptions: {
HTMLAttributes: {},
},
parseHTML() {
return [
{
tag: 's',
},
{
tag: 'del',
},
{
tag: 'strike',
},
{
style: 'text-decoration',
consuming: false,
getAttrs: style => ((style as string).includes('line-through') ? {} : false),
},
]
},
renderHTML({ HTMLAttributes }) {
return ['s', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]
},
addCommands() {
return {
setStrike: () => ({ commands }) => {
return commands.setMark('strike')
},
toggleStrike: () => ({ commands }) => {
return commands.toggleMark('strike')
},
unsetStrike: () => ({ commands }) => {
return commands.unsetMark('strike')
},
}
},
addKeyboardShortcuts() {
return {
'Mod-Shift-x': () => this.editor.commands.toggleStrike(),
}
},
addInputRules() {
return [
markInputRule(inputRegex, this.type),
]
},
addPasteRules() {
return [
markPasteRule(pasteRegex, this.type),
]
},
})