## Editor
Editor contains the top level API which you'll probably use to customize the editor or extend it with plugins.
You get the Editor instance on init method and you can pass options via its [Configuration Object][1]
```js
const editor = grapesjs.init({
// options
});
```
## Available Events
You can make use of available events in this way
```js
editor.on('EVENT-NAME', (some, argument) => {
// do something
})
```
### Components
* `component:create` - Component is created (only the model, is not yet mounted in the canvas), called after the init() method
* `component:mount` - Component is mounted to an element and rendered in canvas
* `component:add` - Triggered when a new component is added to the editor, the model is passed as an argument to the callback
* `component:remove` - Triggered when a component is removed, the model is passed as an argument to the callback
* `component:remove:before` - Triggered before the remove of the component, the model, remove function (if aborted via options, with this function you can complete the remove) and options (use options.abort = true to prevent remove), are passed as arguments to the callback
* `component:clone` - Triggered when a component is cloned, the new model is passed as an argument to the callback
* `component:update` - Triggered when a component is updated (moved, styled, etc.), the model is passed as an argument to the callback
* `component:update:{propertyName}` - Listen any property change, the model is passed as an argument to the callback
* `component:styleUpdate` - Triggered when the style of the component is updated, the model is passed as an argument to the callback
* `component:styleUpdate:{propertyName}` - Listen for a specific style property change, the model is passed as an argument to the callback
* `component:selected` - New component selected, the selected model is passed as an argument to the callback
* `component:deselected` - Component deselected, the deselected model is passed as an argument to the callback
* `component:toggled` - Component selection changed, toggled model is passed as an argument to the callback
* `component:type:add` - New component type added, the new type is passed as an argument to the callback
* `component:type:update` - Component type updated, the updated type is passed as an argument to the callback
* `component:drag:start` - Component drag started. Passed an object, to the callback, containing the `target` (component to drag), `parent` (parent of the component) and `index` (component index in the parent)
* `component:drag` - During component drag. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the current pointer
* `component:drag:end` - Component drag ended. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the final pointer
### Blocks
* `block:add` - New block added
* `block:remove` - Block removed
* `block:drag:start` - Started dragging block, model of the block is passed as an argument
* `block:drag` - Dragging block, the block's model and the drag event are passed as arguments
* `block:drag:stop` - Dragging of the block is stopped. As agruments for the callback you get, the dropped component model (if dropped successfully) and the model of the block
### Assets
* `asset:add` - New asset added
* `asset:remove` - Asset removed
* `asset:upload:start` - Before the upload is started
* `asset:upload:end` - After the upload is ended
* `asset:upload:error` - On any error in upload, passes the error as an argument
* `asset:upload:response` - On upload response, passes the result as an argument
### Keymaps
* `keymap:add` - New keymap added. The new keyamp object is passed as an argument
* `keymap:remove` - Keymap removed. The removed keyamp object is passed as an argument
* `keymap:emit` - Some keymap emitted, in arguments you get keymapId, shortcutUsed, Event
* `keymap:emit:{keymapId}` - `keymapId` emitted, in arguments you get keymapId, shortcutUsed, Event
### Style Manager
* `styleManager:update:target` - The target (Component or CSSRule) is changed
* `styleManager:change` - Triggered on style property change from new selected component, the view of the property is passed as an argument to the callback
* `styleManager:change:{propertyName}` - As above but for a specific style property
### Storages
* `storage:start` - Before the storage request is started
* `storage:start:store` - Before the store request. The object to store is passed as an argumnet (which you can edit)
* `storage:start:load` - Before the load request. Items to load are passed as an argumnet (which you can edit)
* `storage:load` - Triggered when something was loaded from the storage, loaded object passed as an argumnet
* `storage:store` - Triggered when something is stored to the storage, stored object passed as an argumnet
* `storage:end` - After the storage request is ended
* `storage:end:store` - After the store request
* `storage:end:load` - After the load request
* `storage:error` - On any error on storage request, passes the error as an argument
* `storage:error:store` - Error on store request, passes the error as an argument
* `storage:error:load` - Error on load request, passes the error as an argument
### Canvas
* `canvas:dragenter` - When something is dragged inside the canvas, `DataTransfer` instance passed as an argument
* `canvas:dragover` - When something is dragging on canvas, `DataTransfer` instance passed as an argument
* `canvas:drop` - Something is dropped in canvas, `DataTransfer` instance and the dropped model are passed as arguments
* `canvas:dragend` - When a drag operation is ended, `DataTransfer` instance passed as an argument
* `canvas:dragdata` - On any dataTransfer parse, `DataTransfer` instance and the `result` are passed as arguments.
By changing `result.content` you're able to customize what is dropped
### Selectors
* `selector:add` - New selector is add. Passes the new selector as an argument
* `selector:remove` - Selector removed. Passes the removed selector as an argument
* `selector:update` - Selector updated. Passes the updated selector as an argument
* `selector:state` - State changed. Passes the new state value as an argument
### RTE
* `rte:enable` - RTE enabled. The view, on which RTE is enabled, is passed as an argument
* `rte:disable` - RTE disabled. The view, on which RTE is disabled, is passed as an argument
### Modal
* `modal:open` - Modal is opened
* `modal:close` - Modal is closed
### Parser
* `parse:html` - On HTML parse, an object containing the input and the output of the parser is passed as an argument
* `parse:css` - On CSS parse, an object containing the input and the output of the parser is passed as an argument
### Commands
* `run:{commandName}` - Triggered when some command is called to run (eg. editor.runCommand('preview'))
* `stop:{commandName}` - Triggered when some command is called to stop (eg. editor.stopCommand('preview'))
* `run:{commandName}:before` - Triggered before the command is called
* `stop:{commandName}:before` - Triggered before the command is called to stop
* `abort:{commandName}` - Triggered when the command execution is aborted (`editor.on(`run:preview:before`, opts => opts.abort = 1);`)
* `run` - Triggered on run of any command. The id and the result are passed as arguments to the callback
* `stop` - Triggered on stop of any command. The id and the result are passed as arguments to the callback
### Pages
Check the [Pages][2] module.
### General
* `canvasScroll` - Canvas is scrolled
* `update` - The structure of the template is updated (its HTML/CSS)
* `undo` - Undo executed
* `redo` - Redo executed
* `load` - Editor is loaded
## getConfig
Returns configuration object
### Parameters
* `prop` **[string][3]?** Property name
Returns **any** Returns the configuration object or
the value of the specified property
## getHtml
Returns HTML built inside canvas
### Parameters
* `opts` **[Object][4]** Options (optional, default `{}`)
* `opts.cleanId` **[Boolean][5]** Remove unnecessary IDs (eg. those created automatically) (optional, default `false`)
Returns **[string][3]** HTML string
## getCss
Returns CSS built inside canvas
### Parameters
* `opts` **[Object][4]** Options (optional, default `{}`)
* `opts.avoidProtected` **[Boolean][5]** Don't include protected CSS (optional, default `false`)
Returns **[string][3]** CSS string
## getJs
Returns JS of all components
### Parameters
* `opts` **[Object][4]** Options (optional, default `{}`)
* `opts.component` **Component?** Get the JS of a particular component
Returns **[string][3]** JS string
## getComponents
Return the complete tree of components. Use `getWrapper` to include also the wrapper
Returns **Components**
## getWrapper
Return the wrapper and its all components
Returns **Component**
## setComponents
Set components inside editor's canvas. This method overrides actual components
### Parameters
* `components` **([Array][6]<[Object][4]> | [Object][4] | [string][3])** HTML string or components model
* `opt` **[Object][4]** the options object to be used by the \[setComponents][em#setComponents][7] method (optional, default `{}`)
### Examples
```javascript
editor.setComponents('
New component
');
// or
editor.setComponents({
type: 'text',
classes:['cls'],
content: 'New component'
});
```
Returns **this**
## addComponents
Add components
### Parameters
* `components` **([Array][6]<[Object][4]> | [Object][4] | [string][3])** HTML string or components model
* `opts` **[Object][4]** Options
* `opts.avoidUpdateStyle` **[Boolean][5]** If the HTML string contains styles,
by default, they will be created and, if already exist, updated. When this option
is true, styles already created will not be updated. (optional, default `false`)
### Examples
```javascript
editor.addComponents('New component
');
// or
editor.addComponents({
type: 'text',
classes:['cls'],
content: 'New component'
});
```
Returns **[Array][6]\**
## getStyle
Returns style in JSON format object
Returns **[Object][4]**
## setStyle
Set style inside editor's canvas. This method overrides actual style
### Parameters
* `style` **([Array][6]<[Object][4]> | [Object][4] | [string][3])** CSS string or style model
* `opt` (optional, default `{}`)
### Examples
```javascript
editor.setStyle('.cls{color: red}');
//or
editor.setStyle({
selectors: ['cls']
style: { color: 'red' }
});
```
Returns **this**
## addStyle
Add styles to the editor
### Parameters
* `style` **([Array][6]<[Object][4]> | [Object][4] | [string][3])** CSS string or style model
* `opts` (optional, default `{}`)
### Examples
```javascript
editor.addStyle('.cls{color: red}');
```
Returns **[Array][6]\** Array of created CssRule instances
## getSelected
Returns the last selected component, if there is one
Returns **Model**
## getSelectedAll
Returns an array of all selected components
Returns **[Array][6]**
## getSelectedToStyle
Get a stylable entity from the selected component.
If you select a component without classes the entity is the Component
itself and all changes will go inside its 'style' attribute. Otherwise,
if the selected component has one or more classes, the function will
return the corresponding CSS Rule
Returns **Model**
## select
Select a component
### Parameters
* `el` **(Component | [HTMLElement][8])** Component to select
* `opts` **[Object][4]?** Options
* `opts.scroll` **[Boolean][5]?** Scroll canvas to the selected element
### Examples
```javascript
// Select dropped block
editor.on('block:drag:stop', function(model) {
editor.select(model);
});
```
Returns **this**
## selectAdd
Add component to selection
### Parameters
* `el` **(Component | [HTMLElement][8] | [Array][6])** Component to select
### Examples
```javascript
editor.selectAdd(model);
```
Returns **this**
## selectRemove
Remove component from selection
### Parameters
* `el` **(Component | [HTMLElement][8] | [Array][6])** Component to select
### Examples
```javascript
editor.selectRemove(model);
```
Returns **this**
## selectToggle
Toggle component selection
### Parameters
* `el` **(Component | [HTMLElement][8] | [Array][6])** Component to select
### Examples
```javascript
editor.selectToggle(model);
```
Returns **this**
## getEditing
Returns, if active, the Component enabled in rich text editing mode.
### Examples
```javascript
const textComp = editor.getEditing();
if (textComp) {
console.log('HTML: ', textComp.toHTML());
}
```
Returns **(Component | null)**
## setDevice
Set device to the editor. If the device exists it will
change the canvas to the proper width
### Parameters
* `name` **[string][3]** Name of the device
### Examples
```javascript
editor.setDevice('Tablet');
```
Returns **this**
## getDevice
Return the actual active device
### Examples
```javascript
var device = editor.getDevice();
console.log(device);
// 'Tablet'
```
Returns **[string][3]** Device name
## runCommand
Execute command
### Parameters
* `id` **[string][3]** Command ID
* `options` **[Object][4]** Custom options (optional, default `{}`)
### Examples
```javascript
editor.runCommand('myCommand', {someValue: 1});
```
Returns **any** The return is defined by the command
## stopCommand
Stop the command if stop method was provided
### Parameters
* `id` **[string][3]** Command ID
* `options` **[Object][4]** Custom options (optional, default `{}`)
### Examples
```javascript
editor.stopCommand('myCommand', {someValue: 1});
```
Returns **any** The return is defined by the command
## store
Store data to the current storage
### Parameters
* `clb` **[Function][9]** Callback function
Returns **[Object][4]** Stored data
## load
Load data from the current storage
### Parameters
* `clb` **[Function][9]** Callback function
Returns **[Object][4]** Stored data
## getContainer
Returns container element. The one which was indicated as 'container'
on init method
Returns **[HTMLElement][8]**
## getDirtyCount
Return the count of changes made to the content and not yet stored.
This count resets at any `store()`
Returns **[number][10]**
## refresh
Update editor dimension offsets
This method could be useful when you update, for example, some position
of the editor element (eg. canvas, panels, etc.) with CSS, where without
refresh you'll get misleading position of tools
### Parameters
* `opts`
* `options` **[Object][4]?** Options
* `options.tools` **[Boolean][5]** Update the position of tools (eg. rich text editor, component highlighter, etc.) (optional, default `false`)
## setCustomRte
Replace the built-in Rich Text Editor with a custom one.
### Parameters
* `obj` **[Object][4]** Custom RTE Interface
### Examples
```javascript
editor.setCustomRte({
// Function for enabling custom RTE
// el is the HTMLElement of the double clicked Text Component
// rte is the same instance you have returned the first time you call
// enable(). This is useful if need to check if the RTE is already enabled so
// ion this case you'll need to return the RTE and the end of the function
enable: function(el, rte) {
rte = new MyCustomRte(el, {}); // this depends on the Custom RTE API
...
return rte; // return the RTE instance
},
// Disable the editor, called for example when you unfocus the Text Component
disable: function(el, rte) {
rte.blur(); // this depends on the Custom RTE API
}
// Called when the Text Component is focused again. If you returned the RTE instance
// from the enable function, the enable won't be called again instead will call focus,
// in this case to avoid double binding of the editor
focus: function (el, rte) {
rte.focus(); // this depends on the Custom RTE API
}
});
```
## setCustomParserCss
Replace the default CSS parser with a custom one.
The parser function receives a CSS string as a parameter and expects
an array of CSSRule objects as a result. If you need to remove the
custom parser, pass `null` as the argument
### Parameters
* `parser` **([Function][9] | null)** Parser function
### Examples
```javascript
editor.setCustomParserCss(css => {
const result = [];
// ... parse the CSS string
result.push({
selectors: '.someclass, div .otherclass',
style: { color: 'red' }
})
// ...
return result;
});
```
Returns **this**
## setDragMode
Change the global drag mode of components.
To get more about this feature read: [https://github.com/artf/grapesjs/issues/1936][11]
### Parameters
* `value` **[String][3]** Drag mode, options: 'absolute' | 'translate'
Returns **this**
## log
Trigger event log message
### Parameters
* `msg` **any** Message to log
* `opts` **[Object][4]** Custom options (optional, default `{}`)
* `opts.ns` **[String][3]** Namespace of the log (eg. to use in plugins) (optional, default `''`)
* `opts.level` **[String][3]** Level of the log, `debug`, `info`, `warning`, `error` (optional, default `'debug'`)
### Examples
```javascript
editor.log('Something done!', { ns: 'from-plugin-x', level: 'info' });
// This will trigger following events
// `log`, `log:info`, `log-from-plugin-x`, `log-from-plugin-x:info`
// Callbacks of those events will always receive the message and
// options, as arguments, eg:
// editor.on('log:info', (msg, opts) => console.info(msg, opts))
```
Returns **this**
## t
Translate label
### Parameters
* `args` **...any**
* `key` **[String][3]** Label to translate
* `opts` **[Object][4]?** Options for the translation
* `opts.params` **[Object][4]?** Params for the translation
* `opts.noWarn` **[Boolean][5]?** Avoid warnings in case of missing resources
### Examples
```javascript
editor.t('msg');
// use params
editor.t('msg2', { params: { test: 'hello' } });
// custom local
editor.t('msg2', { params: { test: 'hello' }, l: 'it' });
```
Returns **[String][3]**
## on
Attach event
### Parameters
* `event` **[string][3]** Event name
* `callback` **[Function][9]** Callback function
Returns **this**
## once
Attach event and detach it after the first run
### Parameters
* `event` **[string][3]** Event name
* `callback` **[Function][9]** Callback function
Returns **this**
## off
Detach event
### Parameters
* `event` **[string][3]** Event name
* `callback` **[Function][9]** Callback function
Returns **this**
## trigger
Trigger event
### Parameters
* `event` **[string][3]** Event to trigger
Returns **this**
## destroy
Destroy the editor
## render
Render editor
Returns **[HTMLElement][8]**
## html
Print safe HTML by using ES6 tagged template strings.
### Parameters
* `literals` **[Array][6]<[String][3]>**
* `substs` **[Array][6]<[String][3]>**
### Examples
```javascript
const unsafeStr = '';
const safeStr = 'Hello';
// Use `$${var}` to avoid escaping
const strHtml = editor.html`Escaped ${unsafeStr}, unescaped $${safeStr}`;
```
Returns **[String][3]**
[1]: https://github.com/artf/grapesjs/blob/master/src/editor/config/config.js
[2]: /api/pages.html
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[7]: em#setComponents
[8]: https://developer.mozilla.org/docs/Web/HTML/Element
[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[11]: https://github.com/artf/grapesjs/issues/1936