Skip to content

Support extensions as configurable ES6 classes

Denys Mishunov requested to merge 288312-editor-lite-extension-options into master

What does this MR do?

Introduces support for ES6 classes as the first-class citizen for Editor Lite's extensions eco-system. This allows for creating the configurable extensions instead of just the plain objects.

Usage example

Simple use:

import { MyFancyExtension } from './some_path';
...
editorInstance.use(new MyFancyExtension({ foo: 'bar' }));

Simple, non-configurable extension

export class MyFancyExtension {
  constructor(options = {}) {
    // do something with the options
  }
  makeThingsFancy() {
     alert(🎉);
  }
}

Keep in mind that by default, the constructor of your extension knows nothing about the editor's instance at the time you invoke it, unfortunately. At the same time, due to the way the extensions get applied, the methods of your extension know nothing about the options passed to the constructor. So, alert(this.foo) in makeThingsFancy() would fail even though you have passed that prop to the extension.

To fix this, you have to explicitly connect the dots in your constructor:

Configurable extension

export class MyFancyExtension {
  constructor({ instance, ...options } = {}) {
    // 🛑 Here, `this` points to the extension itself.
    // So store the options somewhere on the instance
    Object.assign(instance, options);
  }
  makeThingsFancy() {
    // 🛑 Here, `this` points to the instance. So we can fetch the stored options:
     alert(this.foo);
  }
}

Configurable extension based on EditorLiteExtension

To make things easier, the base extension class (app/assets/javascripts/editor/editor_lite_extension_base.js) has been added. So, the next example will also yield the correct alert when makeThingsFancy will be invoked:

import { EditorLiteExtension } from './editor_lite_extension_base';

export class MyFancyExtension extends EditorLiteExtension {
  makeThingsFancy() {
    alert(this.foo);
  }
}

Screenshots (strongly suggested)

No visible changes

Does this MR meet the acceptance criteria?

Conformity

Availability and Testing

Related to #288312 (closed)

Edited by Denys Mishunov

Merge request reports