Skip to content

Custom Buttons and Extensions

Nate Mielnik edited this page Jun 21, 2015 · 54 revisions

Extensions (v5.0.0)

What is an Extension?

Extensions are custom actions or commands that can be passed in via the extensions option to medium-editor. They can replace existing buttons if they share the same name, or can add additional custom functionality into the editor. Extensions can be implemented in any way, and just provide a way to hook into medium-editor. New extensions can be created by extending the exposed MediumEditor.Extension object via MediumEditor.Extension.extend().

Examples of functionality that are implemented via built-in extensions:

Examples of custom built external extensions:

What is a Button?

Buttons are a specific type of Extension which have a contract with the MediumEditor toolbar. Buttons have specific lifecycle methods that MediumEditor and the toolbar use to interact with these specific types of Extensions. These contract create easy hooks, allowing custom buttons to:

  • Display an element in the toolbar (ie a clickable button/link)
  • Execute an action on the editor text when clicked (ie bold, underline, blockquote, etc.)
  • Update the appearance of the element based on the user selection (ie the bold button looks 'active' if the selected text is already bold, 'inactive' if the text is not bold)

All of the built-in MediumEditor buttons are just Button Extensions with different configuration:

  • bold, italic, underline, strikethrough
  • subscript, superscript
  • image
  • quote, pre
  • orderedlist, unorderedlist
  • indent, outdent
  • justifyLeft, justifyCenter, justifyRight, justifyFull
  • h1, h2, h3, h4, h5, h6
  • removeFormat

Examples of custom built external buttons:

What is a Form Extension?

Form Extensions are a specific type of Button Extension which collect input from the user via the toolbar. Form Extensions extend from Button, and thus inherit all of the lifecycle methods of a Button. In addition, Form Extensions have some additional methods exposed to interact with MediumEditor and provide some common functionality.

Built-in Form Extensions

  • Anchor Button
    • The 'anchor' Button is actually a form extension, which when clicked, prompts the the user for a url (as well as some optional checkboxes) via a control in the toolbar and converts the selected text into a link. If the selection is already a link, clicking the button unwraps text within the anchor tag.
  • FontSize Button (beta)
    • The 'fontsize' Button is a form extension, which when clicked, allows the user to modify the size of the existing text via a control in the toolbar.

Extensions

Example: DisableContextMenuExtension

Define the Extension

As a simple example, let's create an extension that disables the context menu from appearing when the user right-clicks on the editor.

Defining this extension is as simple as calling MediumEditor.Extension.extend() and passing in the methods/properties we want to override.

var DisableContextMenuExtension = MediumEditor.Extension.extend({
  name: 'disable-context-menu'
});

We now have an extension named 'disable-context-menu' which we can pass into MediumEditor like this:

new MediumEditor('.editable', {
  extensions: {
    'disable-context-menu': new DisableContextMenuExtension()
  }
});

Attaching To Click

To make the extension actually do something, we'll want to attach to the click event on any elements of the editor. We can set this up by implementing the init() method, which is called on every Extension during setup of MediumEditor:

var DisableContextMenuExtension = MediumEditor.Extension.extend({
  name: 'disable-context-menu',

  init: function () {
    this.base.subscribe('editableClick', this.handleClick.bind(this));
  },

  handleClick: function (event, editable) { }
});

Here, we're leveraging some of the helpers that are available to all Extensions.

  • We're using this.base, which is a reference to the MediumEditor instance.
  • We're using this.base.subscribe(), which is a method of MediumEditor for subscribing to custom events.
  • We're using the editableClick custom event, which will automatically attach to the native click event, but for all of the elements within the editor (since MediumEditor supports passing multiple elements).

NOTE

  • There are a few helper methods that allow us to make calls directly into the MediumEditor instance without having to reference this.base. One of them is a reference to the subscribe() method, so instead of the above code we can just use this.subscribe('editableClick', this.handleClick.bind(this))

Adding Functionality

So, the last piece we need is to handle the click event and, if it's a right-click, prevent the default action:

var DisableContextMenuExtension = MediumEditor.Extension.extend({
  name: 'disable-context-menu',

  init: function () {
    this.subscribe('editableClick', this.handleClick.bind(this));
  },

  handleClick: function (event, editable) { 
    if ((event.which && event.which === 3) ||
        (event.button && event.button === 2)) {
      event.preventDefault();
    }
  }
});

Leveraging Custom Event Listeners

Let's say we wanted to allow users to be able to set an attribute on any of the elements which would disable our extension (thus allowing right-click). Since this could happen at any point, we can't just not attach the event handler, we'll need to inspect the editor element on each click. One way to accomplish this would be to leverage one of the features of custom events, where the 2nd argument is always the editable that triggered the event. So, let's use the 2nd argument of the custom event listener to detect if a data-allow-right-click attribute exists on the element.

