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

84 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-09-24 06:29:05 +08:00
import {
Command, Mark, markInputRule, markPasteRule,
2020-09-24 06:29:05 +08:00
} from '@tiptap/core'
2020-09-22 05:17:30 +08:00
2020-11-13 23:44:22 +08:00
export interface BoldOptions {
HTMLAttributes: {
[key: string]: any
},
}
2020-09-24 06:37:31 +08:00
export const starInputRegex = /(?:^|\s)((?:\*\*)((?:[^*]+))(?:\*\*))$/gm
export const starPasteRegex = /(?:^|\s)((?:\*\*)((?:[^*]+))(?:\*\*))/gm
2020-09-10 00:47:47 +08:00
export const underscoreInputRegex = /(?:^|\s)((?:__)((?:[^__]+))(?:__))$/gm
export const underscorePasteRegex = /(?:^|\s)((?:__)((?:[^__]+))(?:__))/gm
const Bold = Mark.create({
2020-10-22 18:34:49 +08:00
name: 'bold',
2020-11-13 23:44:22 +08:00
defaultOptions: <BoldOptions>{
HTMLAttributes: {},
},
2020-10-22 18:34:49 +08:00
parseHTML() {
return [
2020-09-09 05:44:45 +08:00
{
tag: 'strong',
2020-04-02 20:34:07 +08:00
},
2020-09-09 05:44:45 +08:00
{
tag: 'b',
getAttrs: node => (node as HTMLElement).style.fontWeight !== 'normal' && null,
},
{
style: 'font-weight',
getAttrs: value => /^(bold(er)?|[5-9]\d{2,})$/.test(value as string) && null,
},
2020-10-22 18:34:49 +08:00
]
},
2020-11-13 23:07:20 +08:00
renderHTML({ HTMLAttributes }) {
return ['strong', HTMLAttributes, 0]
2020-10-22 18:34:49 +08:00
},
addCommands() {
return {
2020-10-23 04:40:40 +08:00
/**
2020-11-13 22:08:30 +08:00
* Toggle a bold mark
2020-10-23 04:40:40 +08:00
*/
bold: (): Command => ({ commands }) => {
2020-10-22 18:34:49 +08:00
return commands.toggleMark('bold')
},
}
},
addKeyboardShortcuts() {
return {
'Mod-b': () => this.editor.commands.bold(),
2020-10-22 18:34:49 +08:00
}
},
addInputRules() {
return [
markInputRule(starInputRegex, this.type),
markInputRule(underscoreInputRegex, this.type),
]
},
addPasteRules() {
return [
markPasteRule(starPasteRegex, this.type),
markPasteRule(underscorePasteRegex, this.type),
]
},
})
2020-10-23 04:40:40 +08:00
export default Bold
2020-11-16 22:40:05 +08:00
declare global {
namespace Tiptap {
interface AllExtensions {
Bold: typeof Bold,
}
2020-10-23 04:40:40 +08:00
}
}