Draft Extend's plugin infrastructure gives you the tools to modularly add functionality to your editor using familiar Draft.js concepts while also including support for conversion to and from HTML.
Here's an example plugin: a button that adds a link to http://draftjs.org around any selected text when the button is clicked. The options available for defining a plugin are described in the createPlugin section. A live example of this can be run using its example file.
// LinkPlugin.js
import React from 'react';
import {Entity, Modifier, EditorState} from 'draft-js';
import {createPlugin, pluginUtils} from 'draft-extend';
const ENTITY_TYPE = 'LINK';
// Button component to add below the editor
const LinkButton = ({editorState, onChange}) => {
const addLink = () => {
const contentState = Modifier.applyEntity(
editorState.getCurrentContent(),
editorState.getSelection(),
Entity.create(
ENTITY_TYPE,
'MUTABLE',
{
href: 'http://draftjs.org',
target: '_blank'
}
)
);
onChange(
EditorState.push(
editorState,
contentState,
'apply-entity'
)
);
}
return <button onClick={addLink}>Add Draft Link</button>;
};
// Decorator to render links while editing
const LinkDecorator = {
strategy: pluginUtils.entityStrategy(ENTITY_TYPE),
component: (props) => {
const entity = Entity.get(props.entityKey);
const {href, target} = entity.getData();
return (
<a href={href} target={target}>
{props.children}
</a>
);
}
};
// Convert links in input HTML to entities
const htmlToEntity = (nodeName, node) => {
if (nodeName === 'a') {
return Entity.create(
ENTITY_TYPE,
'MUTABLE',
{
href: node.getAttribute('href'),
target: node.getAttribute('target')
}
)
}
};
// Convert entities to HTML for output
const entityToHTML = (entity, originalText) => {
if (entity.type === ENTITY_TYPE) {
return (
<a href={entity.data.href} target={entity.data.target}>
{originalText}
</a>
);
}
return originalText;
};
const LinkPlugin = createPlugin({
displayName: 'LinkPlugin',
buttons: LinkButton,
decorators: LinkDecorator,
htmlToEntity,
entityToHTML
});
export default LinkPlugin;Factory function to create plugins. createPlugin takes one options object argument. All properties of options are optional.
displayName: string-displayNameof the higher-order component when wrapping aroundEditor.- default:
'Plugin'
- default:
buttons: Array<Component> | Component- Zero or more button components to add to the Editor. If only one button is needed it may be passed by itself without an array. See Buttons & Overlays for more information on props and usage.- default:
[]
- default:
overlays: Array<Component> | Component- Zero or more overlay components to add to the Editor. If only one overlay is needed it may be passed by itself without an array. See Buttons & Overlays for more information on props and usage.- default:
[]
- default:
decorators: Array<Decorator> | Decorator- Zero or more decorator objects that the plugin uses to decorate editor content. If only one decorator is needed it may be passed by itself without an array. Decorator objects are of shape{strategy, component}. See Draft.js' Decorator documentation for more information.- default:
[]
- default:
styleMap: {[inlineStyleType: string]: Object}- Object map of styles to apply to any inline styles in the editor. Used in thecustomStyleMapprop on the Draft.jsEditorcomponent.- default:
{}
- default:
styleFn: {[style: DraftInlineStyle, block: ContentBlock]: ?Object}- Function that inspects each content block and its current inline styles and returns an object of CSS styles which are applied to a span containing the content block's text. Used in thecustomStyleFnprop on the Draft.jsEditorcomponent.- default:
() => {}
- default:
blockStyleFn: function(contentBlock: ContentBlock): ?string- Function that inspects a Draft.js ContentBlock and returns a stringclassthat if it exists is applied to the block element in the DOM. If no class should be added it may return nothing. See Draft.js' block styling documentation for more information.- default:
() => {}
- default:
blockRendererFn: function(contentBlock: ContentBlock): ?BlockRendererObject- Function that inspects a Draft.js ContentBlock and returns a custom block renderer object if it should be rendered differently. If no custom renderer should be used it may return nothing. The block renderer object is of shape{component, editable, props}. See Draft.js' custom block components documentation for more information.- default:
() => {}
- default:
keyBindingFn: function(e: SyntheticKeyboardEvent): ?string- Function to assign named key commands to key events on the editor. Works as described in Draft.js' key bindings documentation. If the plugin should not name the key command it may returnundefined. Note that if no plugin names a key commmand theEditorcomponent will fall back toDraft.getDefaultKeyBinding.keyCommandListener: function(editorState: EditorState, command: string, keyboardEvent: SyntheticKeyboardEvent): boolean | EditorState- Function to handle key commands without using a button or overlay component.
Plugins can include options to handle serialization and deserialization of their functionality to and from HTML.
Middleware usage
draft-extend conversion options are all middleware functions that allow plugins to transform the result of those that were composed before it. An example plugin leveraging middleware is a block alignment plugin that adds an align property to the block's metadata. This plugin should add a text-align: right style to any block with the property regardless of block type. Transforming the result of next(block) instead of building markup from scratch allows the plugin to only apply the changes it needs to. If middleware functionality is not necessary, any conversion option may omit the higher-order function receiving next and merely return null or undefined to defer the entire result to subsequent plugins.
const AlignmentPlugin = createPlugin({
...
blockToHTML: (next) => (block) => {
const result = next(block);
if (block.data.align && React.isValidElement(result)) {
const style = result.props.style || {};
style.textAlign = block.data.align;
return React.cloneElement(result, {style});
}
return result;
}
});Options
styleToHTML: (next: function) => (style: string) => (ReactElement | MarkupObject)- Function that takes inline style types and returns an emptyReactElement(most likely created via JS) or HTML markup for output. AMarkupObjectis an object of shape{start, end}, for example:
const styleToHTML = (style) => {
if (style === 'BOLD') {
return {
start: '<strong>',
end: '</strong>'
};
}
};blockToHTML: (next: function) => (block: RawBlock) => (ReactElement | {element: ReactElement, nest?: ReactElement} | BlockMarkupObject)- Function accepting a raw block object and returningReactElements or HTML markup for output. If usingReactElements as return values for nestable blocks (ordered-list-itemandunordered-list-item), aReactElementfor both the wrapping element and the block being nested may be included in an object of shape{element, nest}. ABlockMarkupObjectis identical toMarkupObjectwith the exception of nestable blocks. These block types include properties for handling nesting. The default values forordered-list-itemare:
{
start: '<li>',
end: '</li>',
nestStart: '<ol>',
nestEnd: '</ol>'
}entityToHTML: (next: function) => (entity: RawEntity, originalText: string): (ReactElement | MarkupObject | string)- Function to transform instances into HTML output. ARawEntityis an object of shape{type: string, mutability: string, data: object}. If the returnedReactElementcontains no children it will be wrapped aroundoriginalText. AMarkupObjectwill also be wrapped aroundorignalText.htmlToStyle: (next: function) => (nodeName: string, node: Node) => OrderedSet- Function that is passed an HTML Node. It should return a list of styles to be applied to all children of the node. The function will be invoked on all HTML nodes in the input.htmlToBlock: (next: function) => (nodeName: string, node: Node) => RawBlock | string- Function that inspects an HTMLNodeand can return data to assign to the block in the shape{type, data}. If no data is necessary a block type may be returned as a string. If no custom type should be used it may returnnullorundefined.htmlToEntity: (next: function) => (nodeName: string, node: Node) => ?string- Function that inspects an HTML Node and converts it to any Draft.js Entity that should be applied to the contents of the Node. If an Entity should be applied this function should callEntity.create()and return the string return value that is the Entity instance's key. If no entity is necessary it may return nothing.textToEntity: (next: function) => (text: string) => Array<TextEntityObject>- Function to convert plain input text to entities. Note thattextToEntityis invoked with the value of each individual text DOM Node. For example, with input<div>node one<span>node two</span></div>textToEntitywill be called with strings'node one'and'node two'. Implementations of this function generally uses a regular expression to return an array of as manyTextEntityObjects as necessary for the text string. ATextEntityObjectis an object with properties:offset: number: Offset of the entity to add withintextlength: number: Length of the entity starting atoffsetwithintextresult: string: If necessary, a new string to replace the substring intextdefined byoffsetandlength. If omitted from the object no replacement will be made.entity: string: key of the Entity instance to be applied for this range. This is generally the result ofEntity.create().
Plugins can augment the rendered UI of the editor by adding always-visible controls by passing a component to the buttons option or by adding UI on top of the editor itself (e.g. at-mention typeahead results) using the overlays option. Either of these component types may want to respond to or handle keyboard events within the Draft.js editor, so they are provided props to handle subscription to Draft.js key commands. Draft.js' key bindings documentation has more information on key commands.
editorState: EditorState- current EditorState of theEditorcomponent.onChange: function(editorState: EditorState)- handler for making changes to editor state. Passed down from theEditorcomponentaddKeyCommandListener(listener: (editorState: EditorState, command: string, keyboardEvent: SyntheticKeyboardEvent): ?boolean)- Subscribes a listener function to handleEditorkey commands. Subscription should usually happen on component mount. If no further handling should be made by other handlers then a listener may returntrue. Listeners are called in order of most recently added to least recently added. Key events normally handled in Draft.js byhandleReturn,onEscape,onTab,onUpArrow, andonDownArrowprops (and therefore not in the normalhandleKeyCommand) are also routed through the listener. These events are the only ones that include thekeyboardEventargument and have commands'return','escape','tab','up-arrow', and'down-arrow'respectively.keyboardEventis useful for callingpreventDefault()since Draft.js' built in event handling cannot respsect the return value of the listener.removeKeyCommandListener(listener: function): void- Unsubscribes a listener function that was previously subscribed. Unsubscription should generally happen before component unmount.
Overlay components are often absolutely positioned using Draft.getVisibleSelectionRect(window)'s coordinates. To make sure that no parent elements with position: relative style affect positioning, the overlay components are 'portaled' out of the component tree to be children of document.body.
A collection of useful functions for building plugins.
camelCaseToHyphen: function(camelCase: string): string- Converts a camelCased word to a hyphenated-string. Used instyleObjectToString.styleObjectToString: function(styles: object): string- Converts a style object (i.e. object passed into thestyleprop of a React component) to a CSS string for use in astyleHTML attribute. Useful for converting inline style types to HTML while keeping a single source of truth for the style for bothstyleMapandstyleToHTML.entityStrategy: function(entityType: string): function(contentBlock, callback)- factory function to generate decorator strategies to decorate all instances of a given entity type. For example:
const MyPlugin = createPlugin({
...
decorators: {
strategy: entityStrategy('myEntity'),
component: MyEntityComponent
}
});getEntitySelection: function(editorState: EditorState, entityKey: string): SelectionState- Returns the selection of an Entity instance ineditorStatewith keyentityKey.getSelectedInlineStyles: function(editorState): Set- Returns aSetof all inline style types matched by any character in the current selection. Ths acts differently fromEditorState.getCurrentInlineStyle()when the selection is not collapsed sincegetSelectedInlineStyleswill include styles from every character in the selection instead of the single character at the focus index of the selection.getActiveEntity(editorState: EditorState): ?string- Returns the key for the Entity that the current selection start is within, if it exists. Returnsundefinedif the selection start is not within an entity range.isEntityActive(editorState, entityType): bool- Returnstrueif the current selection start is within an entity of typeentityType, and false otherwise. Useful for setting a button's active state when associated with an entity type.