tiptap/packages/extension-focus/index.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-08-21 23:32:47 +08:00
import { Extension } from '@tiptap/core'
import { Plugin } from 'prosemirror-state'
import { DecorationSet, Decoration } from 'prosemirror-view'
2020-08-22 03:01:41 +08:00
interface FocusOptions {
2020-08-22 02:33:57 +08:00
className: string,
nested: boolean,
}
2020-09-09 05:44:45 +08:00
export default new Extension<FocusOptions>()
.name('focus')
.defaults({
className: 'has-focus',
nested: false,
})
.plugins(({ editor, options }) => [
new Plugin({
props: {
decorations: ({ doc, selection }) => {
const { isEditable, isFocused } = editor
const { anchor } = selection
const decorations: Decoration[] = []
if (!isEditable || !isFocused) {
return
}
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: options.className,
})
decorations.push(decoration)
2020-08-21 23:32:47 +08:00
}
2020-09-09 05:44:45 +08:00
return options.nested
})
2020-08-21 23:32:47 +08:00
2020-09-09 05:44:45 +08:00
return DecorationSet.create(doc, decorations)
2020-08-21 23:32:47 +08:00
},
2020-09-09 05:44:45 +08:00
},
}),
])
.create()