Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prosemirror example: replacing form textareas
import { EditorState } from 'prosemirror-state'
import { EditorView } from 'prosemirror-view'
import {
defaultMarkdownParser,
defaultMarkdownSerializer,
schema,
} from 'prosemirror-markdown'
import { exampleSetup } from 'prosemirror-example-setup'
import 'prosemirror-view/style/prosemirror.css'
import 'prosemirror-menu/style/menu.css'
import './prosemirror.scss'
// Setup Prosemirror as WYSIWYG editor
// This will hide and replace every textarea with "prosemirror" class
// by an editor. Changes are sync in background between editors and textareas.
function initWysiwyEditors() {
// Loop over every textareas to replace with dynamic editor
for (const area of document.querySelectorAll('textarea.prosemirror')) {
// Hide textarea
area.style.display = 'none'
// Create container zone
const container = document.createElement('div')
container.classList = area.classList
if (area.nextSibling) {
area.parentElement.insertBefore(container, area.nextSibling)
} else {
area.parentElement.appendChild(container)
}
// Load editor view
const view = new EditorView(container, {
// Set initial state
state: EditorState.create({
doc: defaultMarkdownParser.parse(area.value),
plugins: exampleSetup({ schema }),
}),
dispatchTransaction(tr) {
const { state } = view.state.applyTransaction(tr)
view.updateState(state)
// Update textarea only if content has changed
if (tr.docChanged) {
area.value = defaultMarkdownSerializer.serialize(tr.doc)
}
},
})
}
}
document.addEventListener('DOMContentLoaded', initWysiwyEditors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment