-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Custom Buttons and Extensions
-
Overview
- What is an Extension?
-
What is a Button?
- [All of the built-in MediumEditor buttons are just Button Extensions with different configuration:](#all-of-the-built-in-mediumeditor-buttons-are-just-button-extensions-with-different-configurationhttpsgithubcomyabwemedium-editorblobmastersrcjsdefaultsbuttonsjs)
- Examples of custom built external buttons:
- What is a Form Extension?
-
Extensions
-
Example: DisableContextMenuExtension
- Define the Extension
- Attaching To Click
- Adding Functionality
- [Leveraging Custom Event Listeners](#leveraging-custom-eventhttpsgithubcomyabwemedium-editorwikicustom-events-listeners)
- Extension Interface
- Extension Helpers
- Extension Proxy Methods
-
Example: DisableContextMenuExtension
- Buttons
- Form Buttons
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()
.
-
The MediumEditor Toolbar
- The entire toolbar which contains all of the MediumEditor buttons is implemented as an extension!
-
Auto-Link Detection
- Automatically detecting when a url has been added and converting it into an anchor tag
-
Anchor Preview Tooltip
- When a user hovers over a link a tooltip is displayed showing the href of the anchor tag
-
Image Drag & Drop
- Allows users to drag and drop images into the editor
-
Keyboard Commands
- Mapping keyboard shortcuts to various commands
-
Placeholder Text
- Shows placeholder text when the editor is empty
-
Paste Handling
- Handles filtering and modifying text that is pasted into the editor
-
MediumEditor markdown
- A Medium Editor extension to add markdown support.
-
MediumEditor Insert Plugin
- Enables users to insert into the editor various types of content like images or embeds.
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
-
MediumEditor tables
- Extension to add a table button/behavior to MediumEditor
-
MediumEditor Custom HTML
- An extension that inserts custom HTML using a new button in the Medium Editor toolbar
-
MediumButton
- Extends your Medium Editor with the possibility add buttons.
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.
-
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.
- The
-
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.
- The
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()
}
});
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 nativeclick
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 thesubscribe()
method, so instead of the above code we can just usethis.subscribe('editableClick', this.handleClick.bind(this))
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.
The following are properties and method that MediumEditor will attempt to use / call to interact with the extension internally.
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.
var MyExtension = MediumEditor.Extension.extend({
name: 'myextension'
});
var myExt = new MyExtension();
var editor = new MediumEditor('.editor', {
extensions: {
'myextension': myExt
}
});
editor.getExtensionByName(`myextension`) === myExt //true
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.
See the code above for an example of implementing the init()
method.
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:
- Find the parent node containing the current selection
- Call
checkState(node)
on each extension, passing the node as an argument - Get the parent node of the previous node
- Repeat steps #2 and #3 until we move outside the parent contenteditable
Arguments
-
node (
Node
):
- Current node, within the ancestors of the selection, that is being checked whenever a selection change occurred.
Here's an example of an extension that will add/remove a class to editor elements depending on whether or the current selection is within an element with a custom data attribute:
var EditedExtension = MediumEditor.Extension.extend({
name: 'edited',
checkState: function (node) {
// checkState is called multiple times for each selection change
// so only store a value if the attribute was found
if (!this.foundAttribute && node.getAttribute('data-edited')) {
this.foundAttribute = true;
}
// Once we've moved up the ancestors to the container element
// we know we're done iterating up and can add/remove the css class
if (MediumEditor.util.isMediumEditorElement(node)) {
if (this.foundAttribute) {
node.classList.add('edited-text');
} else {
node.classList.remove('edited-text');
}
// Make sure the property is not persisted for the next time
// selection is updated
delete this.foundAttribute;
}
}
});
var editedExt = new EditedExtension();
var editor = new MediumEditor('.editor', {
extensions: {
'edited': editedExt
}
});
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.
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
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
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
-
node (
Node
):
- Node to check for whether the current extension has already been applied.
Returns: boolean
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.
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()
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.
A reference to the instance of MediumEditor that this extension is part of.
A reference to the content window to be used by this instance of MediumEditor
A reference to the owner document to be used by this instance of MediumEditor
Returns a reference to the array of elements monitored by this instance of MediumEditor.
Returns: Array
of HTMLElement
s
Returns the unique identifier for this instance of MediumEditor
Returns: Number
Returns the value of a specific option used to initialize the MediumEditor object.
Arguments
- option ('String')
- Name of the MediumEditor option to retrieve.
Returns: Value of the MediumEditor option
- These are methods that are just proxied calls into existing MediumEditor functions:
Calls MediumEditor.execAction(action, opts)
Calls MediumEditor.on(target, event, listener, useCapture)
Calls MediumEditor.off(target, event, listener, useCapture)
Calls MediumEditor.subscribe(name, listener)
Calls MediumEditor.trigger(name, data, editable)
A simple example that uses rangy and the CSS Class Applier Module to support highlighting of text:
rangy.init();
var Highlighter = MediumEditor.extensions.button.extend({
name: 'highlighter',
init: function () {
Extension.prototype.init.apply(this, arguments);
this.classApplier = rangy.createCssClassApplier("highlight", {
elementTagName: 'mark',
normalize: true
});
this.button = this.document.createElement('');
this.button.classList.add('medium-editor-action');
this.button.innerHTML = '<b>H</b>';
this.button.title = 'Highlight';
this.on(this.button, 'click', this.handleClick.bind(this));
},
handleClick: function (event) {
this.classApplier.toggleSelection();
},
checkState: function (node) {
if(node.tagName == 'MARK') {
this.button.classList.add('medium-editor-button-active');
}
}
});
var editor = new MediumEditor('.editor', {
extensions: {
'highlighter': new Highlighter()
}
});