I want to provide a visual editor to an HTML snippet that is currently edited using a simple <textarea>
field.
I am trying to learn GrapesJs to achieve this, but I can't grasp the idea. As far as I understood GrapesJs is rendered into the specified <div>
, possibly taking the same <div>
contents as it's initial template to edit, and then I guess it modifies the DOM or stores its work in browser storage.
If I understand it correctly I still can't get how to change this behaviour to deal with my <textarea>
situation. I need the editor to take the <textarea>
contents as its initial template and eventually put the modified HTML snippet back into it as text (?). So we don't need to store our DOM anywhere or send the HTML to server. The form in which this <textarea>
is will be responsible to put it to the backend.
This also makes me wonder how GrapesJs can be separated from the form on which the <textarea>
is placed, which may have its own styles and code.
And what will Grapes do to the styles and javascripts of the page being edited? Will they be the part of the text that GrapesJs will produce?...
I will appreciate a small code example that will open up a GrapesJs visual editor that will take and store its work to/from a <textarea>
I can create two <textarea>
s for html and styles if it is unavoidabe
(I find the docs confusing for my level of knowledge in terms of logical separation of the editor itself and the page that we are editing, I currently fail to get my head around these notions in the docs)
I think in this case you can hook into component
events like add, update, remove to update your textareas.
In the following example I'm doing so Codepen
const editor = grapesjs.init({
height: '100%',
container: '#gjs',
showOffsets: true,
fromElement: true,
noticeOnUnload: false,
storageManager: false,
plugins: ['grapesjs-preset-webpage'],
});
const htmlTextarea = document.getElementById('html')
const cssTextarea = document.getElementById('css')
const updateTextarea = (component, editor)=>{
const e = component.em.get("Editor");
htmlTextarea.value= e.getHtml();
cssTextarea.value= e.getCss();
}
editor.on('component:add', updateTextarea);
editor.on('component:update', updateTextarea);
editor.on('component:remove', updateTextarea);
const updateInstance = () => {
editor.setComponents(htmlTextarea.value)
editor.setStyle(cssTextarea.value)
}
document.getElementById('save').onclick=updateInstance;