2020-04-22 04:16:26 +08:00
|
|
|
import { Node, CommandSpec } from '@tiptap/core'
|
|
|
|
import { NodeSpec } from 'prosemirror-model'
|
2020-04-22 04:48:27 +08:00
|
|
|
import VerEx from 'verbal-expressions'
|
|
|
|
import { textblockTypeInputRule } from 'prosemirror-inputrules'
|
2020-04-22 04:16:26 +08:00
|
|
|
|
|
|
|
type Level = 1 | 2 | 3 | 4 | 5 | 6
|
|
|
|
|
|
|
|
interface HeadingOptions {
|
|
|
|
levels?: Level[],
|
|
|
|
}
|
|
|
|
|
|
|
|
declare module '@tiptap/core/src/Editor' {
|
|
|
|
interface Editor {
|
|
|
|
heading(level: Level): Editor,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default class Heading extends Node {
|
|
|
|
|
|
|
|
name = 'heading'
|
|
|
|
|
|
|
|
defaultOptions(): HeadingOptions {
|
|
|
|
return {
|
|
|
|
levels: [1, 2, 3, 4, 5, 6],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
schema(): NodeSpec {
|
|
|
|
return {
|
|
|
|
attrs: {
|
|
|
|
level: {
|
|
|
|
default: 1,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
content: 'inline*',
|
|
|
|
group: 'block',
|
|
|
|
defining: true,
|
|
|
|
draggable: false,
|
|
|
|
parseDOM: this.options.levels
|
|
|
|
.map((level: Level) => ({
|
|
|
|
tag: `h${level}`,
|
|
|
|
attrs: { level },
|
|
|
|
})),
|
|
|
|
toDOM: node => [`h${node.attrs.level}`, 0],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-22 04:36:31 +08:00
|
|
|
commands(): CommandSpec {
|
|
|
|
return {
|
2020-04-22 05:22:27 +08:00
|
|
|
heading: next => attrs => {
|
2020-04-22 06:09:31 +08:00
|
|
|
this.editor.toggleBlockType(this.name, 'paragraph', attrs)
|
2020-04-22 04:36:31 +08:00
|
|
|
next()
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2020-04-22 04:16:26 +08:00
|
|
|
|
2020-04-22 04:48:27 +08:00
|
|
|
inputRules() {
|
|
|
|
return this.options.levels.map((level: Level) => {
|
|
|
|
const regex = VerEx()
|
|
|
|
.startOfLine()
|
|
|
|
.find('#')
|
|
|
|
.repeatPrevious(level)
|
|
|
|
.whitespace()
|
|
|
|
.endOfLine()
|
|
|
|
|
|
|
|
return textblockTypeInputRule(regex, this.type, { level })
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-04-22 04:16:26 +08:00
|
|
|
}
|