Skip to content

Instantly share code, notes, and snippets.

@mbrehin
Created January 26, 2018 08:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbrehin/05c0d41a7e50eef7f95711e237502c85 to your computer and use it in GitHub Desktop.
Save mbrehin/05c0d41a7e50eef7f95711e237502c85 to your computer and use it in GitHub Desktop.
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