Filter Draft.js content to preserve only the formatting you allow
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.githooks chore(qa): run flow CI check on build output Sep 28, 2018
.github docs(readme): move dev docs to CONTRIBUTING.md Sep 28, 2018
docs style: reformat whole project with latest Prettier Sep 25, 2018
pasting style: reformat whole project with latest Prettier Sep 25, 2018
public chore(demo): update Draftail link Oct 27, 2018
src chore(qa): refactor types of main filterEditorState Sep 28, 2018
.editorconfig chore(qa): add .editorconfig from cookbook Sep 25, 2018
.env chore(demo): add analytics to demo site Jan 12, 2018
.env.production chore(demo): update GA key to the right property Jan 12, 2018
.eslintignore chore: packageify Jan 9, 2018
.eslintrc.js chore(qa): extra configs of dev tools outside of package.json Sep 25, 2018
.flowconfig chore(qa): turn on flow linting with all rules except unclear-type Sep 25, 2018
.gitignore chore(demo): add analytics to demo site Jan 12, 2018
.nvmrc chore(qa): upgrade to Node 10 Sep 25, 2018
.prettierignore chore(qa): update Prettier to latest Sep 25, 2018
.travis.yml chore(release): set up semantic-release on the project. Fix #6 Sep 25, 2018
CHANGELOG.md chore(release): v2.1.0 [skip ci] Oct 26, 2018
LICENSE chore: packageify Jan 9, 2018
README.md chore(readme): update Draftail link Oct 27, 2018
commitlint.config.js chore(qa): extra configs of dev tools outside of package.json Sep 25, 2018
dangerfile.js chore(qa): check Dangerfile with Flow Sep 28, 2018
package-lock.json chore(release): v2.1.0 [skip ci] Oct 26, 2018
package.json chore(release): v2.1.0 [skip ci] Oct 26, 2018
prettier.config.js chore(qa): extra configs of dev tools outside of package.json Sep 25, 2018
release.config.js chore(release): set up semantic-release on the project. Fix #6 Sep 25, 2018
rollup.config.js feat(api): publish package with Flow annotations built in Sep 28, 2018

README.md

Draft.js filters npm Build Status Coverage Status Wagtail

Filter Draft.js content to preserve only the formatting you allow. Built for Draftail and Wagtail.

Screenshot of Microsoft Word with tens of toolbars activated

The main use case is to select what formatting to keep when copy-pasting rich text into an editor, for example from Word or Google Docs, addressing Draft.js limitations like #166 and #504. Check out the online demo!

If you want to learn more about how this is used in practice, have a look at Rethinking rich text pipelines with Draft.js.

Using the filters

First, grab the package from npm:

npm install --save draftjs-filters

Then, in your editor import filterEditorState and call it in the Draft.js onChange handler. This function takes two parameters: the filtering configuration, and the editorState.

import { filterEditorState } from "draftjs-filters"

function onChange(nextState) {
  const { editorState } = this.state
  let filteredState = nextState

  const shouldFilterPaste =
    nextState.getCurrentContent() !== editorState.getCurrentContent() &&
    nextState.getLastChangeType() === "insert-fragment"

  if (shouldFilterPaste) {
    filteredState = filterEditorState(
      {
        blocks: ["header-two", "header-three", "unordered-list-item"],
        styles: ["BOLD"],
        entities: [
          {
            type: "IMAGE",
            attributes: ["src"],
            whitelist: {
              src: "^http",
            },
          },
          {
            type: "LINK",
            attributes: ["url"],
          },
        ],
        maxNesting: 1,
        whitespacedCharacters: ["\n", "\t", "📷"],
      },
      filteredState,
    )
  }

  this.setState({ editorState: filteredState })
}

Here are the available options:

// Whitelist of allowed block types. unstyled and atomic are always included.
blocks: Array<string>,
// Whitelist of allowed inline styles.
styles: Array<string>,
// Whitelist of allowed entities.
entities: Array<{
    // Entity type, eg. "LINK"
    type: string,
    // Allowed attributes. Other attributes will be removed.
    attributes: Array<string>,
    // Refine which entities are kept by whitelisting acceptable values with regular expression patterns.
    whitelist: {
      [attribute: string]: string,
    },
}>,
// Maximum amount of depth for lists (0 = no nesting).
maxNesting: number,
// Characters to replace with whitespace.
whitespacedCharacters: Array<string>,

Types

If your project uses Flow, type inference should just work. If you don't use Flow, it won't get in your way either.

Advanced usage

filterEditorState isn't very flexible. If you want more control over the filtering, simply compose your own filter function with the other single-purpose utilities. The Draft.js filters are published as ES6 modules using Rollup – module bundlers like Rollup and Webpack will tree shake (remove) the unused functions so you only bundle the code you use.

