# Table of Contents - [Introduction | GrapesJS](#introduction-grapesjs) - [API Reference | GrapesJS](#api-reference-grapesjs) - [Component Manager | GrapesJS](#component-manager-grapesjs) - [Components & JS | GrapesJS](#components-js-grapesjs) - [Getting Started | GrapesJS](#getting-started-grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [Plugins | GrapesJS](#plugins-grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [GrapesJS](#grapesjs) - [Trait Manager | GrapesJS](#trait-manager-grapesjs) - [Block Manager | GrapesJS](#block-manager-grapesjs) - [Asset Manager | GrapesJS](#asset-manager-grapesjs) - [Pages | GrapesJS](#pages-grapesjs) - [I18n (Internationalization) | GrapesJS](#i18n-internationalization-grapesjs) - [Selector Manager | GrapesJS](#selector-manager-grapesjs) - [Commands | GrapesJS](#commands-grapesjs) - [Layer Manager | GrapesJS](#layer-manager-grapesjs) - [Style Manager | GrapesJS](#style-manager-grapesjs) - [Modal | GrapesJS](#modal-grapesjs) - [Replace the built-in Rich Text Editor | GrapesJS](#replace-the-built-in-rich-text-editor-grapesjs) - [Storage Manager | GrapesJS](#storage-manager-grapesjs) - [Symbols | GrapesJS](#symbols-grapesjs) - [Use Custom CSS Parser | GrapesJS](#use-custom-css-parser-grapesjs) - [GrapesJS Telemetry | GrapesJS](#grapesjs-telemetry-grapesjs) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) --- # Introduction | GrapesJS [#](#introduction) Introduction ================================ * [What is GrapesJS?](#what-is-grapesjs) * [Why GrapesJS?](#why-grapesjs) * [Quick Start](#quick-start) * [Download](#download) * [Changelog](#changelog) [#](#what-is-grapesjs) What is GrapesJS? ----------------------------------------- At first glance one might think this is just another page/HTML builder, but it's something more. GrapesJS is a multi-purpose, Web Builder Framework, which means it allows you to easily create a drag & drop enabled builder of "things". By "things" we mean anything with HTML-like structure, which entails much more than web pages. We use HTML-like structure basically everywhere: Newsletters (eg. [MJML (opens new window)](https://mjml.io/) ), Native Mobile Applications (eg. [React Native (opens new window)](https://github.com/facebook/react-native) ), Native Desktop Applications (eg. [Vuido (opens new window)](https://vuido.mimec.org) ), PDFs (eg. [React PDF (opens new window)](https://github.com/diegomura/react-pdf) ), etc. So, for everything you can imagine as a set of elements like `... other nested elements ...` you can create easily a GrapesJS builder around it and then use it independently in your applications. GrapesJS ships with features and tools that enable you to craft easy to use builders. Which allows your users to create complex HTML-like templates without any knowledge of coding. [#](#why-grapesjs) Why GrapesJS? --------------------------------- GrapesJS was designed primarily for use inside Content Management Systems to speed up the creation of dynamic templates and replace common WYSIWYG editors, which are good for content editing, but inappropriate for creating HTML structures. Instead of creating an application we decided to create an extensible framework that could be used by anyone for any purpose. [#](#quick-start) Quick Start ------------------------------ To showcase the power of GrapesJS we have created some presets. * [grapesjs-preset-webpage (opens new window)](https://github.com/GrapesJS/preset-webpage) - [Webpage Builder (opens new window)](https://grapesjs.com/demo.html) * [grapesjs-preset-newsletter (opens new window)](https://github.com/GrapesJS/preset-newsletter) - [Newsletter Builder (opens new window)](https://grapesjs.com/demo-newsletter-editor.html) * [grapesjs-mjml (opens new window)](https://github.com/GrapesJS/mjml) - [Newsletter Builder with MJML (opens new window)](https://grapesjs.com/demo-mjml.html) You can actually use them as a starting point for your editors, so, just follow the instructions on their repositories to get a quick start for your builder. [#](#download) Download ------------------------ Latest version: [![npm](https://img.shields.io/npm/v/grapesjs.svg?colorB=e67891) (opens new window)](https://www.npmjs.com/package/grapesjs) You can download GrapesJS from one of these sources * CDNs * unpkg * `https://unpkg.com/grapesjs` * `https://unpkg.com/grapesjs/dist/css/grapes.min.css` * cdnjs * `https://cdnjs.cloudflare.com/ajax/libs/grapesjs/0.12.17/grapes.min.js` * `https://cdnjs.cloudflare.com/ajax/libs/grapesjs/0.12.17/css/grapes.min.css` * npm * `npm i grapesjs` * git * `git clone https://github.com/GrapesJS/grapesjs.git` [#](#changelog) Changelog -------------------------- To track changes made in the library we rely on [Github Releases (opens new window)](https://github.com/GrapesJS/grapesjs/releases) [Getting Started](/docs/getting-started.html) → --- # API Reference | GrapesJS [#](#api-reference) API Reference ================================== Here you can find the documentation about GrapesJS' APIs. Mainly, you would use them for your editor to extend the basic functionality of the framework or you could also [create a plugin](/docs/modules/Plugins.html) and make those extensions reusable and available to others. [Editor](/docs/api/editor.html) → --- # Component Manager | GrapesJS [#](#component-manager) Component Manager ========================================== The Component is a base element of the template. It might be something simple and atomic like an image or a text box, but also complex structures, more probably composed by other components, like sections or pages. The concept of the component was made to allow the developer to bind different behaviors to different elements. For example, opening the Asset Manager on double click of the image is a custom behavior bound to that particular type of element. WARNING This guide is referring to GrapesJS v0.15.8 or higher * [How Components work?](#how-components-work) * [Component Definition](#component-definition) * [Component Recognition and Component Type Stack](#component-recognition-and-component-type-stack) * [Component instance](#component-instance) * [Component rendering](#component-rendering) * [Built-in Component Types](#built-in-component-types) * [Define Custom Component Type](#define-custom-component-type) * [isComponent](#iscomponent) * [Model](#model) * [View](#view) * [Update Component Type](#update-component-type) * [Extend Component Type](#extend-component-type) * [Extend parent functions](#extend-parent-functions) * [Lifecycle Hooks](#lifecycle-hooks) * [Components & CSS](#components-css) * [External CSS](#external-css) * [Components & JS](#components-js) * [Tips](#tips) * [JSX syntax](#jsx-syntax) [#](#how-components-work) How Components work? ----------------------------------------------- Let's see in detail how components work by looking at all the steps from adding an HTML string to the editor. TIP All the following snippets can be run directly in console from the [main demo (opens new window)](https://grapesjs.com/demo.html) This is how we can add new components to the canvas: // Append components directly to the canvas editor.addComponents(`
Hello world!!!
`); // or into some, already defined, component. // For instance, appending to a selected component would be: editor.getSelected().append(`
...`); // Actually, editor.addComponents is an alias of... editor.getWrapper().append(`
...`); TIP If you need to append a component at a specific position, you can use `at` option. So, to add a component on top of all others (in the same collection) you would use component.append('
...', { at: 0 }); or in the middle const { length } = component.components(); component.append('
...', { at: parseInt(length / 2, 10) }); ### [#](#component-definition) Component Definition In the first step, the HTML string is parsed and transformed to what is called **Component Definition**, so the result of the input above would be: { tagName: 'div', components: [\ {\ type: 'image',\ attributes: { src: 'https://path/image' },\ }, {\ tagName: 'span',\ type: 'text',\ attributes: { title: 'foo' },\ components: [{\ type: 'textnode',\ content: 'Hello world!!!'\ }]\ }\ ] } The real **Component Definition** would be a little bit bigger so we've reduced the JSON for the sake of simplicity. You might notice the result is similar to what is generally called a **Virtual DOM**, a lightweight representation of the DOM element. This actually helps the editor to keep track of the state of our elements and make performance-friendly changes/updates. The meaning of properties like `tagName`, `attributes` and `components` are quite obvious, but what about `type`?! This particular property specifies the **Component Type** of our **Component Definition** (you check the list of default components [below](#built-in-component-types) ) and if it's omitted, the default one will be used `type: 'default'`. At this point, a good question would be, how the editor assigns those types by starting from a simple HTML string? This step is identified as **Component Recognition** and it's explained in detail in the next paragraph. ### [#](#component-recognition-and-component-type-stack) Component Recognition and Component Type Stack As we mentioned before, when you pass an HTML string as a component to the editor, that string is parsed and compiled to the [Component Definition](#component-definition) with a new `type` property. To understand what `type` should be assigned, for each parsed HTML Element, the editor iterates over all the defined components, called **Component Type Stack**, and checks via `isComponent` method (we will see it later) if that component type is appropriate for that element. The Component Type Stack is just a simple array of component types but what matters is the order of those types. Any new added custom **Component Type** (we'll see later how to create them) goes on top of the Component Type Stack and each element returned from the parser iterates the stack from top to bottom (the last element of the stack is the `default` one), the iteration stops once one of the component returns a truthy value from the `isComponent` method. ![](/docs/component-type-stack.svg) TIP If you're importing big string chunks of HTML code you might want to improve the performances by skipping the parsing and the component recognition steps by passing directly Component Definition objects or using the JSX syntax. Read [here](#setup-jsx-syntax) about how to setup JSX syntax parser ### [#](#component-instance) Component instance Once the **Component Definition** is ready and the type is assigned, the [Component](/docs/api/component.html) instance can be created (known also as the **Model**). Let's step back to our previous example with the HTML string, the result of the `append` method is an array of added components. const component = editor.addComponents(`
Hello world!!!
`)[0]; The Component instance contains properties and methods which allows you to obtain its data and change them. You can read properties with the `get` method, like, for example, the `type` const componentType = component.get('type'); // eg. 'image' and to update properties you'd use `set`, which might change the way a component behaves in the canvas. // Make the component not draggable component.set('draggable', false); You can also use methods like `getAttributes`, `setAttributes`, `components`, etc. const innerComponents = component.components(); innerComponents.forEach((comp) => console.log(comp.toHTML())); // Update component content component.components(`
Component 1
Component 2
`); Each component can define its own properties and methods but all of them will always extend, at least, the `default` one (then you will see how to create new custom components and how to extend the already defined) so it's good to check the [Component API](/docs/api/component.html) to see all available properties and methods. The **main purpose of the Component** is to keep track of its data and to return them when necessary. One common thing you might need to ask from the component is to show its current HTML const componentHTML = component.toHTML(); This will return a string containing the HTML of the component and all of its children. The component implements also `toJSON` methods so you can get its JSON structure in this way JSON.stringify(component); TIP For storing/loading all the components you should rely on the [Storage Manager](/docs/modules/storage.html) So, the **Component instance** is responsible for the **final data** (eg. HTML, JSON) of your templates. If you need, for example, to update/add some attribute in the HTML you need to update its component (eg. `component.addAttributes({ title: 'Title added' })`), so the Component/Model is your **Source of Truth**. ### [#](#component-rendering) Component rendering Another important part of components is how they are rendered in the **canvas**, this aspect is handled by its **View**. It has nothing to do with the **final HTML data**, you can return a big `
...
` string as HTML of your component but render it as a simple image in the canvas (think about placeholders for complex/dynamic data). By default, the view of components is automatically synced with the data of its models (you can't have a View without a Model). If you update the attribute of the component or append a new one as a child, the view will render it in the canvas. Unfortunately, sometimes, you might need some additional logic to handle better the component result. Think about allowing a user build its `` element, for this specific case you might want to add custom buttons in the canvas, so it'd be easier adding/removing columns/rows. To handle those cases you can rely on the View, where you can add additional DOM component, attach events, etc. All of this will be completely unrelated with the final HTML of the `
` (the result the user would expect) as it handled by the Model. Once the component is rendered you can always access its View and the DOM element. const component = editor.getSelected(); // Get the View const view = component.getView(); // Get the DOM element const el = component.getEl(); Generally, the View is something you wouldn't need to change as the default one handles already the sync with the Model but in case you'd need more control over elements (eg. custom UI in canvas) you'll probably need to create a custom component type and extend the default View with your logic. We'll see later how to create custom Component Types. So far we have seen the core concept behind Components and how they work. The **Model/Component** is the **source of truth** for the final code of templates (eg. the HTML export relies on it) and the **View/ComponentView** is what is used by the editor to **preview our components** to users in the canvas. [#](#built-in-component-types) Built-in Component Types -------------------------------------------------------- Here below you can see the list of built-in component types, ordered by their position in the **Component Type Stack** * [`cell` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentTableCell.ts) - Component for handle `` elements * [`table` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentTable.ts) - Component for handle `
` and `` elements * [`row` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentTableRow.ts) - Component for handle `
` elements * [`thead` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentTableHead.ts) - Component for handle `` elements * [`tbody` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentTableBody.ts) - Component for handle `` elements * [`tfoot` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentTableFoot.ts) - Component for handle `` elements * [`map` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentMap.ts) - Component for handle `` elements * [`link` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentLink.ts) - Component for handle `` elements * [`label` (opens new window)](https://github.com/GrapesJS/grapesjs/blob/dev/packages/core/src/dom_components/model/ComponentLabel.ts) - Component for handle properly `

