-
-
Save JSoon/bcbffb68c8666cb4e23e226600664795 to your computer and use it in GitHub Desktop.
Prosemirror placeholder plugin approach
This file contains hidden or 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
| /** | |
| * Pseudo content is used, positioned absolutely. Because otherwise, when clicking into the editor, | |
| * the cursor would be placed at the _end_ of the placeholder text, and then flicker to the beginning | |
| * as prosemirror moves the decoration to the correct side. | |
| */ | |
| .ProseMirror__placeholder { | |
| color: grey; | |
| } | |
| .ProseMirror__placeholder::after { | |
| position: absolute; | |
| content: attr(data-placeholder); | |
| pointer-events: none | |
| } |
This file contains hidden or 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 { Plugin } from 'prosemirror-state'; | |
| import { Decoration, DecorationSet } from 'prosemirror-view'; | |
| /** | |
| * Placeholder plugin for prosemirror that supports documents with an inline, or a block schema. | |
| */ | |
| export default function placeholderPlugin(text) { | |
| return new Plugin({ | |
| props: { | |
| decorations(state) { | |
| const doc = state.doc; | |
| const hasNoChildren = doc.childCount === 0; | |
| const isEmptyTextBlock = | |
| doc.childCount === 1 && doc.firstChild.isTextblock && doc.firstChild.content.size === 0; | |
| if (hasNoChildren || isEmptyTextBlock) { | |
| const position = doc.inlineContent ? 0 : 1; | |
| const placeholder = document.createElement('span'); | |
| placeholder.classList.add('ProseMirror__placeholder'); | |
| placeholder.setAttribute('data-placeholder', text); | |
| return DecorationSet.create(doc, [Decoration.widget(position, placeholder)]); | |
| } | |
| } | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment