File: README.md
[GrapesJS](http://grapesjs.com)
If you looking to embed the Studio editor in your application, we now offer the Studio SDK, a ready-to-use visual builder that's easy to embed in external applications, with GrapesJS team support included.
GrapesJS is a free and open source Web Builder Framework which helps building HTML templates, faster and easily, to be delivered in sites, newsletters or mobile apps. Mainly, GrapesJS was designed to be used inside a CMS to speed up the creation of dynamic templates. To better understand this concept check the image below
Generally any 'template system', that you'd find in various applications like CMS, is composed by the structure (HTML), style (CSS) and variables, which are then replaced with other templates and contents on server-side and rendered on client.
This demos show examples of what is possible to achieve:
Webpage Demo - http://grapesjs.com/demo.html
Newsletter Demo - http://grapesjs.com/demo-newsletter-editor.html
Table of contents
- Features
- Download
- Usage
- Development
- Documentation
- API
- Testing
- Plugins
- Support
- Changelog
- Contributing
- License
Features
| Blocks | Style Manager | Layer Manager |
|---|---|---|
| Code Viewer | Asset Manager |
|---|---|
Local and remote storage
Default built-in commands (basically for creating and managing different components)
Download
- CDNs
- UNPKG (resolves to the latest version)
https://unpkg.com/grapesjshttps://unpkg.com/grapesjs/dist/css/grapes.min.css
- CDNJS (replace
X.X.Xwith the current version)https://cdnjs.cloudflare.com/ajax/libs/grapesjs/X.X.X/grapes.min.jshttps://cdnjs.cloudflare.com/ajax/libs/grapesjs/X.X.X/css/grapes.min.css
- UNPKG (resolves to the latest version)
- NPM
npm i grapesjs
- GIT
git clone https://github.com/GrapesJS/grapesjs.git
For the development purpose you should follow instructions below.
Usage
<link rel="stylesheet" href="path/to/grapes.min.css" />
<script src="path/to/grapes.min.js"></script>
<script type="text/javascript">
var editor = grapesjs.init({
container: '#gjs',
components: 'Hello world!',
style: '.txt-red{color: red}',
});
</script>For a more practical example I'd suggest looking up the code inside this demo: http://grapesjs.com/demo.html
Development
Follow the Contributing Guide.
Documentation
Check the getting started guide here: Documentation
API
API References could be found here: API-Reference
Testing
$ pnpm testPlugins
Official Plugins | Community Plugins
Wrappers
- @grapesjs/react - GrapesJS wrapper for React that allows you to build custom and declarative UI for your editor.
Extensions
- grapesjs-plugin-export - Export GrapesJS templates in a zip archive
- grapesjs-plugin-filestack - Add Filestack uploader in Asset Manager
- grapesjs-plugin-ckeditor - Replaces the built-in RTE with CKEditor
- grapesjs-tui-image-editor - GrapesJS TOAST UI Image Editor
- grapesjs-blocks-basic - Basic set of blocks
- grapesjs-plugin-forms - Set of form components and blocks
- grapesjs-navbar - Simple navbar component
- grapesjs-component-countdown - Simple countdown component
- grapesjs-style-gradient - Add
gradienttype input to the Style Manager - grapesjs-style-filter - Add
filtertype input to the Style Manager - grapesjs-style-bg - Full-stack background style property type, with the possibility to add images, colors, and gradients
- grapesjs-blocks-flexbox - Add the flexbox block
- grapesjs-lory-slider - Slider component by using lory
- grapesjs-tabs - Simple tabs component
- grapesjs-tooltip - Simple, CSS only, tooltip component for GrapesJS
- grapesjs-custom-code - Embed custom code
- grapesjs-touch - Enable touch support
- grapesjs-indexeddb - Storage wrapper for IndexedDB
- grapesjs-firestore - Storage wrapper for Cloud Firestore
- grapesjs-parser-postcss - Custom CSS parser for GrapesJS by using PostCSS
- grapesjs-typed - Typed component made by wrapping Typed.js library
- grapesjs-ui-suggest-classes - Enable auto-complete of classes in the SelectorManager UI
- grapesjs-fonts - Custom Fonts plugin, adds a UI to manage fonts in websites
- grapesjs-symbols - Symbols plugin to reuse elements in a website and accross pages
- grapesjs-click - Grab and drop blocks and components with click (no more drag-and-drop)
- grapesjs-float - Anchor a floating element next to another element (selected component, ...)
Presets
- grapesjs-preset-webpage - Webpage Builder
- grapesjs-preset-newsletter - Newsletter Builder
- grapesjs-mjml - Newsletter Builder with MJML components
Find out more about plugins here: Creating plugins
Support
If you like the project and you wish to see it grow, please consider supporting us with a donation of your choice or become a backer/sponsor via Open Collective
Thanks to BrowserStack for providing us browser testing services
License
BSD 3-clause
File: docs/api/asset.md
Asset
Properties
getType
Get asset type.
Examples
// Asset: { src: 'https://.../image.png', type: 'image' }
asset.getType(); // -> 'image'Returns String
getSrc
Get asset URL.
Examples
// Asset: { src: 'https://.../image.png' }
asset.getSrc(); // -> 'https://.../image.png'Returns String
getFilename
Get filename of the asset (based on src).
Examples
// Asset: { src: 'https://.../image.png' }
asset.getFilename(); // -> 'image.png'
// Asset: { src: 'https://.../image' }
asset.getFilename(); // -> 'image'Returns String
getExtension
Get extension of the asset (based on src).
Examples
// Asset: { src: 'https://.../image.png' }
asset.getExtension(); // -> 'png'
// Asset: { src: 'https://.../image' }
asset.getExtension(); // -> ''Returns String
File: docs/api/assets.md
Assets
You can customize the initial state of the module from the editor initialization, by passing the following Configuration Object
const editor = grapesjs.init({
assetManager: {
// options
}
})Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
const assetManager = editor.AssetManager;Available Events
asset:addNew asset added to the collection. The Asset is passed as an argument to the callback.
editor.on('asset:add', (asset) => { ... });asset:removeAsset removed from the collection. The Asset is passed as an argument to the callback.
editor.on('asset:remove', (asset) => { ... });asset:updateAsset updated. The Asset and the object containing changes are passed as arguments to the callback.
editor.on('asset:update', (asset, updatedProps) => { ... });asset:openAsset Manager opened.
editor.on('asset:open', () => { ... });asset:closeAsset Manager closed.
editor.on('asset:close', () => { ... });asset:upload:startAsset upload start.
editor.on('asset:upload:start', () => { ... });asset:upload:endAsset upload end.
editor.on('asset:upload:end', (result) => { ... });asset:upload:errorAsset upload error.
editor.on('asset:upload:error', (error) => { ... });asset:upload:responseAsset upload response.
editor.on('asset:upload:response', (res) => { ... });asset:customEvent to use in case of custom Asset Manager UI.
editor.on('asset:custom', ({ container, assets, ... }) => { ... });assetCatch-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('asset', ({ event, model, ... }) => { ... });Methods
open
Open the asset manager.
Parameters
optionsObject? Options for the asset manager. (optional, default{})
Examples
assetManager.open({
select(asset, complete) {
const selected = editor.getSelected();
if (selected && selected.is('image')) {
selected.addAttributes({ src: asset.getSrc() });
// The default AssetManager UI will trigger `select(asset, false)` on asset click
// and `select(asset, true)` on double-click
complete && assetManager.close();
}
}
});
// with your custom types (you should have assets with those types declared)
assetManager.open({ types: ['doc'], ... });close
Close the asset manager.
Examples
assetManager.close();isOpen
Checks if the asset manager is open
Examples
assetManager.isOpen(); // true | falseReturns Boolean
add
Add new asset/s to the collection. URLs are supposed to be unique
Parameters
asset(String | Object | Array<String> | Array<Object>) URL strings or an objects representing the resource.optsObject? Options (optional, default{})
Examples
// As strings
assetManager.add('http://img.jpg');
assetManager.add(['http://img.jpg', './path/to/img.png']);
// Using objects you can indicate the type and other meta informations
assetManager.add({
// type: 'image', // image is default
src: 'http://img.jpg',
height: 300,
width: 200,
});
assetManager.add([{ src: 'img2.jpg' }, { src: 'img2.png' }]);Returns Asset
get
Return asset by URL
Parameters
srcString URL of the asset
Examples
const asset = assetManager.get('http://img.jpg');Returns (Asset | null)
getAll
Return the global collection, containing all the assets
Returns Collection<Asset>
getAllVisible
Return the visible collection, which contains assets actually rendered
Returns Collection<Asset>
remove
Remove asset
Parameters
Examples
const removed = assetManager.remove('http://img.jpg');
// or by passing the Asset
const asset = assetManager.get('http://img.jpg');
assetManager.remove(asset);Returns Asset Removed asset
getContainer
Return the Asset Manager Container
Returns HTMLElement
File: docs/api/block.md
Block
Properties
labelString Block label, eg.My blockcontent(String | Object) The content of the block. Might be an HTML string or a Component DefinitionmediaString? HTML string for the media/icon of the block, eg.<svg ...,editor.getWrapper().append(block.get('content'))attributesObject? Block attributes to apply in the view element
getId
Get block id
Returns String
getLabel
Get block label
Returns String
getMedia
Get block media
Returns String
getContent
Get block content
Returns (Object | String | Array<(Object | String)>)
getDragDef
Get block component dragDef
Returns ComponentDefinition
getCategoryLabel
Get block category label
Returns String
File: docs/api/block_manager.md
Blocks
You can customize the initial state of the module from the editor initialization, by passing the following Configuration Object
const editor = grapesjs.init({
blockManager: {
// 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('block:add', (block) => { ... });
// Use the API
const blockManager = editor.Blocks;
blockManager.add(...);Available Events
block:addNew block added to the collection. The Block is passed as an argument to the callback.
editor.on('block:add', (block) => { ... });block:removeBlock removed from the collection. The Block is passed as an argument to the callback.
editor.on('block:remove', (block) => { ... });block:remove:beforeEvent triggered before Block remove.
editor.on('block:remove:before', (block, remove, opts) => { ... });block:updateBlock updated. The Block and the object containing changes are passed as arguments to the callback.
editor.on('block:update', (block, updatedProps) => { ... });block:drag:startStarted dragging block. The Block is passed as an argument.
editor.on('block:drag:start', (block) => { ... });block:dragThe block is dragging. The Block is passed as an argument.
editor.on('block:drag', (block) => { ... });block:drag:stopDragging of the block is stopped. The dropped Component (if dropped successfully) and the Block are passed as arguments.
editor.on('block:drag:stop', (component, block) => { ... });block:category:updateBlock category updated.
editor.on('block:category:update', ({ category, changes }) => { ... });block:customEvent to use in case of custom Block Manager UI.
editor.on('block:custom', ({ container, blocks, ... }) => { ... });blockCatch-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('block', ({ event, model, ... }) => { ... });- BlocksEventCallback
getConfig
Get configuration object
Returns Object
add
Add new block.
Parameters
Examples
blockManager.add('h1-block', {
label: 'Heading',
content: '<h1>Put your title here</h1>',
category: 'Basic',
attributes: {
title: 'Insert h1 block'
}
});Returns Block Added block
get
Get the block by id.
Parameters
idString Block id
Examples
const block = blockManager.get('h1-block');
console.log(JSON.stringify(block));
// {label: 'Heading', content: '<h1>Put your ...', ...}Returns Block
getAll
Return all blocks.
Examples
const blocks = blockManager.getAll();
console.log(JSON.stringify(blocks));
// [{label: 'Heading', content: '<h1>Put your ...'}, ...]Returns Collection<Block>
getAllVisible
Return the visible collection, which containes blocks actually rendered
Returns Collection<Block>
remove
Remove block.
Parameters
Examples
const removed = blockManager.remove('BLOCK_ID');
// or by passing the Block
const block = blockManager.get('BLOCK_ID');
blockManager.remove(block);Returns Block Removed block
getCategories
Get all available categories.
It's possible to add categories only within blocks via 'add()' method
Returns (Array | Collection)
getContainer
Return the Blocks container element
Returns HTMLElement
getDragBlock
Returns currently dragging block.
Updated when the drag starts and cleared once it's done.
getBlocksByCategory
Get blocks by category.
Parameters
blocksArray?
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.getBlocksByCategorymyFilteredBlocksReturns **Array**
render
Render blocks
Parameters
blocksArray Blocks to render, without the argument will render all global blocksoptsObject Options (optional, default{})
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 Rendered element
File: docs/api/canvas.md
Canvas
You can customize the initial state of the module from the editor initialization, by passing the following Configuration Object
const editor = grapesjs.init({
canvas: {
// 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('canvas:drop', () => { ... });
// Use the API
const canvas = editor.Canvas;
canvas.setCoords(...);Available Events
canvas:dragenterSomething is dragged inside the canvas.DataTransferinstance and dragged content are passed as arguments.canvas:dragoverSomething is dragging on the canvas. Triggering event is passed as an argument.canvas:dragendWhen a drag operation is ended, triggering event is passed as an argument.canvas:dragdataOn any dataTransfer parse,DataTransferinstance and theresultare passed as arguments. By changingresult.contentyou're able to customize what is dropped.canvas:dropSomething is dropped in canvas,DataTransferinstance and the dropped model are passed as arguments.canvas:spotSpots updated.
editor.on('canvas:spot', () => {
console.log('Spots', editor.Canvas.getSpots());
});canvas:spot:addNew canvas spot added.
editor.on('canvas:spot:add', ({ spot }) => {
console.log('Spot added', spot);
});canvas:spot:updateCanvas spot updated.
editor.on('canvas:spot:update', ({ spot }) => {
console.log('Spot updated', spot);
});canvas:spot:removeCanvas spot removed.
editor.on('canvas:spot:remove', ({ spot }) => {
console.log('Spot removed', spot);
});canvas:coordsCanvas coordinates updated.
editor.on('canvas:coords', () => {
console.log('Canvas coordinates updated:', editor.Canvas.getCoords());
});canvas:zoomCanvas zoom updated.
editor.on('canvas:zoom', () => {
console.log('Canvas zoom updated:', editor.Canvas.getZoom());
});canvas:pointerCanvas pointer updated.
editor.on('canvas:pointer', () => {
console.log('Canvas pointer updated:', editor.Canvas.getPointer());
});canvas:refreshCanvas was refreshed to update elements on top, like spots/tools (eg. viaeditor.Canvas.refresh()or on frame resize).
editor.on('canvas:refresh', (canvasRefreshOptions) => {
console.log('Canvas refreshed with options:', canvasRefreshOptions);
});canvas:updateCanvas was updated.canvas:tools:updateCanvas tools were updated.canvas:move:startCanvas move started.canvas:moveCanvas is moving.canvas:move:endCanvas move ended.canvas:frame:loadFrame loaded in canvas. The event is triggered right after iframe'sonload.
editor.on('canvas:frame:load', ({ window }) => {
console.log('Frame loaded', window);
});canvas:frame:load:headFrame head loaded in canvas. The event is triggered right after iframe's finished to load the head elements (eg. scripts)
editor.on('canvas:frame:load:head', ({ window }) => {
console.log('Frame head loaded', window);
});canvas:frame:load:bodyFrame body loaded in canvas. The event is triggered when the body is rendered with components.
editor.on('canvas:frame:load:body', ({ window }) => {
console.log('Frame completed the body render', window);
});canvas:frame:unloadFrame is unloading from the canvas.
editor.on('canvas:frame:unload', ({ frame }) => {
console.log('Unloading frame', frame);
});getConfig
Get configuration object
Returns Object
getElement
Get the canvas element
Returns HTMLElement
getFrameEl
Get the main frame element of the canvas
Returns HTMLIFrameElement
getWindow
Get the main frame window instance
Returns Window
getDocument
Get the main frame document element
Returns HTMLDocument
getBody
Get the main frame body element
Returns HTMLBodyElement
setCustomBadgeLabel
Set custom badge naming strategy
Parameters
fFunction
Examples
canvas.setCustomBadgeLabel(function(component){
return component.getName();
});getRect
Get canvas rectangular data
Returns Object
startDrag
Start custom drag-and-drop process.
Parameters
dragSourceDragSource<Component> The source object for the drag operation, containing the component being dragged.
Examples
// as component definition
canvas.startDrag({
content: { type: 'my-component' }
});
// as HTML
canvas.startDrag({
content: '...'
});endDrag
Ends the drag-and-drop process, resetting the drag source and clearing any drag results.
This method can be used to finalize custom drag-and-drop content operations.
Examples
canvas.startDrag({...});
// ... drag finished ...
canvas.endDrag();hasFocus
Check if the canvas is focused
Returns Boolean
scrollTo
Scroll canvas to the element if it's not visible. The scrolling is
executed via scrollIntoView API and options of this method are
passed to it. For instance, you can scroll smoothly by using{ behavior: 'smooth' }.
Parameters
el(HTMLElement | Component)optsObject Options, same as options forscrollIntoView(optional, default{})opts.forceBoolean Force the scroll, even if the element is already visible (optional, defaultfalse)
Examples
const selected = editor.getSelected();
// Scroll smoothly (this behavior can be polyfilled)
canvas.scrollTo(selected, { behavior: 'smooth' });
// Force the scroll, even if the element is already visible
canvas.scrollTo(selected, { force: true });setZoom
Set canvas zoom value
Parameters
valueNumber The zoom value, from 0 to 100optsSetZoomOptions (optional, default{})
Examples
canvas.setZoom(50); // set zoom to 50%Returns this
getZoom
Get canvas zoom value
Examples
canvas.setZoom(50); // set zoom to 50%
const zoom = canvas.getZoom(); // 50Returns Number
setCoords
Set canvas position coordinates
Parameters
Examples
canvas.setCoords(100, 100);Returns this
getCoords
Get canvas position coordinates
Examples
canvas.setCoords(100, 100);
const coords = canvas.getCoords();
// { x: 100, y: 100 }Returns Object Object containing coordinates
getLastDragResult
Get the last created Component from a drag & drop to the canvas.
Returns (Component | undefined)
addSpot
Add or update canvas spot.
Parameters
propsObject Canvas spot properties.optsAddOptions (optional, default{})
Examples
// Add new canvas spot
const spot = canvas.addSpot({
type: 'select', // 'select' is one of the built-in spots
component: editor.getSelected(),
});
// Add custom canvas spot
const spot = canvas.addSpot({
type: 'my-custom-spot',
component: editor.getSelected(),
});
// Update the same spot by reusing its ID
canvas.addSpot({
id: spot.id,
component: anotherComponent,
});Returns CanvasSpot
getSpots
Get canvas spots.
Parameters
spotPropsObject? Canvas spot properties for filtering the result. With no properties, all available spots will be returned. (optional, default{})
Examples
canvas.addSpot({ type: 'select', component: cmp1 });
canvas.addSpot({ type: 'select', component: cmp2 });
canvas.addSpot({ type: 'target', component: cmp3 });
// Get all spots
const allSpots = canvas.getSpots();
allSpots.length; // 3
// Get all 'select' spots
const allSelectSpots = canvas.getSpots({ type: 'select' });
allSelectSpots.length; // 2Returns Array<CanvasSpot>
removeSpots
Remove canvas spots.
Parameters
spotProps(Object | Array<CanvasSpot>)? Canvas spot properties for filtering spots to remove or an array of spots to remove. With no properties, all available spots will be removed. (optional, default{})
Examples
canvas.addSpot({ type: 'select', component: cmp1 });
canvas.addSpot({ type: 'select', component: cmp2 });
canvas.addSpot({ type: 'target', component: cmp3 });
// Remove all 'select' spots
canvas.removeSpots({ type: 'select' });
// Remove spots by an array of canvas spots
const filteredSpots = canvas.getSpots().filter(spot => myCustomCondition);
canvas.removeSpots(filteredSpots);
// Remove all spots
canvas.removeSpots();Returns Array<CanvasSpot>
hasCustomSpot
Check if the built-in canvas spot has a declared custom rendering.
Parameters
typeString Built-in canvas spot type
Examples
grapesjs.init({
// ...
canvas: {
// avoid rendering the built-in 'target' canvas spot
customSpots: { target: true }
}
});
// ...
canvas.hasCustomSpot('select'); // false
canvas.hasCustomSpot('target'); // trueReturns Boolean
getWorldRectToScreen
Transform a box rect from the world coordinate system to the screen one.
Parameters
boxRectObject
Returns Object
refresh
Update canvas for spots/tools positioning.
Parameters
optsObject? Options. (optional, default{})opts.spotsObject Update the position of spots. (optional, defaultfalse)
File: docs/api/canvas_spot.md
CanvasSpot
Canvas spots are elements drawn on top of the canvas. They can be used to represent anything you
might need but the most common use case of canvas spots is rendering information and managing
components rendered in the canvas.
Read here for more information about Canvas Spots
Properties
idString Spot ID.typeString Spot type.componentComponent? Component to which the spot will be attached.componentViewComponentView? ComponentView to which the spot will be attached.boxRectObject? Fixed box rect of the spot, eg.{ width: 100, height: 100, x: 0, y: 0 }.
getBoxRect
Get the box rect of the spot.
Parameters
optsObject (optional, default{})
Examples
canvasSpot.getBoxRect();
// { width: 100, height: 50, x: 0, y: 0 }Returns Object The box rect object
getStyle
Get the style object of the spot.
Parameters
optsObject (optional, default{})
Examples
canvasSpot.getStyle();
// { width: '100px', height: '...', ... }Returns CSSStyleDeclaration [opts]
isType
Check the spot type.
Parameters
typeString
Examples
canvasSpot.isType('select');Returns Boolean
File: docs/api/commands.md
Commands
You can customize the initial state of the module from the editor initialization, by passing the following Configuration Object
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
command:runTriggered on run of any command.
editor.on('command:run', ({ id, result, options }) => {
console.log('Command id', id, 'command result', result);
});command:run:COMMAND_IDTriggered on run of a specific command.
editor.on('command:run:my-command', ({ result, options }) => { ... });command:run:before:COMMAND_IDTriggered before the command is called.
editor.on('command:run:before:my-command', ({ options }) => { ... });command:abort:COMMAND_IDTriggered 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:stopTriggered on stop of any command.
editor.on('command:stop', ({ id, result, options }) => {
console.log('Command id', id, 'command result', result);
});command:stop:COMMAND_IDTriggered on stop of a specific command.
editor.on('command:run:my-command', ({ result, options }) => { ... });command:stop:before:COMMAND_IDTriggered before the command is called to stop.
editor.on('command:stop:before:my-command', ({ options }) => { ... });Methods
add
Add new command to the collection
Parameters
idstring Command's IDcommand(Object | Function) Object representing your command,
By passing just a function it's intended as a stateless command
(just like passing an object with onlyrunmethod).
Examples
commands.add('myCommand', {
run(editor, sender) {
alert('Hello world!');
},
stop(editor, sender) {
},
});
// As a function
commands.add('myCommand2', editor => { ... });Returns this
get
Get command by ID
Parameters
idstring Command's ID
Examples
var myCommand = commands.get('myCommand');
myCommand.run();Returns Object Object representing the command
extend
Extend the command. The command to extend should be defined as an object
Parameters
idstring Command's IDcmdCommandObject (optional, default{})ObjectObject with the new command functions
Examples
commands.extend('old-command', {
someInnerFunction() {
// ...
}
});Returns this
has
Check if command exists
Parameters
idstring Command's ID
Returns Boolean
getAll
Get an object containing all the commands
Returns Object
run
Execute the command
Parameters
Examples
commands.run('myCommand', { someOption: 1 });Returns any The return is defined by the command
stop
Stop the command
Parameters
Examples
commands.stop('myCommand', { someOption: 1 });Returns any The return is defined by the command
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
idString Command id
Examples
const cId = 'some-command';
commands.run(cId);
commands.isActive(cId);
// -> true
commands.stop(cId);
commands.isActive(cId);
// -> falseReturns Boolean
getActive
Get all active commands
Examples
console.log(commands.getActive());
// -> { someCommand: itsLastReturn, anotherOne: ... };Returns Object
File: docs/api/component.md
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
typeString? Component type, eg.text,image,video, etc.tagNameString? HTML tag of the component, eg.span. Default:divattributesObject? Key-value object of the component's attributes, eg.{ title: 'Hello' }Default:{}nameString? Name of the component. Will be used, for example, in Layers and badgesremovableBoolean? Whentruethe component is removable from the canvas, default:truedraggable(Boolean | String | Function)? Indicates if it's possible to drag the component inside others.
You can also specify a query string to identify elements,
eg.'.some-class[title=Hello], [data-gjs-type=column]'means you can drag the component only inside elements
containingsome-classclass andHellotitle, andcolumncomponents. 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:truedroppable(Boolean | String | Function)? Indicates if it's possible to drop other components inside. You can use
a query string as withdraggable. 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:truebadgableBoolean? Set to false if you don't want to see the badge (with the name) over the component. Default:truestylable(Boolean | Array<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:truestylable-requireArray<String>? Indicate an array of style properties to show up which has been marked astoRequire. Default:[]unstylableArray<String>? Indicate an array of style properties which should be hidden from the style manager. Default:[]highlightableBoolean? It can be highlighted with 'dotted' borders if true. Default:truecopyableBoolean? True if it's possible to clone the component. Default:trueresizableBoolean? Indicates if it's possible to resize the component. It's also possible to pass an object as options for the Resizer. Default:falseeditableBoolean? Allow to edit the content of the component (used on Text components). Default:falselayerableBoolean? Set tofalseif you need to hide the component inside Layers. Default:trueselectableBoolean? Allow component to be selected when clicked. Default:truehoverableBoolean? Shows a highlight outline when hovering on the element iftrue. Default:truelockedBoolean? Disable the selection of the component and its children in the canvas. You can unlock a children by setting its locked property tofalse. Default:undefinedvoidBoolean? This property is used by the HTML exporter as void elements don't have closing tags, eg. ``,<hr/>, etc. Default:falsestyleObject? Component default style, eg.{ width: '100px', height: '100px', 'background-color': 'red' }stylesString? Component related styles, eg..my-component-class { color: red }contentString? Content of the component (not escaped) which will be appended before children rendering. Default:''iconString? 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 | Function)? Component's javascript. More about it here. Default:''script-export(String | Function)? You can specify javascript available only in export functions (eg. when you get the HTML).
If this property is defined it will overwrite thescriptone (in export functions). Default:''traitsArray<(Object | String)>? Component's traits. More about it here. Default:['id', 'title']propagateArray<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 thepropagatearray (and thepropagateproperty itself). Default:[]toolbarArray<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, whentoolbarproperty is falsy the editor will add automatically commandscore:component-exit(select parent component, added if there is one),tlb-move(added ifdraggable) ,tlb-clone(added ifcopyable),tlb-delete(added ifremovable).componentsCollection<Component>? Children components. Default:nulldelegateObject? Delegate commands to other components. Available commandsremove|move|copy|select. eg.{ remove: (cmp) => cmp.closestType('other-type') }
init
Hook method, called once the model is created
updated
Hook method, called when the model has been updated (eg. updated some model's property)
Parameters
propertyString Property name, if triggered after some property updatevalueany Property value, if triggered after some property updatepreviousany Property previous value, if triggered after some property update
removed
Hook method, called once the model has been removed
is
Check component's type
Parameters
typestring Component type
Examples
component.is('image')
// -> falseReturns Boolean
props
Return all the propeties
Returns Object
index
Get the index of the component in the parent collection.
Returns Number
setDragMode
Change the drag mode of the component.
To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936
Parameters
valueString Drag mode, options:'absolute'|'translate'|''
Returns this
getDragMode
Get the drag mode of the component.
Returns String Drag mode value, options: 'absolute' | 'translate' | ''
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
Examples
component.setSymbolOverride(['children', 'classes']);getSymbolOverride
Get symbol override value.
Returns (Boolean | Array<String>)
find
Find inner components by query string.
ATTENTION: this method works only with already rendered component
Parameters
queryString Query string
Examples
component.find('div > .class');
// -> [Component, Component, ...]Returns Array Array of components
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
query(String | Function) Component type or matcher functionoptsObject? Search optionsopts.maxNumber? Maximum number of matches before exiting
Examples
const allImages = component.findType('image');
console.log(allImages[0]) // prints the first found component
const someComponents = component.findType((cmp) => cmp.getType() === 'something', { max: 2 });Returns Array<Component>
findFirstType
Find the first inner component by component type.
If no component is found, it returns undefined.
Parameters
query(String | Function) Component type or matcher function
Examples
const image = component.findFirstType('image');
if (image) {
console.log(image);
}
const firstImage = component.findFirstType((cmp) => cmp.is('image'));Returns (Component | undefined)
closest
Find the closest parent component by query string.
ATTENTION: this method works only with already rendered component
Parameters
querystring Query string
Examples
component.closest('div.some-class');
// -> ComponentReturns Component
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
query(String | Function) Component type or matcher function
Examples
const Section = component.closestType('section');
console.log(Section);
const namedSection = component.closestType((cmp) => cmp.getName() === 'Section');Returns Component Found component, otherwise undefined
contains
The method returns a Boolean value indicating whether the passed
component is a descendant of a given component
Parameters
componentComponent Component to check
Returns Boolean
replaceWith
Replace a component with another one
Parameters
el(String | Component) Component or HTML stringoptsObject Options for the append action (optional, default{})
Examples
const result = component.replaceWith('Some new content');
// result -> [Component]Returns Array<Component> New replaced components
setAttributes
Update attributes of the component
Parameters
attrsObject Key value attributesoptsSetAttrOptions (optional, default{skipWatcherUpdates:false,fromDataSource:false})optionsObject Options for the model update
Examples
component.setAttributes({ id: 'test', 'data-key': 'value' });Returns this
addAttributes
Add attributes to the component
Parameters
attrsObject Key value attributesoptsSetAttrOptions (optional, default{})optionsObject Options for the model update
Examples
component.addAttributes({ 'data-key': 'value' });Returns this
removeAttributes
Remove attributes from the component
Parameters
attrs(String | Array<String>) Array of attributes to remove (optional, default[])optsSetOptions (optional, default{})optionsObject Options for the model update
Examples
component.removeAttributes('some-attr');
component.removeAttributes(['some-attr1', 'some-attr2']);Returns this
getStyle
Get the style of the component
Parameters
optsGetComponentStyleOpts?
Returns Object
setStyle
Set the style on the component
Parameters
propObject Key value style object (optional, default{})optsUpdateStyleOptions (optional, default{})
Examples
component.setStyle({ color: 'red' });Returns Object
getAttributes
Return all component's attributes
Parameters
Returns Object
addClass
Add classes
Parameters
Examples
model.addClass('class1');
model.addClass('class1 class2');
model.addClass(['class1', 'class2']);
// -> [SelectorObject, ...]Returns Array Array of added selectors
setClass
Set classes (resets current collection)
Parameters
Examples
model.setClass('class1');
model.setClass('class1 class2');
model.setClass(['class1', 'class2']);
// -> [SelectorObject, ...]Returns Array Array of added selectors
removeClass
Remove classes
Parameters
Examples
model.removeClass('class1');
model.removeClass('class1 class2');
model.removeClass(['class1', 'class2']);
// -> [SelectorObject, ...]Returns Array Array of removed selectors
getClasses
Returns component's classes as an array of strings
Returns Array
append
Add new component children
Parameters
components(Component | String) Component to addoptsObject Options for the append action (optional, default{})
Examples
someComponent.get('components').length // -> 0
const videoComponent = someComponent.append('<video></video>')[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 Array of appended components
components
Set new collection if components are provided, otherwise the
current collection is returned
Parameters
components(Component | Array<Component> | String)? Component Definitions or HTML stringoptsObject Options, same as inComponent.append()(optional, default{})
Examples
// Set new collection
component.components('');
// Get current collection
const collection = component.components();
console.log(collection.length);
// -> 2Returns (Collection | Array<Component>)
getChildAt
If exists, returns the child component at specific index.
Parameters
indexNumber Index of the component to return
Examples
// Return first child
component.getChildAt(0);
// Return second child
component.getChildAt(1);Returns (Component | null)
getLastChild
If exists, returns the last child component.
Examples
const lastChild = component.getLastChild();Returns (Component | null)
empty
Remove all inner components
- @return {this}
Parameters
opts(optional, default{})
parent
Get the parent component, if exists
Parameters
optsany (optional, default{})
Examples
component.parent();
// -> ComponentReturns (Component | null)
parents
Return all parents of the component.
Returns Array<Component>
getTraits
Get traits.
Examples
const traits = component.getTraits();
console.log(traits);
// [Trait, Trait, Trait, ...]Returns **Array**
setTraits
Replace current collection of traits with a new one.
Parameters
Examples
const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]);
console.log(traits);
// [Trait, ...]Returns **Array**
getTrait
Get the trait by id/name.
Parameters
idString Theidornameof the trait
Examples
const traitTitle = component.getTrait('title');
traitTitle && traitTitle.set('label', 'New label');Returns (Trait | null) Trait getModelToStyle
updateTrait
Update a trait.
Parameters
Examples
component.updateTrait('title', {
type: 'select',
options: [ 'Option 1', 'Option 2' ],
});Returns this
getTraitIndex
Get the trait position index by id/name. Useful in case you want to
replace some trait, at runtime, with something else.
Parameters
idString Theidornameof the trait
Examples
const traitTitle = component.getTraitIndex('title');
console.log(traitTitle); // 1Returns Number Index position of the current trait
removeTrait
Remove trait/s by id/s.
Parameters
Examples
component.removeTrait('title');
component.removeTrait(['title', 'id']);Returns **Array** Array of removed traits
addTrait
Add new trait/s.
Parameters
trait(String | Object | Array<(String | Object)>) Trait to add (or an array of traits)optsOptions Options for the add (optional, default{})
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** Array of added traits
getName
Get the name of the component.
Parameters
optsObject Options (optional, default{})opts.noCustomBoolean? Avoid custom name assigned to the component.
Returns String
setName
Update component name.
Parameters
nameString New name.optsSetOptions (optional, default{})
getIcon
Get the icon string
Returns String
toHTML
Return HTML string of the component
Parameters
optsObject Options (optional, default{})opts.tagString? Custom tagNameopts.attributes(Object | 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, defaultnull)opts.withPropsBoolean? Include component properties asdata-gjs-*attributes. This allows you to have re-importable HTML.opts.altQuoteAttrBoolean? 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
// 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 HTML string
getInnerHTML
Get inner HTML of the component
Parameters
optsObject Same options oftoHTML(optional, default{})
Returns String HTML string
getChangedProps
Return an object containing only changed props
Parameters
resPartial<ComponentDefinition>
Returns Partial<ComponentDefinition>
getId
Return the component id
Returns String
setId
Set new id on the component
Parameters
idStringoptsany?
Returns this
getEl
Get the DOM element of the component.
This works only if the component is already rendered
Parameters
frameFrame Specific frame from which taking the element
Returns HTMLElement
getView
Get the View of the component.
This works only if the component is already rendered
Parameters
frameFrame Get View of a specific frame
Returns ComponentView
onAll
Execute callback function on itself and all inner components
Parameters
clbFunction Callback function, the model is passed as an argument
Examples
component.onAll(component => {
// do something with component
})Returns this
forEachChild
Execute a callback function on all inner child components.
Parameters
clbFunction Callback function, the child component is passed as an argument
Examples
component.forEachChild(child => {
console.log(child)
})remove
Remove the component
Parameters
optsany (optional, default{})
Returns this
move
Move the component to another destination component
Parameters
componentComponent Destination component (so the current one will be appended as a child)optsObject Options for the append action (optional, default{})
Examples
// Move the selected component on top of the wrapper
const dest = editor.getWrapper();
editor.getSelected().move(dest, { at: 0 });Returns this
isInstanceOf
Check if the component is an instance of some component type.
Parameters
typeString Component type
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'); // trueReturns Boolean
isChildOf
Check if the component is a child of some other component (or component type)
Parameters
component(Component | String) Component parent to check. In case a string is passed,
the check will be performed on the component type.
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'); // trueReturns Boolean
File: docs/api/components.md
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
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
component:create- Component is created (only the model, is not yet mounted in the canvas), called after the init() methodcomponent:mount- Component is mounted to an element and rendered in canvascomponent:add- Triggered when a new component is added to the editor, the model is passed as an argument to the callbackcomponent:remove- Triggered when a component is removed, the model is passed as an argument to the callbackcomponent: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 callbackcomponent:clone- Triggered when a component is cloned, the new model is passed as an argument to the callbackcomponent:update- Triggered when a component is updated (moved, styled, etc.), the model is passed as an argument to the callbackcomponent:update:{propertyName}- Listen any property change, the model is passed as an argument to the callbackcomponent:styleUpdate- Triggered when the style of the component is updated, the model is passed as an argument to the callbackcomponent:styleUpdate:{propertyName}- Listen for a specific style property change, the model is passed as an argument to the callbackcomponent:selected- New component selected, the selected model is passed as an argument to the callbackcomponent:deselected- Component deselected, the deselected model is passed as an argument to the callbackcomponent:toggled- Component selection changed, toggled model is passed as an argument to the callbackcomponent:type:add- New component type added, the new type is passed as an argument to the callbackcomponent:type:update- Component type updated, the updated type is passed as an argument to the callbackcomponent:drag:start- Component drag started. Passed an object, to the callback, containing thetarget(component to drag),parent(parent of the component) andindex(component index in the parent)component:drag- During component drag. Passed the same object as incomponent:drag:startevent, but in this case,parentandindexare updated by the current pointercomponent:drag:end- Component drag ended. Passed the same object as incomponent:drag:startevent, but in this case,parentandindexare updated by the final pointercomponent:resize- During component resize.
Methods
getWrapper
Returns root component inside the canvas. Something like `` inside HTML page
The wrapper doesn't differ from the original Component Model
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 Root Component
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
// 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 Collection of components
addComponent
Add new components to the wrapper's children. It's the same
as 'cmp.getComponents().add(...)'
Parameters
component(Object | Component | Array<Object>) Component/s to addcomponent.tagNamestring Tag name (optional, default'div')component.typestring Type of the component. Available: ''(default), 'text', 'image' (optional, default'')component.removableboolean If component is removable (optional, defaulttrue)component.draggableboolean If is possible to move the component around the structure (optional, defaulttrue)component.droppableboolean If is possible to drop inside other components (optional, defaulttrue)component.badgableboolean If the badge is visible when the component is selected (optional, defaulttrue)component.stylableboolean If is possible to style component (optional, defaulttrue)component.copyableboolean If is possible to copy&paste the component (optional, defaulttrue)component.contentstring String inside component (optional, default'')component.styleObject Style object (optional, default{})component.attributesObject Attribute object (optional, default{})
optObject the options object to be used by the [Components.add]getComponents method (optional, default{})
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 | Array<Component>) Component/s added
clear
Remove all components
Parameters
opts(optional, default{})
Returns this
addType
Add new component type.
Read more about this in Define New Component
Parameters
Returns this
getType
Get component type.
Read more about this in Define New Component
Parameters
typestring Component ID
Returns Object Component type definition, eg. { model: ..., view: ... }
removeType
Remove component type
Parameters
Returns (Object | undefined) Removed component type, undefined otherwise
getTypes
Return the array of all types
Returns Array
isComponent
Check if the object is a [Component].
Parameters
objObject
Examples
cmp.isComponent(editor.getSelected()); // true
cmp.isComponent({}); // falseReturns Boolean
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
componentComponent Component from which create a symbol.
Examples
const symbol = cmp.addSymbol(editor.getSelected());
// cmp.getSymbolInfo(symbol).isSymbol === true;Returns Component
getSymbols
Get the array of main symbols.
Examples
const symbols = cmp.getSymbols();
// [Component, Component, ...]
// Removing the main symbol will detach all the relative instances.
symbols[0].remove();detachSymbol
Detach symbol instance from the main one.
The passed symbol instance will become a regular component.
Parameters
componentComponent The component symbol to detach.
Examples
const cmpInstance = editor.getSelected();
// cmp.getSymbolInfo(cmpInstance).isInstance === true;
cmp.detachSymbol(cmpInstance);
// cmp.getSymbolInfo(cmpInstance).isInstance === false;getSymbolInfo
Get info about the symbol.
Parameters
componentComponent Component symbol from which to get the info.opts{withChanges: string?} (optional, default{})
Examples
cmp.getSymbolInfo(editor.getSelected());
// > { isSymbol: true, isMain: false, isInstance: true, ... }Returns Object Object containing symbol info.
canMove
Check if a component can be moved inside another one.
Parameters
targetComponent The target component is the one that is supposed to receive the source one.source(Component | String) The source can be another component, a component definition or an HTML string.indexNumber? Index position, if not specified, the check will be performed against appending the source to the target.
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, '<form>...</form>');Returns 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.