tiptap/packages/extension-focus/src/focus.ts

86 lines
2.2 KiB
TypeScript
Raw Normal View History

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,
2021-02-06 01:13:51 +08:00
mode: 'all' | 'deepest' | 'shallowest',
2020-08-22 02:33:57 +08:00
}
2021-02-11 01:25:08 +08:00
export const FocusClasses = Extension.create<FocusOptions>({
2020-12-02 16:44:46 +08:00
name: 'focus',
2021-02-11 01:25:08 +08:00
defaultOptions: {
2020-09-09 05:44:45 +08:00
className: 'has-focus',
2021-02-06 01:13:51 +08:00
mode: 'all',
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
}
// Maximum Levels
let maxLevels = 0
2021-02-06 01:13:51 +08:00
if (this.options.mode === 'deepest') {
doc.descendants((node, pos) => {
if (node.isText) {
return
}
const isCurrent = anchor >= pos && anchor <= (pos + node.nodeSize - 1)
if (!isCurrent) {
return false
}
maxLevels += 1
})
}
// Loop through current
let currentLevel = 0
2020-10-22 18:34:49 +08:00
doc.descendants((node, pos) => {
if (node.isText) {
return false
}
const isCurrent = anchor >= pos && anchor <= (pos + node.nodeSize - 1)
if (!isCurrent) {
return false
}
currentLevel += 1
2021-02-06 01:13:51 +08:00
const outOfScope = (this.options.mode === 'deepest' && maxLevels - currentLevel > 0)
|| (this.options.mode === 'shallowest' && currentLevel > 1)
2021-02-05 19:12:16 +08:00
if (outOfScope) {
2021-02-06 01:13:51 +08:00
return this.options.mode === 'deepest'
2020-10-22 18:34:49 +08:00
}
decorations.push(Decoration.node(pos, pos + node.nodeSize, {
class: this.options.className,
}))
2020-10-22 18:34:49 +08:00
})
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
}),
]
},
})