GrapesJS component prevent newlines creating DIV textnode
Prevent CR creating DIVS when editing. See discussion https://github.com/artf/grapesjs/issues/761
by Andy Bulka
HTML
<script src="https://unpkg.com/grapesjs"></script>
<link rel="stylesheet" href="https://unpkg.com/grapesjs/dist/css/grapes.min.css">
<script src="https://unpkg.com/grapesjs-blocks-basic"></script>
<div id="gjs">
<div data-mytext="MyText">howdy doody <div>sub-div</div> </div>
</div>
CSS
body, html {
margin: 0;
height: 100%;
}
Babel + JSX
const compType = 'text3'
const text3Plugin = editor => {
editor.DomComponents.addType(compType, {
extend: "text",
isComponent: function (el) {
if (el.tagName === 'DIV' && el.getAttribute('data-mytext') === 'MyText') {
const contentTexts = []
Array.from(el.childNodes).forEach((node) => {
if (node.textContent !== '') {
contentTexts.push(node.textContent)
}
})
const content = contentTexts.join('<br/>')
return { type: compType, name: 'MyText', content: content, components: [] }
}
},
model: {
defaults: {
tagName: 'div',
},
},
})
editor.BlockManager.add(compType, {
label: compType,
category: 'Extra',
content: '<div data-mytext="MyText">HI THERE <div>sub-div</div> </div>',
});
}
const editor = grapesjs.init({
container: '#gjs',
fromElement: 1,
height: '100%',
storageManager: { type: 0 },
style: '.expand {color: green; vertical-align: top; width: 100%; height: 100%;}',
plugins: ['gjs-blocks-basic', text3Plugin]
});
// Prevent DIVs whilst editing.
var iframeBody = editor.Canvas.getBody();
iframeBody.addEventListener("keydown", (e) => {
if (e.keyCode === 13 && e.target.getAttribute('contenteditable') && e.target.getAttribute('data-gjs-type') == compType) {
e.preventDefault();
// insert 2 br tags (if only one br tag is inserted the cursor won't go to the next line)
e.target.ownerDocument.execCommand("insertHTML", false, "<br><br>");
// prevent the default behaviour of return key pressed
return false;
}
});