Free and Open source Web Builder Framework. Next generation tool for building templates without coding
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

11 KiB

title
Commands

Commands

A basic command in GrapesJS it's a simple function, but you will see in this guide how powerfull they can be. The main goal of the Command module is to centralize functions and be easily reused across the editor. Another big advantage of using commands is the ability to track them, extend or even interrupt beside some conditions.

::: warning This guide is referring to GrapesJS v0.14.59 or higher :::

toc

Basic configuration

You can create your commands already from the initialization by passing them in the commands.defaults options:

const editor = grapesjs.init({
  ...
  commands: {
    defaults: [
      {
        // id and run are mandatory in this case
        id: 'my-command-id',
        run() {
          alert('This is my command');
        },
      }, {
        id: '...',
        // ...
      }
    ],
  }
});

For all other available options check directly the configuration source file.

Most commonly commands are created dynamicly post initialization, in that case you'll need to use the Commands API (eg. this is what you need if you create a plugin)

const commands = editor.Commands;
commands.add('my-command-id', editor => {
  alert('This is my command');
});

// or it would be the same...
commands.add('my-command-id', {
  run(editor) {
    alert('This is my command');
  },
});

As you see the definiton is quite easy, you just add an ID and the callback function. The Editor instance is passed as the first argument to the callback so you can access any other module or API method.

Now if you want to call that command you should just run this

editor.runCommand('my-command-id');

::: tip The method editor.runCommand is an alias of editor.Commands.run :::

You could also pass options if you need

editor.runCommand('my-command-id', { some: 'option' });

Then you can get the same object as a third argument of the callback.

commands.add('my-command-id', (editor, sender, options = {}) => {
  alert(`This is my command ${options.some}`);
});

The second argument, sender, just indicates who requested the command, in our case will be always the editor

Until now there is nothing exiting except a common entry point for functions, but we'll see later its real advantages.

Default commands

GrapesJS comes along with some default set of commands and you can get a list of all currently availlable commands via editor.Commands.getAll(). This will give you an object of all available commands, so, also those added later, like via plugins. You can recognize default commands by their namespace core:*, we also recommend to use namepsaces in your own custom commands, but let's get a look more in detail here:

Stateful commands

As we've already seen the command is just a function and once executed nothing is left behined, but in some cases we'd like to keep a track of executed commands. GrapesJS can handle by default this case and to enable it you just need to declare a command as an object with run and stop methods

commands.add('my-command-state', {
  run(editor) {
    alert('This command is now active');
  },
  stop(editor) {
    alert('This command is disabled');
  },
});

So if we now run editor.runCommand('my-command-state') the command will be registered as active. To check the state of the command you can use commands.isActive('my-command-state') or you can even get the list of all active commands via commands.getActive(), it our case the result would be something like this

{
  ...
  'my-command-state': undefined
}

The key of the result object tells you the active command, the value is the last return of the run command, in our case is undefined because we didn't return anything, but it's up to your implementation decide what to return and if you actually need it.

// Let's return something
...
run(editor) {
    alert('This command is now active');
    return {
      activated: new Date(),
    }
},
...
// Now instead of the `undefined` you'll see object from the run method

To disable the command use editor.runCommand method, so in our case it'll be editor.runCommand('my-command-state'). As for the runCoomand you can pass options object as a second argument and use them in your stop method.

Once the command is active, if you try to run editor.runCommand('my-command-state') again you'll notice that that the run is not triggering. This behavior is useful to prevent executing multiple times the activation process which might lead to an inconsitent state (think about, for instance, having a counter, which should be increased on run and decreased on stop). If you need to run a command multiple times probably you're dealing with a not stateful command, so try to use it without the stop method, but in case you're aware of your application state you can actually force the execution with editor.runCommand('my-command-state', { force: true }). The same logic applies to the stopCommand method.

WARNING

If you deal with UI in your stateful commands, be careful to keep the state coherent with your logic. Let's take, for example, the use of a modal as an indicator of the command state.

commands.add('my-command-modal', {
  run(editor) {
    editor.Modal.open({
      title: 'Modal example',
      content: 'My content',
    });
  },
  stop(editor) {
    editor.Modal.close();
  },
});

If you run it, close the modal (eg. by clicking the 'x' on top) and then try to run it again you'll see that the modal is not opening anymore. This happenes because the command is still active (you should see it in commands.getActive()) and to fix it you have to disable it once the modal is closed.

...
  run(editor) {
    editor.Modal.open({
      title: 'Modal example',
      content: 'My content',
    }).onceClose(() => this.stopCommand());
  },
...

In the example above, we make use of few helper methods from the Modal module (onceClose) and the commmand itself (stopCommand) but obviosly the logic might be different due to your requirements and specific UI.

Extending commands

Another big advantage of commands is the possibility to easily extand or ovverride them wit another command. Let's take a simple example

commands.add('my-command-1', editor => {
  alert('This is command 1');
});

If you need to overwrite this command with another one, just add it and keep the same id.

commands.add('my-command-1', editor => {
  alert('This is command 1 overwritten');
});

Let's see now instead how can we extend one

commands.add('my-command-2', {
  someFunction1() {
    alert('This is function 1');
  },
  someFunction2() {
    alert('This is function 2');
  },
  run() {
    this.someFunction1();
    this.someFunction2();
  },
});

to extend it just use extend method by passing the id

commands.extend('my-command-2', {
  someFunction2() {
    alert('This is function 2 extended');
  },
});

Events

The Commands module offers also a set of events that you can use to intercept the command flow for adding more functionality or even interrupting it.

Intercept run and stop

By using our previosly created my-command-modal command let's see what events we can listen to

editor.on('run:my-command-modal', function() {
  console.log('After `my-command-modal` execution');
  editor.Modal.getContent().append('<div>Some test</div>');
});
editor.on('run:my-command-modal:before', function() {
  console.log('Before `my-command-modal` execution');
});

Interrupt command flow

Let's use our previosly created my-command-modal command to describe

    • run:{commandName} - Triggered when some command is called to run (eg. editor.runCommand('preview'))
    • stop:{commandName} - Triggered when some command is called to stop (eg. editor.stopCommand('preview'))
    • run:{commandName}:before - Triggered before the command is called
    • stop:{commandName}:before - Triggered before the command is called to stop
    • abort:{commandName} - Triggered when the command execution is aborted (editor.on(run:preview:before, opts => opts.abort = 1);)
    • run - Triggered on run of any command. The id and the result are passed as arguments to the callback
    • stop - Triggered on stop of any command. The id and the result are passed as arguments to the callback