Draft.js

repository·main·Indexed 12 days ago

https://github.com/facebookarchive/draft-js

A JavaScript rich text editor framework built for React. It uses an immutable model to provide a declarative API for managing complex text composition, including styles and embedded media. Version 0.11.7.

Tokens
38.7K
Snippets
137
Records
203
Agent score
98%

What's inside Draft.js

  1. Use RichUtils for rich text editing utilities

    main
    The RichUtils module provides a static set of utility functions designed to simplify rich text editing operations. Most methods accept an EditorState object and return a new EditorState object reflecting the changes. These utilities are useful for handling common editor interactions like toggling styles, managing block types, and handling specific key commands.
  2. What is EditorChangeType and how to use it

    main

    EditorChangeType is an enum (represented as a union of strings in Flow) that specifies the type of operation being performed when transitioning the Draft model to a new ContentState.

    It is passed as a parameter to EditorState.push(contentState, changeType). This value is critical because the Draft core uses it to determine appropriate undo/redo handling, spellcheck behavior, and other internal logic.

    Important: While you can technically pass arbitrary strings, you should only use the predefined enum values to ensure correct editor behavior. Using Flow for static typechecking is highly recommended to enforce the use of valid EditorChangeType values.

  3. What is EditorState?

    main

    EditorState is the top-level state object for the Draft.js editor. It is an Immutable Record that represents the entire state of a Draft editor, including:

    • The current text content state (ContentState)
    • The current selection state (SelectionState)
    • The fully decorated representation of the contents
    • Undo/redo stacks
    • The most recent type of change made to the contents

    Important: Do not use the standard Immutable API directly with EditorState objects. Instead, use the provided instance getters and static methods to interact with or modify the state.

  4. What is a ContentBlock?

    main

    A ContentBlock is an Immutable Record that represents the full state of a single block of editor content. It is analogous to a block-level HTML element (like a <p> or <li>).

    A ContentBlock contains:

    • Plain text contents: The raw text of the block.
    • Type: The block type (e.g., paragraph, header-one, unordered-list-item).
    • Metadata: Entity, inline style, and depth information.

    In a ContentState object, multiple ContentBlock objects are stored in an OrderedMap to comprise the full contents of the editor.

  5. What is ContentState?

    main

    ContentState is an Immutable Record that represents the complete state of a Draft.js editor. It encapsulates:

    • The entire contents: All text, block styles (e.g., headers, lists), inline styles (e.g., bold, italic), and entity ranges.
    • Two selection states: selectionBefore (the selection state before rendering) and selectionAfter (the selection state after rendering).

    In a typical workflow, you access the current state via EditorState.getCurrentContent(). Note that EditorState manages undo/redo stacks by storing sequences of ContentState objects.

  6. What is CharacterMetadata and how is it managed?

    main

    CharacterMetadata is an Immutable Record that represents the inline style and entity information for a single character.

    Key Concept: Pooling CharacterMetadata objects are aggressively pooled and shared to keep the memory footprint small. If two characters share the same inline style and entity, they point to the exact same object.

    Important Usage Rule: Because of this pooling mechanism, you must never attempt to instantiate or modify these objects directly. You must use the provided static methods (create, applyStyle, removeStyle, applyEntity) to ensure that the pooling logic is correctly utilized and that you receive either a matching pooled object or a new pooled instance.

  7. Understand SelectionState in Draft.js

    main

    A SelectionState is an Immutable Record that represents a selection range in the editor. It is most commonly accessed via EditorState.getSelection() to retrieve the current selection being rendered.

    Selection points in Draft.js are tracked using key/offset pairs rather than DOM nodes. A key identifies the specific ContentBlock, and the offset is the character position within that block.

  8. Understand the Draft default block render map

    main

    The block render map defines how HTML elements are converted into Draft block types during pasting or when using convertFromHTML. It also determines which block types are supported by the editor.

    Default Mappings:

    HTML elementDraft block type
    <h1>header-one
    <h2>header-two
    <h3>header-three
    <h4>header-four
    <h5>header-five
    <h6>header-six
    <blockquote>blockquote
    <pre>code-block
    <figure>atomic
    <li>unordered-list-item or ordered-list-item (based on parent <ul> or <ol>)
    <div>unstyled (any unrecognized block defaults to unstyled)
  9. Understand the playground folder structure

    main

    The project follows a standard Create React App structure. For the project to build correctly, the following files must exist with these exact names:

    • public/index.html: The page template.
    • src/index.js: The JavaScript entry point.

    Important constraints:

    • Processing: Only files inside src are processed by Webpack. To ensure your JS and CSS files are bundled, you must put them inside src.
    • Assets: Only files inside public can be referenced directly from public/index.html.
    • Top-level directories: You can create other top-level directories, but they will not be included in the production build (useful for documentation).
    my-app/
      README.md
      node_modules/
      package.json
      public/
        index.html
        favicon.ico
      src/
        App.css
        App.js
        App.test.js
        index.css
        index.js
        logo.svg
  10. Structure of the Universal Rendering Example

    main

    The universal rendering demo consists of three primary files that implement the isomorphic pattern:

    • editor.js: Defines and exports a <SimpleEditor /> component, which is a basic Draft.js editor.
    • client.js: The client-side entrypoint. It handles the client-side rendering of the index page logic into a DOM element with the ID #react-content.
    • index.js: An Express server that performs server-side prerendering of the <SimpleEditor /> into the #react-content div before sending the HTML to the client.
  11. Render decorated ranges using treeMap

    main

    The treeMap is an OrderedMap<string, List> representing the fully decorated and styled tree of ranges to be rendered. It is generated based on the ContentState and an optional DraftDecoratorType.

    At render time, components should iterate through the treeMap object to render decorated and styled ranges, typically using the getBlockTree() method to navigate the structure.