GrapesJS / grapesjs

Free and Open source Web Builder Framework. Next generation tool for building templates without coding
https://grapesjs.com
BSD 3-Clause "New" or "Revised" License
22.38k stars 4.06k forks source link

How to get the latest css property of a component? #1838

Closed NicoEngler closed 5 years ago

NicoEngler commented 5 years ago

Hi, awesome job with grapesjs!

I already read the docs (especially CssComposer) and also relevant issues but still, I am stuck.

A custom plugin allows me to add css to a component using component.setStyle(). On reload, I need my plugin to initialize with these values.

For example I want to read the margin property of a component. I observed that css gets added inline when using setStyle() and once the data is stored and loaded, the css is defined in classes.

Right now, I am parsing the property value manually with the assumption that the last entry represents the "active" entry. But that approach feels totally wrong! :)

function latestCSSPropertyValue(component, property) {
    let css = editor.CodeManager.getCode(component, 'css', {cssc: editor.CssComposer});
    let pos1 = css.lastIndexOf(property);
    let pos2 = css.indexOf(';', pos1);
    return (pos2 > pos1) ? css.substring(pos1, pos2).split(':')[1] : "";
}

I feel like I can achieve this differently with CssComposer but again, I am stuck.

Thanks, Nico

artf commented 5 years ago

I observed that css gets added inline when using setStyle() and once the data is stored and loaded, the css is defined in classes.

First of all, be sure to store your templates correctly: Store and load templates in that case, when you set style via component.setStyle(...) on the next page reload you should be able to get that style via component.getStyle(...) without the need to touch the CodeManager/CssComposer You might also want to take in account setRule/getRule if you need to manipulate CSS rules

lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.