Skip to content

Instantly share code, notes, and snippets.

@hanspagel
Created February 3, 2021 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanspagel/7e81b5f31cf8ce036b249cc41e89f741 to your computer and use it in GitHub Desktop.
Save hanspagel/7e81b5f31cf8ce036b249cc41e89f741 to your computer and use it in GitHub Desktop.
Placeholder.js
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