2020-11-16 06:25:25 +08:00
|
|
|
import { Extension } from '@tiptap/core'
|
2020-11-10 16:21:47 +08:00
|
|
|
import { Plugin, PluginKey } from 'prosemirror-state'
|
2020-08-21 23:32:47 +08:00
|
|
|
import { DecorationSet, Decoration } from 'prosemirror-view'
|
|
|
|
|
2020-09-10 00:55:19 +08:00
|
|
|
export interface FocusOptions {
|
2020-08-22 02:33:57 +08:00
|
|
|
className: string,
|
|
|
|
nested: boolean,
|
|
|
|
}
|
|
|
|
|
2020-11-16 06:25:25 +08:00
|
|
|
const FocusClasses = Extension.create({
|
2020-10-22 18:34:49 +08:00
|
|
|
defaultOptions: <FocusOptions>{
|
2020-09-09 05:44:45 +08:00
|
|
|
className: 'has-focus',
|
|
|
|
nested: false,
|
2020-10-22 18:34:49 +08:00
|
|
|
},
|
|
|
|
|
|
|
|
addProseMirrorPlugins() {
|
|
|
|
return [
|
|
|
|
new Plugin({
|
2020-11-10 16:21:47 +08:00
|
|
|
key: new PluginKey('focus'),
|
2020-10-22 18:34:49 +08:00
|
|
|
props: {
|
|
|
|
decorations: ({ doc, selection }) => {
|
|
|
|
const { isEditable, isFocused } = this.editor
|
|
|
|
const { anchor } = selection
|
|
|
|
const decorations: Decoration[] = []
|
|
|
|
|
|
|
|
if (!isEditable || !isFocused) {
|
|
|
|
return DecorationSet.create(doc, [])
|
2020-08-21 23:32:47 +08:00
|
|
|
}
|
|
|
|
|
2020-10-22 18:34:49 +08:00
|
|
|
doc.descendants((node, pos) => {
|
|
|
|
const hasAnchor = anchor >= pos && anchor <= (pos + node.nodeSize)
|
|
|
|
|
|
|
|
if (hasAnchor && !node.isText) {
|
|
|
|
const decoration = Decoration.node(pos, pos + node.nodeSize, {
|
|
|
|
class: this.options.className,
|
|
|
|
})
|
|
|
|
decorations.push(decoration)
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.options.nested
|
|
|
|
})
|
2020-08-21 23:32:47 +08:00
|
|
|
|
2020-10-22 18:34:49 +08:00
|
|
|
return DecorationSet.create(doc, decorations)
|
|
|
|
},
|
2020-08-21 23:32:47 +08:00
|
|
|
},
|
2020-10-22 18:34:49 +08:00
|
|
|
}),
|
|
|
|
]
|
|
|
|
},
|
|
|
|
})
|
2020-10-23 04:40:40 +08:00
|
|
|
|
2020-10-23 17:24:27 +08:00
|
|
|
export default FocusClasses
|
2020-10-23 04:40:40 +08:00
|
|
|
|
2020-11-11 04:18:22 +08:00
|
|
|
declare module '@tiptap/core' {
|
2020-10-23 04:40:40 +08:00
|
|
|
interface AllExtensions {
|
2020-10-23 17:24:27 +08:00
|
|
|
FocusClasses: typeof FocusClasses,
|
2020-10-23 04:40:40 +08:00
|
|
|
}
|
|
|
|
}
|