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

84 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-09-24 06:29:05 +08:00
import {
2020-11-13 23:44:22 +08:00
Command,
2020-11-16 06:25:25 +08:00
MarkExtension,
2020-11-13 23:44:22 +08:00
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 ItalicOptions {
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
2020-11-16 06:25:25 +08:00
const Italic = MarkExtension.create({
2020-10-22 18:34:49 +08:00
name: 'italic',
2020-11-13 23:44:22 +08:00
defaultOptions: <ItalicOptions>{
HTMLAttributes: {},
},
2020-10-22 18:34:49 +08:00
parseHTML() {
return [
2020-10-08 09:57:45 +08:00
{
tag: 'em',
},
{
tag: 'i',
getAttrs: node => (node as HTMLElement).style.fontStyle !== 'normal' && null,
},
{
style: 'font-style=italic',
},
2020-10-22 18:34:49 +08:00
]
},
2020-11-13 23:07:20 +08:00
renderHTML({ HTMLAttributes }) {
return ['em', HTMLAttributes, 0]
2020-10-22 18:34:49 +08:00
},
addCommands() {
return {
2020-11-13 22:08:30 +08:00
/**
* Toggle an italic mark
*/
2020-10-23 04:40:40 +08:00
italic: (): Command => ({ commands }) => {
2020-10-22 18:34:49 +08:00
return commands.toggleMark('italic')
},
}
},
addKeyboardShortcuts() {
return {
'Mod-i': () => this.editor.commands.italic(),
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 Italic
2020-11-11 04:18:22 +08:00
declare module '@tiptap/core' {
2020-10-23 04:40:40 +08:00
interface AllExtensions {
Italic: typeof Italic,
}
}