Put your ...'}, ...] Returns **Collection<[Block](/docs/api/block.html) \>** [#](#getallvisible) getAllVisible ---------------------------------- Return the visible collection, which containes blocks actually rendered Returns **Collection<[Block](/docs/api/block.html) \>** [#](#remove) remove -------------------- Remove block. ### [#](#parameters-3) Parameters * `block` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Block](/docs/api/block.html) )** Block or block ID * `opts` (optional, default `{}`) ### [#](#examples-4) Examples const removed = blockManager.remove('BLOCK_ID'); // or by passing the Block const block = blockManager.get('BLOCK_ID'); blockManager.remove(block); Returns **[Block](/docs/api/block.html) ** Removed block [#](#getcategories) getCategories ---------------------------------- Get all available categories. It's possible to add categories only within blocks via 'add()' method Returns **([Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) | Collection)** [#](#getcontainer) getContainer -------------------------------- Return the Blocks container element Returns **[HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) ** [#](#getdragblock) getDragBlock -------------------------------- Returns currently dragging block. Updated when the drag starts and cleared once it's done. Returns **([Block](/docs/api/block.html) | [undefined (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined) )** [#](#getblocksbycategory) getBlocksByCategory ---------------------------------------------- Get blocks by category. ### [#](#parameters-4) Parameters * `blocks` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ?** ### [#](#examples-5) Examples blockManager.getBlocksByCategory(); // Returns an array of items of this type // > { category?: Category; items: Block[] } // NOTE: The item without category is the one containing blocks without category. // You can also get the same output format by passing your own array of Blocks const myFilteredBlocks: Block[] = [...]; blockManager.getBlocksByCategorymyFilteredBlocks Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#render) render -------------------- Render blocks ### [#](#parameters-5) Parameters * `blocks` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Blocks to render, without the argument will render all global blocks * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.external` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Render blocks in a new container (HTMLElement will be returned) * `opts.ignoreCategories` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Render blocks without categories ### [#](#examples-6) Examples // Render all blocks (inside the global collection) blockManager.render(); // Render new set of blocks const blocks = blockManager.getAll(); const filtered = blocks.filter(block => block.get('category') == 'sections') blockManager.render(filtered); // Or a new set from an array blockManager.render([\ {label: 'Label text', content: '
Content
'}\ ]); // Back to blocks from the global collection blockManager.render(); // You can also render your blocks outside of the main block container const newBlocksEl = blockManager.render(filtered, { external: true }); document.getElementById('some-id').appendChild(newBlocksEl); Returns **[HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) ** Rendered element ← [‍ ‍ ‍ Asset](/docs/api/asset.html) [‍ ‍ ‍ Block](/docs/api/block.html) → --- # GrapesJS [#](#block) Block ------------------ ### [#](#properties) Properties * `label` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Block label, eg. `My block` * `content` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) )** The content of the block. Might be an HTML string or a [Component Defintion](/docs/modules/Components.html#component-definition) * `media` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** HTML string for the media/icon of the block, eg. ` editor.getWrapper().append(block.get('content'))` * `attributes` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Block attributes to apply in the view element [#](#getid) getId ------------------ Get block id Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getlabel) getLabel ------------------------ Get block label Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getmedia) getMedia ------------------------ Get block media Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getcontent) getContent ---------------------------- Get block content Returns **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )>)** [#](#getdragdef) getDragDef ---------------------------- Get block component dragDef Returns **ComponentDefinition** [#](#getcategorylabel) getCategoryLabel ---------------------------------------- Get block category label Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ← [Block Manager](/docs/api/block_manager.html) [Commands](/docs/api/commands.html) → --- # GrapesJS [#](#commands) Commands ------------------------ You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/commands/config/config.ts) const editor = grapesjs.init({ commands: { // options } }) Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. // Listen to events editor.on('run', () => { ... }); // Use the API const commands = editor.Commands; commands.add(...); [#](#available-events) Available Events ---------------------------------------- * `command:run` Triggered on run of any command. editor.on('command:run', ({ id, result, options }) => { console.log('Command id', id, 'command result', result); }); * `command:run:COMMAND-ID` Triggered on run of a specific command. editor.on('command:run:my-command', ({ result, options }) => { ... }); * `command:run:before:COMMAND-ID` Triggered before the command is called. editor.on('command:run:before:my-command', ({ options }) => { ... }); * `command:abort:COMMAND-ID` Triggered when the command execution is aborted. editor.on('command:abort:my-command', ({ options }) => { ... }); // The command could be aborted during the before event editor.on('command:run:before:my-command', ({ options }) => { if (someCondition) { options.abort = true; } }); * `command:stop` Triggered on stop of any command. editor.on('command:stop', ({ id, result, options }) => { console.log('Command id', id, 'command result', result); }); * `command:stop:COMMAND-ID` Triggered on stop of a specific command. editor.on('command:run:my-command', ({ result, options }) => { ... }); * `command:stop:before:COMMAND-ID` Triggered before the command is called to stop. editor.on('command:stop:before:my-command', ({ options }) => { ... }); [#](#methods) Methods ---------------------- * [add](#add) * [get](#get) * [getAll](#getall) * [extend](#extend) * [has](#has) * [run](#run) * [stop](#stop) * [isActive](#isactive) * [getActive](#getactive) [#](#add) add -------------- Add new command to the collection ### [#](#parameters) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Command's ID * `command` **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) )** Object representing your command, By passing just a function it's intended as a stateless command (just like passing an object with only `run` method). ### [#](#examples) Examples commands.add('myCommand', { run(editor, sender) { alert('Hello world!'); }, stop(editor, sender) { }, }); // As a function commands.add('myCommand2', editor => { ... }); Returns **this** [#](#get) get -------------- Get command by ID ### [#](#parameters-2) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Command's ID ### [#](#examples-2) Examples var myCommand = commands.get('myCommand'); myCommand.run(); Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Object representing the command [#](#extend) extend -------------------- Extend the command. The command to extend should be defined as an object ### [#](#parameters-3) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Command's ID * `cmd` **CommandObject** (optional, default `{}`) * `Object` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** with the new command functions ### [#](#examples-3) Examples commands.extend('old-command', { someInnerFunction() { // ... } }); Returns **this** [#](#has) has -------------- Check if command exists ### [#](#parameters-4) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Command's ID Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#getall) getAll -------------------- Get an object containing all the commands Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#run) run -------------- Execute the command ### [#](#parameters-5) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Command ID * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) ### [#](#examples-4) Examples commands.run('myCommand', { someOption: 1 }); Returns **any** The return is defined by the command [#](#stop) stop ---------------- Stop the command ### [#](#parameters-6) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Command ID * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) ### [#](#examples-5) Examples commands.stop('myCommand', { someOption: 1 }); Returns **any** The return is defined by the command [#](#isactive) isActive ------------------------ Check if the command is active. You activate commands with `run` and disable them with `stop`. If the command was created without `stop` method it can't be registered as active ### [#](#parameters-7) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Command id ### [#](#examples-6) Examples const cId = 'some-command'; commands.run(cId); commands.isActive(cId); // -> true commands.stop(cId); commands.isActive(cId); // -> false Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#getactive) getActive -------------------------- Get all active commands ### [#](#examples-7) Examples console.log(commands.getActive()); // -> { someCommand: itsLastReturn, anotherOne: ... }; Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** ← [‍ ‍ ‍ Block](/docs/api/block.html) [DOM Components](/docs/api/components.html) → --- # GrapesJS [#](#pages) Pages ------------------ You can customize the initial state of the module from the editor initialization const editor = grapesjs.init({ .... pageManager: { pages: [\ {\ id: 'page-id',\ styles: `.my-class { color: red }`, // or a JSON of styles\ component: '
My element
', // or a JSON of components\ }\ ] }, }) Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance const pageManager = editor.Pages; [#](#available-events) Available Events ---------------------------------------- * `page:add` Added new page. The page is passed as an argument to the callback. editor.on('page:add', (page) => { ... }); * `page:remove` Page removed. The page is passed as an argument to the callback. editor.on('page:remove', (page) => { ... }); * `page:select` New page selected. The newly selected page and the previous one, are passed as arguments to the callback. editor.on('page:select', (page, previousPage) => { ... }); * `page:update` Page updated. The updated page and the object containing changes are passed as arguments to the callback. editor.on('page:update', (page, changes) => { ... }); * `page` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. editor.on('page', ({ event, model, ... }) => { ... }); [#](#getall) getAll -------------------- Get all pages ### [#](#examples) Examples const arrayOfPages = pageManager.getAll(); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Page](/docs/api/page.html) \>** [#](#add) add -------------- Add new page ### [#](#parameters) Parameters * `props` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Page properties * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Options (optional, default `{}`) ### [#](#examples-2) Examples 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](/docs/api/page.html) ** [#](#remove) remove -------------------- Remove page ### [#](#parameters-2) Parameters * `page` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Page](/docs/api/page.html) )** Page or page id * `opts` **any** (optional, default `{}`) ### [#](#examples-3) Examples const removedPage = pageManager.remove('page-id'); // or by passing the page const somePage = pageManager.get('page-id'); pageManager.remove(somePage); Returns **[Page](/docs/api/page.html) ** Removed Page [#](#get) get -------------- Get page by id ### [#](#parameters-3) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Page id ### [#](#examples-4) Examples const somePage = pageManager.get('page-id'); Returns **[Page](/docs/api/page.html) ** [#](#getmain) getMain ---------------------- Get main page (the first one available) ### [#](#examples-5) Examples const mainPage = pageManager.getMain(); Returns **[Page](/docs/api/page.html) ** [#](#getallwrappers) getAllWrappers ------------------------------------ Get wrapper components (aka body) from all pages and frames. ### [#](#examples-6) Examples const wrappers = pageManager.getAllWrappers(); // Get all `image` components from the project const allImages = wrappers.map(wrp => wrp.findType('image')).flat(); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Component](/docs/api/component.html) \>** [#](#select) select -------------------- Change the selected page. This will switch the page rendered in canvas ### [#](#parameters-4) Parameters * `page` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Page](/docs/api/page.html) )** Page or page id * `opts` **SetOptions** (optional, default `{}`) ### [#](#examples-7) Examples pageManager.select('page-id'); // or by passing the page const somePage = pageManager.get('page-id'); pageManager.select(somePage); Returns **this** [#](#getselected) getSelected ------------------------------ Get the selected page ### [#](#examples-8) Examples const selectedPage = pageManager.getSelected(); Returns **[Page](/docs/api/page.html) ** ← [Panels](/docs/api/panels.html) [‍ ‍ ‍ Page](/docs/api/page.html) → --- # GrapesJS [#](#components) Components ---------------------------- With this module is possible to manage components inside the canvas. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/dom_components/config/config.ts) const editor = grapesjs.init({ domComponents: { // options } }) Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. // Listen to events editor.on('component:create', () => { ... }); // Use the API const cmp = editor.Components; cmp.addType(...); [#](#available-events) Available Events ---------------------------------------- * `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 * `component:resize` - During component resize. [#](#methods) Methods ---------------------- * [getWrapper](#getwrapper) * [getComponents](#getcomponents) * [addComponent](#addcomponent) * [clear](#clear) * [addType](#addtype) * [getType](#gettype) * [getTypes](#gettypes) [#](#getwrapper) getWrapper ---------------------------- Returns root component inside the canvas. Something like `` inside HTML page The wrapper doesn't differ from the original Component Model ### [#](#examples) Examples // Change background of the wrapper and set some attribute var wrapper = cmp.getWrapper(); wrapper.set('style', {'background-color': 'red'}); wrapper.set('attributes', {'title': 'Hello!'}); Returns **[Component](/docs/api/component.html) ** Root Component [#](#getcomponents) getComponents ---------------------------------- Returns wrapper's children collection. Once you have the collection you can add other Components(Models) inside. Each component can have several nested components inside and you can nest them as more as you wish. ### [#](#examples-2) Examples // 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); Returns **[Components](#components) ** Collection of components [#](#addcomponent) addComponent -------------------------------- Add new components to the wrapper's children. It's the same as 'cmp.getComponents().add(...)' ### [#](#parameters) Parameters * `component` **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [Component](/docs/api/component.html) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>)** Component/s to add * `component.tagName` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Tag name (optional, default `'div'`) * `component.type` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Type of the component. Available: ''(default), 'text', 'image' (optional, default `''`) * `component.removable` **[boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If component is removable (optional, default `true`) * `component.draggable` **[boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If is possible to move the component around the structure (optional, default `true`) * `component.droppable` **[boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If is possible to drop inside other components (optional, default `true`) * `component.badgable` **[boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If the badge is visible when the component is selected (optional, default `true`) * `component.stylable` **[boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If is possible to style component (optional, default `true`) * `component.copyable` **[boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If is possible to copy&paste the component (optional, default `true`) * `component.content` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** String inside component (optional, default `''`) * `component.style` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Style object (optional, default `{}`) * `component.attributes` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Attribute object (optional, default `{}`) * `opt` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** the options object to be used by the \[Components.add\][getComponents](getComponents) method (optional, default `{}`) ### [#](#examples-3) Examples // Example of a new component with some extra property var comp1 = cmp.addComponent({ tagName: 'div', removable: true, // Can't remove it draggable: true, // Can't move it copyable: true, // Disable copy/past content: 'Content text', // Text inside component style: { color: 'red'}, attributes: { title: 'here' } }); Returns **([Component](/docs/api/component.html) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Component](/docs/api/component.html) \>)** Component/s added [#](#clear) clear ------------------ Remove all components ### [#](#parameters-2) Parameters * `opts` (optional, default `{}`) Returns **this** [#](#addtype) addType ---------------------- Add new component type. Read more about this in [Define New Component (opens new window)](https://grapesjs.com/docs/modules/Components.html#define-new-component) ### [#](#parameters-3) Parameters * `type` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component ID * `methods` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Component methods Returns **this** [#](#gettype) getType ---------------------- Get component type. Read more about this in [Define New Component (opens new window)](https://grapesjs.com/docs/modules/Components.html#define-new-component) ### [#](#parameters-4) Parameters * `type` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component ID Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Component type definition, eg. `{ model: ..., view: ... }` [#](#removetype) removeType ---------------------------- Remove component type ### [#](#parameters-5) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** * `type` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component ID Returns **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [undefined (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined) )** Removed component type, undefined otherwise [#](#gettypes) getTypes ------------------------ Return the array of all types Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#iscomponent) isComponent ------------------------------ Check if the object is a \[Component\]. ### [#](#parameters-6) Parameters * `obj` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** ### [#](#examples-4) Examples cmp.isComponent(editor.getSelected()); // true cmp.isComponent({}); // false Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#addsymbol) addSymbol -------------------------- Add a new symbol from a component. If the passed component is not a symbol, it will be converted to an instance and will return the main symbol. If the passed component is already an instance, a new instance will be created and returned. If the passed component is the main symbol, a new instance will be created and returned. ### [#](#parameters-7) Parameters * `component` **[Component](/docs/api/component.html) ** Component from which create a symbol. ### [#](#examples-5) Examples const symbol = cmp.addSymbol(editor.getSelected()); // cmp.getSymbolInfo(symbol).isSymbol === true; Returns **[Component](/docs/api/component.html) ** [#](#getsymbols) getSymbols ---------------------------- Get the array of main symbols. ### [#](#examples-6) Examples const symbols = cmp.getSymbols(); // [Component, Component, ...] // Removing the main symbol will detach all the relative instances. symbols[0].remove(); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Component](/docs/api/component.html) \>** [#](#detachsymbol) detachSymbol -------------------------------- Detach symbol instance from the main one. The passed symbol instance will become a regular component. ### [#](#parameters-8) Parameters * `component` **[Component](/docs/api/component.html) ** The component symbol to detach. ### [#](#examples-7) Examples const cmpInstance = editor.getSelected(); // cmp.getSymbolInfo(cmpInstance).isInstance === true; cmp.detachSymbol(cmpInstance); // cmp.getSymbolInfo(cmpInstance).isInstance === false; [#](#getsymbolinfo) getSymbolInfo ---------------------------------- Get info about the symbol. ### [#](#parameters-9) Parameters * `component` **[Component](/docs/api/component.html) ** Component symbol from which to get the info. * `opts` **{withChanges: [string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?}** (optional, default `{}`) ### [#](#examples-8) Examples cmp.getSymbolInfo(editor.getSelected()); // > { isSymbol: true, isMain: false, isInstance: true, ... } Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Object containing symbol info. [#](#canmove) canMove ---------------------- Check if a component can be moved inside another one. ### [#](#parameters-10) Parameters * `target` **[Component](/docs/api/component.html) ** The target component is the one that is supposed to receive the source one. * `source` **([Component](/docs/api/component.html) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** The source can be another component, a component definition or an HTML string. * `index` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ?** Index position, if not specified, the check will be performed against appending the source to the target. ### [#](#examples-9) Examples const rootComponent = editor.getWrapper(); const someComponent = editor.getSelected(); // Check with two components editor.Components.canMove(rootComponent, someComponent); // Check with component definition editor.Components.canMove(rootComponent, { tagName: 'a', draggable: false }); // Check with HTML string editor.Components.canMove(rootComponent, '
...'); Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Object containing the `result` (Boolean), `source`, `target` (as Components), and a `reason` (Number) with these meanings:\* `0` - Invalid source. This is a default value and should be ignored in case the `result` is true. * `1` - Source doesn't accept target as destination. * `2` - Target doesn't accept source. ← [Commands](/docs/api/commands.html) [‍ ‍ ‍ Component](/docs/api/component.html) → --- # GrapesJS [#](#getid) getId ------------------ Get page id Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getname) getName ---------------------- Get page name Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#setname) setName ---------------------- Update page name ### [#](#parameters) Parameters * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** New page name ### [#](#examples) Examples page.setName('New name'); [#](#getallframes) getAllFrames -------------------------------- Get all frames ### [#](#examples-2) Examples const arrayOfFrames = page.getAllFrames(); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#getmainframe) getMainFrame -------------------------------- Get the first frame of the page (identified always as the main one) ### [#](#examples-3) Examples const mainFrame = page.getMainFrame(); Returns **Frame** [#](#getmaincomponent) getMainComponent ---------------------------------------- Get the root component (usually is the `wrapper` component) from the main frame ### [#](#examples-4) Examples const rootComponent = page.getMainComponent(); console.log(rootComponent.toHTML()); Returns **Component** ← [Pages](/docs/api/pages.html) [Layers](/docs/api/layer_manager.html) → --- # GrapesJS [#](#layers) Layers -------------------- You can customize the initial state of the module from the editor initialization const editor = grapesjs.init({ // ... layerManager: { // ... }, }) Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance const layers = editor.Layers; [#](#available-events) Available Events ---------------------------------------- * `layer:root` - Root layer changed. The new root component is passed as an argument to the callback. * `layer:component` - Component layer is updated. The updated component is passed as an argument to the callback. [#](#methods) Methods ---------------------- * [setRoot](#setroot) * [getRoot](#getroot) * [getComponents](#getcomponents) * [setOpen](#setopen) * [isOpen](#isopen) * [setVisible](#setvisible) * [isVisible](#isvisible) * [setlocked](#setlocked) * [isLocked](#islocked) * [setName](#setname) * [getName](#getname) * [getLayerData](#getlayerdata) [#](#setroot) setRoot ---------------------- Update the root layer with another component. ### [#](#parameters) Parameters * `component` **([Component](/docs/api/component.html) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Component to be set as root ### [#](#examples) Examples const component = editor.getSelected(); layers.setRoot(component); Returns **[Component](/docs/api/component.html) ** [#](#getroot) getRoot ---------------------- Get the current root layer. ### [#](#examples-2) Examples const layerRoot = layers.getRoot(); Returns **[Component](/docs/api/component.html) ** [#](#getcomponents) getComponents ---------------------------------- Get valid layer child components (eg. excludes non layerable components). ### [#](#parameters-2) Parameters * `component` **[Component](/docs/api/component.html) ** Component from which you want to get child components ### [#](#examples-3) Examples const component = editor.getSelected(); const components = layers.getComponents(component); console.log(components); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Component](/docs/api/component.html) \>** [#](#setopen) setOpen ---------------------- Update the layer open state of the component. ### [#](#parameters-3) Parameters * `component` **[Component](/docs/api/component.html) ** Component to update * `value` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#isopen) isOpen -------------------- Check the layer open state of the component. ### [#](#parameters-4) Parameters * `component` **[Component](/docs/api/component.html) ** Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#setvisible) setVisible ---------------------------- Update the layer visibility state of the component. ### [#](#parameters-5) Parameters * `component` **[Component](/docs/api/component.html) ** Component to update * `value` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#isvisible) isVisible -------------------------- Check the layer visibility state of the component. ### [#](#parameters-6) Parameters * `component` **[Component](/docs/api/component.html) ** Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#setlocked) setLocked -------------------------- Update the layer locked state of the component. ### [#](#parameters-7) Parameters * `component` **[Component](/docs/api/component.html) ** Component to update * `value` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#islocked) isLocked ------------------------ Check the layer locked state of the component. ### [#](#parameters-8) Parameters * `component` **[Component](/docs/api/component.html) ** Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#setname) setName ---------------------- Update the layer name of the component. ### [#](#parameters-9) Parameters * `component` **[Component](/docs/api/component.html) ** Component to update * `value` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** New name [#](#getname) getName ---------------------- Get the layer name of the component. ### [#](#parameters-10) Parameters * `component` **[Component](/docs/api/component.html) ** Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component layer name [#](#getlayerdata) getLayerData -------------------------------- Get layer data from a component. ### [#](#parameters-11) Parameters * `component` **[Component](/docs/api/component.html) ** Component from which you want to read layer data. ### [#](#examples-4) Examples const component = editor.getSelected(); const layerData = layers.getLayerData(component); console.log(layerData); Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Object containing the layer data. ← [‍ ‍ ‍ Page](/docs/api/page.html) [Style Manager](/docs/api/style_manager.html) → --- # GrapesJS [#](#panels) Panels -------------------- You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/panels/config/config.ts) const editor = grapesjs.init({ panels: { // options } }) Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance const panelManager = editor.Panels; * [addPanel](#addpanel) * [addButton](#addbutton) * [getButton](#getbutton) * [getPanel](#getpanel) * [getPanels](#getpanels) * [getPanelsEl](#getpanelsel) * [removePanel](#removepanel) * [removeButton](#removebutton) [#](#getpanels) getPanels -------------------------- Returns the collection of panels Returns **Collection** Collection of panel [#](#getpanelsel) getPanelsEl ------------------------------ Returns panels element Returns **[HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) ** [#](#addpanel) addPanel ------------------------ Add new panel to the collection ### [#](#parameters) Parameters * `panel` **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | Panel)** Object with right properties or an instance of Panel ### [#](#examples) Examples const newPanel = panelManager.addPanel({ id: 'myNewPanel', visible: true, buttons: [...], }); Returns **Panel** Added panel. Useful in case passed argument was an Object [#](#removepanel) removePanel ------------------------------ Remove a panel from the collection ### [#](#parameters-2) Parameters * `panel` **(Panel | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Panel instance or panel id ### [#](#examples-2) Examples const somePanel = panelManager.getPanel('somePanel'); const removedPanel = panelManager.removePanel(somePanel); // or by id const removedPanel = panelManager.removePanel('myNewPanel'); Returns **Panel** Removed panel [#](#getpanel) getPanel ------------------------ Get panel by ID ### [#](#parameters-3) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Id string ### [#](#examples-3) Examples const myPanel = panelManager.getPanel('myPanel'); Returns **(Panel | null)** [#](#addbutton) addButton -------------------------- Add button to the panel ### [#](#parameters-4) Parameters * `panelId` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Panel's ID * `button` **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | Button)** Button object or instance of Button ### [#](#examples-4) Examples const newButton = panelManager.addButton('myNewPanel',{ id: 'myNewButton', className: 'someClass', command: 'someCommand', attributes: { title: 'Some title'}, active: false, }); // It's also possible to pass the command as an object // with .run and .stop methods ... command: { run: function(editor) { ... }, stop: function(editor) { ... } }, // Or simply like a function which will be evaluated as a single .run command ... command: function(editor) { ... } Returns **(Button | null)** Added button. Useful in case passed button was an Object [#](#removebutton) removeButton -------------------------------- Remove button from the panel ### [#](#parameters-5) Parameters * `panelId` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Panel's ID * `button` **any** * `buttonId` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Button's ID ### [#](#examples-5) Examples const removedButton = panelManager.addButton('myNewPanel',{ id: 'myNewButton', className: 'someClass', command: 'someCommand', attributes: { title: 'Some title'}, active: false, }); const removedButton = panelManager.removeButton('myNewPanel', 'myNewButton'); Returns **(Button | null)** Removed button. [#](#getbutton) getButton -------------------------- Get button from the panel ### [#](#parameters-6) Parameters * `panelId` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Panel's ID * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Button's ID ### [#](#examples-6) Examples const button = panelManager.getButton('myPanel', 'myButton'); Returns **(Button | null)** ← [‍ ‍ ‍ Component](/docs/api/component.html) [Pages](/docs/api/pages.html) → --- # GrapesJS [#](#component) Component -------------------------- The Component object represents a single node of our template structure, so when you update its properties the changes are immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all the tree of nodes). An example on how to update properties: component.set({ tagName: 'span', attributes: { ... }, removable: false, }); component.get('tagName'); // -> 'span' ### [#](#properties) Properties * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Component type, eg. `text`, `image`, `video`, etc. * `tagName` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** HTML tag of the component, eg. `span`. Default: `div` * `attributes` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}` * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Name of the component. Will be used, for example, in Layers and badges * `removable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** When `true` the component is removable from the canvas, default: `true` * `draggable` **([Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) )?** Indicates if it's possible to drag the component inside others. You can also specify a query string to indentify elements, eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true` * `droppable` **([Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) )?** Indicates if it's possible to drop other components inside. You can use a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true` * `badgable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Set to false if you don't want to see the badge (with the name) over the component. Default: `true` * `stylable` **([Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>)?** True if it's possible to style the component. You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties will be hidden from the style manager. Default: `true` * `stylable-require` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>?** Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]` * `unstylable` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>?** Indicate an array of style properties which should be hidden from the style manager. Default: `[]` * `highlightable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** It can be highlighted with 'dotted' borders if true. Default: `true` * `copyable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** True if it's possible to clone the component. Default: `true` * `resizable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/utils/Resizer.ts) . Default: `false` * `editable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Allow to edit the content of the component (used on Text components). Default: `false` * `layerable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Set to `false` if you need to hide the component inside Layers. Default: `true` * `selectable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Allow component to be selected when clicked. Default: `true` * `hoverable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Shows a highlight outline when hovering on the element if `true`. Default: `true` * `locked` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Disable the selection of the component and its children in the canvas. You can unlock a children by setting its locked property to `false`. Default: `undefined` * `void` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** This property is used by the HTML exporter as void elements don't have closing tags, eg. `
`, `
`, etc. Default: `false` * `style` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }` * `styles` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Component related styles, eg. `.my-component-class { color: red }` * `content` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Content of the component (not escaped) which will be appended before children rendering. Default: `''` * `icon` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string ''. Default: `''` * `script` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) )?** Component's javascript. More about it [here](/docs/modules/Components-js.html) . Default: `''` * `script-export` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) )?** You can specify javascript available only in export functions (eg. when you get the HTML). If this property is defined it will overwrite the `script` one (in export functions). Default: `''` * `traits` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )>?** Component's traits. More about it [here](/docs/modules/Traits.html) . Default: `['id', 'title']` * `propagate` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>?** Indicates an array of properties which will be inhereted by all NEW appended children. For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }` and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]` * `toolbar` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>?** Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete). Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`. By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`). * `components` **Collection?** Children components. Default: `null` * `delegate` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Delegate commands to other components. Available commands `remove` | `move` | `copy` | `select`. eg. `{ remove: (cmp) => cmp.closestType('other-type') }` [#](#init) init ---------------- Hook method, called once the model is created [#](#updated) updated ---------------------- Hook method, called when the model has been updated (eg. updated some model's property) ### [#](#parameters) Parameters * `property` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Property name, if triggered after some property update * `value` **any** Property value, if triggered after some property update * `previous` **any** Property previous value, if triggered after some property update [#](#removed) removed ---------------------- Hook method, called once the model has been removed [#](#is) is ------------ Check component's type ### [#](#parameters-2) Parameters * `type` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component type ### [#](#examples) Examples component.is('image') // -> false Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#props) props ------------------ Return all the propeties Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#index) index ------------------ Get the index of the component in the parent collection. Returns **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** [#](#setdragmode) setDragMode ------------------------------ Change the drag mode of the component. To get more about this feature read: [https://github.com/GrapesJS/grapesjs/issues/1936 (opens new window)](https://github.com/GrapesJS/grapesjs/issues/1936) ### [#](#parameters-3) Parameters * `value` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Drag mode, options: `'absolute'` | `'translate'` | `''` Returns **this** [#](#getdragmode) getDragMode ------------------------------ Get the drag mode of the component. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Drag mode value, options: `'absolute'` | `'translate'` | `''` [#](#setsymboloverride) setSymbolOverride ------------------------------------------ Set symbol override. By setting override to `true`, none of its property changes will be propagated to relative symbols. By setting override to specific properties, changes of those properties will be skipped from propagation. ### [#](#parameters-4) Parameters * `value` **([Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>)** ### [#](#examples-2) Examples component.setSymbolOverride(['children', 'classes']); [#](#getsymboloverride) getSymbolOverride ------------------------------------------ Get symbol override value. Returns **([Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>)** [#](#find) find ---------------- Find inner components by query string. **ATTENTION**: this method works only with already rendered component ### [#](#parameters-5) Parameters * `query` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Query string ### [#](#examples-3) Examples component.find('div > .class'); // -> [Component, Component, ...] Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Array of components [#](#findtype) findType ------------------------ Find all inner components by component type. The advantage of this method over `find` is that you can use it also before rendering the component ### [#](#parameters-6) Parameters * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component type ### [#](#examples-4) Examples const allImages = component.findType('image'); console.log(allImages[0]) // prints the first found component Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#findfirsttype) findFirstType ---------------------------------- Find the first inner component by component type. If no component is found, it returns `undefined`. ### [#](#parameters-7) Parameters * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component type ### [#](#examples-5) Examples const image = component.findFirstType('image'); if (image) { console.log(image); } Returns **(Component | [undefined (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined) )** [#](#closest) closest ---------------------- Find the closest parent component by query string. **ATTENTION**: this method works only with already rendered component ### [#](#parameters-8) Parameters * `query` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Query string ### [#](#examples-6) Examples component.closest('div.some-class'); // -> Component Returns **Component** [#](#closesttype) closestType ------------------------------ Find the closest parent component by its type. The advantage of this method over `closest` is that you can use it also before rendering the component ### [#](#parameters-9) Parameters * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component type ### [#](#examples-7) Examples const Section = component.closestType('section'); console.log(Section); Returns **Component** Found component, otherwise `undefined` [#](#contains) contains ------------------------ The method returns a Boolean value indicating whether the passed component is a descendant of a given component ### [#](#parameters-10) Parameters * `component` **Component** Component to check Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#replacewith) replaceWith ------------------------------ Replace a component with another one ### [#](#parameters-11) Parameters * `el` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | Component)** Component or HTML string * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options for the append action (optional, default `{}`) ### [#](#examples-8) Examples const result = component.replaceWith('
Some new content
'); // result -> [Component] Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** New replaced components [#](#setattributes) setAttributes ---------------------------------- Update attributes of the component ### [#](#parameters-12) Parameters * `attrs` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Key value attributes * `opts` **SetAttrOptions** (optional, default `{}`) * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options for the model update ### [#](#examples-9) Examples component.setAttributes({ id: 'test', 'data-key': 'value' }); Returns **this** [#](#addattributes) addAttributes ---------------------------------- Add attributes to the component ### [#](#parameters-13) Parameters * `attrs` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Key value attributes * `opts` **SetAttrOptions** (optional, default `{}`) * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options for the model update ### [#](#examples-10) Examples component.addAttributes({ 'data-key': 'value' }); Returns **this** [#](#removeattributes) removeAttributes ---------------------------------------- Remove attributes from the component ### [#](#parameters-14) Parameters * `attrs` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>)** Array of attributes to remove (optional, default `[]`) * `opts` **SetOptions** (optional, default `{}`) * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options for the model update ### [#](#examples-11) Examples component.removeAttributes('some-attr'); component.removeAttributes(['some-attr1', 'some-attr2']); Returns **this** [#](#getstyle) getStyle ------------------------ Get the style of the component ### [#](#parameters-15) Parameters * `options` **any** (optional, default `{}`) * `optsAdd` **any** (optional, default `{}`) Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#setstyle) setStyle ------------------------ Set the style on the component ### [#](#parameters-16) Parameters * `prop` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Key value style object (optional, default `{}`) * `opts` **UpdateStyleOptions** (optional, default `{}`) ### [#](#examples-12) Examples component.setStyle({ color: 'red' }); Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#getattributes) getAttributes ---------------------------------- Return all component's attributes ### [#](#parameters-17) Parameters * `opts` **{noClass: [boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?, noStyle: [boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?}** (optional, default `{}`) Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#addclass) addClass ------------------------ Add classes ### [#](#parameters-18) Parameters * `classes` **([Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \> | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Array or string of classes ### [#](#examples-13) Examples model.addClass('class1'); model.addClass('class1 class2'); model.addClass(['class1', 'class2']); // -> [SelectorObject, ...] Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Array of added selectors [#](#setclass) setClass ------------------------ Set classes (resets current collection) ### [#](#parameters-19) Parameters * `classes` **([Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \> | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Array or string of classes ### [#](#examples-14) Examples model.setClass('class1'); model.setClass('class1 class2'); model.setClass(['class1', 'class2']); // -> [SelectorObject, ...] Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Array of added selectors [#](#removeclass) removeClass ------------------------------ Remove classes ### [#](#parameters-20) Parameters * `classes` **([Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \> | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Array or string of classes ### [#](#examples-15) Examples model.removeClass('class1'); model.removeClass('class1 class2'); model.removeClass(['class1', 'class2']); // -> [SelectorObject, ...] Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Array of removed selectors [#](#getclasses) getClasses ---------------------------- Returns component's classes as an array of strings Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#append) append -------------------- Add new component children ### [#](#parameters-21) Parameters * `components` **(Component | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Component to add * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options for the append action (optional, default `{}`) ### [#](#examples-16) Examples someComponent.get('components').length // -> 0 const videoComponent = someComponent.append('
')[0]; // This will add 2 components (`video` and `div`) to your `someComponent` someComponent.get('components').length // -> 2 // You can pass components directly otherComponent.append(otherComponent2); otherComponent.append([otherComponent3, otherComponent4]); // append at specific index (eg. at the beginning) someComponent.append(otherComponent, { at: 0 }); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Array of appended components [#](#components) components ---------------------------- Set new collection if `components` are provided, otherwise the current collection is returned ### [#](#parameters-22) Parameters * `components` **(Component | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )?** Component Definitions or HTML string * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options, same as in `Component.append()` (optional, default `{}`) ### [#](#examples-17) Examples // Set new collection component.components('
'); // Get current collection const collection = component.components(); console.log(collection.length); // -> 2 Returns **(Collection | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Component](/docs/api/component.html) \>)** [#](#getchildat) getChildAt ---------------------------- If exists, returns the child component at specific index. ### [#](#parameters-23) Parameters * `index` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Index of the component to return ### [#](#examples-18) Examples // Return first child component.getChildAt(0); // Return second child component.getChildAt(1); Returns **([Component](/docs/api/component.html) | null)** [#](#getlastchild) getLastChild -------------------------------- If exists, returns the last child component. ### [#](#examples-19) Examples const lastChild = component.getLastChild(); Returns **([Component](/docs/api/component.html) | null)** [#](#empty) empty ------------------ Remove all inner components * @return {this} ### [#](#parameters-24) Parameters * `opts` (optional, default `{}`) [#](#parent) parent -------------------- Get the parent component, if exists ### [#](#parameters-25) Parameters * `opts` **any** (optional, default `{}`) ### [#](#examples-20) Examples component.parent(); // -> Component Returns **(Component | null)** [#](#parents) parents ---------------------- Return all parents of the component. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#gettraits) getTraits -------------------------- Get traits. ### [#](#examples-21) Examples const traits = component.getTraits(); console.log(traits); // [Trait, Trait, Trait, ...] Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#settraits) setTraits -------------------------- Replace current collection of traits with a new one. ### [#](#parameters-26) Parameters * `traits` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>** Array of trait definitions ### [#](#examples-22) Examples const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]); console.log(traits); // [Trait, ...] Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#gettrait) getTrait ------------------------ Get the trait by id/name. ### [#](#parameters-27) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** The `id` or `name` of the trait ### [#](#examples-23) Examples const traitTitle = component.getTrait('title'); traitTitle && traitTitle.set('label', 'New label'); Returns **(Trait | null)** Trait getModelToStyle [#](#updatetrait) updateTrait ------------------------------ Update a trait. ### [#](#parameters-28) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** The `id` or `name` of the trait * `props` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Object with the props to update ### [#](#examples-24) Examples component.updateTrait('title', { type: 'select', options: [ 'Option 1', 'Option 2' ], }); Returns **this** [#](#gettraitindex) getTraitIndex ---------------------------------- Get the trait position index by id/name. Useful in case you want to replace some trait, at runtime, with something else. ### [#](#parameters-29) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** The `id` or `name` of the trait ### [#](#examples-25) Examples const traitTitle = component.getTraitIndex('title'); console.log(traitTitle); // 1 Returns **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Index position of the current trait [#](#removetrait) removeTrait ------------------------------ Remove trait/s by id/s. ### [#](#parameters-30) Parameters * `id` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>)** The `id`/`name` of the trait (or an array) ### [#](#examples-26) Examples component.removeTrait('title'); component.removeTrait(['title', 'id']); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Array of removed traits [#](#addtrait) addTrait ------------------------ Add new trait/s. ### [#](#parameters-31) Parameters * `trait` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) )>)** Trait to add (or an array of traits) * `opts` **Options** Options for the add (optional, default `{}`) ### [#](#examples-27) Examples component.addTrait('title', { at: 1 }); // Add title trait (`at` option is the position index) component.addTrait({ type: 'checkbox', name: 'disabled', }); component.addTrait(['title', {...}, ...]); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Array of added traits [#](#getname) getName ---------------------- Get the name of the component. ### [#](#parameters-32) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.noCustom` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Avoid custom name assigned to the component. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#setname) setName ---------------------- Update component name. ### [#](#parameters-33) Parameters * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** New name. * `opts` **SetOptions** (optional, default `{}`) [#](#geticon) getIcon ---------------------- Get the icon string Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#tohtml) toHTML -------------------- Return HTML string of the component ### [#](#parameters-34) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.tag` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Custom tagName * `opts.attributes` **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) )** You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically. (optional, default `null`) * `opts.withProps` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML. * `opts.altQuoteAttr` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** In case the attribute value contains a `"` char, instead of escaping it (`attr="value ""`), the attribute will be quoted using single quotes (`attr='value "'`). ### [#](#examples-28) Examples // Simple HTML return component.set({ tagName: 'span' }); component.setAttributes({ title: 'Hello' }); component.toHTML(); // -> // Custom attributes component.toHTML({ attributes: { 'data-test': 'Hello' } }); // -> // Custom dynamic attributes component.toHTML({ attributes(component, attributes) { if (component.get('tagName') == 'span') { attributes.title = 'Custom attribute'; } return attributes; }, }); // -> Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** HTML string [#](#getinnerhtml) getInnerHTML -------------------------------- Get inner HTML of the component ### [#](#parameters-35) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Same options of `toHTML` (optional, default `{}`) Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** HTML string [#](#getchangedprops) getChangedProps -------------------------------------- Return an object containing only changed props ### [#](#parameters-36) Parameters * `res` **Partial** Returns **Partial** [#](#getid) getId ------------------ Return the component id Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#setid) setId ------------------ Set new id on the component ### [#](#parameters-37) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** * `opts` **any?** Returns **this** [#](#getel) getEl ------------------ Get the DOM element of the component. This works only if the component is already rendered ### [#](#parameters-38) Parameters * `frame` **Frame** Specific frame from which taking the element Returns **[HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) ** [#](#getview) getView ---------------------- Get the View of the component. This works only if the component is already rendered ### [#](#parameters-39) Parameters * `frame` **Frame** Get View of a specific frame Returns **ComponentView** [#](#onall) onAll ------------------ Execute callback function on itself and all inner components ### [#](#parameters-40) Parameters * `clb` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ** Callback function, the model is passed as an argument ### [#](#examples-29) Examples component.onAll(component => { // do something with component }) Returns **this** [#](#foreachchild) forEachChild -------------------------------- Execute a callback function on all inner child components. ### [#](#parameters-41) Parameters * `clb` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ** Callback function, the child component is passed as an argument ### [#](#examples-30) Examples component.forEachChild(child => { console.log(child) }) [#](#remove) remove -------------------- Remove the component ### [#](#parameters-42) Parameters * `opts` **any** (optional, default `{}`) Returns **this** [#](#move) move ---------------- Move the component to another destination component ### [#](#parameters-43) Parameters * `component` **Component** Destination component (so the current one will be appended as a child) * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options for the append action (optional, default `{}`) ### [#](#examples-31) Examples // Move the selected component on top of the wrapper const dest = editor.getWrapper(); editor.getSelected().move(dest, { at: 0 }); Returns **this** [#](#isinstanceof) isInstanceOf -------------------------------- Check if the component is an instance of some component type. ### [#](#parameters-44) Parameters * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Component type ### [#](#examples-32) Examples // Add a new component type by extending an existing one editor.Components.addType('text-ext', { extend: 'text' }); // Append a new component somewhere const newTextExt = editor.getSelected().append({ type: 'text-ext' })[0]; newTextExt.isInstanceOf('text-ext'); // true newTextExt.isInstanceOf('text'); // true Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#ischildof) isChildOf -------------------------- Check if the component is a child of some other component (or component type) ### [#](#parameters-45) Parameters * `component` **([Component](/docs/api/component.html) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Component parent to check. In case a string is passed, the check will be performed on the component type. ### [#](#examples-33) Examples const newTextComponent = editor.getSelected().append({ type: 'text', components: 'My text here', })[0]; const innerComponent = newTextComponent.find('b')[0]; innerComponent.isChildOf(newTextComponent); // true innerComponent.isChildOf('text'); // true Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ← [DOM Components](/docs/api/components.html) [Panels](/docs/api/panels.html) → --- # GrapesJS [#](#sector) Sector -------------------- ### [#](#properties) Properties * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector id, eg. `typography` * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector name, eg. `Typography` * `open` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Indicates the open state. * `properties` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>?** Indicate an array of Property defintions. ### [#](#getid) getId Get sector id. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getname) getName Get sector name. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#setname) setName Update sector name. #### [#](#parameters) Parameters * `value` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** New sector name ### [#](#isopen) isOpen Check if the sector is open Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#setopen) setOpen Update Sector open state #### [#](#parameters-2) Parameters * `value` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#isvisible) isVisible Check if the sector is visible Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#getproperties) getProperties Get sector properties. #### [#](#parameters-3) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.withValue` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Get only properties with value (optional, default `false`) * `opts.withParentValue` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Get only properties with parent value (optional, default `false`) Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Property](/docs/api/property.html) \>** ← [Style Manager](/docs/api/style_manager.html) [‍ ‍ ‍ Property](/docs/api/property.html) → --- # GrapesJS [#](#stylemanager) StyleManager -------------------------------- With Style Manager you build categories (called sectors) of CSS properties which could be used to customize the style of components. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/style_manager/config/config.ts) const editor = grapesjs.init({ styleManager: { // options } }) Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. // Listen to events editor.on('style:sector:add', (sector) => { ... }); // Use the API const styleManager = editor.StyleManager; styleManager.addSector(...); [#](#available-events) Available Events ---------------------------------------- * `style:sector:add` - Sector added. The [Sector](/docs/api/sector.html) is passed as an argument to the callback. * `style:sector:remove` - Sector removed. The [Sector](/docs/api/sector.html) is passed as an argument to the callback. * `style:sector:update` - Sector updated. The [Sector](/docs/api/sector.html) and the object containing changes are passed as arguments to the callback. * `style:property:add` - Property added. The [Property](/docs/api/property.html) is passed as an argument to the callback. * `style:property:remove` - Property removed. The [Property](/docs/api/property.html) is passed as an argument to the callback. * `style:property:update` - Property updated. The [Property](/docs/api/property.html) and the object containing changes are passed as arguments to the callback. * `style:target` - Target selection changed. The target (or `null` in case the target is deselected) is passed as an argument to the callback. [#](#methods) Methods ---------------------- * [getConfig](#getconfig) * [addSector](#addsector) * [getSector](#getsector) * [getSectors](#getsectors) * [removeSector](#removesector) * [addProperty](#addproperty) * [getProperty](#getproperty) * [getProperties](#getproperties) * [removeProperty](#removeproperty) * [select](#select) * [getSelected](#getselected) * [getSelectedAll](#getselectedall) * [getSelectedParents](#getselectedparents) * [addStyleTargets](#addstyletargets) * [getBuiltIn](#getbuiltin) * [getBuiltInAll](#getbuiltinall) * [addBuiltIn](#addbuiltin) * [addType](#addtype) * [getType](#gettype) * [getTypes](#gettypes) [#](#sectors) Sectors ---------------------- [#](#getconfig) getConfig -------------------------- Get configuration object Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#addsector) addSector -------------------------- Add new sector. If the sector with the same id already exists, that one will be returned. ### [#](#parameters) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector id * `sector` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Sector definition. Check the [available properties](/docs/api/sector.html#properties) * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `options.at` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ?** Position index (by default, will be appended at the end). ### [#](#examples) Examples const sector = styleManager.addSector('mySector',{ name: 'My sector', open: true, properties: [{ name: 'My property'}] }, { at: 0 }); // With `at: 0` we place the new sector at the beginning of the list Returns **[Sector](/docs/api/sector.html) ** Added Sector [#](#getsector) getSector -------------------------- Get sector by id. ### [#](#parameters-2) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector id * `opts` **{warn: [boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?}** (optional, default `{}`) ### [#](#examples-2) Examples const sector = styleManager.getSector('mySector'); Returns **([Sector](/docs/api/sector.html) | null)** [#](#getsectors) getSectors ---------------------------- Get all sectors. ### [#](#parameters-3) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.visible` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Returns only visible sectors ### [#](#examples-3) Examples const sectors = styleManager.getSectors(); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Sector](/docs/api/sector.html) \>** [#](#removesector) removeSector -------------------------------- Remove sector by id. ### [#](#parameters-4) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector id ### [#](#examples-4) Examples const removed = styleManager.removeSector('mySector'); Returns **[Sector](/docs/api/sector.html) ** Removed sector [#](#addproperty) addProperty ------------------------------ Add new property to the sector. ### [#](#parameters-5) Parameters * `sectorId` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector id. * `property` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Property definition. Check the [base available properties](/docs/api/property.html#properties) + others based on the `type` of your property. * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.at` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ?** Position index (by default, will be appended at the end). ### [#](#examples-5) Examples const property = styleManager.addProperty('mySector', { label: 'Minimum height', property: 'min-height', type: 'select', default: '100px', options: [\ { id: '100px', label: '100' },\ { id: '200px', label: '200' },\ ], }, { at: 0 }); Returns **([Property](/docs/api/property.html) | null)** Added property or `null` in case the sector doesn't exist. [#](#getproperty) getProperty ------------------------------ Get the property. ### [#](#parameters-6) Parameters * `sectorId` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector id. * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Property id. ### [#](#examples-6) Examples const property = styleManager.getProperty('mySector', 'min-height'); Returns **([Property](/docs/api/property.html) | [undefined (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined) )** [#](#getproperties) getProperties ---------------------------------- Get all properties of the sector. ### [#](#parameters-7) Parameters * `sectorId` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector id. ### [#](#examples-7) Examples const properties = styleManager.getProperties('mySector'); Returns **(Collection<[Property](/docs/api/property.html) \> | [undefined (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined) )** Collection of properties [#](#removeproperty) removeProperty ------------------------------------ Remove the property. ### [#](#parameters-8) Parameters * `sectorId` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Sector id. * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Property id. ### [#](#examples-8) Examples const property = styleManager.removeProperty('mySector', 'min-height'); Returns **([Property](/docs/api/property.html) | null)** Removed property [#](#select) select -------------------- Select new target. The target could be a Component, CSSRule, or a CSS selector string. ### [#](#parameters-9) Parameters * `target` **([Component](/docs/api/component.html) | [CSSRule](/docs/api/css_rule.html) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** * `opts` **{stylable: [boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?, component: Component?}** (optional, default `{}`) ### [#](#examples-9) Examples // Select the first button in the current page const wrapperCmp = editor.Pages.getSelected().getMainComponent(); const btnCmp = wrapperCmp.find('button')[0]; btnCmp && styleManager.select(btnCmp); // Set as a target the CSS selector styleManager.select('.btn > span'); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <([Component](/docs/api/component.html) | [CSSRule](/docs/api/css_rule.html) )>** Array containing selected Components or CSSRules [#](#getselected) getSelected ------------------------------ Get the last selected target. By default, the Style Manager shows styles of the last selected target. Returns **([Component](/docs/api/component.html) | [CSSRule](/docs/api/css_rule.html) | null)** [#](#getselectedall) getSelectedAll ------------------------------------ Get the array of selected targets. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <([Component](/docs/api/component.html) | [CSSRule](/docs/api/css_rule.html) )>** [#](#getselectedparents) getSelectedParents -------------------------------------------- Get parent rules of the last selected target. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[CSSRule](/docs/api/css_rule.html) \>** [#](#addstyletargets) addStyleTargets -------------------------------------- Update selected targets with a custom style. ### [#](#parameters-10) Parameters * `style` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Style object * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) ### [#](#examples-10) Examples styleManager.addStyleTargets({ color: 'red' }); [#](#getbuiltin) getBuiltIn ---------------------------- Return built-in property definition ### [#](#parameters-11) Parameters * `prop` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Property name. ### [#](#examples-11) Examples const widthPropDefinition = styleManager.getBuiltIn('width'); Returns **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | null)** Property definition. [#](#getbuiltinall) getBuiltInAll ---------------------------------- Get all the available built-in property definitions. Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#addbuiltin) addBuiltIn ---------------------------- Add built-in property definition. If the property exists already, it will extend it. ### [#](#parameters-12) Parameters * `prop` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Property name. * `definition` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Property definition. ### [#](#examples-12) Examples const sector = styleManager.addBuiltIn('new-property', { type: 'select', default: 'value1', options: [{ id: 'value1', label: 'Some label' }, ...], }) Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Added property definition. [#](#addtype) addType ---------------------- Add new property type ### [#](#parameters-13) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Type ID * `definition` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Definition of the type. ### [#](#examples-13) Examples styleManager.addType('my-custom-prop', { // Create UI create({ props, change }) { const el = document.createElement('div'); el.innerHTML = ''; const inputEl = el.querySelector('.my-input'); inputEl.addEventListener('change', event => change({ event })); inputEl.addEventListener('input', event => change({ event, partial: true })); return el; }, // Propagate UI changes up to the targets emit({ props, updateStyle }, { event, partial }) { const { value } = event.target; updateStyle(`${value}px`, { partial }); }, // Update UI (eg. when the target is changed) update({ value, el }) { el.querySelector('.my-input').value = parseInt(value, 10); }, // Clean the memory from side effects if necessary (eg. global event listeners, etc.) destroy() {} }) [#](#gettype) getType ---------------------- Get type ### [#](#parameters-14) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Type ID Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Type definition [#](#gettypes) getTypes ------------------------ Get all types Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** ← [Layers](/docs/api/layer_manager.html) [‍ ‍ ‍ Sector](/docs/api/sector.html) → --- # GrapesJS [#](#propertyselect) PropertySelect ------------------------------------ **Extends Property** ### [#](#properties) Properties * `options` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>** Array of option definitions. options: [\ { id: '100', label: 'Set 100' },\ { id: '200', label: 'Set 200' },\ ] ### [#](#getoptions) getOptions Get available options. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>** Array of options ### [#](#getoption) getOption Get current selected option or by id. #### [#](#parameters) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Option id. Returns **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | null)** ### [#](#setoptions) setOptions Update options. #### [#](#parameters-2) Parameters * `value` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>** New array of options, eg. `[{ id: 'val-1', label: 'Value 1' }]` (optional, default `[]`) ### [#](#addoption) addOption Add new option. #### [#](#parameters-3) Parameters * `value` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Option object, eg. `{ id: 'val-1', label: 'Value 1' }` ### [#](#getoptionid) getOptionId Get the option id from the option object. #### [#](#parameters-4) Parameters * `option` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Option object Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Option id ### [#](#getoptionlabel) getOptionLabel Get option label. #### [#](#parameters-5) Parameters * `id` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) )** Option id or the option object * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.locale` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Use the locale string from i18n module (optional, default `true`) Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Option label ← [‍ ‍ ‍ PropertyNumber](/docs/api/property_number.html) [‍ ‍ ‍ PropertyComposite](/docs/api/property_composite.html) → --- # GrapesJS [#](#property) Property ------------------------ ### [#](#properties) Properties * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Property id, eg. `my-property-id`. * `property` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Related CSS property name, eg. `text-align`. * `default` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Defaul value of the property. * `label` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Label to use in UI, eg. `Text Align`. * `onChange` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ?** Change callback. onChange: ({ property, from, to }) => { console.log(`Changed property`, property.getName(), { from, to }); } ### [#](#getid) getId Get property id. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#gettype) 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 (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getname) getName Get name (the CSS property name). Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getlabel) getLabel Get property label. #### [#](#parameters) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.locale` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Use the locale string from i18n module (optional, default `true`) Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getvalue) getValue Get property value. #### [#](#parameters-2) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.noDefault` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Avoid returning the default value (optional, default `false`) Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#hasvalue) hasValue Check if the property has value. #### [#](#parameters-3) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.noParent` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Ignore the value if it comes from the parent target. (optional, default `false`) Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#hasvalueparent) hasValueParent Indicates if the current value is coming from a parent target (eg. another CSSRule). Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#getstyle) getStyle Get the CSS style object of the property. #### [#](#parameters-4) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.camelCase` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Return property name in camelCase. #### [#](#examples) Examples // In case the property is `color` with a value of `red`. console.log(property.getStyle()); // { color: 'red' }; Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** ### [#](#getdefaultvalue) getDefaultValue Get the default value. Returns **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#upvalue) upValue Update the value. The change is also propagated to the selected targets (eg. CSS rule). #### [#](#parameters-5) Parameters * `value` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** New value * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.partial` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If `true` the update on targets won't be considered complete (not stored in UndoManager) (optional, default `false`) * `opts.noTarget` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If `true` the change won't be propagated to selected targets. (optional, default `false`) ### [#](#isvisible) isVisible Check if the property is visible Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#clear) clear Clear the value. The change is also propagated to the selected targets (eg. the css property is cleared). #### [#](#parameters-6) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.noTarget` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If `true` the change won't be propagated to selected targets. (optional, default `false`) ### [#](#canclear) canClear Indicates if the current value comes directly from the selected target and so can be cleared. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#getparent) getParent If the current property is a sub-property, this will return the parent Property. Returns **(\[[Property](#property)\ \] | null)** ### [#](#isfull) isFull Indicates if the property is full-width in UI. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ← [‍ ‍ ‍ Sector](/docs/api/sector.html) [‍ ‍ ‍ PropertyNumber](/docs/api/property_number.html) → --- # GrapesJS [#](#propertynumber) PropertyNumber ------------------------------------ **Extends Property** ### [#](#properties) Properties * `units` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>** Array of units, eg. `['px', '%']` * `min` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Minimum value. * `max` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Maximum value. * `step` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Step value. ### [#](#getunits) getUnits Get property units. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>** ### [#](#getunit) getUnit Get property unit value. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getmin) getMin Get min value. Returns **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** ### [#](#getmax) getMax Get max value. Returns **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** ### [#](#getstep) getStep Get step value. Returns **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** ### [#](#upunit) upUnit Update property unit value. The change is also propagated to the selected targets. #### [#](#parameters) Parameters * `unit` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** New unit value * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.noTarget` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If `true` the change won't be propagated to selected targets. (optional, default `false`) Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ← [‍ ‍ ‍ Property](/docs/api/property.html) [‍ ‍ ‍ PropertySelect](/docs/api/property_select.html) → --- # GrapesJS [#](#propertycomposite) PropertyComposite ------------------------------------------ **Extends Property** ### [#](#properties) Properties * `properties` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>** Array of sub properties, eg. `[{ type: 'number', property: 'margin-top' }, ...]` * `detached` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Indicate if the final CSS property is splitted (detached: `margin-top: X; margin-right: Y; ...`) or combined (not detached: `margin: X Y ...;`) * `separator` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [RegExp (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) )?** Value used to split property values, default `" "`. * `join` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Value used to join property values, default `" "`. * `fromStyle` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ?** Custom logic for getting property values from the target style object. fromStyle: (style) => { const margins = parseMarginShorthand(style.margin); return { 'margin-top': margins.top, // ... }; } * `toStyle` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ?** Custom logic for creating the CSS style object to apply on selected targets. toStyle: (values) => { const top = values['margin-top'] || 0; const right = values['margin-right'] || 0; // ... return { margin: `${top} ${right} ...`, }; } ### [#](#getproperties) getProperties Get properties. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Property](/docs/api/property.html) \>** ### [#](#getproperty) getProperty Get property by id. #### [#](#parameters) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Property id. Returns **([Property](/docs/api/property.html) | null)** ### [#](#getpropertyat) getPropertyAt Get property at index. #### [#](#parameters-2) Parameters * `index` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Returns **([Property](/docs/api/property.html) | null)** ### [#](#isdetached) isDetached Check if the property is detached. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#getvalues) getValues Get current values of properties. #### [#](#parameters-3) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.byName` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Use property names as a key instead of the id. (optional, default `false`) #### [#](#examples) Examples // In case the property is `margin` with sub properties like `margin-top`, `margin-right`, etc. console.log(property.getValues()); // { 'margin-top': '10px', 'margin-right': '20px', ... }; Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** ### [#](#getseparator) getSeparator Get property separator. Returns **[RegExp (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) ** ### [#](#getjoin) getJoin Get the join value. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ← [‍ ‍ ‍ PropertySelect](/docs/api/property_select.html) [‍ ‍ ‍ PropertyStack](/docs/api/property_stack.html) → --- # GrapesJS [#](#propertystack) PropertyStack ---------------------------------- **Extends PropertyComposite** ### [#](#properties) Properties * `preview` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Indicate if the layer should display a preview. * `layerSeparator` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [RegExp (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) )?** The separator used to split layer values. * `layerJoin` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Value used to join layer values. * `layerLabel` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ?** Custom logic for creating layer labels. layerLabel: (layer) => { const values = layer.getValues(); return `A: ${values['prop-a']} B: ${values['prop-b']}`; } * `emptyValue` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) )?** Empty value to apply when all layers are removed. // use simple string emptyValue: 'inherit', // or a function for a custom style object emptyValue: () => ({ color: 'unset', width: 'auto' }), ### [#](#getlayers) getLayers Get all available layers. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Layer](/docs/api/layer.html) \>** ### [#](#haslayers) hasLayers Check if the property has layers. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#getlayer) getLayer Get layer by index. #### [#](#parameters) Parameters * `index` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Layer index position. (optional, default `0`) #### [#](#examples) Examples // Get the first layer const layerFirst = property.getLayer(0); // Get the last layer const layers = this.getLayers(); const layerLast = property.getLayer(layers.length - 1); Returns **([Layer](/docs/api/layer.html) | null)** ### [#](#getselectedlayer) getSelectedLayer Get selected layer. Returns **([Layer](/docs/api/layer.html) | [undefined (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined) )** ### [#](#selectlayer) selectLayer Select layer. Without a selected layer any update made on inner properties has no effect. #### [#](#parameters-2) Parameters * `layer` **[Layer](/docs/api/layer.html) ** Layer to select #### [#](#examples-2) Examples const layer = property.getLayer(0); property.selectLayer(layer); ### [#](#selectlayerat) selectLayerAt Select layer by index. #### [#](#parameters-3) Parameters * `index` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Index of the layer to select. (optional, default `0`) #### [#](#examples-3) Examples property.selectLayerAt(1); ### [#](#movelayer) moveLayer Move layer by index. #### [#](#parameters-4) Parameters * `layer` **[Layer](/docs/api/layer.html) ** Layer to move. * `index` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** New layer index. (optional, default `0`) #### [#](#examples-4) Examples const layer = property.getLayer(1); property.moveLayer(layer, 0); ### [#](#addlayer) addLayer Add new layer to the stack. #### [#](#parameters-5) Parameters * `props` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Custom property values to use in a new layer. (optional, default `{}`) * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.at` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ?** Position index (by default the layer will be appended at the end). #### [#](#examples-5) Examples // Add new layer at the beginning of the stack with custom values property.addLayer({ 'sub-prop1': 'value1', 'sub-prop2': 'value2' }, { at: 0 }); Returns **[Layer](/docs/api/layer.html) ** Added layer. ### [#](#removelayer) removeLayer Remove layer. #### [#](#parameters-6) Parameters * `layer` **[Layer](/docs/api/layer.html) ** Layer to remove. #### [#](#examples-6) Examples const layer = property.getLayer(0); property.removeLayer(layer); Returns **[Layer](/docs/api/layer.html) ** Removed layer ### [#](#removelayerat) removeLayerAt Remove layer by index. #### [#](#parameters-7) Parameters * `index` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** Index of the layer to remove (optional, default `0`) #### [#](#examples-7) Examples property.removeLayerAt(0); Returns **([Layer](/docs/api/layer.html) | null)** Removed layer ### [#](#getlayerlabel) getLayerLabel Get the layer label. The label can be customized with the `layerLabel` property. #### [#](#parameters-8) Parameters * `layer` **[Layer](/docs/api/layer.html) ** #### [#](#examples-8) Examples const layer = this.getLayer(1); const label = this.getLayerLabel(layer); Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getstylefromlayer) getStyleFromLayer Get style object from the layer. #### [#](#parameters-9) Parameters * `layer` **[Layer](/docs/api/layer.html) ** * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.camelCase` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Return property names in camelCase. * `opts.number` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Limit the result of the number types, eg. `number: { min: -3, max: 3 }` Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Style object ### [#](#getstylepreview) getStylePreview Get preview style object from the layer. If the property has `preview: false` the returned object will be empty. #### [#](#parameters-10) Parameters * `layer` **[Layer](/docs/api/layer.html) ** * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options. Same of `getStyleFromLayer` (optional, default `{}`) Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Style object ### [#](#getlayerseparator) getLayerSeparator Get layer separator. Returns **[RegExp (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) ** ### [#](#hasemptyvalue) hasEmptyValue Check if the property is with an empty value. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ← [‍ ‍ ‍ PropertyComposite](/docs/api/property_composite.html) [‍ ‍ ‍ Layer](/docs/api/layer.html) → --- # GrapesJS [#](#getid) getId ------------------ Get layer id. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getindex) getIndex ------------------------ Get layer index. Returns **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** [#](#getvalues) getValues -------------------------- Get layer values. ### [#](#parameters) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.camelCase` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Return property names in camelCase. Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#getlabel) getLabel ------------------------ Get layer label. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#isselected) isSelected ---------------------------- Check if the layer is selected. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#select) select -------------------- Select the layer. [#](#remove) remove -------------------- Remove the layer. [#](#move) move ---------------- Move layer to a new index. ### [#](#parameters-2) Parameters * `index` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** New index [#](#getstylepreview) getStylePreview -------------------------------------- Get style object for the preview. ### [#](#parameters-3) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options. Same of `PropertyStack.getStyleFromLayer` (optional, default `{}`) Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Style object [#](#haspreview) hasPreview ---------------------------- Check if the property has the preview enabled for this layer. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ← [‍ ‍ ‍ PropertyStack](/docs/api/property_stack.html) [Storage Manager](/docs/api/storage_manager.html) → --- # GrapesJS [#](#storage) Storage ---------------------- You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/storage_manager/config/config.ts) const editor = grapesjs.init({ storageManager: { // options } }) Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. // Listen to events editor.on('storage:start', () => { ... }); // Use the API const storageManager = editor.Storage; storageManager.add(...); [#](#available-events) Available Events ---------------------------------------- * `storage:start` Storage request start. editor.on('storage:start', (type) => { console.log('Storage start'); }); * `storage:start:store` Storage store request start. The project JSON object to store is passed as an argument (which you can edit). editor.on('storage:start:store', (data) => { console.log('Storage start store'); }); * `storage:start:load` Storage load request start. editor.on('storage:start:load', () => { console.log('Storage start load'); }); * `storage:load` Storage loaded the project. The loaded project is passed as an argument. editor.on('storage:load', (data, res) => { console.log('Storage loaded the project'); }); * `storage:store` Storage stored the project. The stored project is passed as an argument. editor.on('storage:store', (data, res) => { console.log('Storage stored the project'); }); * `storage:after` Storage request completed. Triggered right after `storage:load`/`storage:store`. editor.on('storage:after', (type) => { console.log('Storage request completed'); }); * `storage:end` Storage request ended. This event triggers also in case of errors. editor.on('storage:end', (type) => { console.log('Storage request ended'); }); * `storage:end:store` Storage store request ended. This event triggers also in case of errors. editor.on('storage:end:store', () => { console.log('Storage store request ended'); }); * `storage:end:load` Storage load request ended. This event triggers also in case of errors. editor.on('storage:end:load', () => { console.log('Storage load request ended'); }); * `storage:error` Error on storage request. editor.on('storage:error', (err, type) => { console.log('Storage error'); }); * `storage:error:store` Error on store request. editor.on('storage:error:store', (err) => { console.log('Error on store'); }); * `storage:error:load` Error on load request. editor.on('storage:error:load', (err) => { console.log('Error on load'); }); [#](#methods) Methods ---------------------- * [getConfig](#getconfig) * [isAutosave](#isautosave) * [setAutosave](#setautosave) * [getStepsBeforeSave](#getstepsbeforesave) * [setStepsBeforeSave](#setstepsbeforesave) * [getStorages](#getstorages) * [getCurrent](#getcurrent) * [getCurrentStorage](#getcurrentstorage) * [setCurrent](#setcurrent) * [getStorageOptions](#getstorageoptions) * [add](#add) * [get](#get) * [store](#store) * [load](#load) [#](#getconfig) getConfig -------------------------- Get configuration object Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#isautosave) isAutosave ---------------------------- Check if autosave is enabled. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#setautosave) setAutosave ------------------------------ Set autosave value. ### [#](#parameters) Parameters * `value` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#getstepsbeforesave) getStepsBeforeSave -------------------------------------------- Returns number of steps required before trigger autosave. Returns **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** [#](#setstepsbeforesave) setStepsBeforeSave -------------------------------------------- Set steps required before trigger autosave. ### [#](#parameters-2) Parameters * `value` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ** [#](#add) add -------------- Add new storage. ### [#](#parameters-3) Parameters * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Storage type * `storage` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Storage definition * `storage.load` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ** Load method * `storage.store` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ** Store method ### [#](#examples) Examples storageManager.add('local2', { async load(storageOptions) { // ... }, async store(data, storageOptions) { // ... }, }); [#](#get) get -------------- Return storage by type. ### [#](#parameters-4) Parameters * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Storage type Returns **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | null)** [#](#getstorages) getStorages ------------------------------ Get all storages. Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#getcurrent) getCurrent ---------------------------- Get current storage type. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#setcurrent) setCurrent ---------------------------- Set current storage type. ### [#](#parameters-5) Parameters * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Storage type [#](#getstorageoptions) getStorageOptions ------------------------------------------ Get storage options by type. ### [#](#parameters-6) Parameters * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Storage type Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#store) store ------------------ Store data in the current storage. ### [#](#parameters-7) Parameters * `data` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Project data. * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Storage options. (optional, default `{}as T`) ### [#](#examples-2) Examples const data = editor.getProjectData(); await storageManager.store(data); Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Stored data. [#](#load) load ---------------- Load resource from the current storage by keys ### [#](#parameters-8) Parameters * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Storage options. (optional, default `{}as T`) ### [#](#examples-3) Examples const data = await storageManager.load(); editor.loadProjectData(data); Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Loaded data. ← [‍ ‍ ‍ Layer](/docs/api/layer.html) [Device Manager](/docs/api/device_manager.html) → --- # GrapesJS [#](#devices) Devices ---------------------- You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/device_manager/config/config.ts) const editor = grapesjs.init({ deviceManager: { // options } }) Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance const deviceManager = editor.Devices; [#](#available-events) Available Events ---------------------------------------- * `device:add` - Added new device. The [Device](/docs/api/device.html) is passed as an argument to the callback * `device:remove` - Device removed. The [Device](/docs/api/device.html) is passed as an argument to the callback * `device:select` - New device selected. The newly selected [Device](/docs/api/device.html) and the previous one, are passed as arguments to the callback * `device:update` - Device updated. The updated [Device](/docs/api/device.html) and the object containing changes are passed as arguments to the callback * `device` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback [#](#methods) Methods ---------------------- * [add](#add) * [get](#get) * [getDevices](#getdevices) * [remove](#remove) * [select](#select) * [getSelected](#getselected) [#](#add) add -------------- Add new device ### [#](#parameters) Parameters * `props` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Device properties * `options` **Record<[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) , any>** (optional, default `{}`) ### [#](#examples) Examples const device1 = deviceManager.add({ // Without an explicit ID, the `name` will be taken. In case of missing `name`, a random ID will be created. id: 'tablet', name: 'Tablet', width: '900px', // This width will be applied on the canvas frame and for the CSS media }); const device2 = deviceManager.add({ id: 'tablet2', name: 'Tablet 2', width: '800px', // This width will be applied on the canvas frame widthMedia: '810px', // This width that will be used for the CSS media height: '600px', // Height will be applied on the canvas frame }); Returns **[Device](/docs/api/device.html) ** Added device [#](#get) get -------------- Return device by ID ### [#](#parameters-2) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ID of the device ### [#](#examples-2) Examples const device = deviceManager.get('Tablet'); console.log(JSON.stringify(device)); // {name: 'Tablet', width: '900px'} Returns **([Device](/docs/api/device.html) | null)** [#](#remove) remove -------------------- Remove device ### [#](#parameters-3) Parameters * `device` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Device](/docs/api/device.html) )** Device or device id * `opts` (optional, default `{}`) ### [#](#examples-3) Examples const removed = deviceManager.remove('device-id'); // or by passing the Device const device = deviceManager.get('device-id'); deviceManager.remove(device); Returns **[Device](/docs/api/device.html) ** Removed device [#](#getdevices) getDevices ---------------------------- Return all devices ### [#](#examples-4) Examples const devices = deviceManager.getDevices(); console.log(JSON.stringify(devices)); // [{name: 'Desktop', width: ''}, ...] Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Device](/docs/api/device.html) \>** [#](#select) select -------------------- Change the selected device. This will update the frame in the canvas ### [#](#parameters-4) Parameters * `device` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Device](/docs/api/device.html) )** Device or device id * `opts` (optional, default `{}`) ### [#](#examples-5) Examples deviceManager.select('some-id'); // or by passing the page const device = deviceManager.get('some-id'); deviceManager.select(device); [#](#getselected) getSelected ------------------------------ Get the selected device ### [#](#examples-6) Examples const selected = deviceManager.getSelected(); Returns **[Device](/docs/api/device.html) ** ← [Storage Manager](/docs/api/storage_manager.html) [‍ ‍ ‍ Device](/docs/api/device.html) → --- # GrapesJS [#](#device) Device -------------------- ### [#](#properties) Properties * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Device type, eg. `Mobile` * `width` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Width to set for the editor iframe, eg. '900px' * `height` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Height to set for the editor iframe, eg. '600px' * `widthMedia` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** The width which will be used in media queries, If empty the width will be used * `priority` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ?** Setup the order of media queries ← [Device Manager](/docs/api/device_manager.html) [Selector Manager](/docs/api/selector_manager.html) → --- # GrapesJS [#](#selectors) Selectors -------------------------- Selectors in GrapesJS are used in CSS Composer inside Rules and in Components as classes. To illustrate this concept let's take a look at this code: span > #send-btn.btn{ ... } In this scenario we get: * span -> selector of type `tag` * send-btn -> selector of type `id` * btn -> selector of type `class` So, for example, being `btn` the same class entity it'll be easier to refactor and track things. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/selector_manager/config/config.ts) const editor = grapesjs.init({ selectorManager: { // options } }) Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. // Listen to events editor.on('selector:add', (selector) => { ... }); // Use the API const sm = editor.Selectors; sm.add(...); [#](#available-events) Available Events ---------------------------------------- * `selector:add` - Selector added. The [Selector](/docs/api/selector.html) is passed as an argument to the callback. * `selector:remove` - Selector removed. The [Selector](/docs/api/selector.html) is passed as an argument to the callback. * `selector:update` - Selector updated. The [Selector](/docs/api/selector.html) and the object containing changes are passed as arguments to the callback. * `selector:state` - States changed. An object containing all the available data about the triggered event is passed as an argument to the callback. * `selector` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. [#](#methods) Methods ---------------------- * [getConfig](#getconfig) * [add](#add) * [get](#get) * [remove](#remove) * [rename](#rename) * [getAll](#getall) * [setState](#setstate) * [getState](#getstate) * [getStates](#getstates) * [setStates](#setstates) * [getSelected](#getselected) * [addSelected](#addselected) * [removeSelected](#removeselected) * [getSelectedTargets](#getselectedtargets) * [setComponentFirst](#setcomponentfirst) * [getComponentFirst](#getcomponentfirst) [#](#getconfig) getConfig -------------------------- Get configuration object Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#add) add -------------- Add a new selector to the collection if it does not already exist. You can pass selectors properties or string identifiers. ### [#](#parameters) Parameters * `props` **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls` * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Selector options (optional, default `{}`) ### [#](#examples) Examples const selector = selectorManager.add({ name: 'my-class', label: 'My class' }); console.log(selector.toString()) // `.my-class` // Same as const selector = selectorManager.add('.my-class'); console.log(selector.toString()) // `.my-class` Returns **[Selector](/docs/api/selector.html) ** [#](#get) get -------------- Get the selector by its name/type ### [#](#parameters-2) Parameters * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Selector name or string identifier * `type` **[number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ?** ### [#](#examples-2) Examples const selector = selectorManager.get('.my-class'); // Get Id const selectorId = selectorManager.get('#my-id'); Returns **([Selector](/docs/api/selector.html) | null)** [#](#remove) remove -------------------- Remove Selector. ### [#](#parameters-3) Parameters * `selector` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Selector](/docs/api/selector.html) )** Selector instance or Selector string identifier * `opts` **RemoveOptions?** ### [#](#examples-3) Examples const removed = selectorManager.remove('.myclass'); // or by passing the Selector selectorManager.remove(selectorManager.get('.myclass')); Returns **[Selector](/docs/api/selector.html) ** Removed Selector [#](#rename) rename -------------------- Rename Selector. ### [#](#parameters-4) Parameters * `selector` **[Selector](/docs/api/selector.html) ** Selector to update. * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** New name for the selector. * `opts` **SetOptions?** ### [#](#examples-4) Examples const selector = selectorManager.get('myclass'); const result = selectorManager.rename(selector, 'myclass2'); console.log(result === selector ? 'Selector updated' : 'Selector with this name exists already'); Returns **[Selector](/docs/api/selector.html) ** Selector containing the passed name. [#](#setstate) setState ------------------------ Change the selector state ### [#](#parameters-5) Parameters * `value` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** State value ### [#](#examples-5) Examples selectorManager.setState('hover'); Returns **this** [#](#getstate) getState ------------------------ Get the current selector state value Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getstates) getStates -------------------------- Get states Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[State](/docs/api/state.html) \>** [#](#setstates) setStates -------------------------- Set a new collection of states ### [#](#parameters-6) Parameters * `states` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \>** Array of new states * `opts` **any?** ### [#](#examples-6) Examples const states = selectorManager.setStates([\ { name: 'hover', label: 'Hover' },\ { name: 'nth-of-type(2n)', label: 'Even/Odd' }\ ]); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[State](/docs/api/state.html) \>** [#](#getselected) getSelected ------------------------------ Get commonly selected selectors, based on all selected components. ### [#](#examples-7) Examples const selected = selectorManager.getSelected(); console.log(selected.map(s => s.toString())) Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Selector](/docs/api/selector.html) \>** [#](#getselectedall) getSelectedAll ------------------------------------ Get selected selectors. ### [#](#examples-8) Examples const selected = selectorManager.getSelectedAll(); console.log(selected.map(s => s.toString())) Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Selector](/docs/api/selector.html) \>** [#](#addselected) addSelected ------------------------------ Add new selector to all selected components. ### [#](#parameters-7) Parameters * `props` **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls` ### [#](#examples-9) Examples selectorManager.addSelected('.new-class'); [#](#removeselected) removeSelected ------------------------------------ Remove a common selector from all selected components. ### [#](#parameters-8) Parameters * `selector` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Selector](/docs/api/selector.html) )** Selector instance or Selector string identifier ### [#](#examples-10) Examples selectorManager.removeSelected('.myclass'); [#](#getselectedtargets) getSelectedTargets -------------------------------------------- Get the array of currently selected targets. ### [#](#examples-11) Examples const targetsToStyle = selectorManager.getSelectedTargets(); console.log(targetsToStyle.map(target => target.getSelectorsString())) Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <([Component](/docs/api/component.html) | [CssRule](/docs/api/css_rule.html) )>** [#](#setcomponentfirst) setComponentFirst ------------------------------------------ Update component-first option. If the component-first is enabled, all the style changes will be applied on selected components (ID rules) instead of selectors (which would change styles on all components with those classes). ### [#](#parameters-9) Parameters * `value` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#getcomponentfirst) getComponentFirst ------------------------------------------ Get the value of component-first option. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#getall) getAll -------------------- Get all selectors Returns **Collection<[Selector](/docs/api/selector.html) \>** ← [‍ ‍ ‍ Device](/docs/api/device.html) [‍ ‍ ‍ Selector](/docs/api/selector.html) → --- # GrapesJS [#](#selector) Selector ------------------------ ### [#](#properties) Properties * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Selector name, eg. `my-class` * `label` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Selector label, eg. `My Class` * `type` **[Number (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) ?** Type of the selector. 1 (class) | 2 (id) * `active` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** If not active, it's not selectable by the Style Manager. * `private` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** If true, it can't be seen by the Style Manager, but it will be rendered in the canvas and in export code. * `protected` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** If true, it can't be removed from the attached component. ### [#](#tostring) toString Get selector as a string. #### [#](#examples) Examples // Given such selector: { name: 'my-selector', type: 2 } console.log(selector.toString()); // -> `#my-selector` Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getname) getName Get selector name. #### [#](#examples-2) Examples // Given such selector: { name: 'my-selector', label: 'My selector' } console.log(selector.getName()); // -> `my-selector` Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getlabel) getLabel Get selector label. #### [#](#examples-3) Examples // Given such selector: { name: 'my-selector', label: 'My selector' } console.log(selector.getLabel()); // -> `My selector` Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#setlabel) setLabel Update selector label. #### [#](#parameters) Parameters * `label` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** New label #### [#](#examples-4) Examples // Given such selector: { name: 'my-selector', label: 'My selector' } selector.setLabel('New Label') console.log(selector.getLabel()); // -> `New Label` ### [#](#getactive) getActive Get selector active state. Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** ### [#](#setactive) setActive Update selector active state. #### [#](#parameters-2) Parameters * `value` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** New active state ← [Selector Manager](/docs/api/selector_manager.html) [‍ ‍ ‍ State](/docs/api/state.html) → --- # GrapesJS [#](#state) State ------------------ ### [#](#properties) Properties * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** State name, eg. `hover`, `nth-of-type(2n)` * `label` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** State label, eg. `Hover`, `Even/Odd` ### [#](#getname) getName Get state name Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getlabel) getLabel Get state label. If label was not provided, the name will be returned. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ← [‍ ‍ ‍ Selector](/docs/api/selector.html) [Trait Manager](/docs/api/trait_manager.html) → --- # GrapesJS [#](#traits) Traits -------------------- You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/trait_manager/config/config.ts) const editor = grapesjs.init({ traitManager: { // options } }) Once the editor is instantiated you can use the API below and listen to the events. Before using these methods, you should get the module from the instance. // Listen to events editor.on('trait:value', () => { ... }); // Use the Trait Manager API const tm = editor.Traits; tm.select(...) [#](#available-events) Available Events ---------------------------------------- * `trait:select` New traits selected (eg. by changing a component). editor.on('trait:select', ({ traits, component }) => { ... }); * `trait:value` Trait value updated. editor.on('trait:value', ({ trait, component, value }) => { ... }); * `trait:category:update` Trait category updated. editor.on('trait:category:update', ({ category, changes }) => { ... }); * `trait:custom` Event to use in case of [custom Trait Manager UI (opens new window)](https://grapesjs.com/docs/modules/Traits.html#custom-trait-manager) . editor.on('trait:custom', ({ container }) => { ... }); * `trait` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. editor.on('trait', ({ event, model, ... }) => { ... }); [#](#getconfig) getConfig -------------------------- Get configuration object Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#select) select -------------------- Select traits from a component. ### [#](#parameters) Parameters * `component` **[Component](/docs/api/component.html) ** ### [#](#examples) Examples tm.select(someComponent); [#](#getcategories) getCategories ---------------------------------- Get trait categories from the currently selected component. ### [#](#examples-2) Examples const traitCategories: Category[] = tm.getCategories(); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#gettraits) getTraits -------------------------- Get traits from the currently selected component. ### [#](#examples-3) Examples const currentTraits: Trait[] = tm.getTraits(); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[Trait](/docs/api/trait.html) \>** [#](#gettraitsbycategory) getTraitsByCategory ---------------------------------------------- Get traits by category from the currently selected component. ### [#](#parameters-2) Parameters * `traits` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ?** ### [#](#examples-4) Examples tm.getTraitsByCategory(); // Returns an array of items of this type // > { category?: Category; items: Trait[] } // NOTE: The item without category is the one containing traits without category. // You can also get the same output format by passing your own array of Traits const myFilteredTraits: Trait[] = [...]; tm.getTraitsByCategory(myFilteredTraits); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#getcomponent) getComponent -------------------------------- Get component from the currently selected traits. ### [#](#examples-5) Examples tm.getComponent(); // Component {} [#](#addtype) addType ---------------------- Add new trait type. More about it here: [Define new Trait type (opens new window)](https://grapesjs.com/docs/modules/Traits.html#define-new-trait-type) . ### [#](#parameters-3) Parameters * `name` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Type name. * `methods` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Object representing the trait. ← [‍ ‍ ‍ State](/docs/api/state.html) [‍ ‍ ‍ Trait](/docs/api/trait.html) → --- # GrapesJS [#](#cssrule) CssRule ---------------------- **Extends StyleableModel** ### [#](#parameters) Parameters * `props` **CssRuleProperties** * `opt` **any** (optional, default `{}`) ### [#](#properties) Properties * `selectors` **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Array of selectors * `style` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Object containing style definitions * `selectorsAdd` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Additional string css selectors * `atRuleType` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Type of at-rule, eg. `media`, 'font-face' * `mediaText` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** At-rule value, eg. `(max-width: 1000px)` * `singleAtRule` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** This property is used only on at-rules, like 'page' or 'font-face', where the block containes only style declarations * `state` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** State of the rule, eg: `hover`, `focused` * `important` **([Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \>)?** If true, sets `!important` on all properties. You can also pass an array to specify properties on which use important * `stylable` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Indicates if the rule is stylable from the editor\[Device\]: device.html\[State\]: state.html\[Component\]: component.html ### [#](#getatrule) getAtRule Returns the at-rule statement when exists, eg. `@media (...)`, `@keyframes` #### [#](#examples) Examples const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { atRuleType: 'media', atRuleParams: '(min-width: 500px)' }); cssRule.getAtRule(); // "@media (min-width: 500px)" Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#selectorstostring) selectorsToString Return selectors of the rule as a string #### [#](#parameters-2) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Options (optional, default `{}`) * `opts.skipState` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** Skip state from the result #### [#](#examples-2) Examples const cssRule = editor.Css.setRule('.class1:hover', { color: 'red' }); cssRule.selectorsToString(); // ".class1:hover" cssRule.selectorsToString({ skipState: true }); // ".class1" Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getdeclaration) getDeclaration Get declaration block (without the at-rule statement) #### [#](#parameters-3) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (same as in `selectorsToString`) (optional, default `{}`) #### [#](#examples-3) Examples const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { atRuleType: 'media', atRuleParams: '(min-width: 500px)' }); cssRule.getDeclaration() // ".class1{color:red;}" Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#getdevice) getDevice Get the Device the rule is related to. #### [#](#examples-4) Examples const device = rule.getDevice(); console.log(device?.getName()); Returns **(\[Device\] | null)** ### [#](#getstate) getState Get the State the rule is related to. #### [#](#examples-5) Examples const state = rule.getState(); console.log(state?.getLabel()); Returns **(\[State\] | null)** ### [#](#getcomponent) getComponent Returns the related Component (valid only for component-specific rules). #### [#](#examples-6) Examples const cmp = rule.getComponent(); console.log(cmp?.toHTML()); Returns **(\[Component\] | null)** ### [#](#tocss) toCSS Return the CSS string of the rule #### [#](#parameters-4) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (same as in `getDeclaration`) (optional, default `{}`) #### [#](#examples-7) Examples const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { atRuleType: 'media', atRuleParams: '(min-width: 500px)' }); cssRule.toCSS() // "@media (min-width: 500px){.class1{color:red;}}" Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** CSS string ← [CSS Composer](/docs/api/css_composer.html) [Modal](/docs/api/modal_dialog.html) → --- # GrapesJS [#](#trait) Trait ------------------ ### [#](#properties) Properties * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Trait id, eg. `my-trait-id`. * `type` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Trait type, defines how the trait should be rendered. Possible values: `text` (default), `number`, `select`, `checkbox`, `color`, `button` * `label` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** The trait label to show for the rendered trait. * `name` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** The name of the trait used as a key for the attribute/property. By default, the name is used as attribute name or property in case `changeProp` in enabled. * `default` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Default value to use in case the value is not defined on the component. * `placeholder` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Placeholder to show inside the default input (if the UI type allows it). * `category` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Trait category. * `changeProp` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If `true`, the trait value is applied on the component property, otherwise, on component attributes. [#](#getid) getId ------------------ Get the trait id. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#gettype) getType ---------------------- Get the trait type. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getname) getName ---------------------- Get the trait name. Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getlabel) getLabel ------------------------ Get the trait label. ### [#](#parameters) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options. (optional, default `{}`) * `opts.locale` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Use the locale string from i18n module. (optional, default `true`) Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#getvalue) getValue ------------------------ Get the trait value. The value is taken from component attributes by default or from properties if the trait has the `changeProp` enabled. ### [#](#parameters-2) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options. (optional, default `{}`) * `opts.useType` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Get the value based on type (eg. the checkbox will always return a boolean). (optional, default `false`) Returns **any** [#](#setvalue) setValue ------------------------ Update the trait value. The value is applied on component attributes by default or on properties if the trait has the `changeProp` enabled. ### [#](#parameters-3) Parameters * `value` **any** Value of the trait. * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options. (optional, default `{}`) * `opts.partial` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ?** If `true` the update won't be considered complete (not stored in UndoManager). [#](#getdefault) getDefault ---------------------------- Get default value. [#](#getoptions) getOptions ---------------------------- Get trait options. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#getoption) getOption -------------------------- Get current selected option or by id. ### [#](#parameters-4) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** Option id. Returns **([Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) | null)** [#](#getoptionid) getOptionId ------------------------------ Get the option id from the option object. ### [#](#parameters-5) Parameters * `option` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Option object Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Option id [#](#getoptionlabel) getOptionLabel ------------------------------------ Get option label. ### [#](#parameters-6) Parameters * `id` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) )** Option id or the option object * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.locale` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Use the locale string from i18n module (optional, default `true`) Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Option label [#](#getcategorylabel) getCategoryLabel ---------------------------------------- Get category label. ### [#](#parameters-7) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options. (optional, default `{}`) * `opts.locale` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Use the locale string from i18n module. (optional, default `true`) Returns **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** [#](#runcommand) runCommand ---------------------------- Run the trait command (used on the button trait type). ← [Trait Manager](/docs/api/trait_manager.html) [CSS Composer](/docs/api/css_composer.html) → --- # GrapesJS [#](#richtexteditor) RichTextEditor ------------------------------------ This module allows to customize the built-in toolbar of the Rich Text Editor and use commands from the [HTML Editing APIs (opens new window)](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) . It's highly recommended to keep this toolbar as small as possible, especially from styling commands (eg. 'fontSize') and leave this task to the Style Manager You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/rich_text_editor/config/config.ts) const editor = grapesjs.init({ richTextEditor: { // options } }) Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. // Listen to events editor.on('rte:enable', () => { ... }); // Use the API const rte = editor.RichTextEditor; rte.add(...); [#](#available-events) Available Events ---------------------------------------- * `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 [#](#methods) Methods ---------------------- * [add](#add) * [get](#get) * [run](#run) * [getAll](#getall) * [remove](#remove) * [getToolbarEl](#gettoolbarel) [#](#getconfig) getConfig -------------------------- Get configuration object Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#add) add -------------- Add a new action to the built-in RTE toolbar ### [#](#parameters) Parameters * `name` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Action name * `action` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Action options (optional, default `{}`) ### [#](#examples) Examples rte.add('bold', { icon: 'B', attributes: {title: 'Bold'}, result: rte => rte.exec('bold') }); rte.add('link', { icon: document.getElementById('t'), attributes: { title: 'Link' }, // Example on how to wrap selected content result: rte => rte.insertHTML(`
${rte.selection()}`) }); // An example with fontSize rte.add('fontSize', { icon: ``, // Bind the 'result' on 'change' listener event: 'change', result: (rte, action) => rte.exec('fontSize', action.btn.firstChild.value), // Callback on any input change (mousedown, keydown, etc..) update: (rte, action) => { const value = rte.doc.queryCommandValue(action.name); if (value != 'false') { // value is a string action.btn.firstChild.value = value; } } }) // An example with state const isValidAnchor = (rte) => { // a utility function to help determine if the selected is a valid anchor node const anchor = rte.selection().anchorNode; const parentNode = anchor && anchor.parentNode; const nextSibling = anchor && anchor.nextSibling; return (parentNode && parentNode.nodeName == 'A') || (nextSibling && nextSibling.nodeName == 'A') } rte.add('toggleAnchor', { icon: ``, state: (rte, doc) => { if (rte && rte.selection()) { // `btnState` is a integer, -1 for disabled, 0 for inactive, 1 for active return isValidAnchor(rte) ? btnState.ACTIVE : btnState.INACTIVE; } else { return btnState.INACTIVE; } }, result: (rte, action) => { if (isValidAnchor(rte)) { rte.exec('unlink'); } else { rte.insertHTML(`${rte.selection()}`); } } }) [#](#get) get -------------- Get the action by its name ### [#](#parameters-2) Parameters * `name` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Action name ### [#](#examples-2) Examples const action = rte.get('bold'); // {name: 'bold', ...} Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#getall) getAll -------------------- Get all actions Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** [#](#remove) remove -------------------- Remove the action from the toolbar ### [#](#parameters-3) Parameters * `name` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** ### [#](#examples-3) Examples const action = rte.remove('bold'); // {name: 'bold', ...} Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Removed action [#](#run) run -------------- Run action command. ### [#](#parameters-4) Parameters * `action` **([string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | RichTextEditorAction)** Action to run ### [#](#examples-4) Examples const action = rte.get('bold'); rte.run(action) // or rte.run('bold') [#](#gettoolbarel) getToolbarEl -------------------------------- Get the toolbar element Returns **[HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) ** ← [Modal](/docs/api/modal_dialog.html) [Keymaps](/docs/api/keymaps.html) → --- # GrapesJS You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/modal_dialog/config/config.ts) const editor = grapesjs.init({ modal: { // options } }) Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance const modal = editor.Modal; [#](#available-events) Available Events ---------------------------------------- * `modal:open` - Modal is opened * `modal:close` - Modal is closed * `modal` - Event triggered on any change related to the modal. An object containing all the available data about the triggered event is passed as an argument to the callback. [#](#methods) Methods ---------------------- * [open](#open) * [close](#close) * [isOpen](#isopen) * [setTitle](#settitle) * [getTitle](#gettitle) * [setContent](#setcontent) * [getContent](#getcontent) * [onceClose](#onceclose) * [onceOpen](#onceopen) [#](#open) open ---------------- Open the modal window ### [#](#parameters) Parameters * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.title` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) )?** Title to set for the modal * `opts.content` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) )?** Content to set for the modal * `opts.attributes` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Updates the modal wrapper with custom attributes ### [#](#examples) Examples modal.open({ title: 'My title', content: 'My content', attributes: { class: 'my-class' }, }); Returns **this** [#](#close) close ------------------ Close the modal window ### [#](#examples-2) Examples modal.close(); Returns **this** [#](#onceclose) onceClose -------------------------- Execute callback when the modal will be closed. The callback will be called one only time ### [#](#parameters-2) Parameters * `clb` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ** Callback to call ### [#](#examples-3) Examples modal.onceClose(() => { console.log('The modal is closed'); }); Returns **this** [#](#onceopen) onceOpen ------------------------ Execute callback when the modal will be opened. The callback will be called one only time ### [#](#parameters-3) Parameters * `clb` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ** Callback to call ### [#](#examples-4) Examples modal.onceOpen(() => { console.log('The modal is opened'); }); Returns **this** [#](#isopen) isOpen -------------------- Checks if the modal window is open ### [#](#examples-5) Examples modal.isOpen(); // true | false Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#settitle) setTitle ------------------------ Set the title to the modal window ### [#](#parameters-4) Parameters * `title` **([string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) )** Title ### [#](#examples-6) Examples // pass a string modal.setTitle('Some title'); // or an HTMLElement const el = document.createElement('div'); el.innerText = 'New title'; modal.setTitle(el); Returns **this** [#](#gettitle) getTitle ------------------------ Returns the title of the modal window ### [#](#examples-7) Examples modal.getTitle(); Returns **([string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) )** [#](#setcontent) setContent ---------------------------- Set the content of the modal window ### [#](#parameters-5) Parameters * `content` **([string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) )** Content ### [#](#examples-8) Examples // pass a string modal.setContent('Some content'); // or an HTMLElement const el = document.createElement('div'); el.innerText = 'New content'; modal.setContent(el); Returns **this** [#](#getcontent) getContent ---------------------------- Get the content of the modal window ### [#](#examples-9) Examples modal.getContent(); Returns **([string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [HTMLElement (opens new window)](https://developer.mozilla.org/docs/Web/HTML/Element) )** ← [‍ ‍ ‍ CssRule](/docs/api/css_rule.html) [Rich Text Editor](/docs/api/rich_text_editor.html) → --- # GrapesJS [#](#css) Css -------------- This module manages CSS rules in the canvas. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/css_composer/config/config.ts) const editor = grapesjs.init({ cssComposer: { // options } }) Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance const css = editor.Css; * [addRules](#addrules) * [setRule](#setrule) * [getRule](#getrule) * [getRules](#getrules) * [remove](#remove) * [clear](#clear) [#](#addrules) addRules ------------------------ Add CssRules via CSS string. ### [#](#parameters) Parameters * `css` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** CSS string of rules to add. ### [#](#examples) Examples const addedRules = css.addRules('.my-cls{ color: red } @media (max-width: 992px) { .my-cls{ color: darkred } }'); // Check rules console.log(addedRules.map(rule => rule.toCSS())); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[CssRule](/docs/api/css_rule.html) \>** Array of rules [#](#setrule) setRule ---------------------- Add/update the CssRule. ### [#](#parameters-2) Parameters * `selectors` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Selector string, eg. `.myclass` * `style` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Style properties and values. If the rule exists, styles will be replaced unless `addStyles` option is used. (optional, default `{}`) * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Additional properties. (optional, default `{}`) * `opts.atRuleType` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** At-rule type, eg. `media`. (optional, default `''`) * `opts.atRuleParams` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** At-rule parameters, eg. `(min-width: 500px)`. (optional, default `''`) * `opts.addStyles` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** If the rule exists already, merge passed styles instead of replacing them. (optional, default `false`) ### [#](#examples-2) Examples // Simple class-based rule const rule = css.setRule('.class1.class2', { color: 'red' }); console.log(rule.toCSS()) // output: .class1.class2 { color: red } // With state and other mixed selector const rule = css.setRule('.class1.class2:hover, div#myid', { color: 'red' }); // output: .class1.class2:hover, div#myid { color: red } // With media const rule = css.setRule('.class1:hover', { color: 'red' }, { atRuleType: 'media', atRuleParams: '(min-width: 500px)', }); // output: `@media (min-width: 500px) { .class1:hover { color: red } }` // Update styles of existent rule css.setRule('.class1', { color: 'red', background: 'red' }); css.setRule('.class1', { color: 'blue' }, { addStyles: true }); // output: .class1 { color: blue; background: red } Returns **[CssRule](/docs/api/css_rule.html) ** The new/updated CssRule. [#](#getrule) getRule ---------------------- Get the CssRule. ### [#](#parameters-3) Parameters * `selectors` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Selector string, eg. `.myclass:hover` * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Additional properties (optional, default `{}`) * `opts.atRuleType` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** At-rule type, eg. `media` (optional, default `''`) * `opts.atRuleParams` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** At-rule parameters, eg. '(min-width: 500px)' (optional, default `''`) ### [#](#examples-3) Examples const rule = css.getRule('.myclass1:hover'); const rule2 = css.getRule('.myclass1:hover, div#myid'); const rule3 = css.getRule('.myclass1', { atRuleType: 'media', atRuleParams: '(min-width: 500px)', }); Returns **[CssRule](/docs/api/css_rule.html) ** [#](#getrules) getRules ------------------------ Get all rules or filtered by a matching selector. ### [#](#parameters-4) Parameters * `selector` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Selector, eg. `.myclass` (optional, default `''`) ### [#](#examples-4) Examples // Take all the component specific rules const id = someComponent.getId(); const rules = css.getRules(`#${id}`); console.log(rules.map(rule => rule.toCSS())) // All rules in the project console.log(css.getRules()) Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[CssRule](/docs/api/css_rule.html) \>** [#](#remove) remove -------------------- Remove rule, by CssRule or matching selector (eg. the selector will match also at-rules like `@media`) ### [#](#parameters-5) Parameters * `rule` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [CssRule](/docs/api/css_rule.html) | [Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[CssRule](/docs/api/css_rule.html) \>)** CssRule or matching selector. * `opts` **any?** ### [#](#examples-5) Examples // Remove by CssRule const toRemove = css.getRules('.my-cls'); css.remove(toRemove); // Remove by selector css.remove('.my-cls-2'); Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) <[CssRule](/docs/api/css_rule.html) \>** Removed rules [#](#clear) clear ------------------ Remove all rules ### [#](#parameters-6) Parameters * `opts` (optional, default `{}`) Returns **this** ← [‍ ‍ ‍ Trait](/docs/api/trait.html) [‍ ‍ ‍ CssRule](/docs/api/css_rule.html) → --- # GrapesJS [#](#keymaps) Keymaps ---------------------- You can customize the initial state of the module from the editor initialization const editor = grapesjs.init({ keymaps: { // Object of keymaps defaults: { 'your-namespace:keymap-name' { keys: '⌘+z, ctrl+z', handler: 'some-command-id' }, ... } } }) Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. // Listen to events editor.on('keymap:add', () => { ... }); // Use the API const keymaps = editor.Keymaps; keymaps.add(...); [#](#available-events) Available Events ---------------------------------------- * `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 [#](#methods) Methods ---------------------- * [getConfig](#getconfig) * [add](#add) * [get](#get) * [getAll](#getAll) * [remove](#remove) * [removeAll](#removeall) [#](#getconfig) getConfig -------------------------- Get configuration object Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#add) add -------------- Add new keymap ### [#](#parameters) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Keymap id * `keys` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Keymap keys, eg. `ctrl+a`, `⌘+z, ctrl+z` * `handler` **([Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) | [string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) )** Keymap handler, might be a function * `opts` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Options (optional, default `{}`) * `opts.force` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Force the handler to be executed. (optional, default `false`) * `opts.prevent` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Prevent default of the original triggered event. (optional, default `false`) ### [#](#examples) Examples // 'ns' is just a custom namespace keymaps.add('ns:my-keymap', '⌘+j, ⌘+u, ctrl+j, alt+u', editor => { console.log('do stuff'); }); // or keymaps.add('ns:my-keymap', '⌘+s, ctrl+s', 'some-gjs-command', { // Prevent the default browser action prevent: true, }); // listen to events editor.on('keymap:emit', (id, shortcut, event) => { // ... }) Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Added keymap [#](#get) get -------------- Get the keymap by id ### [#](#parameters-2) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Keymap id ### [#](#examples-2) Examples keymaps.get('ns:my-keymap'); // -> {keys, handler}; Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Keymap object [#](#getall) getAll -------------------- Get all keymaps ### [#](#examples-3) Examples keymaps.getAll(); // -> {id1: {}, id2: {}}; Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#remove) remove -------------------- Remove the keymap by id ### [#](#parameters-3) Parameters * `id` **[string (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Keymap id ### [#](#examples-4) Examples keymaps.remove('ns:my-keymap'); // -> {keys, handler}; Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Removed keymap [#](#removeall) removeAll -------------------------- Remove all binded keymaps Returns **this** ← [Rich Text Editor](/docs/api/rich_text_editor.html) [Undo Manager](/docs/api/undo_manager.html) → --- # GrapesJS [#](#undomanager) UndoManager ------------------------------ This module allows to manage the stack of changes applied in canvas. Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance const um = editor.UndoManager; * [getConfig](#getconfig) * [add](#add) * [remove](#remove) * [removeAll](#removeall) * [start](#start) * [stop](#stop) * [undo](#undo) * [undoAll](#undoall) * [redo](#redo) * [redoAll](#redoall) * [hasUndo](#hasundo) * [hasRedo](#hasredo) * [getStack](#getstack) * [clear](#clear) [#](#getconfig) getConfig -------------------------- Get configuration object Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#add) add -------------- Add an entity (Model/Collection) to track Note: New Components and CSSRules will be added automatically ### [#](#parameters) Parameters * `entity` **(Model | Collection)** Entity to track ### [#](#examples) Examples um.add(someModelOrCollection); Returns **this** [#](#remove) remove -------------------- Remove and stop tracking the entity (Model/Collection) ### [#](#parameters-2) Parameters * `entity` **(Model | Collection)** Entity to remove ### [#](#examples-2) Examples um.remove(someModelOrCollection); Returns **this** [#](#removeall) removeAll -------------------------- Remove all entities ### [#](#examples-3) Examples um.removeAll(); Returns **this** [#](#start) start ------------------ Start/resume tracking changes ### [#](#examples-4) Examples um.start(); Returns **this** [#](#stop) stop ---------------- Stop tracking changes ### [#](#examples-5) Examples um.stop(); Returns **this** [#](#undo) undo ---------------- Undo last change ### [#](#parameters-3) Parameters * `all` (optional, default `true`) ### [#](#examples-6) Examples um.undo(); Returns **this** [#](#undoall) undoAll ---------------------- Undo all changes ### [#](#examples-7) Examples um.undoAll(); Returns **this** [#](#redo) redo ---------------- Redo last change ### [#](#parameters-4) Parameters * `all` (optional, default `true`) ### [#](#examples-8) Examples um.redo(); Returns **this** [#](#redoall) redoAll ---------------------- Redo all changes ### [#](#examples-9) Examples um.redoAll(); Returns **this** [#](#hasundo) hasUndo ---------------------- Checks if exists an available undo ### [#](#examples-10) Examples um.hasUndo(); Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#hasredo) hasRedo ---------------------- Checks if exists an available redo ### [#](#examples-11) Examples um.hasRedo(); Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#isregistered) isRegistered -------------------------------- Check if the entity (Model/Collection) to tracked Note: New Components and CSSRules will be added automatically ### [#](#parameters-5) Parameters * `obj` **any** * `entity` **(Model | Collection)** Entity to track Returns **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** [#](#getstack) getStack ------------------------ Get stack of changes ### [#](#examples-12) Examples const stack = um.getStack(); stack.each(item => ...); Returns **Collection** [#](#skip) skip ---------------- Execute the provided callback temporarily stopping tracking changes ### [#](#parameters-6) Parameters * `clb` **[Function (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) ** The callback to execute with changes tracking stopped ### [#](#examples-13) Examples um.skip(() => { // Do stuff without tracking }); [#](#clear) clear ------------------ Clear the stack ### [#](#examples-14) Examples um.clear(); Returns **this** ← [Keymaps](/docs/api/keymaps.html) [Parser](/docs/api/parser.html) → --- # GrapesJS [#](#datasources) DataSources ------------------------------ This module manages data sources within the editor. You can initialize the module with the editor by passing an instance of `EditorModel`. const editor = new EditorModel(); const dsm = new DataSourceManager(editor); Once the editor is instantiated, you can use the following API to manage data sources: const dsm = editor.DataSources; * [add](#add) - Add a new data source. * [get](#get) - Retrieve a data source by its ID. * [getAll](#getall) - Retrieve all data sources. * [remove](#remove) - Remove a data source by its ID. * [clear](#clear) - Remove all data sources. Example of adding a data source: const ds = dsm.add({ id: 'my_data_source_id', records: [\ { id: 'id1', name: 'value1' },\ { id: 'id2', name: 'value2' }\ ] }); ### [#](#parameters) Parameters * `em` **EditorModel** Editor model. [#](#add) add -------------- Add new data source. ### [#](#parameters-2) Parameters * `props` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Data source properties. * `opts` **AddOptions** (optional, default `{}`) ### [#](#examples) Examples const ds = dsm.add({ id: 'my_data_source_id', records: [\ { id: 'id1', name: 'value1' },\ { id: 'id2', name: 'value2' }\ ] }); Returns **\[DataSource\]** Added data source. [#](#get) get -------------- Get data source. ### [#](#parameters-3) Parameters * `id` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Data source id. ### [#](#examples-2) Examples const ds = dsm.get('my_data_source_id'); Returns **\[DataSource\]** Data source. [#](#getvalue) getValue ------------------------ Get value from data sources by key ### [#](#parameters-4) Parameters * `key` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** Path to value. * `defValue` **any** Returns **any** const value = dsm.getValue('ds\_id.record\_id.propName', 'defaultValue'); [#](#remove) remove -------------------- Remove data source. ### [#](#parameters-5) Parameters * `id` **([String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | \[DataSource\])** Id of the data source. * `opts` **RemoveOptions?** ### [#](#examples-3) Examples const removed = dsm.remove('DS_ID'); Returns **\[DataSource\]** Removed data source. [#](#frompath) fromPath ------------------------ Retrieve a data source, data record, and optional property path based on a string path. This method parses a string path to identify and retrieve the corresponding data source and data record. If a property path is included in the input, it will also be returned. The method is useful for accessing nested data within data sources. ### [#](#parameters-6) Parameters * `path` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** The string path in the format 'dataSourceId.recordId.property'. ### [#](#examples-4) Examples const [dataSource, dataRecord, propPath] = dsm.fromPath('my_data_source_id.record_id.myProp'); // e.g., [DataSource, DataRecord, 'myProp'] Returns **\[DataSource?, DataRecord?, [String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)\ ?\]** An array containing the data source, data record, and optional property path. [#](#store) store ------------------ Store data sources to a JSON object. Returns **[Array (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) ** Stored data sources. [#](#load) load ---------------- Load data sources from a JSON object. ### [#](#parameters-7) Parameters * `data` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** The data object containing data sources. Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** Loaded data sources. ← [Parser](/docs/api/parser.html) [‍ ‍ ‍ DataSource](/docs/api/datasource.html) → --- # Plugins | GrapesJS [#](#plugins) Plugins ====================== Creating plugins in GrapesJS is pretty straightforward and here you'll get how to achieve it. WARNING This guide is referring to GrapesJS v0.21.2 or higher * [Basic plugin](#basic-plugin) * [Plugins with options](#plugins-with-options) * [Usage with TS](#usage-with-ts) * [Boilerplate](#boilerplate) [#](#basic-plugin) Basic plugin -------------------------------- Plugins are simple functions that are run when the editor is initialized. function myPlugin(editor) { // Use the API: https://grapesjs.com/docs/api/ editor.Blocks.add('my-first-block', { label: 'Simple block', content: '
This is a simple block
', }); } const editor = grapesjs.init({ container: '#gjs', plugins: [myPlugin], }); This means plugins can be moved to separate folders to keep thing cleaner or imported from NPM. import myPlugin from './plugins/myPlugin'; import npmPackage from '@npm/package'; const editor = grapesjs.init({ container: '#gjs', plugins: [myPlugin, npmPackage], }); [#](#plugins-with-options) Plugins with options ------------------------------------------------ It's also possible to pass custom parameters to plugins in to make them more flexible. const myPluginWithOptions = (editor, options) => { console.log(options); // { customField: 'customValue' } }; const editor = grapesjs.init({ container: '#gjs', plugins: [myPluginWithOptions], pluginsOpts: { [myPluginWithOptions]: { customField: 'customValue', }, }, }); [#](#usage-with-ts) Usage with TS ---------------------------------- If you're using TypeScript, for a better type safety, we recommend using the `usePlugin` helper. import grapesjs, { usePlugin } from 'grapesjs'; import type { Plugin } from 'grapesjs'; interface MyPluginOptions { opt1: string; opt2?: number; } const myPlugin: Plugin = (editor, options) => { // ... }; grapesjs.init({ // ... plugins: [\ // no need for `pluginsOpts`\ usePlugin(myPlugin, { opt1: 'A', opt2: 1 }),\ ], }); [#](#boilerplate) Boilerplate ------------------------------ For fast plugin development, we highly recommend using [grapesjs-cli (opens new window)](https://github.com/GrapesJS/cli) which helps to avoid the hassle of setting up all the dependencies and configurations for development and building (no need to touch Webpack or Babel configurations). For more information check the repository. ← [Modal](/docs/modules/Modal.html) [Symbols](/docs/guides/Symbols.html) → --- # GrapesJS [#](#parser) Parser -------------------- You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object (opens new window)](https://github.com/GrapesJS/grapesjs/blob/master/src/parser/config/config.ts) const editor = grapesjs.init({ parser: { // options } }) Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance const { Parser } = editor; [#](#available-events) Available Events ---------------------------------------- * `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 [#](#methods) Methods ---------------------- * [getConfig](#getconfig) * [parseHtml](#parsehtml) * [parseCss](#parsecss) [#](#getconfig) getConfig -------------------------- Get configuration object Returns **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ** [#](#parsehtml) parseHtml -------------------------- Parse HTML string and return the object containing the Component Definition ### [#](#parameters) Parameters * `input` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ** HTML string to parse * `options` **[Object (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) ?** Options (optional, default `{}`) * `options.htmlType` **[String (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) ?** [HTML mime type (opens new window)](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02) to parse * `options.allowScripts` **[Boolean (opens new window)](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) ** Allow ` In the example above we're relying on two hidden inputs, one for containing the project data and the another one for the HTML/CSS. [#](#events) Events -------------------- For a complete list of available events, you can check it [here](/docs/api/storage_manager.html#available-events) . ← [Style Manager](/docs/modules/Style-manager.html) [Modal](/docs/modules/Modal.html) → --- # Symbols | GrapesJS [#](#symbols) Symbols ====================== WARNING This feature is released as a beta from GrapesJS v0.21.11 To get a better understanding of the content in this guide we recommend reading [Components](/docs/modules/Components.html) first Symbols are a special type of [Component](/docs/modules/Components.html) that allows you to easily reuse common elements across your project. They are particularly useful for components that appear multiple times in your project and need to remain consistent. By using Symbols, you can easily update these components in one place and have the changes reflected everywhere they are used. * [Concept](#concept) * [Programmatic usage](#programmatic-usage) * [Create symbol](#create-symbol) * [Symbol details](#symbol-details) * [Overrides](#overrides) * [Detach symbol](#detach-symbol) * [Remove symbol](#remove-symbol) * [Events](#events) * [Example](#example) [#](#concept) Concept ---------------------- A Symbol created from a component retains the same shape and uses the same [Components API](/docs/api/component.html) , but it includes a reference to other related Symbols. When you create a new Symbol from a Component, it creates a Main Symbol, and the original component becomes an Instance Symbol. When you reuse the Symbol elsewhere, it creates new Instance Symbols. Any updates made to the Main Symbol are automatically replicated in all Instance Symbols, ensuring consistency throughout your project. Below is a simple representation of the connection between Main and Instance Symbols. ![](/docs/symbols-model.svg) Note This feature operates at a low level, meaning there is no built-in UI for creating and managing symbols. Developers need to implement their own UI to interact with this feature. Below you'll find an example of implementation. [#](#programmatic-usage) Programmatic usage -------------------------------------------- Let's see how to work with and manage Symbols in your project. ### [#](#create-symbol) Create symbol Create a new Symbol from any component in your project: const anyComponent = editor.getSelected(); const symbolMain = editor.Components.addSymbol(anyComponent); This will transform `anyComponent` to an Instance and the returned `symbolMain` will be the Main Symbol. GrapesJS keeps track of Main Symbols separately in your project JSON, and they will be automatically reconnected when you reload the project. The `addSymbol` method also handles the creation of Instances. If you call it again by passing `symbolMain` or `anyComponent`, it will create a new Instance of `symbolMain`. const secondInstance = editor.Components.addSymbol(symbolMain); Now, `symbolMain` references two instances of its shape. To get all the available Symbols in your project, use `getSymbols`: const symbols = editor.Components.getSymbols(); const symbolMain = symbols[0]; ### [#](#symbol-details) 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: // 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 ### [#](#overrides) Overrides When you update a Symbol's properties, changes are propagated to all related Symbols. To avoid propagating specific properties, you can specify at the component level which properties to skip: anyComponent.set('my-property', true); secondInstance.get('my-property'); // true; change propagated anyComponent.setSymbolOverride(['my-property']); // Get current override value: anyComponent.getSymbolOverride(); anyComponent.set('my-property', false); secondInstance.get('my-property'); // true; change didn't propagate ### [#](#detach-symbol) Detach symbol Once you have Symbol instances you might need to disconnect one to create a new custom shape with other components inside, in that case you can use `detachSymbol`. editor.Components.detachSymbol(anyComponent); const info = editor.Components.getSymbolInfo(anyComponent); info.isSymbol; // false; Not a Symbol anymore const infoMain = editor.Components.getSymbolInfo(symbolMain); infoMain.instances; // [secondInstance]; Removed the reference ### [#](#remove-symbol) Remove symbol To remove a Main Symbol and detach all related instances: const symbolMain = editor.Components.getSymbols()[0]; symbolMain.remove(); [#](#events) Events -------------------- The editor triggers several symbol-related events that you can leverage for your integration: * `symbol:main:add` Added new root main symbol. editor.on('symbol:main:add', ({ component }) => { ... }); * `symbol:main:update` Root main symbol updated. editor.on('symbol:main:update', ({ component }) => { ... }); * `symbol:main:remove` Root main symbol removed. editor.on('symbol:main:remove', ({ component }) => { ... }); * `symbol:main` Catch-all event related to root main symbol updates. editor.on('symbol:main', ({ event, component }) => { ... }); * `symbol:instance:add` Added new root instance symbol. editor.on('symbol:instance:add', ({ component }) => { ... }); * `symbol:instance:remove` Root instance symbol removed. editor.on('symbol:instance:remove', ({ component }) => { ... }); * `symbol:instance` Catch-all event related to root instance symbol updates. editor.on('symbol:instance', ({ event, component }) => { ... }); * `symbol` Catch-all event for any symbol update (main or instance). editor.on('symbol', () => { ... }); [#](#example) Example ---------------------- Below is a basic UI implementation leveraging the Symbols API: ← [Plugins](/docs/modules/Plugins.html) [Replace Rich Text Editor](/docs/guides/Replace-Rich-Text-Editor.html) → --- # Use Custom CSS Parser | GrapesJS [#](#use-custom-css-parser) Use Custom CSS Parser ================================================== If you just use GrapesJS for building templates from scratch, so you start from an empty canvas and for editing you strictly rely on the generated JSON (final HTML/CSS only for end-users) then, probably, you might skip this guide. On the other hand, if you import templates from already defined HTML/CSS or let the user embed custom codes (eg. using the [grapesjs-custom-code (opens new window)](https://github.com/GrapesJS/components-custom-code) plugin), then you have to know that you might face strange behaviors. WARNING This guide requires GrapesJS v0.14.33 or higher * [Import HTML/CSS](#import-html-css) * [CSSOM results are inconsistent](#cssom-results-are-inconsistent) * [Results](#results) * [CSSOM results can be nonintuitive](#cssom-results-can-be-nonintuitive) * [Set CSS parser](#set-css-parser) * [Rule Objects](#rule-objects) * [Plugins](#plugins) [#](#import-html-css) Import HTML/CSS -------------------------------------- Importing already defined HTML/CSS is a really good feature as it lets you start editing immediately any kind of template and obviously, GrapesJS itself promotes this kind of approach
Hello world!
To work fast and easier GrapesJS needs to compile a simple string (HTML/CSS) into structured nodes (nested JS objects). Fortunately, most of the hard work (parsing) is already done by the browser itself which translates that string into its own objects ([DOM (opens new window)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) /[CSSOM (opens new window)](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model) ) and so we just rely on those, by traversing them and creating our nodes (unfortunately browser's objects are not enough). The fact we're able to parse our strings just by using the browser itself it's very cool, we can enable the import feature without requiring any third-party library, so... where is the problem? Well, while the generated DOM is performing quite well, as we're able to extract what we need, unfortunately, it's not the same for the CSSOM, so let's see in the next paragraph what is wrong with it. [#](#cssom-results-are-inconsistent) CSSOM results are inconsistent -------------------------------------------------------------------- Unfortunately, we have discovered that the CSSOM generated by browsers are highly inconsistent from what we ask to parse. To demonstrate it, we gonna create a simple example by using the built-in parser and we'll check its result. So, for our case we just take in account a simple rule, we'll parse it and print the CSSOM result on screen.

To parse

      .simple-class {
        background-image:url("https://image1.png"), url("https://image2.jpg");
        background-attachment: fixed, scroll;
        background-position:left top, center center;
        background-repeat:repeat-y, no-repeat;
        background-size: contain, cover;
        box-shadow: 0 0 5px #9d7aa5, 0 0 10px #e6c3ee;
        border: 2px solid #FF0000;
      }
    

Result


    
    
    

### [#](#results)
 Results

Here some results (using latest versions + IE11)

![](/docs/cssom-result.jpg)

As you see, this is what we get for asking only 7 properties, who adds more or less, someone converts colors to rgba functions and someone else changes the order of our values (eg. `box-shadow`). Webkit-based browsers attach also properties they self don't understand

![](/docs/cssom-devtools.png)

So it's clear that we can't rely on CSSOM objects, that's why we added the possibility to set custom CSS parser via `editor.setCustomParserCss` method or `config.Parser.parserCss` option to use on initialization. Let's see in detail how it's expected to work

[#](#cssom-results-can-be-nonintuitive)
 CSSOM results can be nonintuitive
--------------------------------------------------------------------------

As per current [csswg specification (opens new window)](https://drafts.csswg.org/css-variables-1/#variables-in-shorthands)
 variables in shorthand properties can serialize to the empty string. This means that while `background-color: var(--my-var)` will serialize fine `background: var(--my-var)` will not.

[#](#set-css-parser)
 Set CSS parser
------------------------------------

The custom parser you have to use it's just a function receiving 2 arguments: `css`, as the CSS string to parse, and `editor`, the instance of the current editor. As the result, you should return an array containing valid rule objects, the syntax of those objects are explained below. This is how you can set the custom parser

    const parserCss = (css, editor) => {
      const result = [];
      // ... parse the CSS string
      result.push({
        selectors: '.someclass, div .otherclass',
        style: { color: 'red' },
      });
      // ...
      return result; // Result should be ALWAYS an array
    };
    
    // On initialization
    // This is the recommended way, as you gonna use the parser from the beginning
    const editor = grapesjs.init({
      //...
      parser: {
        parserCss,
      },
    });
    
    // Or later, via editor API
    editor.setCustomParserCss(parserCss);
    

[#](#rule-objects)
 Rule Objects
--------------------------------

The syntax of rule objects is pretty straightforward, each object might contain following keys

| Key | Description | Example |
| --- | --- | --- |
| `selectors` | Selectors of the rule.  
**REQUIRED** return an empty string in case the rule has no selectors | `.class1, div > #someid` | | `style` | Style declarations as an object | `{ color: 'red' }` | | `atRule` | At-rule name | `media` | | `params` | Parameters of the at-rule | `screen and (min-width: 480px)` | To make it more clear let's see a few examples // Input ` @font-face { font-family: "Font Name"; src: url("https://font-url.eot"); } ` // Output [\ {\ selectors: '',\ atRule: 'font-face',\ style: {\ 'font-family': '"Font Name"',\ src: 'url("https://font-url.eot")',\ },\ }\ ] // Input ` @keyframes keyframe-name { from { opacity: 0; } to { opacity: 1; } } ` // Output [\ {\ params: 'keyframe-name',\ selectors: 'from',\ atRule: 'keyframes',\ style: {\ opacity: '0',\ },\ }, {\ params: 'keyframe-name',\ selectors: 'to',\ atRule: 'keyframes',\ style: {\ opacity: '1',\ },\ }\ ] // Input ` @media screen and (min-width: 480px) { body { background-color: lightgreen; } .class-test, .class-test2:hover { color: blue !important; } } ` // Output [\ {\ params: 'screen and (min-width: 480px)',\ selectors: 'body',\ atRule: 'media',\ style: {\ 'background-color': 'lightgreen',\ },\ }, {\ params: 'screen and (min-width: 480px)',\ selectors: '.class-test, .class-test2:hover',\ atRule: 'media',\ style: {\ color: 'blue !important',\ },\ }\ ] // Input ` :root { --some-color: red; --some-width: 55px; } ` // Output [\ {\ selectors: ':root',\ style: {\ '--some-color': 'red',\ '--some-width': '55px',\ },\ },\ ] [#](#plugins) Plugins ---------------------- Below the list of current available CSS parsers as plugins, if you need to create your own we highly suggest to explore their sources * [grapesjs-parser-postcss (opens new window)](https://github.com/GrapesJS/parser-postcss) - Using [PostCSS (opens new window)](https://github.com/postcss/postcss) parser ← [Replace Rich Text Editor](/docs/guides/Replace-Rich-Text-Editor.html) [GrapesJS Telemetry](/docs/guides/Telemetry.html) → --- # GrapesJS Telemetry | GrapesJS [#](#grapesjs-telemetry) GrapesJS Telemetry ============================================ We collect and use data to improve GrapesJS. This page explains what data we collect and how we use it. [#](#what-data-we-collect) What data we collect ------------------------------------------------ We collect the following data: * **domain**: The domain of the website where GrapesJS is used. * **version**: The version of GrapesJS used. * **timestamp**: The time when the editor is loaded. [#](#how-we-use-data) How we use data -------------------------------------- We use data to: * **Improve GrapesJS**: We use data to improve GrapesJS. For example, we use data to identify bugs and fix them. * **Analyze usage**: We use data to analyze how GrapesJS is used. For example, we use data to understand which features are used most often. * **Provide support**: We use data to provide support to users. For example, we use data to understand how users interact with GrapesJS. [#](#how-to-opt-out) How to opt-out ------------------------------------ You can opt-out of data collection by setting the `telemetry` option to `false` when initializing GrapesJS: const editor = grapesjs.init({ // ... telemetry: false, }); ← [Use Custom CSS Parser](/docs/guides/Custom-CSS-parser.html) --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- ---