├── .eslintrc ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── babel.config.js ├── building-plugins.md ├── example ├── ToolbarButton.js ├── blockStyles.html ├── inlineStyles.html ├── link.html ├── mention.html ├── token.html └── tray.html ├── package.json ├── rollup.config.js ├── src ├── components │ ├── Editor.js │ ├── KeyCommandController.js │ ├── OverlayWrapper.js │ ├── Toolbar.js │ └── withDraftExtendContext.js ├── index.js ├── plugins │ ├── accumulatePluginOptions.js │ ├── createPlugin.js │ └── utils.js ├── style │ └── draft-extend.css └── util │ ├── accumulateFunction.js │ ├── buildTag.js │ ├── compose.js │ ├── memoize.js │ └── middlewareAdapter.js └── yarn.lock /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "hubspot" 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist/ 3 | lib/ 4 | esm/ 5 | npm-debug.log 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 2.0.0 2 | 3 | - Upgrade to utilize React Context API 4 | - Exposes the `DraftEditorContext` React context 5 | 6 | ## 2.1.1 7 | 8 | - Add `withDraftExtendContext` HOC 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 HubSpot, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # draft-extend 2 | 3 | [![npm version](https://badge.fury.io/js/draft-extend.svg)](https://www.npmjs.com/package/draft-extend) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 4 | 5 | *Build extensible [Draft.js](http://draftjs.org) editors with configurable plugins and integrated serialization* 6 | 7 | *** 8 | 9 | ###### Jump to: 10 | - [Overview](#overview) 11 | - [Examples](#examples) 12 | - [Editor](#editor) 13 | - [compose](#compose) 14 | - [Building Plugins](building-plugins.md) 15 | 16 | *** 17 | 18 | ## Overview 19 | Draft Extend is a platform to build a full-featured Draft.js editor using modular plugins that can integrate with [draft-convert](http://github.com/HubSpot/draft-convert) to serialize with HTML. The higher-order function API makes it extremely easy to use any number of plugins for rendering and conversion. 20 | 21 | #### Usage: 22 | ```javascript 23 | import React from 'react'; 24 | import ReactDOM from 'react-dom'; 25 | import {EditorState} from 'draft-js'; 26 | import {Editor, compose} from 'draft-extend'; 27 | import {convertFromHTML, convertToHTML} from 'draft-convert'; 28 | 29 | const plugins = compose( 30 | FirstPlugin, 31 | SecondPlugin, 32 | ThirdPlugin 33 | ); 34 | 35 | const EditorWithPlugins = plugins(Editor); // Rich text editor component with plugin functionality 36 | const toHTML = plugins(convertFromHTML); // function to convert from HTML including plugin functionality 37 | const fromHTML = plugins(convertToHTML); // function to convert to HTML including plugin functionality 38 | 39 | const MyEditor = React.createClass({ 40 | getInitialState() { 41 | return { 42 | editorState: EditorState.createWithContent(fromHTML('
')) 43 | }; 44 | }, 45 | 46 | onChange(editorState) { 47 | const html = toHTML(editorState.getCurrentContent()); 48 | console.log(html); // don't actually convert to HTML on every change! 49 | this.setState({editorState}); 50 | }, 51 | 52 | render() { 53 | return ( 54 | 58 | ); 59 | } 60 | }); 61 | 62 | ReactDOM.render( 63 | , 64 | document.querySelector('.app') 65 | ); 66 | ``` 67 | 68 | *** 69 | 70 | ## Examples 71 | 72 | Examples of how to build plugins of different types are included in the [example](example/) directory. To run the examples locally: 73 | 74 | 1. run `npm install` in the `draft-extend` directory 75 | 2. open any HTML file in the `examples` directory in your web browser - no local server is necessary 76 | 77 | *** 78 | 79 | ## Editor 80 | **Editor component on which to extend functionality with plugins created by [`createPlugin`](#createplugin).** 81 | 82 | #### Props 83 | The most important two props are: 84 | - `editorState` - Draft.js `EditorState` instance to be rendered. 85 | - `onChange: function(editorState: EditorState): void` - Like with vanilla Draft.js, function called on any editor change passing the `EditorState`. 86 | 87 | Other props are used by plugins composed around `Editor`. See [Building Plugins](building-plugins.md) for more information. **These should generally not be used outside of the context of a plugin**: 88 | - `buttons`: `Array` Array of React components to add to the controls of the editor. 89 | - `overlays`: `Array` Array of React components to add as overlays to the editor. 90 | - `decorators`: `Array` Array of Draft.js decorator objects used to render the EditorState. They are added to the EditorState as a CompositeDecorator within the component and are of shape `{strategy, component}`. 91 | - `baseDecorator`: `DraftDecoratorType` Replacement decorator object to override the built-in `CompositeDecorator`'s behavior. See the "Beyond CompositeDecorator" section on [this page of the Draft.js docs](https://draftjs.org/docs/advanced-topics-decorators.html#content) for more information. 92 | - `styleMap`: `Object` Object map from Draft.js inline style type to style object. Used for the Draft.js Editor's `customStyleMap` prop. 93 | 94 | All other props are passed down to the [Draft.js `Editor` component](https://facebook.github.io/draft-js/docs/api-reference-editor.html) and to any buttons and overlays added by plugins. 95 | 96 | *** 97 | 98 | ## compose 99 | Since the API of plugins is based around composition, a basic `compose` function is provided to make it easy to apply plugins to the component as well as conversion functions and provides a single source of truth for plugin configuration. 100 | ```javascript 101 | // without compose 102 | const EditorWithPlugins = FirstPlugin(SecondPlugin(ThirdPlugin(Editor))); 103 | const fromHTML = FirstPlugin(SecondPlugin(ThirdPlugin(convertFromHTML))); 104 | const toHTML = FirstPlugin(SecondPlugin(ThirdPlugin(convertToHTML))); 105 | 106 | // with compose 107 | const plugins = compose( 108 | FirstPlugin, 109 | SecondPlugin, 110 | ThirdPlugin 111 | ); 112 | 113 | const EditorWithPlugins = plugins(Editor); 114 | const toHTML = plugins(convertToHTML); 115 | const fromHTML = plugins(convertFromHTML); 116 | ``` 117 | 118 | *** 119 | 120 | ## KeyCommandController 121 | **Higher-order component to consolidate key command listeners across the component tree** 122 | 123 | An increasingly common pattern for rich text editors is a toolbar detached from the main `Editor` component. This toolbar will be outside of the `Editor` component subtree, but will often need to respond to key commands that would otherwise be encapsulated by the `Editor`. `KeyCommandController` is a higher-order component that allows the subscription to key commands to move up the React tree so that components outside that subtree may listen and emit changes to editor state. `KeyCommandController`. It may be used with any component, but a good example is the `Toolbar` component: 124 | 125 | ```javascript 126 | import {Editor, Toolbar, KeyCommandController, compose} from 'draft-extend'; 127 | 128 | const plugins = compose( 129 | FirstPlugin, 130 | SecondPlugin 131 | ); 132 | 133 | const WrappedEditor = plugins(Editor); 134 | const WrappedToolbar = plugins(Toolbar); 135 | 136 | const Parent = ({editorState, onChange, handleKeyCommand, addKeyCommandListener, removeKeyCommandListener}) => { 137 | return ( 138 |
139 | 146 | 152 |
153 | ); 154 | }; 155 | 156 | export default KeyCommandController(Parent); 157 | ``` 158 | 159 | `KeyCommandController` provides the final `handleKeyCommand` to use in the `Editor` component as well as subscribe/unsubscribe functions. As long as these props are passed from some common parent wrapped with `KeyCommandController` that also receives `editorState` and `onChange` props, other components may subscribe and emit chagnes to the editor state. 160 | 161 | Additionally, `KeyCommandController`s are composable and will defer to the highest parent instance. That is, if a `KeyCommandController` receives `handleKeyCommand`, `addKeyCommandListener`, and `removeKeyCommandListener` props (presumably from another controller) it will delegate to that controller's record of subscribed functions, keeping all listeners in one place. 162 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | commonjs: { 4 | presets: ['@babel/env', '@babel/react'], 5 | plugins: ['@babel/transform-runtime'], 6 | }, 7 | esm: { 8 | presets: [ 9 | ['@babel/react', { useBuiltIns: true }] 10 | ] 11 | } 12 | } 13 | }; -------------------------------------------------------------------------------- /building-plugins.md: -------------------------------------------------------------------------------- 1 | # Building Plugins 2 | 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. 3 | 4 | ## Example 5 | 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](#createplugin) section. A live example of this can be run using its [example file](example/link.html). 6 | 7 | ```javascript 8 | // LinkPlugin.js 9 | 10 | import React from 'react'; 11 | import {Entity, Modifier, EditorState} from 'draft-js'; 12 | import {createPlugin, pluginUtils} from 'draft-extend'; 13 | 14 | const ENTITY_TYPE = 'LINK'; 15 | 16 | // Button component to add below the editor 17 | const LinkButton = ({editorState, onChange}) => { 18 | const addLink = () => { 19 | const contentState = Modifier.applyEntity( 20 | editorState.getCurrentContent(), 21 | editorState.getSelection(), 22 | Entity.create( 23 | ENTITY_TYPE, 24 | 'MUTABLE', 25 | { 26 | href: 'http://draftjs.org', 27 | target: '_blank' 28 | } 29 | ) 30 | ); 31 | onChange( 32 | EditorState.push( 33 | editorState, 34 | contentState, 35 | 'apply-entity' 36 | ) 37 | ); 38 | } 39 | 40 | return ; 41 | }; 42 | 43 | // Decorator to render links while editing 44 | const LinkDecorator = { 45 | strategy: pluginUtils.entityStrategy(ENTITY_TYPE), 46 | component: (props) => { 47 | const entity = Entity.get(props.entityKey); 48 | const {href, target} = entity.getData(); 49 | 50 | return ( 51 | 52 | {props.children} 53 | 54 | ); 55 | } 56 | }; 57 | 58 | // Convert links in input HTML to entities 59 | const htmlToEntity = (nodeName, node) => { 60 | if (nodeName === 'a') { 61 | return Entity.create( 62 | ENTITY_TYPE, 63 | 'MUTABLE', 64 | { 65 | href: node.getAttribute('href'), 66 | target: node.getAttribute('target') 67 | } 68 | ) 69 | } 70 | }; 71 | 72 | // Convert entities to HTML for output 73 | const entityToHTML = (entity, originalText) => { 74 | if (entity.type === ENTITY_TYPE) { 75 | return ( 76 | 77 | {originalText} 78 | 79 | ); 80 | } 81 | return originalText; 82 | }; 83 | 84 | const LinkPlugin = createPlugin({ 85 | displayName: 'LinkPlugin', 86 | buttons: LinkButton, 87 | decorators: LinkDecorator, 88 | htmlToEntity, 89 | entityToHTML 90 | }); 91 | 92 | export default LinkPlugin; 93 | ``` 94 | 95 | ## createPlugin 96 | Factory function to create plugins. `createPlugin` takes one `options` object argument. All properties of `options` are optional. 97 | ### Plugin options 98 | #### Editor rendering options 99 | - `displayName: string` - `displayName` of the higher-order component when wrapping around `Editor`. 100 | - default: `'Plugin'` 101 | - `buttons: Array | 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](#buttons--overlays) for more information on props and usage. 102 | - default: `[]` 103 | - `overlays: Array | 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](#buttons--overlays) for more information on props and usage. 104 | - default: `[]` 105 | - `decorators: Array | 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](https://facebook.github.io/draft-js/docs/advanced-topics-decorators.html) for more information. 106 | - default: `[]` 107 | - `styleMap: {[inlineStyleType: string]: Object}` - Object map of styles to apply to any inline styles in the editor. Used in the `customStyleMap` prop on the Draft.js `Editor` component. 108 | - default: `{}` 109 | - `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 the `customStyleFn` prop on the Draft.js `Editor` component. 110 | - default: `() => {}` 111 | - `blockStyleFn: function(contentBlock: ContentBlock): ?string` - Function that inspects a Draft.js ContentBlock and returns a string `class` that 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](https://facebook.github.io/draft-js/docs/advanced-topics-block-styling.html) for more information. 112 | - default: `() => {}` 113 | - `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](https://facebook.github.io/draft-js/docs/advanced-topics-block-components.html) for more information. 114 | - default: `() => {}` 115 | - `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](https://facebook.github.io/draft-js/docs/advanced-topics-key-bindings.html). If the plugin should not name the key command it may return `undefined`. Note that if no plugin names a key commmand the `Editor` component will fall back to `Draft.getDefaultKeyBinding`. 116 | - `keyCommandListener: function(editorState: EditorState, command: string, keyboardEvent: SyntheticKeyboardEvent): boolean | EditorState` - Function to handle key commands without using a button or overlay component. 117 | 118 | #### Conversion Options 119 | Plugins can include options to handle serialization and deserialization of their functionality to and from HTML. 120 | 121 | **Middleware usage** 122 | `draft-extend` conversion options are all [middleware functions](http://redux.js.org/docs/advanced/Middleware.html) 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. 123 | ```javascript 124 | const AlignmentPlugin = createPlugin({ 125 | ... 126 | blockToHTML: (next) => (block) => { 127 | const result = next(block); 128 | if (block.data.align && React.isValidElement(result)) { 129 | const style = result.props.style || {}; 130 | style.textAlign = block.data.align; 131 | return React.cloneElement(result, {style}); 132 | } 133 | return result; 134 | } 135 | }); 136 | ``` 137 | 138 | **Options** 139 | - `styleToHTML: (next: function) => (style: string) => (ReactElement | MarkupObject)` - Function that takes inline style types and returns an empty `ReactElement` (most likely created via JS) or HTML markup for output. A `MarkupObject` is an object of shape `{start, end}`, for example: 140 | ```javascript 141 | const styleToHTML = (style) => { 142 | if (style === 'BOLD') { 143 | return { 144 | start: '', 145 | end: '' 146 | }; 147 | } 148 | }; 149 | ``` 150 | - `blockToHTML: (next: function) => (block: RawBlock) => (ReactElement | {element: ReactElement, nest?: ReactElement} | BlockMarkupObject)` - Function accepting a raw block object and returning `ReactElement`s or HTML markup for output. If using `ReactElement`s as return values for nestable blocks (`ordered-list-item` and `unordered-list-item`), a `ReactElement` for both the wrapping element and the block being nested may be included in an object of shape `{element, nest}`. A `BlockMarkupObject` is identical to `MarkupObject` with the exception of nestable blocks. These block types include properties for handling nesting. The default values for `ordered-list-item` are: 151 | ```javascript 152 | { 153 | start: '
  • ', 154 | end: '
  • ', 155 | nestStart: '
      ', 156 | nestEnd: '
    ' 157 | } 158 | ``` 159 | - `entityToHTML: (next: function) => (entity: RawEntity, originalText: string): (ReactElement | MarkupObject | string)` - Function to transform instances into HTML output. A `RawEntity` is an object of shape `{type: string, mutability: string, data: object}`. If the returned `ReactElement` contains no children it will be wrapped around `originalText`. A `MarkupObject` will also be wrapped around `orignalText`. 160 | - `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. 161 | - `htmlToBlock: (next: function) => (nodeName: string, node: Node) => RawBlock | string` - Function that inspects an HTML `Node` and 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 return `null` or `undefined`. 162 | - `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 call `Entity.create()` and return the string return value that is the Entity instance's key. If no entity is necessary it may return nothing. 163 | - `textToEntity: (next: function) => (text: string) => Array` - Function to convert plain input text to entities. Note that `textToEntity` is invoked with the value of each individual text DOM Node. For example, with input `
    node onenode two
    ` `textToEntity` will be called with strings `'node one'` and `'node two'`. Implementations of this function generally uses a regular expression to return an array of as many `TextEntityObject`s as necessary for the text string. A `TextEntityObject` is an object with properties: 164 | - `offset: number`: Offset of the entity to add within `text` 165 | - `length: number`: Length of the entity starting at `offset` within `text` 166 | - `result: string`: If necessary, a new string to replace the substring in `text` defined by `offset` and `length`. If omitted from the object no replacement will be made. 167 | - `entity: string`: key of the Entity instance to be applied for this range. This is generally the result of `Entity.create()`. 168 | 169 | *** 170 | 171 | ## Buttons & Overlays 172 | 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](https://facebook.github.io/draft-js/docs/advanced-topics-key-bindings.html) has more information on key commands. 173 | 174 | #### Button & Overlay Props 175 | - `editorState: EditorState` - current EditorState of the `Editor` component. 176 | - `onChange: function(editorState: EditorState)` - handler for making changes to editor state. Passed down from the `Editor` component 177 | - `addKeyCommandListener(listener: (editorState: EditorState, command: string, keyboardEvent: SyntheticKeyboardEvent): ?boolean)`- Subscribes a listener function to handle `Editor` key commands. Subscription should usually happen on component mount. If no further handling should be made by other handlers then a listener may return `true`. Listeners are called in order of most recently added to least recently added. Key events normally handled in Draft.js by `handleReturn`, `onEscape`, `onTab`, `onUpArrow`, and `onDownArrow` props (and therefore not in the normal `handleKeyCommand`) are also routed through the listener. These events are the only ones that include the `keyboardEvent` argument and have commands `'return'`, `'escape'`, `'tab'`, `'up-arrow'`, and `'down-arrow'` respectively. `keyboardEvent` is useful for calling `preventDefault()` since Draft.js' built in event handling cannot respsect the return value of the listener. 178 | - `removeKeyCommandListener(listener: function): void` - Unsubscribes a listener function that was previously subscribed. Unsubscription should generally happen before component unmount. 179 | 180 | #### Overlay notes 181 | 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`. 182 | 183 | *** 184 | 185 | ## pluginUtils 186 | A collection of useful functions for building plugins. 187 | 188 | - `camelCaseToHyphen: function(camelCase: string): string` - Converts a camelCased word to a hyphenated-string. Used in `styleObjectToString`. 189 | - `styleObjectToString: function(styles: object): string` - Converts a style object (i.e. object passed into the `style` prop of a React component) to a CSS string for use in a `style` HTML attribute. Useful for converting inline style types to HTML while keeping a single source of truth for the style for both `styleMap` and `styleToHTML`. 190 | - `entityStrategy: function(entityType: string): function(contentBlock, callback)` - factory function to generate decorator strategies to decorate all instances of a given entity type. For example: 191 | ```javascript 192 | const MyPlugin = createPlugin({ 193 | ... 194 | decorators: { 195 | strategy: entityStrategy('myEntity'), 196 | component: MyEntityComponent 197 | } 198 | }); 199 | ``` 200 | - `getEntitySelection: function(editorState: EditorState, entityKey: string): SelectionState` - Returns the selection of an Entity instance in `editorState` with key `entityKey`. 201 | - `getSelectedInlineStyles: function(editorState): Set` - Returns a `Set` of all inline style types matched by any character in the current selection. Ths acts differently from `EditorState.getCurrentInlineStyle()` when the selection is not collapsed since `getSelectedInlineStyles` will include styles from every character in the selection instead of the single character at the focus index of the selection. 202 | - `getActiveEntity(editorState: EditorState): ?string` - Returns the key for the Entity that the current selection start is within, if it exists. Returns `undefined` if the selection start is not within an entity range. 203 | - `isEntityActive(editorState, entityType): bool` - Returns `true` if the current selection start is within an entity of type `entityType`, and false otherwise. Useful for setting a button's active state when associated with an entity type. 204 | -------------------------------------------------------------------------------- /example/ToolbarButton.js: -------------------------------------------------------------------------------- 1 | window.ToolbarButton = function({ active, label, onClick }) { 2 | var toolbarButtonStyle = { 3 | display: 'inline-block', 4 | minWidth: '24px', 5 | padding: '4px', 6 | borderRadius: '3px', 7 | textAlign: 'center', 8 | cursor: 'pointer', 9 | }; 10 | 11 | if (active) { 12 | toolbarButtonStyle.background = '#000'; 13 | toolbarButtonStyle.color = '#fff'; 14 | } 15 | 16 | return React.createElement( 17 | 'div', 18 | { 19 | style: toolbarButtonStyle, 20 | onClick: onClick, 21 | }, 22 | label 23 | ); 24 | }; 25 | 26 | ToolbarButton.defaultProps = { 27 | active: false, 28 | label: '', 29 | onClick: function() {}, 30 | }; 31 | -------------------------------------------------------------------------------- /example/blockStyles.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | draft-extend 6 | 7 | 8 | 15 | 16 | 17 |
    18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 128 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /example/inlineStyles.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | draft-extend 6 | 7 | 8 | 15 | 16 | 17 |
    18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 117 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /example/link.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | draft-extend 6 | 7 | 8 | 15 | 16 | 17 |
    18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 133 | 141 | 142 | 143 | -------------------------------------------------------------------------------- /example/mention.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | draft-extend 6 | 7 | 8 | 15 | 16 | 17 |
    18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 425 | 433 | 434 | 435 | -------------------------------------------------------------------------------- /example/token.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | draft-extend 6 | 7 | 8 | 15 | 16 | 17 |
    18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 142 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /example/tray.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | draft-extend 6 | 7 | 8 | 15 | 16 | 17 |
    18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 134 | 142 | 143 | 144 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "draft-extend", 3 | "version": "2.1.1", 4 | "description": "Build extensible Draft.js editors with configurable plugins and integrated serialization.", 5 | "main": "lib/index.js", 6 | "module": "esm/index.js", 7 | "repository": "HubSpot/draft-extend", 8 | "scripts": { 9 | "build": "npm run clean && npm run build:commonjs && npm run build:esm && npm run build:umd && npm run build:css", 10 | "build:commonjs": "BABEL_ENV=commonjs babel src --out-dir lib", 11 | "build:esm": "BABEL_ENV=esm babel src --out-dir esm", 12 | "build:umd": "rollup -c", 13 | "build:css": "cp ./src/style/*.css ./dist/", 14 | "clean": "rm -rf ./dist && rm -rf ./lib && rm -rf ./esm", 15 | "prepublish": "npm run build" 16 | }, 17 | "files": [ 18 | "dist", 19 | "lib", 20 | "esm" 21 | ], 22 | "keywords": [ 23 | "draft", 24 | "extend", 25 | "plugin", 26 | "draft-js" 27 | ], 28 | "author": "Ben Briggs", 29 | "license": "Apache-2.0", 30 | "peerDependencies": { 31 | "draft-js": ">=0.7.0", 32 | "react": "^16.3.0", 33 | "react-dom": "^16.3.0" 34 | }, 35 | "dependencies": { 36 | "@babel/runtime": "^7.7.2", 37 | "immutable": "^3.8.1", 38 | "invariant": "^2.2.1", 39 | "prop-types": "^15.7.2" 40 | }, 41 | "devDependencies": { 42 | "@babel/cli": "^7.5.0", 43 | "@babel/core": "^7.5.4", 44 | "@babel/plugin-transform-runtime": "^7.5.5", 45 | "@babel/preset-env": "^7.5.4", 46 | "@babel/preset-react": "^7.0.0", 47 | "@babel/standalone": "^7.7.3", 48 | "draft-convert": "^2.1.4", 49 | "draft-js": "^0.10.5", 50 | "es6-shim": "^0.35.0", 51 | "react": "^16.3.0", 52 | "react-dom": "^16.3.0", 53 | "rollup": "^1.26.3", 54 | "rollup-plugin-commonjs": "^10.1.0", 55 | "rollup-plugin-node-resolve": "^5.2.0", 56 | "rollup-plugin-replace": "^2.2.0", 57 | "rollup-plugin-terser": "^5.1.2" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import nodeResolve from 'rollup-plugin-node-resolve'; 2 | import commonjs from 'rollup-plugin-commonjs'; 3 | import replace from 'rollup-plugin-replace'; 4 | import { terser } from 'rollup-plugin-terser'; 5 | 6 | const globals = { 7 | 'draft-js': 'Draft', 8 | 'immutable': 'Immutable', 9 | 'react': 'React', 10 | 'react-dom': 'ReactDOM' 11 | }; 12 | 13 | const bundle = (env) => ({ 14 | input: 'esm/index.js', 15 | external: Object.keys(globals), 16 | output: { 17 | globals, 18 | file: env === 'production' ? 'dist/draft-extend.min.js' : 'dist/draft-extend.js' , 19 | format: 'umd', 20 | name: 'DraftExtend', 21 | }, 22 | plugins: [ 23 | nodeResolve(), 24 | commonjs(), 25 | replace({ 26 | 'process.env.NODE_ENV': JSON.stringify(env) 27 | }), 28 | env === 'production' && terser(), 29 | ].filter(Boolean), 30 | }) 31 | 32 | export default [bundle('production'), bundle('development')]; -------------------------------------------------------------------------------- /src/components/Editor.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { 4 | Editor, 5 | EditorState, 6 | CompositeDecorator, 7 | getDefaultKeyBinding, 8 | } from 'draft-js'; 9 | import KeyCommandController from './KeyCommandController'; 10 | import OverlayWrapper from './OverlayWrapper'; 11 | 12 | const propTypes = { 13 | className: PropTypes.string, 14 | editorState: PropTypes.object, 15 | onChange: PropTypes.func, 16 | decorators: PropTypes.array, 17 | baseDecorator: PropTypes.func, 18 | styleMap: PropTypes.object, 19 | styleFn: PropTypes.func, 20 | buttons: PropTypes.array, 21 | overlays: PropTypes.array, 22 | blockRendererFn: PropTypes.func, 23 | blockStyleFn: PropTypes.func, 24 | keyBindingFn: PropTypes.func, 25 | addKeyCommandListener: PropTypes.func.isRequired, 26 | removeKeyCommandListener: PropTypes.func.isRequired, 27 | handleReturn: PropTypes.func, 28 | onEscape: PropTypes.func, 29 | onTab: PropTypes.func, 30 | onUpArrow: PropTypes.func, 31 | onDownArrow: PropTypes.func, 32 | readOnly: PropTypes.bool, 33 | showButtons: PropTypes.bool, 34 | renderTray: PropTypes.func, 35 | }; 36 | 37 | const defaultContextFn = () => 38 | console.error( 39 | 'DraftEditorContext is not provided in this scope. Please check your setup.' 40 | ); 41 | export const DraftEditorContext = React.createContext({ 42 | getEditorState: defaultContextFn, 43 | getReadOnly: defaultContextFn, 44 | setReadOnly: defaultContextFn, 45 | onChange: defaultContextFn, 46 | focus: defaultContextFn, 47 | blur: defaultContextFn, 48 | editorRef: defaultContextFn, 49 | }); 50 | 51 | class EditorWrapper extends React.Component { 52 | constructor(props) { 53 | super(props); 54 | 55 | const { baseDecorator } = props; 56 | 57 | const decorator = new baseDecorator(props.decorators); 58 | this.state = { 59 | decorator, 60 | readOnly: false, 61 | }; 62 | 63 | this.keyBindingFn = this.keyBindingFn.bind(this); 64 | this.handleReturn = this.handleReturn.bind(this); 65 | this.onEscape = this.onEscape.bind(this); 66 | this.onTab = this.onTab.bind(this); 67 | this.onUpArrow = this.onUpArrow.bind(this); 68 | this.onDownArrow = this.onDownArrow.bind(this); 69 | this.focus = this.focus.bind(this); 70 | this.blur = this.blur.bind(this); 71 | this.getOtherProps = this.getOtherProps.bind(this); 72 | this.getReadOnly = this.getReadOnly.bind(this); 73 | this.setReadOnly = this.setReadOnly.bind(this); 74 | this.getDecoratedState = this.getDecoratedState.bind(this); 75 | 76 | this.contextValue = { 77 | getEditorState: this.getDecoratedState, 78 | getReadOnly: this.getReadOnly, 79 | setReadOnly: this.setReadOnly, 80 | onChange: this.props.onChange, 81 | focus: this.focus, 82 | blur: this.blur, 83 | editorRef: this.refs.editor, 84 | }; 85 | } 86 | 87 | static getDerivedStateFromProps(props, state) { 88 | if (props.decorators.length === state.decorator._decorators.length) { 89 | const allDecoratorsMatch = state.decorator._decorators.every( 90 | (decorator, i) => { 91 | return decorator === props.decorators[i]; 92 | } 93 | ); 94 | if (allDecoratorsMatch) { 95 | return {}; 96 | } 97 | } 98 | 99 | return { 100 | decorator: new props.baseDecorator(props.decorators), 101 | }; 102 | } 103 | 104 | keyBindingFn(e) { 105 | const pluginsCommand = this.props.keyBindingFn(e); 106 | if (pluginsCommand) { 107 | return pluginsCommand; 108 | } 109 | 110 | return getDefaultKeyBinding(e); 111 | } 112 | 113 | handleReturn(e, editorState) { 114 | return ( 115 | (this.props.handleReturn && this.props.handleReturn(e, editorState)) || 116 | this.props.handleKeyCommand('return', e) 117 | ); 118 | } 119 | 120 | onEscape(e) { 121 | return ( 122 | (this.props.onEscape && this.props.onEscape(e)) || 123 | this.props.handleKeyCommand('escape', e) 124 | ); 125 | } 126 | 127 | onTab(e) { 128 | return ( 129 | (this.props.onTab && this.props.onTab(e)) || 130 | this.props.handleKeyCommand('tab', e) 131 | ); 132 | } 133 | 134 | onUpArrow(e) { 135 | return ( 136 | (this.props.onUpArrow && this.props.onUpArrow(e)) || 137 | this.props.handleKeyCommand('up-arrow', e) 138 | ); 139 | } 140 | 141 | onDownArrow(e) { 142 | return ( 143 | (this.props.onDownArrow && this.props.onDownArrow(e)) || 144 | this.props.handleKeyCommand('down-arrow', e) 145 | ); 146 | } 147 | 148 | focus() { 149 | this.refs.editor.focus(); 150 | } 151 | 152 | blur() { 153 | this.refs.editor.blur(); 154 | } 155 | 156 | getOtherProps() { 157 | const propKeys = Object.keys(this.props); 158 | const propTypeKeys = Object.keys(propTypes); 159 | 160 | const propsToPass = propKeys.filter((prop) => { 161 | return propTypeKeys.indexOf(prop) === -1; 162 | }); 163 | 164 | return propsToPass.reduce((acc, prop) => { 165 | acc[prop] = this.props[prop]; 166 | return acc; 167 | }, {}); 168 | } 169 | 170 | getReadOnly() { 171 | return this.state.readOnly || this.props.readOnly; 172 | } 173 | 174 | setReadOnly(readOnly) { 175 | this.setState({ readOnly }); 176 | } 177 | 178 | getDecoratedState() { 179 | const { editorState } = this.props; 180 | const { decorator } = this.state; 181 | 182 | const currentDecorator = editorState.getDecorator(); 183 | 184 | if ( 185 | currentDecorator && 186 | currentDecorator._decorators === decorator._decorators 187 | ) { 188 | return editorState; 189 | } 190 | 191 | return EditorState.set(editorState, { decorator }); 192 | } 193 | 194 | renderTray() { 195 | const { renderTray } = this.props; 196 | 197 | if (typeof renderTray !== 'function') { 198 | return null; 199 | } 200 | 201 | return renderTray(); 202 | } 203 | 204 | renderPluginButtons() { 205 | const { 206 | onChange, 207 | addKeyCommandListener, 208 | removeKeyCommandListener, 209 | showButtons, 210 | } = this.props; 211 | 212 | if (showButtons === false) { 213 | return null; 214 | } 215 | 216 | const decoratedState = this.getDecoratedState(); 217 | 218 | return this.props.buttons.map((Button, index) => { 219 | return ( 220 |