Created
February 3, 2021 10:09
-
-
Save hanspagel/7e81b5f31cf8ce036b249cc41e89f741 to your computer and use it in GitHub Desktop.
Placeholder.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Extension } from '@tiptap/core' | |
import { Decoration, DecorationSet } from 'prosemirror-view' | |
import { Plugin } from 'prosemirror-state' | |
export default Extension.create({ | |
name: 'placeholder', | |
defaultOptions: { | |
emptyEditorClass: 'is-editor-empty', | |
emptyNodeClass: 'is-empty', | |
placeholder: 'Write something …', | |
showOnlyWhenEditable: true, | |
showOnlyCurrent: true, | |
}, | |
addProseMirrorPlugins() { | |
return [ | |
new Plugin({ | |
props: { | |
decorations: ({ doc, selection }) => { | |
const active = this.editor.isEditable || !this.options.showOnlyWhenEditable | |
const { anchor } = selection | |
const decorations = [] | |
const isEditorEmpty = doc.textContent.length === 0 | |
if (!active) { | |
return | |
} | |
doc.descendants((node, pos) => { | |
const hasAnchor = anchor >= pos && anchor <= (pos + node.nodeSize) | |
const isNodeEmpty = node.content.size === 0 | |
if ((hasAnchor || !this.options.showOnlyCurrent) && isNodeEmpty) { | |
const classes = [this.options.emptyNodeClass] | |
if (isEditorEmpty) { | |
classes.push(this.options.emptyEditorClass) | |
} | |
const decoration = Decoration.node(pos, pos + node.nodeSize, { | |
class: classes.join(' '), | |
'data-empty-text': typeof this.options.placeholder === 'function' | |
? this.options.placeholder(node) | |
: this.options.placeholder, | |
}) | |
decorations.push(decoration) | |
} | |
return false | |
}) | |
return DecorationSet.create(doc, decorations) | |
}, | |
}, | |
}), | |
] | |
}, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment