Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

draftjs-filters

Package Overview
Dependencies
Maintainers
1
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

draftjs-filters

Filter Draft.js content to preserve only the formatting you allow

  • 0.3.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4.5K
decreased by-7.92%
Maintainers
1
Weekly downloads
 
Created
Source

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 filter out disallowed formattings when copy-pasting rich text into an editor, for example from Word or Google Docs. Check out the online demo!

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(nextEditorState) {
  const { editorState } = this.state
  const content = editorState.getCurrentContent()
  const nextContent = nextEditorState.getCurrentContent()
  const shouldFilterPaste =
    nextContent !== content &&
    nextEditorState.getLastChangeType() === "insert-fragment"

  let filteredEditorState = nextEditorState
  if (shouldFilterPaste) {
    filteredEditorState = 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", "📷"],
      },
      filteredEditorState,
    )
  }

  this.setState({ editorState: filteredEditorState })
}

Here are the available options:

// Whitelist of allowed block types. unstyled and atomic are always included.
blocks: Array<DraftBlockType>,
// 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: Object,
}>,
// Maximum amount of depth for lists (0 = no nesting).
maxNesting: number,
// Characters to replace with whitespace.
whitespacedCharacters: Array<string>,

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))

/**
 * Removes all block types not present in the whitelist.
 */

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

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

filterInlineStyles((whitelist: Array<string>), (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: DraftBlockType))

/**
 * 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 - BrowserChrome WindowsChrome macOSFirefox WindowsFirefox macOSEdge WindowsIE11 WindowsSafari macOSSafari iOSChrome Android
Word 2016N/AN/A
Word 2010N/AN/AN/AN/AN/A
Apple PagesN/AN/AN/AN/AN/A
Google Docs
Word OnlineUnsupported??
Dropbox PaperUnsupported??
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.

Development

Install

Clone the project on your computer, and install Node. This project also uses nvm.

nvm install
# Then, install all project dependencies.
npm install
# Install the git hooks.
./.githooks/deploy

Working on the project

Everything mentioned in the installation process should already be done.

# Make sure you use the right node version.
nvm use
# Start the server and the development tools.
npm run start
# Runs linting.
npm run lint
# Start a Flow server for type errors.
npm run flow
# Re-formats all of the files in the project (with Prettier).
npm run format
# Run tests in a watcher.
npm run test:watch
# Run test coverage
npm run test:coverage
# Open the coverage report with:
npm run report:coverage
# Open the build report with:
npm run report:build
# View other available commands with:
npm run

Releases

Use npm run release, which uses standard-version to generate the CHANGELOG and decide on the version bump based on the commits since the last release.

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.

Keywords

FAQs

Package last updated on 15 Jan 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc