tiptap/packages/extension-heading/index.ts

52 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-09-22 05:17:30 +08:00
import { Command, Node } from '@tiptap/core'
2020-04-22 04:48:27 +08:00
import { textblockTypeInputRule } from 'prosemirror-inputrules'
2020-04-22 04:16:26 +08:00
type Level = 1 | 2 | 3 | 4 | 5 | 6
2020-09-10 00:55:19 +08:00
export interface HeadingOptions {
2020-08-22 03:01:41 +08:00
levels: Level[],
2020-04-22 04:16:26 +08:00
}
2020-09-22 05:17:30 +08:00
export type HeadingCommand = (level: Level) => Command
2020-04-22 04:16:26 +08:00
declare module '@tiptap/core/src/Editor' {
2020-09-22 16:49:38 +08:00
interface Commands {
2020-09-22 05:17:30 +08:00
heading: HeadingCommand,
2020-04-22 04:16:26 +08:00
}
}
2020-09-09 05:44:45 +08:00
export default new Node<HeadingOptions>()
.name('heading')
.defaults({
levels: [1, 2, 3, 4, 5, 6],
})
.schema(({ options }) => ({
attrs: {
level: {
default: 1,
2020-04-22 04:36:31 +08:00
},
2020-09-09 05:44:45 +08:00
},
content: 'inline*',
group: 'block',
defining: true,
draggable: false,
parseDOM: options.levels
.map((level: Level) => ({
tag: `h${level}`,
attrs: { level },
})),
toDOM: node => [`h${node.attrs.level}`, 0],
}))
2020-09-22 05:17:30 +08:00
.commands(({ name }) => ({
[name]: attrs => ({ commands }) => {
return commands.toggleNode(name, 'paragraph', attrs)
2020-09-09 05:44:45 +08:00
},
}))
2020-09-15 22:44:20 +08:00
// TODO: Keyboard Shortcuts
2020-09-10 00:07:17 +08:00
.inputRules(({ options, type }) => {
return options.levels.map((level: Level) => {
2020-09-10 02:29:50 +08:00
return textblockTypeInputRule(new RegExp(`^(#{1,${level}})\\s$`), type, { level })
2020-09-10 00:07:17 +08:00
})
})
2020-09-09 05:44:45 +08:00
.create()