add focus extension

This commit is contained in:
Philipp Kühn
2019-07-31 10:10:40 +02:00
parent ae33e76feb
commit c991e1f017
5 changed files with 161 additions and 0 deletions

View File

@@ -0,0 +1,53 @@
import { Extension, Plugin } from 'tiptap'
import { DecorationSet, Decoration } from 'prosemirror-view'
export default class Focus extends Extension {
get name() {
return 'focus'
}
get defaultOptions() {
return {
className: 'has-focus',
nested: false,
}
}
get plugins() {
return [
new Plugin({
props: {
decorations: ({ doc, plugins, selection }) => {
const editablePlugin = plugins.find(plugin => plugin.key.startsWith('editable$'))
const editable = editablePlugin.props.editable()
const active = editable && this.options.className
const { focused } = this.editor
const { anchor } = selection
const decorations = []
if (!active || !focused) {
return false
}
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
})
return DecorationSet.create(doc, decorations)
},
},
}),
]
}
}

View File

@@ -24,6 +24,7 @@ export { default as Strike } from './marks/Strike'
export { default as Underline } from './marks/Underline'
export { default as Collaboration } from './extensions/Collaboration'
export { default as Focus } from './extensions/Focus'
export { default as History } from './extensions/History'
export { default as Placeholder } from './extensions/Placeholder'
export { default as Search } from './extensions/Search'