var DisableContextMenuExtension = MediumEditor.Extension.extend({
  name: 'disable-context-menu',

  init: function () {
    this.subscribe('editableClick', this.handleClick.bind(this));
  },

  handleClick: function (event, editable) {
    if (editable.getAttribute('data-allow-right-click')) {
      return;
    }

    if ((event.which && event.which === 3) ||
        (event.button && event.button === 2)) {
      event.preventDefault();
    }
  }
});

NOTE

For events like click, we could always use currentTarget and not need to use the reference to the editable element. However, there may be times when we want to trigger one of these events manually, and this allows us to specify exactly which editable element we want to trigger the event for. It's also a handy standardization for events which are more complicated, like the custom focus and blur events.

Extension Interface

The following are properties and method that MediumEditor will attempt to use / call to interact with the extension internally.

name (string)

The name to identify the extension by. This is used for calls to MediumEditor.getExtensionByName(name) to retrieve the extension. If not defined, this will be set to whatever identifier was used when passing the extension into MediumEditor via the extensions option.


init()

Called by MediumEditor during initialization. The .base property will already have been set to current instance of MediumEditor when this is called. All helper methods will exist as well.


checkState(node)

If implemented, this method will be called one or more times after the state of the editor & toolbar are updated. When the state is updated, the editor does the following:

  1. Find the parent node containing the current selection
  2. Call checkState(node) on each extension, passing the node as an argument
  3. Get the parent node of the previous node
  4. Repeat steps #2 and #3 until we move outside the parent contenteditable

Arguments

  1. node (Node):
  • Current node, within the ancestors of the selection, that is being checked whenever a selection change occurred.

destroy()

If implemented, this method will be called whenever the MediumEditor is being destroyed (via a call to `MediumEditor.destroy()).

This gives the extensions the chance to remove any created html, custom event handlers or execute any other cleanup tasks that should be performed.


queryCommandState()

If implemented, this method will be called once on each extension when the state of the editor/toolbar is being updated.

If this method returns a non-null value, the extension will be ignored as the code climbs the dom tree.

If this method returns true, and the setActive() method is defined on the extension, the setActive() method will be called by MediumEditor.

Returns: boolean OR null


isActive()

If implemented, this method will be called when MediumEditor has determined that this extension is 'active' for the current selection.

This may be called when the editor & toolbar are being updated, but only if the queryCommandState() or isAlreadyApplied() methods are implemented, and when called, return true.

Returns: boolean


isAlreadyApplied(node)

If implemented, this method is similar to checkState() in that it will be called repeatedly as MediumEditor moves up the DOM to update the editor & toolbar after a state change.

NOTE:

  • This method will NOT be called if checkState() has been implemented.
  • This method will NOT be called if queryCommandState() is implemented and returns a non-null value when called.

Arguments

  1. node (Node):
  • Node to check for whether the current extension has already been applied.

Returns: boolean


setActive()

If implemented, this method is called when MediumEditor knows that this extension is currently enabled.

Currently, this method is called when updating the editor & toolbar, and if queryCommandState() or isAlreadyApplied(node) return true when called.


setInactive()

If implemented, this method is called when MediumEditor knows that this extension has not been applied to the current selection. Curently, this is called at the beginning of each state change for the editor & toolbar.

After calling this, MediumEditor will attempt to update the extension, either via checkState() or the combination of queryCommandState(), isAlreadyApplied(node), isActive(), and setActive()

Extension Helpers

The following are helpers that are either set by MediumEditor during initialization, or are helper methods which either route calls to the MediumEditor instance or provide common functionality for all extensions.

base (MediumEditor)

A reference to the instance of MediumEditor that this extension is part of.


window (Window)

A reference to the content window to be used by this instance of MediumEditor


document (Document)

A reference to the owner document to be used by this instance of MediumEditor


getEditorElements()

Returns a reference to the array of elements monitored by this instance of MediumEditor.

Returns: Array of HTMLElements


getEditorId()

Returns the unique identifier for this instance of MediumEditor

Returns: Number


getEditorOption(option)

Returns the value of a specific option used to initialize the MediumEditor object.

Arguments

  1. option ('String')
  • Name of the MediumEditor option to retrieve.

Returns: Value of the MediumEditor option

Extension Proxy Methods

  • These are methods that are just proxied calls into existing MediumEditor functions:

execAction(action, opts)

Calls MediumEditor.execAction(action, opts)

on(target, event, listener, useCapture)

Calls MediumEditor.on(target, event, listener, useCapture)

off(target, event, listener, useCapture)

Calls MediumEditor.off(target, event, listener, useCapture)

subscribe(name, listener)

Calls MediumEditor.subscribe(name, listener)

trigger(name, data, editable)

Calls MediumEditor.trigger(name, data, editable)

Buttons

Example: Highlight Button

Button Extension API

Form ButtonsS

Example: Anchor

From Extension API

Clone this wiki locally