2021-01-20 01:01:25 +08:00
|
|
|
import { Extension } from '@tiptap/core'
|
2021-01-26 06:40:15 +08:00
|
|
|
import { Plugin, PluginKey } from 'prosemirror-state'
|
2021-01-20 01:01:25 +08:00
|
|
|
|
2021-01-25 18:44:22 +08:00
|
|
|
export const pluginKey = new PluginKey('characterLimit')
|
|
|
|
|
2021-01-26 06:40:15 +08:00
|
|
|
export interface CharacterCountOptions {
|
|
|
|
limit?: number,
|
2021-01-20 01:01:25 +08:00
|
|
|
}
|
|
|
|
|
2021-01-26 06:40:15 +08:00
|
|
|
export const CharacterCount = Extension.create({
|
|
|
|
name: 'characterCount',
|
2021-01-20 01:01:25 +08:00
|
|
|
|
2021-01-26 06:40:15 +08:00
|
|
|
defaultOptions: <CharacterCountOptions>{
|
|
|
|
limit: 0,
|
2021-01-20 01:01:25 +08:00
|
|
|
},
|
|
|
|
|
|
|
|
addProseMirrorPlugins() {
|
|
|
|
const { options } = this
|
|
|
|
|
|
|
|
return [
|
|
|
|
new Plugin({
|
|
|
|
|
2021-01-25 18:44:22 +08:00
|
|
|
key: pluginKey,
|
2021-01-20 01:01:25 +08:00
|
|
|
|
|
|
|
appendTransaction: (transactions, oldState, newState) => {
|
2021-01-25 18:44:22 +08:00
|
|
|
const length = newState.doc.content.size
|
2021-01-20 01:01:25 +08:00
|
|
|
|
2021-01-26 06:40:15 +08:00
|
|
|
if (options.limit && length > options.limit) {
|
2021-01-25 18:44:22 +08:00
|
|
|
return newState.tr.insertText('', options.limit + 1, length)
|
2021-01-20 01:01:25 +08:00
|
|
|
}
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
]
|
|
|
|
},
|
|
|
|
})
|