Created
January 26, 2018 08:59
-
-
Save mbrehin/05c0d41a7e50eef7f95711e237502c85 to your computer and use it in GitHub Desktop.
Prosemirror example: replacing form textareas
This file contains 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 { 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