How can I extend a new custom trait to all components? #6619
Answered
by
lexoyo
rainerregan
asked this question in
Q&A
-
|
Hello, could anyone help me? I need to extend a new custom trait that applicable to all components. I have tried using my code below but it just overrides every components' traits. I have do some researching and reading the documentations, but I still have no idea on how to do it. import { Editor } from "grapesjs";
export const customVisibilityTrait = (editor: Editor) => {
editor.DomComponents.addType('visibility', {
isComponent: (el) => true,
model: {
defaults: {
traits: [
{
type: 'select',
label: 'Visibility',
name: 'visibility',
options: [
{ id: 'visible', name: 'Visible' },
{ id: 'hidden', name: 'Hidden' }
],
getValue: ({ component }) => {
const display = component?.getStyle()?.display;
return display === 'none' ? 'hidden' : 'visible';
},
setValue: ({ value, emitUpdate, component }) => {
const displayValue = value === 'visible' ? 'block' : 'none';
const previousDisplay = component?.getAttributes()['data-previous-display'];
const currentDisplay = component?.getStyle()?.display || 'block';
// Store the current display value before hiding
if (currentDisplay !== 'none' && value === 'hidden') {
component?.setAttributes({ 'data-previous-display': currentDisplay });
}
if (value === 'visible' && previousDisplay) {
component?.setStyle({
...(component.getStyle() ?? {}),
display: previousDisplay
});
component?.removeAttributes(['data-previous-display']);
}
component?.setStyle({
...(component.getStyle() ?? {}),
display: displayValue
});
emitUpdate();
}
}
]
},
},
});
} |
Beta Was this translation helpful? Give feedback.
Answered by
lexoyo
Oct 5, 2025
Replies: 1 comment 1 reply
-
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
rainerregan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello
Here is how I do this:
https://github.com/silexlabs/silex-lib/blob/main/src/ts/client/grapesjs/semantic.ts#L54
inspired by https://github.com/olivmonnier/grapesjs-plugin-header/blob/master/src/components.js