tiptap/packages/extension-focus/index.ts

57 lines
1.4 KiB
TypeScript
Raw Normal View History

2020-10-22 18:34:49 +08:00
import { createExtension } from '@tiptap/core'
2020-08-21 23:32:47 +08:00
import { Plugin } from 'prosemirror-state'
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-10-23 17:24:27 +08:00
const FocusClasses = createExtension({
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({
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
declare module '@tiptap/core/src/Editor' {
interface AllExtensions {
2020-10-23 17:24:27 +08:00
FocusClasses: typeof FocusClasses,
2020-10-23 04:40:40 +08:00
}
}