Skip to content

Instantly share code, notes, and snippets.

@JSoon
Forked from amk221/placeholder.css
Created February 14, 2025 06:34
Show Gist options
  • Select an option

  • Save JSoon/bcbffb68c8666cb4e23e226600664795 to your computer and use it in GitHub Desktop.

Select an option

Save JSoon/bcbffb68c8666cb4e23e226600664795 to your computer and use it in GitHub Desktop.
Prosemirror placeholder plugin approach
/**
* 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
}
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