/**
 * Creates atomic blocks where they would be required for a block-level entity
 * to work correctly, when such an entity exists.
 * Note: at the moment, this is only useful for IMAGE entities that Draft.js
 * injects on arbitrary blocks on paste.
 */

preserveAtomicBlocks((content: ContentState))

/**
 * Resets atomic blocks to have a single-space char and no styles.
 */

resetAtomicBlocks((content: ContentState))

/**
 * Removes atomic blocks for which the entity isn't whitelisted.
 */

removeInvalidAtomicBlocks((whitelist: Array<Object>), (content: ContentState))

/**
 * Removes blocks that have a non-zero depth, and aren't list items.
 * Happens with Apple Pages inserting `unstyled` items between list items.
 */

removeInvalidDepthBlocks((content: ContentState))

/**
 * Resets the depth of all the content to at most max.
 */

limitBlockDepth((max: number), (content: ContentState))

/**
 * Changes block type and depth based on the block's text. – some word processors
 * add a specific prefix within the text, eg. "· Bulleted list" in Word 2010.
 * Also removes the matched text.
 * This is meant first and foremost for list items where the list bullet or numeral
 * ends up in the text. Other use cases may not be well covered.
 */
preserveBlockByText(
  (rules: Array<{
    test: string,
    type: string,
    depth: number,
  }>),
  (content: ContentState),
)

/**
 * Converts all block types not present in the whitelist to unstyled.
 * Also sets depth to 0 (for potentially nested list items).
 */

filterBlockTypes((whitelist: Array<string>), (content: ContentState))

/**
 * Removes all styles not present in the whitelist.
 */

filterInlineStyles((whitelist: Array<string>), (content: ContentState))

/**
 * Clones entities in the entityMap, so each range points to its own entity instance.
 * This only clones entities as necessary – if an entity is only referenced
 * in a single range, it won't be changed.
 */
cloneEntities((content: ContentState))

/**
 * Filters entity ranges (where entities are applied on text) based on the result of
 * the callback function. Returning true keeps the entity range, false removes it.
 * Draft.js automatically removes entities if they are not applied on any text.
 */

filterEntityRanges(
  (filterFn: (
    content: ContentState,
    entityKey: string,
    block: ContentBlock,
  ) => boolean),
  (content: ContentState),
)

/**
 * Keeps all entity types (images, links, documents, embeds) that are enabled.
 */

shouldKeepEntityType((whitelist: Array<Object>), (type: string))

/**
 * Removes invalid images – they should only be in atomic blocks.
 * This only removes the image entity, not the camera emoji (📷) that Draft.js inserts.
 * If we want to remove this in the future, consider that:
 * - It needs to be removed in the block text, where it's 2 chars / 1 code point.
 * - The corresponding CharacterMetadata needs to be removed too, and it's 2 instances
 */

shouldRemoveImageEntity((entityType: string), (blockType: string))

/**
 * Filters entities based on the data they contain.
 */

shouldKeepEntityByAttribute(
  (entityTypes: Array<Object>),
  (entityType: string),
  (data: Object),
)

/**
 * Filters data on an entity to only retain what is whitelisted.
 */

filterEntityData((entityTypes: Array<Object>), (content: ContentState))

/**
 * Replaces the given characters by their equivalent length of spaces, in all blocks.
 */

replaceTextBySpaces((characters: Array<string>), (content: ContentState))

Browser support and polyfills

The Draft.js filters follow the browser support targets of Draft.js. Be sure to have a look at the required Draft.js polyfills.

Word processor support

Have a look at our test data in pasting/.

Editor - Browser Chrome Windows Chrome macOS Firefox Windows Firefox macOS Edge Windows IE11 Windows Safari macOS Safari iOS Chrome Android
Word 2016 N/A N/A
Word 2010 N/A N/A N/A N/A N/A
Apple Pages N/A N/A N/A N/A N/A
Google Docs
Word Online Unsupported ? ?
Dropbox Paper Unsupported ? ?
Draft.js

Use the Draft.js Cut/Copy/Paste testing plan. We target specific external sources, and have ready-made test documents available to test them:

External sources

Here are external sources we want to pay special attention to, and for which we have ready-made test documents with diverse rich content.

IE11

There are known Draft.js issues with pasting in IE11. For now, we advise users to turn on stripPastedStyles in IE11 only so that Draft.js removes all formatting but preserves whitespace:

const IS_IE11 = !window.ActiveXObject && "ActiveXObject" in window

const editor = <Editor stripPastedStyles={IS_IE11} />

Contributing

See anything you like in here? Anything missing? We welcome all support, whether on bug reports, feature requests, code, design, reviews, tests, documentation, and more. Please have a look at our contribution guidelines.

Credits

View the full list of contributors. MIT licensed. Website content available as CC0.

Microsoft Word toolbars screenshot from PCWorld – Microsoft Word Turns 25 article.