### start
Source: https://grapesjs.com/docs/api/undo_manager.html
Starts or resumes tracking changes. This is the default state.
```APIDOC
## # start
Start/resume tracking changes
### # Examples
```
um.start();
```
Returns **this**
```
--------------------------------
### Listen to Project Get Event
Source: https://grapesjs.com/docs/api/editor.html
Listens for the 'project:get' event, allowing extension of project data with custom keys before it's retrieved.
```javascript
editor.on('project:get', ({ project }) => { project.myCustomKey = 'value' });
```
--------------------------------
### Get Style Preview Example
Source: https://grapesjs.com/docs/api/property_stack.html
Retrieve the preview style object for a layer. If the property is configured with `preview: false`, an empty object will be returned.
```javascript
const previewStyle = property.getStylePreview(layer);
```
--------------------------------
### Bootstrap Modal Integration Example
Source: https://grapesjs.com/docs/modules/Modal.html
An example demonstrating how to integrate a custom Bootstrap modal with GrapesJS by using the `modal.custom` option and handling the `modal` event.
```APIDOC
Here an example of using the Bootstrap modal.
#
* Babel + JSX
* HTML
* CSS
* Result
```javascript
const editor = grapesjs.init({
container: '#gjs',
height: '100%',
storageManager: false,
modal: { custom: true },
components: `
Double click on image to open custom modal.
`,
});
// Custom modal
let bstModal, modalTitle, modalBody;
editor.on('modal', (props) => {
if (!bstModal) {
const modalEl = document.getElementById('gjsModal');
modalTitle = document.querySelector('.modal-title');
modalBody = document.querySelector('.modal-body');
bstModal = new bootstrap.Modal(modalEl);
// update GrapesJS modal state when Bootstrap modal is closed
modalEl.addEventListener('hide.bs.modal', props.close);
}
if (props.open) {
// clear the current elements
modalTitle.innerHTML = '';
modalBody.innerHTML = '';
// Add new elements
modalTitle.appendChild(props.title);
modalBody.appendChild(props.content);
bstModal.show();
} else {
bstModal.hide();
}
});
```
```html
Title
Content
```
```css
body, html {
margin: 0;
height: 100%;
}
```
```
--------------------------------
### Initialize GrapesJS Editor with Canvas
Source: https://grapesjs.com/docs/getting-started.html
Initiate the GrapesJS editor, targeting a specific HTML element for the canvas. This setup starts with a basic 'Hello World' component and disables the storage manager.
```html
Hello World Component!
```
```javascript
const editor = grapesjs.init({
// Indicate where to init the editor. You can also pass an HTMLElement
container: '#gjs',
// Get the content for the canvas directly from the element
// As an alternative we could use: `components: '
Hello World Component!
',
fromElement: true,
// Size of the editor
height: '300px',
width: 'auto',
// Disable the storage manager for the moment
storageManager: false,
// Avoid any default panel
panels: { defaults: [] },
});
```
```css
/* Let's highlight canvas boundaries */
#gjs {
border: 3px solid #444;
}
/* Reset some default styling */
.gjs-cv-canvas {
top: 0;
width: 100%;
height: 100%;
}
```
--------------------------------
### Start Tracking Changes
Source: https://grapesjs.com/docs/api/undo_manager.html
Begin or resume tracking changes. This is typically enabled by default.
```javascript
um.start();
```
--------------------------------
### Listen for Asset Upload Start Event
Source: https://grapesjs.com/docs/api/assets.html
Execute a callback function when an asset upload process begins.
```javascript
editor.on('asset:upload:start', () => { ... });
```
--------------------------------
### Listen to Storage Load Start Event
Source: https://grapesjs.com/docs/api/storage_manager.html
This event is triggered at the beginning of a storage load operation.
```javascript
editor.on('storage:start:load', () => {
console.log('Storage start load');
});
```
--------------------------------
### Listen to Storage Start Event
Source: https://grapesjs.com/docs/api/storage_manager.html
This event is triggered when a storage request begins. It provides the type of storage operation.
```javascript
editor.on('storage:start', (type) => {
console.log('Storage start');
});
```
--------------------------------
### get
Source: https://grapesjs.com/docs/api/storage_manager.html
Retrieves a specific storage instance by its type.
```APIDOC
const customStorage = storageManager.get('local2');
```
--------------------------------
### Initialize Editor and Access DataSources
Source: https://grapesjs.com/docs/api/datasources.html
Instantiate the GrapesJS editor and get access to the DataSources manager instance.
```javascript
const editor = grapesjs.init({ ... });
const dsm = editor.DataSources;
```
--------------------------------
### Get All Commands
Source: https://grapesjs.com/docs/api/commands.html
Retrieves an object containing all registered commands.
```javascript
const allCommands = commands.getAll();
```
--------------------------------
### Setup Style Manager with buildProps and Custom Min Height
Source: https://grapesjs.com/docs/Home.html
Demonstrates using `buildProps` to include 'width' and 'min-height' and then customizing the 'width' property with a specific minimum value.
```javascript
styleManager : {
sectors: [{
name: 'Dimension',
buildProps: ['width', 'min-height'],
properties:[{
property: 'width', // Use 'property' as id
min: 30
}]
},
...
]
}
```
--------------------------------
### Get Property Style Example
Source: https://grapesjs.com/docs/api/property.html
Retrieves the CSS style object for a given property. This example shows how to get the style for a 'color' property with the value 'red'.
```javascript
// In case the property is `color` with a value of `red`.
console.log(property.getStyle());
// { color: 'red' };
```
--------------------------------
### Get All Toolbar Actions
Source: https://grapesjs.com/docs/api/rich_text_editor.html
Retrieve all currently available toolbar actions.
```APIDOC
const allActions = rte.getAll();
```
--------------------------------
### Get Layer Examples
Source: https://grapesjs.com/docs/api/property_stack.html
Retrieve layer objects from the PropertyStack. You can get a specific layer by its index or iterate through all layers using `getLayers()`.
```javascript
// Get the first layer
const layerFirst = property.getLayer(0);
// Get the last layer
const layers = this.getLayers();
const layerLast = property.getLayer(layers.length - 1);
```
--------------------------------
### Initialize and Add Record to DataSource
Source: https://grapesjs.com/docs/api/datasource.html
Demonstrates initializing a DataSource with initial records and then adding a new record. Ensure the editor instance is available.
```javascript
const dataSource = new DataSource({
records: [
{ id: 'id1', name: 'value1' },
{ id: 'id2', name: 'value2' }
],
}, { em: editor });
dataSource.addRecord({ id: 'id3', name: 'value3' });
```
--------------------------------
### Get Dragging Block
Source: https://grapesjs.com/docs/api/block_manager.html
Returns the block that is currently being dragged. This is updated when a drag starts and cleared when it finishes.
```APIDOC
## Method
blockManager.getDragBlock()
Returns **(Block | undefined)**
```
--------------------------------
### Get Configuration
Source: https://grapesjs.com/docs/api/rich_text_editor.html
Retrieve the current configuration object for the Rich Text Editor.
```APIDOC
const config = rte.getConfig();
```
--------------------------------
### Add Panels and Action Buttons
Source: https://grapesjs.com/docs/getting-started.html
Configure panels and add buttons that trigger commands. Use built-in commands like 'sw-visibility' or define custom ones. Ensure the `el` property matches your HTML structure.
```javascript
editor.Panels.addPanel({
id: 'panel-top',
el: '.panel__top',
});
editor.Panels.addPanel({
id: 'basic-actions',
el: '.panel__basic-actions',
buttons: [
{
id: 'visibility',
active: true, // active by default
className: 'btn-toggle-borders',
label: 'B',
command: 'sw-visibility', // Built-in command
},
{
id: 'export',
className: 'btn-open-export',
label: 'Exp',
command: 'export-template',
context: 'export-template', // For grouping context of buttons from the same panel
},
{
id: 'show-json',
className: 'btn-show-json',
label: 'JSON',
context: 'show-json',
command(editor) {
editor.Modal.setTitle('Components JSON')
.setContent(
``,
)
.open();
},
},
],
});
```
--------------------------------
### Get Layer Label Example
Source: https://grapesjs.com/docs/api/property_stack.html
Retrieve the display label for a given layer. The label can be customized using the `layerLabel` property.
```javascript
const layer = this.getLayer(1);
const label = this.getLayerLabel(layer);
```
--------------------------------
### Initialize Editor with Storage Options
Source: https://grapesjs.com/docs/api/storage_manager.html
Customize the initial state of the Storage Manager by passing configuration options during editor initialization.
```javascript
const editor = grapesjs.init({
storageManager: {
// options
}
})
```
--------------------------------
### Get Style From Layer Example
Source: https://grapesjs.com/docs/api/property_stack.html
Obtain the style object associated with a specific layer. Options are available to return property names in camelCase or to limit numerical values.
```javascript
const style = property.getStyleFromLayer(layer, { camelCase: true, number: { min: -1, max: 1 } });
```
--------------------------------
### Setup Fake REST API with json-server
Source: https://grapesjs.com/docs/modules/Storage.html
This snippet demonstrates how to set up a local REST API server using json-server to simulate remote storage for GrapesJS projects. It initializes the server with a sample database file and watches for changes.
```bash
mkdir my-server
cd my-server
npm init
npm i json-server
echo '{"projects": [ {"id": 1, "data": {"assets": [], "styles": [], "pages": [{"component": "
Initial content
"}]} } ]}' > db.json
npx json-server --watch db.json
```
--------------------------------
### Initialize Editor with Device Manager Options
Source: https://grapesjs.com/docs/api/device_manager.html
Configure the Device Manager module during editor initialization by passing an options object.
```javascript
const editor = grapesjs.init({
deviceManager: {
// options
}
})
```
--------------------------------
### Get Component Type
Source: https://grapesjs.com/docs/modules/Components.html
Retrieve the type of a component instance using the 'get' method.
```javascript
const componentType = component.get('type'); // eg. 'image'
```
--------------------------------
### Basic Modal Usage
Source: https://grapesjs.com/docs/modules/Modal.html
Demonstrates how to initialize the editor and open a modal with a title and content using a simple API call.
```APIDOC
## Basic usage
You can easily display your content by calling a single API call.
```javascript
// Init editor
const editor = grapesjs.init({ ... });
// Open modal
const openModal = () => {
editor.Modal.open({
title: 'My title', // string | HTMLElement
content: 'My content', // string | HTMLElement
});
};
// Create a simple custom button that will open the modal
document.body.insertAdjacentHTML('afterbegin',
``
);
```
```
--------------------------------
### Get Toolbar Element
Source: https://grapesjs.com/docs/api/rich_text_editor.html
Get the HTML element that represents the Rich Text Editor's toolbar.
```APIDOC
const toolbarElement = rte.getToolbarEl();
```
--------------------------------
### Listen to Storage Store Start Event
Source: https://grapesjs.com/docs/api/storage_manager.html
This event is triggered at the beginning of a storage store operation. The project JSON object to be stored is passed as an argument, allowing for potential modification.
```javascript
editor.on('storage:start:store', (data) => {
console.log('Storage start store');
});
```
--------------------------------
### Initialize Editor with Commands Configuration
Source: https://grapesjs.com/docs/api/commands.html
Configure commands during editor initialization by passing an options object.
```javascript
const editor = grapesjs.init({
commands: {
// options
}
})
```
--------------------------------
### Get All Sectors
Source: https://grapesjs.com/docs/api/style_manager.html
Retrieve all sectors currently managed by the Style Manager. Optionally, filter to get only visible sectors.
```javascript
const sectors = styleManager.getSectors();
```
--------------------------------
### Get Symbol Info
Source: https://grapesjs.com/docs/guides/Symbols.html
Get details about a Symbol, including whether it's a Main Symbol, Instance Symbol, or root.
```APIDOC
## Symbol Details
Once you have Symbols in your project, you might need to know when a Component is a Symbol and get details about it. Use the `getSymbolInfo` method for this:
```javascript
// Details from the Main Symbol
const symbolMainInfo = editor.Components.getSymbolInfo(symbolMain);
symbolMainInfo.isSymbol; // true; It's a Symbol
symbolMainInfo.isRoot; // true; It's the root of the Symbol
symbolMainInfo.isMain; // true; It's the Main Symbol
symbolMainInfo.isInstance; // false; It's not the Instance Symbol
symbolMainInfo.main; // symbolMainInfo; Reference to the Main Symbol
symbolMainInfo.instances; // [anyComponent, secondInstance]; Reference to Instance Symbols
symbolMainInfo.relatives; // [anyComponent, secondInstance]; Relative Symbols
// Details from the Instance Symbol
const secondInstanceInfo = editor.Components.getSymbolInfo(secondInstance);
symbolMainInfo.isSymbol; // true; It's a Symbol
symbolMainInfo.isRoot; // true; It's the root of the Symbol
symbolMainInfo.isMain; // false; It's not the Main Symbol
symbolMainInfo.isInstance; // true; It's the Instance Symbol
symbolMainInfo.main; // symbolMainInfo; Reference to the Main Symbol
symbolMainInfo.instances; // [anyComponent, secondInstance]; Reference to Instance Symbols
symbolMainInfo.relatives; // [anyComponent, symbolMain]; Relative Symbols
```
```
--------------------------------
### Initialize DataRecord
Source: https://grapesjs.com/docs/api/datarecord.html
Instantiate a new DataRecord with initial properties and options. The 'collection' option in 'opts' is often required for proper data source association.
```javascript
const record = new DataRecord({ id: 'record1', name: 'value1' }, { collection: dataRecords });
```
--------------------------------
### Initialize Editor with Asset Manager Options
Source: https://grapesjs.com/docs/api/assets.html
Configure the Asset Manager during editor initialization by passing an options object.
```javascript
const editor = grapesjs.init({
assetManager: {
// options
}
})
```
--------------------------------
### Set or Get Component Collection
Source: https://grapesjs.com/docs/api/component.html
Sets a new collection of child components or retrieves the current collection. Accepts component definitions or HTML strings for setting, and returns a collection object or an array of components when getting.
```javascript
// Set new collection
component.components('');
// Get current collection
const collection = component.components();
console.log(collection.length);
// -> 2
```
--------------------------------
### Editor Initialization with Pages
Source: https://grapesjs.com/docs/modules/Pages.html
Demonstrates how to initialize the GrapesJS editor with multiple pages defined in the configuration.
```APIDOC
## Initialization with Multiple Pages
This shows how to initialize the editor with multiple pages.
```javascript
const editor = grapesjs.init({
// ... other configurations
pageManager: {
pages: [
{
id: 'my-first-page',
styles: '.my-page1-el { color: red }',
component: '
',
},
],
},
});
```
```
--------------------------------
### open
Source: https://grapesjs.com/docs/api/modal_dialog.html
Open the modal window with optional content and title.
```APIDOC
## open
Open the modal window
### Parameters
* `opts` **Object** Options (optional, default `{}`)
* `opts.title` **(String | HTMLElement)?** Title to set for the modal
* `opts.content` **(String | HTMLElement)?** Content to set for the modal
* `opts.attributes` **Object?** Updates the modal wrapper with custom attributes
### Examples
```javascript
modal.open({
title: 'My title',
content: 'My content',
attributes: { class: 'my-class' },
});
```
Returns **this**
```
--------------------------------
### getCurrent
Source: https://grapesjs.com/docs/api/storage_manager.html
Gets the type of the currently active storage.
```APIDOC
const currentStorageType = storageManager.getCurrent();
```
--------------------------------
### Initialize GrapesJS with Device Manager
Source: https://grapesjs.com/docs/getting-started.html
Initializes the GrapesJS editor, configuring the device manager with predefined devices (Desktop, Mobile) and setting up panel buttons for device switching.
```javascript
const editor = grapesjs.init({
// ...
deviceManager: {
devices: [
{
name: 'Desktop',
width: '', // default size
},
{
name: 'Mobile',
width: '320px', // this value will be used on canvas width
widthMedia: '480px', // this value will be used in CSS @media
},
],
},
// ...
panels: {
defaults: [
// ...
{
id: 'panel-devices',
el: '.panel__devices',
buttons: [
{
id: 'device-desktop',
label: 'D',
command: 'set-device-desktop',
active: true,
togglable: false,
},
{
id: 'device-mobile',
label: 'M',
command: 'set-device-mobile',
togglable: false,
},
],
},
],
},
});
```
--------------------------------
### Get Symbols
Source: https://grapesjs.com/docs/guides/Symbols.html
Retrieve all available Symbols in your project.
```APIDOC
## Get Symbols
To get all the available Symbols in your project, use `getSymbols`:
```javascript
const symbols = editor.Components.getSymbols();
const symbolMain = symbols[0];
```
```
--------------------------------
### I18n Configuration for Traits
Source: https://grapesjs.com/docs/modules/Traits.html
Example of internationalization (i18n) configuration for trait labels, placeholders, and option translations.
```json
{
en: {
traitManager: {
empty: 'Select an element before using Trait Manager',
label: 'Component settings',
categories: {
categoryId: 'Category label',
},
traits: {
// The trait `name` property is used as a key
labels: {
href: 'Href label',
},
// For built-in traits, like `text` type, these are used on input DOM attributes
attributes: {
href: { placeholder: 'eg. https://google.com' },
},
// For `select` types, these are used to translate option labels
options: {
target: {
// Here the key is the `id` of the option
_blank: 'New window',
},
},
},
},
}
}
```
--------------------------------
### getElement
Source: https://grapesjs.com/docs/api/canvas.html
Gets the main HTML element of the canvas.
```APIDOC
## getElement
Get the canvas element
Returns **HTMLElement**
```
--------------------------------
### Initialize Editor with Panels Configuration
Source: https://grapesjs.com/docs/api/panels.html
Configure the initial state of the panels module during editor initialization.
```javascript
const editor = grapesjs.init({
panels: {
// options
}
})
```
--------------------------------
### getContent
Source: https://grapesjs.com/docs/api/modal_dialog.html
Get the current content of the modal window.
```APIDOC
## getContent
Get the content of the modal window
### Examples
```javascript
modal.getContent();
```
Returns **(string | HTMLElement)**
```
--------------------------------
### getTitle
Source: https://grapesjs.com/docs/api/modal_dialog.html
Get the current title of the modal window.
```APIDOC
## getTitle
Returns the title of the modal window
### Examples
```javascript
modal.getTitle();
```
Returns **(string | HTMLElement)**
```
--------------------------------
### add(props, opts?)
Source: https://grapesjs.com/docs/api/pages.html
Adds a new page to the project with the specified properties and optional settings.
```APIDOC
## add
Add new page
### Parameters
* `props` **Object(opens new window)** Page properties
* `opts` **Object(opens new window)?** Options (optional, default `{}`)
### Examples
```javascript
const newPage = pageManager.add({
id: 'new-page-id', // without an explicit ID, a random one will be created
styles: `.my-class { color: red }`, // or a JSON of styles
component: '
My element
', // or a JSON of components
});
```
Returns **Page**
```
--------------------------------
### Initialize GrapesJS Editor
Source: https://grapesjs.com/docs/api/editor.html
Initializes the GrapesJS editor with configuration options. This is the starting point for using the editor API.
```javascript
const editor = grapesjs.init({
// options
});
```
--------------------------------
### get
Source: https://grapesjs.com/docs/api/keymaps.html
Retrieves a specific keymap by its unique ID.
```APIDOC
## # get
Get the keymap by id
### # Parameters
* `id` **string(opens new window)** Keymap id
### # Examples
```
keymaps.get('ns:my-keymap');
// -> {keys, handler};
```
Returns **Object(opens new window)** Keymap object
```
--------------------------------
### Create Component Instance
Source: https://grapesjs.com/docs/modules/Components.html
Create a new component instance by appending an HTML string to the editor. The result is an array of added components.
```javascript
const component = editor.addComponents(`
Hello world!!!
`)[0];
```
--------------------------------
### get
Source: https://grapesjs.com/docs/api/datasources.html
Retrieve a data source by its unique ID.
```APIDOC
## # get
Get data source.
### # Parameters
* `id` **String(opens new window)** Data source id.
### # Examples
```
const ds = dsm.get('my_data_source_id');
```
Returns **DataSource** Data source.
```
--------------------------------
### get
Source: https://grapesjs.com/docs/api/selector_manager.html
Retrieves a selector from the collection by its name or string identifier.
```APIDOC
## get
Get the selector by its name/type
### Parameters
* `name` **String(opens new window)** Selector name or string identifier
* `type` **number(opens new window)?**
### Examples
```
const selector = selectorManager.get('.my-class');
// Get Id
const selectorId = selectorManager.get('#my-id');
```
Returns **(Selector | null)**
```
--------------------------------
### Initialize Editor with Keymaps
Source: https://grapesjs.com/docs/api/keymaps.html
Configure initial keymaps during editor initialization. The 'defaults' object accepts keymap definitions with keys and handlers.
```javascript
const editor = grapesjs.init({
keymaps: {
// Object of keymaps
defaults: {
'your-namespace:keymap-name' {
keys: '⌘+z, ctrl+z',
handler: 'some-command-id'
},
...
}
}
})
```
--------------------------------
### get(id)
Source: https://grapesjs.com/docs/api/pages.html
Retrieves a specific page by its unique ID.
```APIDOC
## get
Get page by id
### Parameters
* `id` **String(opens new window)** Page id
### Examples
```javascript
const somePage = pageManager.get('page-id');
```
Returns **Page**
```
--------------------------------
### Import Plugins from Local Files or NPM
Source: https://grapesjs.com/docs/modules/Plugins.html
Plugins can be organized in separate files and imported using standard JavaScript import statements. Include them in the `plugins` array during editor initialization.
```javascript
import myPlugin from './plugins/myPlugin';
import npmPackage from '@npm/package';
const editor = grapesjs.init({
container: '#gjs',
plugins: [myPlugin, npmPackage],
});
```
--------------------------------
### getBody
Source: https://grapesjs.com/docs/api/canvas.html
Gets the body element of the main canvas frame.
```APIDOC
## getBody
Get the main frame body element
Returns **HTMLBodyElement**
```
--------------------------------
### Listing All Available Commands
Source: https://grapesjs.com/docs/modules/Commands.html
You can retrieve an object containing all currently available commands, including default and dynamically added ones, using `editor.Commands.getAll()`.
```APIDOC
## Listing All Available Commands
GrapesJS comes along with some default set of commands and you can get a list of all currently available commands via `editor.Commands.getAll()`. This will give you an object of all available commands, so, also those added later, like via plugins. You can recognize default commands by their namespace `core:*`, we also recommend to use namespaces in your own custom commands, but let's get a look more in detail here:
* `core:canvas-clear` - Clear all the content from the canvas (HTML and CSS)
* `core:component-delete` - Delete a component
* `core:component-enter` - Select the first children component of the selected one
* `core:component-exit` - Select the parent component of the current selected one
* `core:component-next` - Select the next sibling component
* `core:component-prev` - Select the previous sibling component
* `core:component-outline` - Enable outline border on components
* `core:component-offset` - Enable components offset (margins, paddings)
* `core:component-select` - Enable the process of selecting components in the canvas
* `core:copy` - Copy the current selected component
* `core:paste` - Paste copied component
* `core:preview` - Show the preview of the template in canvas
* `core:fullscreen` - Set the editor fullscreen
* `core:open-code` - Open a default panel with the template code
* `core:open-layers` - Open a default panel with layers
* `core:open-styles` - Open a default panel with the style manager
* `core:open-traits` - Open a default panel with the trait manager
* `core:open-blocks` - Open a default panel with the blocks
* `core:open-assets` - Open a default panel with the assets
* `core:undo` - Call undo operation
* `core:redo` - Call redo operation
```
--------------------------------
### Start Custom Drag Operation
Source: https://grapesjs.com/docs/api/canvas.html
Initiate a custom drag-and-drop process. This can be used with component definitions or HTML content.
```javascript
// as component definition
canvas.startDrag({
content: { type: 'my-component' }
});
// as HTML
canvas.startDrag({
content: '
...
'
});
```
--------------------------------
### getDocument
Source: https://grapesjs.com/docs/api/canvas.html
Gets the document element of the main canvas frame.
```APIDOC
## getDocument
Get the main frame document element
Returns **HTMLDocument**
```
--------------------------------
### Basic UI Implementation with Symbols API
Source: https://grapesjs.com/docs/guides/Symbols.html
This example demonstrates a basic UI using Vue.js to interact with the GrapesJS Symbols API, including creating symbols, instances, and managing lists. It requires the GrapesJS editor to be initialized.
```javascript
const editor = grapesjs.init({
container: '#gjs',
storageManager: false,
components: `
Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
```
```css
.app-wrapper {
height: 100vh;
display: flex;
flex-direction: column;
}
.vue-app {
padding: 10px 0;
display: flex;
gap: 10px;
}
.symbols-wrp {
display: flex;
gap: 10px;
width: 100%;
padding: 10px;
flex-direction: column;
border-radius: 3px;
}
.symbols {
display: flex;
gap: 10px;
width: 100%;
}
.symbol {
cursor: pointer;
flex-basis: 100px;
text-align: left;
margin: 0;
}
```
--------------------------------
### getWindow
Source: https://grapesjs.com/docs/api/canvas.html
Gets the window instance of the main canvas frame.
```APIDOC
## getWindow
Get the main frame window instance
Returns **Window**
```
--------------------------------
### Initialize Editor with Parser Options
Source: https://grapesjs.com/docs/api/parser.html
Customize the initial state of the parser module during editor initialization by providing a configuration object.
```javascript
const editor = grapesjs.init({
parser: {
// options
}
})
```
--------------------------------
### getFrameEl
Source: https://grapesjs.com/docs/api/canvas.html
Gets the main frame element (iframe) of the canvas.
```APIDOC
## getFrameEl
Get the main frame element of the canvas
Returns **HTMLIFrameElement**
```
--------------------------------
### Style Manager Initialization
Source: https://grapesjs.com/docs/api/style_manager.html
Initialize the GrapesJS editor with Style Manager configuration options.
```APIDOC
const editor = grapesjs.init({
styleManager: {
// options
}
})
```
--------------------------------
### Open Asset Manager with Selection Callback
Source: https://grapesjs.com/docs/api/assets.html
Opens the asset manager and defines a callback for asset selection, allowing custom logic for selected assets.
```javascript
assetManager.open({
select(asset, complete) {
const selected = editor.getSelected();
if (selected && selected.is('image')) {
selected.addAttributes({ src: asset.getSrc() });
complete && assetManager.close();
}
}
});
```
```javascript
// with your custom types (you should have assets with those types declared)
assetManager.open({ types: ['doc'], ... });
```
--------------------------------
### Initialize Asset Manager with Assets
Source: https://grapesjs.com/docs/modules/Assets.html
Provide an array of asset URLs or objects during editor initialization to populate the Asset Manager. The `type` property defaults to 'image' if omitted.
```javascript
const editor = grapesjs.init({
...
assetManager: {
assets: [
'http://placehold.it/350x250/78c5d6/fff/image1.jpg',
// Pass an object with your properties
{
type: 'image',
src: 'http://placehold.it/350x250/459ba8/fff/image2.jpg',
height: 350,
width: 250,
name: 'displayName'
},
{
// As the 'image' is the base type of assets, omitting it will
// be set as `image` by default
src: 'http://placehold.it/350x250/79c267/fff/image3.jpg',
height: 350,
width: 250,
name: 'displayName'
},
],
}
});
```
--------------------------------
### get
Source: https://grapesjs.com/docs/api/assets.html
Retrieves a specific asset from the collection using its URL.
```APIDOC
## get
Return asset by URL
### Parameters
* `src` **String(opens new window)** URL of the asset
### Examples
```
const asset = assetManager.get('http://img.jpg');
```
Returns **(Asset | null)**
```
--------------------------------
### Configure Mobile-First Approach and Devices
Source: https://grapesjs.com/docs/getting-started.html
Initialize GrapesJS with a mobile-first configuration by setting `mediaCondition` to 'min-width' and defining custom devices. The initial device can also be set.
```javascript
const editor = grapesjs.init({
// ...
mediaCondition: 'min-width', // default is `max-width`
deviceManager: {
devices: [
{
name: 'Mobile',
width: '320',
widthMedia: '',
},
{
name: 'Desktop',
width: '',
widthMedia: '1024',
},
],
},
// ...
});
// Set initial device as Mobile
editor.setDevice('Mobile');
```
--------------------------------
### Get Component Icon
Source: https://grapesjs.com/docs/api/component.html
Retrieves the icon string associated with the component.
```javascript
component.getIcon();
```
--------------------------------
### getType
Source: https://grapesjs.com/docs/api/property.html
Gets the type of the property, which determines its behavior and associated class.
```APIDOC
## getType
Get the property type. The type of the property is defined on property creation and based on its value the proper Property class is assigned. The default type is `base`.
Returns **String**
```
--------------------------------
### Add and Manage Components in the Wrapper
Source: https://grapesjs.com/docs/api/components.html
Add new components to the wrapper's children, including nested components. This example demonstrates adding components with styles and attributes, and removing a component.
```javascript
// Let's add some component
var wrapperChildren = cmp.getComponents();
var comp1 = wrapperChildren.add({
style: { 'background-color': 'red'}
});
var comp2 = wrapperChildren.add({
tagName: 'span',
attributes: { title: 'Hello!'}
});
// Now let's add an other one inside first component
// First we have to get the collection inside. Each
// component has 'components' property
var comp1Children = comp1.get('components');
// Procede as before. You could also add multiple objects
comp1Children.add([
{ style: { 'background-color': 'blue'}},
{ style: { height: '100px', width: '100px'}}
]);
// Remove comp2
wrapperChildren.remove(comp2);
```
--------------------------------
### Initialize GrapesJS with a Toolbar Panel
Source: https://grapesjs.com/docs/Home.html
Extend the editor initialization to include a basic toolbar panel with a specified ID. This sets up the structure for adding commands and buttons.
```javascript
var editor = grapesjs.init({
container : '#gjs',
height: '100%',
panels: {
defaults: [{
id: 'commands',
}],
}
});
```
--------------------------------
### Get Canvas Zoom
Source: https://grapesjs.com/docs/api/canvas.html
Retrieves the current zoom level of the canvas.
```javascript
canvas.setZoom(50); // set zoom to 50%
const zoom = canvas.getZoom(); // 50
```
--------------------------------
### Get Selected Page
Source: https://grapesjs.com/docs/api/pages.html
Retrieve the currently selected page in the editor.
```javascript
const selectedPage = pageManager.getSelected();
```
--------------------------------
### Listen to Storage Load Event
Source: https://grapesjs.com/docs/api/storage_manager.html
This event is triggered after the project has been loaded from storage. The loaded project data is passed as an argument.
```javascript
editor.on('storage:load', (data, res) => {
console.log('Storage loaded the project');
});
```
--------------------------------
### getAll
Source: https://grapesjs.com/docs/api/keymaps.html
Retrieves all currently defined keymaps.
```APIDOC
## # getAll
Get all keymaps
### # Examples
```
keymaps.getAll();
// -> {id1: {}, id2: {}};
```
Returns **Object(opens new window)**
```
--------------------------------
### getValue
Source: https://grapesjs.com/docs/api/datasources.html
Get a specific value from data sources using a path.
```APIDOC
## # getValue
Get value from data sources by path.
### # Parameters
* `path` **String(opens new window)** Path to value.
* `defValue` **any** Default value if the path is not found.
* `opts` **{context: Record ?}?**
Returns **any** const value = dsm.getValue('ds_id.record_id.propName', 'defaultValue');
```
--------------------------------
### Get Configuration
Source: https://grapesjs.com/docs/api/block_manager.html
Retrieves the current configuration object of the Block Manager.
```APIDOC
## Method
blockManager.getConfig()
Returns **Object**
```
--------------------------------
### Component-Oriented Styling Example
Source: https://grapesjs.com/docs/modules/Components.html
Demonstrates component-first styling where styles are declared within individual components. This ensures styles are scoped to the component and removed when the component is removed.
```javascript
domc.addType('cmp-a', {
model: {
defaults: {
attributes: { class: 'cmp-css-a' },
components: 'Component A',
styles: "
.cmp-css-a { color: green }
@media (max-width: 992px) {
.cmp-css-a { color: darkgreen }
}
",
},
},
});
```
```javascript
domc.addType('cmp-b', {
model: {
defaults: {
attributes: { class: 'cmp-css-b' },
components: 'Component B',
styles: "
.cmp-css-b { color: blue }
@media (max-width: 992px) {
.cmp-css-b { color: darkblue }
}
",
},
},
});
```
```javascript
domc.addType('component-css', {
model: {
defaults: {
attributes: { class: 'cmp-css' },
components: ['Component with styles', { type: 'cmp-a' }, { type: 'cmp-b' }],
styles: "
.cmp-css { color: red }
@media (max-width: 992px) {
.cmp-css{ color: darkred; }
}
",
},
},
});
```
--------------------------------
### Get All Active Commands
Source: https://grapesjs.com/docs/api/commands.html
Retrieves a collection of all commands that are currently active.
```javascript
const activeCommands = commands.getActive();
```
--------------------------------
### Rich Text Editor Initialization
Source: https://grapesjs.com/docs/api/rich_text_editor.html
Initialize the editor with custom Rich Text Editor options.
```APIDOC
const editor = grapesjs.init({
richTextEditor: {
// options
}
})
```
--------------------------------
### Get All Data Sources
Source: https://grapesjs.com/docs/api/data_source_manager.html
Retrieves all currently managed data sources.
```APIDOC
## getAll
Retrieve all data sources.
```
--------------------------------
### Using Built-in CSS Properties
Source: https://grapesjs.com/docs/modules/Style-manager.html
Demonstrates how to include built-in CSS properties in the Style Manager sectors. Properties can be passed as strings or extended with custom configurations.
```javascript
sectors: [
{
name: 'First sector',
properties: [
// Pass the built-in CSS property as a string
'width',
'min-width',
// Extend the built-in property with your props
{
extend: 'max-width',
units: ['px', '%'],
},
// If the property doesn't exist it will be converted to a base type
'unknown-property', // -> { type: 'base', property: 'unknown-property' }
],
},
];
```
--------------------------------
### Keymaps Initialization
Source: https://grapesjs.com/docs/api/keymaps.html
You can customize the initial state of the Keymaps module by providing a keymaps object during editor initialization.
```APIDOC
const editor = grapesjs.init({
keymaps: {
// Object of keymaps
defaults: {
'your-namespace:keymap-name': {
keys: '⌘+z, ctrl+z',
handler: 'some-command-id'
},
...
}
}
})
```
--------------------------------
### stop
Source: https://grapesjs.com/docs/api/undo_manager.html
Stops tracking changes temporarily. Tracking can be resumed with the `start` method.
```APIDOC
## # stop
Stop tracking changes
### # Examples
```
um.stop();
```
Returns **this**
```
--------------------------------
### Get Parent Component
Source: https://grapesjs.com/docs/api/component.html
Retrieves the parent component of the current component, if it exists.
```javascript
component.parent();
```
--------------------------------
### Initialize GrapesJS with Style Manager Configuration
Source: https://grapesjs.com/docs/getting-started.html
Initializes the GrapesJS editor, configuring panels, the selector manager, and the style manager with predefined sectors and properties. This setup enables the styling capabilities for components.
```javascript
const editor = grapesjs.init({
// ...
panels: {
defaults: [
// ...
{
id: 'panel-switcher',
el: '.panel__switcher',
buttons: [
{
id: 'show-layers',
active: true,
label: 'Layers',
command: 'show-layers',
// Once activated disable the possibility to turn it off
togglable: false,
},
{
id: 'show-style',
active: true,
label: 'Styles',
command: 'show-styles',
togglable: false,
},
],
},
],
},
// The Selector Manager allows to assign classes and
// different states (eg. :hover) on components.
// Generally, it's used in conjunction with Style Manager
// but it's not mandatory
selectorManager: {
appendTo: '.styles-container',
},
styleManager: {
appendTo: '.styles-container',
sectors: [
{
name: 'Dimension',
open: false,
// Use built-in properties
buildProps: ['width', 'min-height', 'padding'],
// Use `properties` to define/override single property
properties: [
{
// Type of the input,
// options: integer | radio | select | color | slider | file | composite | stack
type: 'integer',
name: 'The width', // Label for the property
property: 'width', // CSS property (if buildProps contains it will be extended)
units: ['px', '%'], // Units, available only for 'integer' types
defaults: 'auto', // Default value
min: 0, // Min value, available only for 'integer' types
},
],
},
{
name: 'Extra',
open: false,
buildProps: ['background-color', 'box-shadow', 'custom-prop'],
properties: [
{
id: 'custom-prop',
name: 'Custom Label',
property: 'font-size',
type: 'select',
defaults: '32px',
// List of options, available only for 'select' and 'radio' types
options: [
{ value: '12px', name: 'Tiny' },
{ value: '18px', name: 'Medium' },
{ value: '32px', name: 'Big' },
],
},
],
},
],
},
});
```
--------------------------------
### Initialize Editor with Modal Options
Source: https://grapesjs.com/docs/api/modal_dialog.html
Customize the initial state of the modal module during editor initialization by passing a configuration object.
```javascript
const editor = grapesjs.init({
modal: {
// options
}
})
```
--------------------------------
### Get All Available States
Source: https://grapesjs.com/docs/api/selector_manager.html
Retrieve an array of all available states that can be applied to selectors.
```javascript
selectorManager.getStates();
```
--------------------------------
### Get Current Selector State
Source: https://grapesjs.com/docs/api/selector_manager.html
Retrieve the value of the current selector state.
```javascript
selectorManager.getState();
```
--------------------------------
### Initialize Style Manager
Source: https://grapesjs.com/docs/api/style_manager.html
Configure the Style Manager during editor initialization by passing an options object.
```javascript
const editor = grapesjs.init({
styleManager: {
// options
}
})
```
--------------------------------
### Get all Symbols
Source: https://grapesjs.com/docs/guides/Symbols.html
Retrieve all Main Symbols currently in the project using `editor.Components.getSymbols()`.
```javascript
const symbols = editor.Components.getSymbols();
const symbolMain = symbols[0];
```
--------------------------------
### Device Manager Methods
Source: https://grapesjs.com/docs/api/device_manager.html
This section details the core methods for interacting with the Device Manager, including adding, retrieving, removing, and selecting devices.
```APIDOC
## add
Add new device
### Parameters
* `props` **Object** Device properties
* `options` **Record** (optional, default `{}`)
### Examples
```javascript
const device1 = deviceManager.add({
id: 'tablet',
name: 'Tablet',
width: '900px',
});
const device2 = deviceManager.add({
id: 'tablet2',
name: 'Tablet 2',
width: '800px',
widthMedia: '810px',
height: '600px',
});
```
Returns **Device** Added device
```
```APIDOC
## get
Return device by ID
### Parameters
* `id` **String** ID of the device
### Examples
```javascript
const device = deviceManager.get('Tablet');
console.log(JSON.stringify(device));
// {name: 'Tablet', width: '900px'}
```
Returns **(Device | null)**
```
```APIDOC
## remove
Remove device
### Parameters
* `device` **(String | Device)** Device or device id
* `opts` (optional, default `{}`)
### Examples
```javascript
const removed = deviceManager.remove('device-id');
// or by passing the Device
const device = deviceManager.get('device-id');
deviceManager.remove(device);
```
Returns **Device** Removed device
```
```APIDOC
## getDevices
Return all devices
### Examples
```javascript
const devices = deviceManager.getDevices();
console.log(JSON.stringify(devices));
// [{name: 'Desktop', width: ''}, ...]
```
Returns **Array**
```
```APIDOC
## select
Change the selected device. This will update the frame in the canvas
### Parameters
* `device` **(String | Device)** Device or device id
* `opts` (optional, default `{}`)
### Examples
```javascript
deviceManager.select('some-id');
// or by passing the page
const device = deviceManager.get('some-id');
deviceManager.select(device);
```
```
```APIDOC
## getSelected
Get the selected device
### Examples
```javascript
const selected = deviceManager.getSelected();
```
Returns **Device**
```
--------------------------------
### Open a Basic Modal
Source: https://grapesjs.com/docs/modules/Modal.html
Initialize the editor and then call `editor.Modal.open()` with title and content to display a modal. A button is added to the body to trigger this function.
```javascript
// Init editor
const editor = grapesjs.init({ ... });
// Open modal
const openModal = () => {
editor.Modal.open({
title: 'My title', // string | HTMLElement
content: 'My content', // string | HTMLElement
});
};
// Create a simple custom button that will open the modal
document.body.insertAdjacentHTML('afterbegin',
'
');
```
--------------------------------
### Get Configuration Object
Source: https://grapesjs.com/docs/api/i18n.html
Retrieve the current configuration object of the I18n module.
```javascript
i18n.getConfig();
```