How to refresh/re-render after new node added?
Optimized TextEditor.vue file: But the problem persist:✔️ span node replaces the previous content of selection, with font-family and color styles.❌ span node isn't recognized by GrapesJS, because there isn't GrapesJS auto-generated styles ID and data-gjs-type='text' attribute.❌ getHTML and getJSON to save modification...
Read full answer below ↓Question
I manually add a new node into a rendered component.
The visual result is OK, but impossible to save, because my style isn't with the auto-generated GrapesJS ID.
To manually resolve this poblem, I double-click on the component to enter to it and I click outside in the canvas body. Then, the GrapesJS ID and data-gjs-type='text' are added to the new node, and save is possible.
Vue.js:
A part of Main.vue file:
// Text Editor
// https://grapesjs.com/docs/api/rich_text_editor.html
// https://css-tricks.com/creating-vue-js-component-instances-programmatically/
const editorToolbar = editorRte.getToolbarEl()
const TextEditorClass = Vue.extend(TextEditor)
const textEditor = new TextEditorClass({
propsData: {
editor: this.editor
}
})
textEditor.$mount()
editorToolbar.innerHTML = ''
editorToolbar.appendChild(textEditor.$el)
editorToolbar.classList.replace('gjs-one-bg', 'bg-primary')
A part of TextEditor.vue file:
methods: {
// OK, no problem
onButtonClick (name) {
const { rte } = this.getRteData()
rte.exec(name)
console.log('onButtonClick()', { name, rte })
},
// Problem, no refresh/re-render after spanNode added
onFontValidate () {
const { rte } = this.getRteData()
let anchorNode = {}
this.selection.childNodes.forEach(childNode => {
if (childNode.textContent !== this.selection.anchorText) {
return
}
anchorNode = childNode
})
const spanNode = document.createElement('span')
const range = new Range()
// spanNode.setAttribute('data-gjs-type', 'text')
spanNode.style.fontFamily = 'Courier New'
range.setStart(anchorNode, this.selection.rangeStart)
range.setEnd(anchorNode, this.selection.rangeEnd)
range.surroundContents(spanNode)
// rte.selection().removeAllRanges()
rte.selection().addRange(range)
// this.editor.runCommand('core:component-exit')
console.log('onFontValidate()', {
rte,
range,
selected: this.editor.getSelected()
})
},
onMenuShow () {
const {
rte,
selection,
anchorNode
} = this.getRteData()
// https://developer.mozilla.org/en-US/docs/Web/API/Selection
// https://javascript.info/selection-range#selecting-parts-of-text-nodes
this.selection.childNodes = rte.el.childNodes
this.selection.anchorText = anchorNode.textContent
this.selection.rangeStart = selection.anchorOffset
this.selection.rangeEnd = selection.focusOffset
console.log('onMenuShow()', {
childNodes: this.selection.childNodes,
anchorText: this.selection.anchorText,
rangeStart: this.selection.rangeStart,
rangeEnd: this.selection.rangeEnd
})
},
getRteData () {
const selected = this.editor.getSelected()
const rte = selected.view.activeRte
const selection = rte.selection()
const anchorNode = selection.anchorNode
return {
rte,
selection,
anchorNode
}
}
}
Answers (3)
Optimized TextEditor.vue file:
// ...
onFontValidate () {
const { rte } = this.getRteData()
const spanNode = document.createElement('span')
let anchorNode = {}
this.selection.childNodes.forEach(childNode => {
console.log({ childNode })
if (childNode.textContent !== this.selection.anchorText) {
return
}
anchorNode = childNode
})
rte.selection().setBaseAndExtent(
anchorNode, this.selection.rangeStart,
anchorNode, this.selection.rangeEnd
)
spanNode.style.fontFamily = 'Courier New'
spanNode.style.color = 'red'
spanNode.innerText = rte.selection().getRangeAt(0).toString()
rte.insertHTML(spanNode.outerHTML)
console.log('onFontValidate()', {
rte,
anchorNode,
spanNode
})
// const range = new Range()
// range.setStart(anchorNode, this.selection.rangeStart)
// range.setEnd(anchorNode, this.selection.rangeEnd)
// range.surroundContents(spanNode)
// rte.selection().removeAllRanges()
// rte.selection().addRange(range)
}
// ....
But the problem persist:
- ✔️
spannode replaces the previous content of selection, withfont-familyandcolorstyles. - ❌
spannode isn't recognized by GrapesJS, because there isn't GrapesJS auto-generated styles ID anddata-gjs-type='text'attribute. - ❌
getHTMLandgetJSONto save modifications doesn't includespannode styles.
To resolve manually this problem:
- After
spannode is added with its styles, double-click on the current selected GrapesJS component. - Click on the iframe
canvasbody. - Double-click on the previously selected GrapesJS component.
spannode is officially added to GrapesJS, with an auto-generated styles ID anddata-gjs-type='text'attribute.
ℹ️ Don't works directly with HTML, works only with JSON.
Component = JSON node (html element + GrapesJS data)
addStylesToText (styles, tagName = 'span') {
const inlineStyles = styles.map(style => style.join(':')).join(';') + ';'
const selectedComponent = this.editor.getSelected()
const components = selectedComponent.components().models
for (const component of components) {
const content = component.get('content')
if (content !== this.selection.anchorText) {
continue
}
const componentId = component.index()
const selectedText = content.substr(
this.selection.rangeStart,
this.selection.rangeEnd - this.selection.rangeStart
)
const [prevSibling, nextSibling] = content.split(selectedText)
selectedComponent.append({
type: 'textnode',
content: prevSibling
}, {
at: componentId
})
selectedComponent.append({
type: 'textnode',
content: nextSibling
}, {
at: componentId + 2
})
component.replaceWith({
tagName: tagName,
type: 'text',
attributes: {
style: inlineStyles
},
components: [{
type: 'textnode',
content: selectedText
}]
})
console.log('addStylesToText()', {
selectedComponent,
component,
selectedText,
prevSibling,
nextSibling
})
break
}
}
Sources:
Thanks for reporting this, @bgrand-ch.
Great question about How to refresh/re-render after new node added?. The recommended approach with ProseMirror is to use the event-driven API.
Start here:
- Check the GrapesJS documentation for your specific module
- Look for the
on()event listener method - Most operations can be achieved by listening to editor and component events
Common patterns:
// Listen for changes
editor.on('change', () => console.log('something changed'));
// Component lifecycle
editor.on('component:mount', (c) => console.log('component ready', c));
editor.on('component:update', (c) => console.log('component updated', c));
If you're still stuck:
- Share a minimal CodeSandbox reproduction
- Include what you've already tried
- Mention your GrapesJS version
- The community is here to help!
Related Questions and Answers
Continue research with similar issue discussions.
Issue #3599
@keyframes not adding even after i pass the the keyframes object
Hi @artf, I have added the let cc = editor.CssComposer; cc.setRule('.fadetop-animate', { opacity: 0, 'animation-name': 'fadeTop' }, { atRul...
Issue #3406
How to create a custom storage manager, it doesnt set saved data from canvas, after reloading the page
Hello everyone, i want to save data from canvas to redux store, and it works, but after reloading the page, storage load method , doesnt se...
Issue #6458
sector.setName doesn't work
GrapesJS version [x] I confirm to use the latest version of GrapesJS What browser are you using? Chrome Reproducible demo link https://jsfi...
Issue #6365
Style Manager Fails to Interpret Descendant Selectors Correctly
GrapesJS version [X] I confirm to use the latest version of GrapesJS What browser are you using? Chrome Version 131.0.6778.205 Reproducible...
Paid Plugins That Match This Issue
Curated by issue keywords and label relevance to help you ship faster.
Loading paid plugin recommendations...
Check the open-source GrapesJS plugins on GitHub or run a quick search in our free catalog.
Browse free plugins →Premium plugins ship with support, regular updates, and production-ready features — save days of integration work.
Browse premium plugins →Related tutorials
In-depth guides on the same topic.
Tutorial
How to Build a Production GrapesJS Editor: The Complete Walkthrough of Brief, Preset, Plugins, and Services
A complete walkthrough of building a production GrapesJS editor: how to choose a preset, pick plugins, and scope setup services without burning a sprint.
Tutorial
Big Updates: TinyMCE 8 and Placeholder 2.0 for GrapesJS
In May we shipped major updates to two of our most popular GrapesJS plugins — TinyMCE Inline Text Editor and Placeholder.
Tutorial
Find the Right GrapesJS Plugin in Seconds: Smarter Discovery Is Live
We're shipping a set of discovery upgrades. New label filters, a proper compatibility switch for GrapesJS vs Studio, one-click and a smarter sort bar.
Browse Plugin Categories
Jump directly to plugin category pages on the marketplace.