Skip to content

Instantly share code, notes, and snippets.

@bjacobel
Last active May 21, 2018 11:54
Show Gist options
  • Save bjacobel/a428149d999ea4bf878919b86296a87d to your computer and use it in GitHub Desktop.
Save bjacobel/a428149d999ea4bf878919b86296a87d to your computer and use it in GitHub Desktop.

Table of Contents

DraftEditor

Extends React.Component

DraftEditor is the root editor component. It composes a contentEditable div, and provides a wide variety of useful function props for managing the state of the editor. See DraftEditorProps for details.

Parameters

  • props DraftEditorProps

_onBeforeInput

Define proxies that can route events to the current handler.

Type: Function

_buildHandler

Build a method that will pass the event to the specified handler method. This allows us to look up the correct handler function for the current editor mode, if any has been specified.

Parameters

Returns Function

componentWillUpdate

Prevent selection events from affecting the current editor state. This is mostly intended to defend against IE, which fires off selectionchange events regardless of whether the selection is set via the browser or programmatically. We only care about selection events that occur because of browser interaction, not re-renders and forced selections.

Parameters

  • nextProps DraftEditorProps

Returns void

_focus

Used via this.focus().

Force focus back onto the editor node.

Forcing focus causes the browser to scroll to the top of the editor, which may be undesirable when the editor is taller than the viewport. To solve this, either use a specified scroll position (in cases like cut behavior where it should be restored to a known position) or store the current scroll state and put it back in place after focus has been forced.

Parameters

  • scrollPosition DraftScrollPosition

Returns void

_setMode

Used via this.setMode(...).

Set the behavior mode for the editor component. This switches the current handler module to ensure that DOM events are managed appropriately for the active mode.

Parameters

  • mode DraftEditorModes

Returns void

_restoreEditorDOM

Used via this.restoreEditorDOM().

Force a complete re-render of the DraftEditorContents based on the current EditorState. This is useful when we know we are going to lose control of the DOM state (cut command, IME) and we want to make sure that reconciliation occurs on a version of the DOM that is synchronized with our EditorState.

Parameters

  • scrollPosition DraftScrollPosition

Returns void

_setClipboard

Used via this.setClipboard(...).

Set the clipboard state for a cut/copy event.

Parameters

  • clipboard BlockMap?

Returns void

_getClipboard

Used via this.getClipboard().

Retrieve the clipboard state for a cut/copy event.

Returns BlockMap?

_update

Used via this.update(...).

Propagate a new EditorState object to higher-level components. This is the method by which event handlers inform the DraftEditor component of state changes. A component that composes a DraftEditor must provide an onChange prop to receive state updates passed along from this function.

Parameters

  • editorState EditorState

Returns void

_onDragEnter

Used in conjunction with _onDragLeave(), by counting the number of times a dragged element enters and leaves the editor (or any of its children), to determine when the dragged element absolutely leaves the editor.

Returns void

_onDragLeave

See _onDragEnter().

Returns void

isIE

IE has a hardcoded "feature" that attempts to convert link text into anchors in contentEditable DOM. This breaks the editor's expectations of the DOM, and control is lost. Disable it to make IE behave. See: http://blogs.msdn.com/b/ieinternals/archive/2010/09/15/ ie9-beta-minor-change-list.aspx

DraftEditorPlaceholder

Extends React.Component

This component is responsible for rendering placeholder text for the DraftEditor component.

Override placeholder style via CSS.

editorState

The two most critical props are editorState and onChange.

The editorState prop defines the entire state of the editor, while the onChange prop is the method in which all state changes are propagated upward to higher-level components.

These props are analogous to value and onChange in controlled React text inputs.

handleReturn

Cancelable event handlers, handled from the top level down. A handler that returns handled will be the last handler to execute for that event.

onEscape

Non-cancelable event triggers.

DraftEditorBlock

Extends React.Component

The default block renderer for a DraftEditor component.

A DraftEditorBlock is able to render a given ContentBlock to its appropriate decorator and inline style components.

componentDidMount

When a block is mounted and overlaps the selection state, we need to make sure that the cursor is visible to match native behavior. This may not be the case if the user has pressed RETURN or pasted some content, since programatically creating these new blocks and setting the DOM selection will miss out on the browser natively scrolling to that position.

To replicate native behavior, if the block overlaps the selection state on mount, force the scroll position. Check the scroll state of the scroll parent, and adjust it to align the entire block to the bottom of the scroll parent.

Returns void

isBlockOnSelectionEdge

Return whether a block overlaps with either edge of the SelectionState.

Parameters

  • selection SelectionState
  • key string

Returns boolean

DraftEditorContents

Extends React.Component

DraftEditorContents is the container component for all block components rendered for a DraftEditor. It is optimized to aggressively avoid re-rendering blocks whenever possible.

This component is separate from DraftEditor because certain props (for instance, ARIA props) must be allowed to update without affecting the contents of the editor.

getListItemClasses

Provide default styling for list items. This way, lists will be styled with proper counters and indentation even if the caller does not specify their own styling at all. If more than five levels of nesting are needed, the necessary CSS classes can be provided via blockStyleFn configuration.

Parameters

Returns string

DraftEditorLeaf

Extends React.Component

All leaf nodes in the editor are spans with single text nodes. Leaf elements are styled based on the merging of an optional custom style map and a default style map.

DraftEditorLeaf also provides a wrapper for calling into the imperative DOM Selection API. In this way, top-level components can declaratively maintain the selection state.

_setSelection

By making individual leaf instances aware of their context within the text of the editor, we can set our selection range more easily than we could in the non-React world.

Note that this depends on our maintaining tight control over the DOM structure of the DraftEditor component. If leaves had multiple text nodes, this would be harder.

Returns void

isNewline

Check whether the node should be considered a newline.

Parameters

Returns boolean

NEWLINE_A

Placeholder elements for empty text content.

What is this data-text attribute, anyway? It turns out that we need to put an attribute on the lowest-level text node in order to preserve correct spellcheck handling. If the is naked, Chrome and Safari may do bizarre things to do the DOM -- split text nodes, create extra spans, etc. If the has an attribute, this appears not to happen. See http://jsfiddle.net/9khdavod/ for the failure case, and http://jsfiddle.net/7pg143f7/ for the fixed case.

DraftEditorTextNode

Extends React.Component

The lowest-level component in a DraftEditor, the text node component replaces the default React text node implementation. This allows us to perform custom handling of newline behavior and avoid re-rendering text nodes with DOM state that already matches the expectations of our immutable editor state.

Parameters

  • props Props

RESOLVE_DELAY

Millisecond delay to allow compositionstart to fire again upon compositionend.

This is used for Korean input to ensure that typing can continue without the editor trying to render too quickly. More specifically, Safari 7.1+ triggers compositionstart a little slower than Chrome/FF, which leads to composed characters being resolved and re-render occurring sooner than we want.

Type: number

resolved

A handful of variables used to track the current composition and its resolution status. These exist at the module level because it is not possible to have compositions occurring in multiple editors simultaneously, and it simplifies state management with respect to the DraftEditor component.

onCompositionStart

A compositionstart event has fired while we're still in composition mode. Continue the current composition session to prevent a re-render.

Parameters

Returns void

onCompositionEnd

Attempt to end the current composition session.

Defer handling because browser will still insert the chars into active element after compositionend. If a compositionstart event fires before resolveComposition executes, our composition session will continue.

The resolved flag is useful because certain IME interfaces fire the compositionend event multiple times, thus queueing up multiple attempts at handling the composition. Since handling the same composition event twice could break the DOM, we only use the first event. Example: Arabic Google Input Tools on Windows 8.1 fires compositionend three times.

Parameters

Returns void

onKeyDown

In Safari, keydown events may fire when committing compositions. If the arrow keys are used to commit, prevent default so that the cursor doesn't move, otherwise it will jump back noticeably on re-render.

Parameters

Returns void

onKeyPress

Keypress events may fire when committing compositions. In Firefox, pressing RETURN commits the composition and inserts extra newline characters that we do not want. preventDefault allows the composition to be committed while preventing the extra characters.

Parameters

Returns void

resolveComposition

Attempt to insert composed characters into the document.

If we are still in a composition session, do nothing. Otherwise, insert the characters into the document and terminate the composition session.

If no characters were composed -- for instance, the user deleted all composed characters and committed nothing new -- force a re-render. We also re-render when the composition occurs at the beginning of a leaf, to ensure that if the browser has created a new text node for the composition, we will discard it.

Resetting innerHTML will move focus to the beginning of the editor, so we update to force it back to the correct place.

Parameters

Returns void

edit is the most common mode for text entry. This includes most typing, deletion, cut/copy/paste, and other behaviors.

composite mode handles IME text entry.

drag mode handles editor behavior while a drag event is occurring.

cut mode allows us to effectively ignore all edit behaviors while thebrowser performs a nativecut` operation on the DOM.

render mode is the normal "null" mode, during which no edit behavior is expected or observed.

getSelectionForEvent

Get a SelectionState for the supplied mouse event.

Parameters

  • event Object
  • editorState EditorState

Returns SelectionState?

onDragEnd

Drag originating from input terminated.

Parameters

Returns void

onDrop

Handle data being dropped.

Parameters

Returns void

insertTextAtSelection

Insert text at a specified selection.

Parameters

  • editorState EditorState
  • selection SelectionState
  • text string

Returns EditorState

keyCommandBackspaceWord

Delete the word that is left of the cursor, as well as any spaces or punctuation after the word.

Parameters

  • editorState EditorState

Returns EditorState

keyCommandDeleteWord

Delete the word that is right of the cursor, as well as any spaces or punctuation before the word.

Parameters

  • editorState EditorState

Returns EditorState

keyCommandMoveSelectionToEndOfBlock

See comment for moveSelectionToStartOfBlock.

Parameters

  • editorState EditorState

Returns EditorState

keyCommandMoveSelectionToStartOfBlock

Collapse selection at the start of the first selected block. This is used for Firefox versions that attempt to navigate forward/backward instead of moving the cursor. Other browsers are able to move the cursor natively.

Parameters

  • editorState EditorState

Returns EditorState

keyCommandPlainBackspace

Remove the selected range. If the cursor is collapsed, remove the preceding character. This operation is Unicode-aware, so removing a single character will remove a surrogate pair properly as well.

Parameters

  • editorState EditorState

Returns EditorState

keyCommandPlainDelete

Remove the selected range. If the cursor is collapsed, remove the following character. This operation is Unicode-aware, so removing a single character will remove a surrogate pair properly as well.

Parameters

  • editorState EditorState

Returns EditorState

keyCommandTransposeCharacters

Transpose the characters on either side of a collapsed cursor, or if the cursor is at the end of the block, transpose the last two characters.

Parameters

  • editorState EditorState

Returns EditorState

moveSelectionBackward

Given a collapsed selection, move the focus maxDistance backward within the selected block. If the selection will go beyond the start of the block, move focus to the end of the previous block, but no further.

This function is not Unicode-aware, so surrogate pairs will be treated as having length 2.

Parameters

  • editorState EditorState
  • maxDistance number

Returns SelectionState

moveSelectionForward

Given a collapsed selection, move the focus maxDistance forward within the selected block. If the selection will go beyond the end of the block, move focus to the start of the next block, but no further.

This function is not Unicode-aware, so surrogate pairs will be treated as having length 2.

Parameters

  • editorState EditorState
  • maxDistance number

Returns SelectionState

removeTextWithStrategy

For a collapsed selection state, remove text based on the specified strategy. If the selection state is not collapsed, remove the entire selected range.

Parameters

  • editorState EditorState
  • strategy function (editorState: EditorState): SelectionState
  • direction DraftRemovalDirection

Returns ContentState

SecondaryClipboard

Some systems offer a "secondary" clipboard to allow quick internal cut and paste behavior. For instance, Ctrl+K (cut) and Ctrl+Y (paste).

replaceText

Replace the current selection with the specified text string, with the inline style and entity key applied to the newly inserted text.

Parameters

  • editorState EditorState
  • text string
  • inlineStyle DraftInlineStyle
  • entityKey string?

Returns EditorState

editOnBeforeInput

When onBeforeInput executes, the browser is attempting to insert a character into the editor. Apply this character data to the document, allowing native insertion if possible.

Native insertion is encouraged in order to limit re-rendering and to preserve spellcheck highlighting, which disappears or flashes if re-render occurs on the relevant text nodes.

Parameters

Returns void

editOnCompositionStart

The user has begun using an IME input system. Switching to composite mode allows handling composition input and disables other edit behavior.

Parameters

Returns void

editOnCopy

If we have a selection, create a ContentState fragment and store it in our internal clipboard. Subsequent paste events will use this fragment if no external clipboard data is supplied.

Parameters

Returns void

editOnCut

On cut events, native behavior is allowed to occur so that the system clipboard is set properly. This means that we need to take steps to recover the editor DOM state after the cut has occurred in order to maintain control of the component.

In addition, we can keep a copy of the removed fragment, including all styles and entities, for use as an internal paste.

Parameters

Returns void

editOnDragOver

Drag behavior has begun from outside the editor element.

Parameters

Returns void

editOnDragStart

A dragstart event has begun within the text editor component.

Parameters

Returns void

editOnInput

This function is intended to handle spellcheck and autocorrect changes, which occur in the DOM natively without any opportunity to observe or interpret the changes before they occur.

The input event fires in contentEditable elements reliably for non-IE browsers, immediately after changes occur to the editor DOM. Since our other handlers override or otherwise handle cover other varieties of text input, the DOM state should match the model in all controlled input cases. Thus, when an input change leads to a DOM/model mismatch, the change should be due to a spellcheck change, and we can incorporate it into our model.

Parameters

Returns void

onKeyCommand

Map a DraftEditorCommand command value to a corresponding function.

Parameters

Returns EditorState

editOnKeyDown

Intercept keydown behavior to handle keys and commands manually, if desired.

Keydown combinations may be mapped to DraftCommand values, which may correspond to command functions that modify the editor or its contents.

See getDefaultKeyBinding for defaults. Alternatively, the top-level component may provide a custom mapping via the keyBindingFn prop.

Parameters

Returns void

editOnPaste

Paste content.

Parameters

Returns void

describe

Test possible selection states for the text editor. This is based on far too many hours of manual testing and bug fixes, and still may not be a completely accurate representation of all subtle and bizarre differences in implementations and APIs across browsers and operating systems.

Welcome to the jungle.

describe

FF: Triple-clicking a block leads to an entire block being selected, with the first text node as the anchor (0 offset) and the block element as the focus (childNodes.length offset)

describe

In some scenarios, the entire editor may be selected by command-A.

describe

A selection possibility that defies logic. In IE11, triple clicking a block leads to the text node being selected as the anchor, and the entire editor being selected as the focus. Ludicrous.

UnicodeUtils

getLineHeightPx

Return the computed line height, in pixels, for the provided element.

Parameters

Returns number

areRectsOnOneLine

Return whether every ClientRect in the provided list lies on the same line.

We assume that the rects on the same line all contain the baseline, so the lowest top line needs to be above the highest bottom line (i.e., if you were to project the rects onto the y-axis, their intersection would be nonempty).

In addition, we require that no two boxes are lineHeight (or more) apart at either top or bottom, which helps protect against false positives for fonts with extremely large glyph heights (e.g., with a font size of 17px, Zapfino produces rects of height 58px!).

Parameters

Returns boolean

getNodeLength

Return the length of a node, as used by Range offsets.

Parameters

Returns number

expandRangeToStartOfLine

Given a collapsed range, move the start position backwards as far as possible while the range still spans only a single line.

Parameters

Returns Range

findAncestorOffsetKey

Get the key from the node's nearest offset-aware ancestor.

Parameters

Returns string?

getDraftEditorSelection

Convert the current selection range to an anchor/focus pair of offset keys and values that can be interpreted by components.

Parameters

Returns DOMDerivedSelection

getDraftEditorSelectionWithNodes

Convert the current selection range to an anchor/focus pair of offset keys and values that can be interpreted by components.

Parameters

Returns DOMDerivedSelection

getFirstLeaf

Identify the first leaf descendant for the given node.

Parameters

Returns Node

getLastLeaf

Identify the last leaf descendant for the given node.

Parameters

Returns Node

getTextContentLength

Return the length of a node's textContent, regarding single newline characters as zero-length. This allows us to avoid problems with identifying the correct selection offset for empty blocks in IE, in which we render newlines instead of break tags.

Parameters

Returns number

getRangeBoundingClientRect

Like range.getBoundingClientRect() but normalizes for browser bugs.

Parameters

Returns FakeClientRect

getRangeClientRects

Like range.getClientRects() but normalizes for browser bugs.

getSelectionOffsetKeyForNode

Get offset key from a node or it's child nodes. Return the first offset key found on the DOM tree of given node.

Parameters

Returns string?

getVisibleSelectionRect

Return the bounding ClientRect for the visible DOM selection, if any. In cases where there are no selected ranges or the bounding rect is temporarily invalid, return null.

Parameters

  • global any

Returns FakeClientRect?

setDraftEditorSelection

In modern non-IE browsers, we can support both forward and backward selections.

Note: IE10+ supports the Selection object, but it does not support the extend method, which means that even in modern IE, it's not possible to programatically create a backward selection. Thus, for all IE versions, we use the old IE API to create our selections.

Parameters

Returns void

addFocusToSelection

Extend selection towards focus point.

Parameters

Returns void

Copyright 2013-present, Facebook, Inc.

getZCommand

Get the appropriate undo/redo command for a Z key command.

Parameters

  • e SyntheticKeyboardEvent

Returns DraftEditorCommand?

getDefaultKeyBinding

Retrieve a bound key command for the given event.

Parameters

  • e SyntheticKeyboardEvent

Returns DraftEditorCommand?

getTextContentFromFiles

Extract the text content from a file list.

Parameters

  • files Array<File>
  • callback function (contents: string): void

Returns void

readFile

todo isaac: Do work to turn html/rtf into a content fragment.

Parameters

  • file File
  • callback function (contents: string): void

Returns void

isEventHandled

Utility method for determining whether or not the value returned from a handler indicates that it was handled.

Parameters

Returns boolean

isCtrlKeyCommand

Check whether the ctrlKey modifier is not being used in conjunction with the altKey modifier. If they are combined, the result is an altGraph key modifier, which should not be handled by this set of key bindings.

Parameters

  • e SyntheticKeyboardEvent

Returns boolean

DraftBlockType

The list of default valid block types.

Type: ("unstyled" | "paragraph" | "header-one" | "header-two" | "header-three" | "header-four" | "header-five" | "header-six" | "unordered-list-item" | "ordered-list-item" | "blockquote" | "code-block" | "atomic")

DraftDragType

A type that allows us to avoid passing boolean arguments around to indicate whether a drag type is internal or external.

Type: ("internal" | "external")

DraftEditorCommand

A set of editor commands that may be invoked by keyboard commands or UI controls. These commands should map to operations that modify content or selection state and update the editor state accordingly.

Type: ("undo" | "redo" | "delete" | "delete-word" | "backspace" | "backspace-word" | "backspace-to-start-of-line" | "bold" | "italic" | "underline" | "code" | "split-block" | "transpose-characters" | "move-selection-to-start-of-block" | "move-selection-to-end-of-block" | "secondary-cut" | "secondary-paste")

Self-explanatory.

Perform a forward deletion.

Perform a forward deletion to the next word boundary after the selection.

Perform a backward deletion.

Perform a backward deletion to the previous word boundary before the selection.

Perform a backward deletion to the beginning of the current line.

Toggle styles. Commands may be intepreted to modify inline text ranges or block types.

Split a block in two.

Self-explanatory.

Commands to support the "secondary" clipboard provided by certain browsers and operating systems.

DraftHandleValue

A type that allows us to avoid returning boolean values to indicate whether an event was handled or not.

Type: ("handled" | "not-handled")

DraftInsertionType

A type that defines if an fragment shall be inserted before or after another fragment or if the selected fragment shall be replaced

Type: ("replace" | "before" | "after")

DraftRemovalDirection

A type that allows us to avoid passing boolean arguments around to indicate whether a deletion is forward or backward.

Type: ("backward" | "forward")

unmock

CompositeDraftDecorator

A CompositeDraftDecorator traverses through a list of DraftDecorator instances to identify sections of a ContentBlock that should be rendered in a "decorated" manner. For example, hashtags, mentions, and links may be intended to stand out visually, be rendered as anchors, etc.

The list of decorators supplied to the constructor will be used in the order they are provided. This allows the caller to specify a priority for string matching, in case of match collisions among decorators.

For instance, I may have a link with a # in its text. Though this section of text may match our hashtag decorator, it should not be treated as a hashtag. I should therefore list my link DraftDecorator before my hashtag DraftDecorator when constructing this composite decorator instance.

Thus, when a collision like this is encountered, the earlier match is preserved and the new match is discarded.

Parameters

canOccupySlice

Determine whether we can occupy the specified slice of the decorations array.

Parameters

Returns boolean

occupySlice

Splice the specified component into our decoration array at the desired range.

Parameters

Returns void

DraftDecorator

A DraftDecorator is a strategy-component pair intended for use when rendering content.

  • A "strategy": A function that accepts a ContentBlock object and continuously executes a callback with start/end values corresponding to relevant matches in the document text. For example, getHashtagMatches uses a hashtag regex to find hashtag strings in the block, and for each hashtag match, executes the callback with start/end pairs.

  • A "component": A React component that will be used to render the "decorated" section of text.

  • "props": Props to be passed into the React component that will be used.

Type: {strategy: DraftDecoratorStrategy, component: Function, props: Object?}

Properties

DraftDecoratorType

An interface for document decorator classes, allowing the creation of custom decorator classes.

See CompositeDraftDecorator for the most common use case.

Type: {getDecorations: function (block: ContentBlock, contentState: ContentState): List<string?>, getComponentForKey: function (key: string): Function, getPropsForKey: function (key: string): Object?}

Properties

  • getDecorations function (block: ContentBlock, contentState: ContentState): List<string?>
  • getComponentForKey function (key: string): Function
  • getPropsForKey function (key: string): Object?

getDecorations

Given a ContentBlock, return an immutable List of decorator keys.

getComponentForKey

Given a decorator key, return the component to use when rendering this decorated range.

getPropsForKey

Given a decorator key, optionally return the props to use when rendering this decorated range.

disableAutomock

disableAutomock

disableAutomock

containsSemanticBlockMarkup

Check to see if we have anything like <p> <blockquote> <h1>... to create block tags from. If we do, we can use those and ignore

tags. If we don't, we can treat <div> tags as meaningful (unstyled) blocks.

Parameters

Returns boolean

decodeEntityRanges

Convert to native JavaScript string lengths to determine ranges.

Parameters

Returns Array<string?>

decodeInlineStyleRanges

Convert to native JavaScript string lengths to determine ranges.

Parameters

Returns Array<DraftInlineStyle>

encodeEntityRanges

Convert to UTF-8 character counts for storage.

Parameters

  • block ContentBlock
  • storageMap Object

Returns Array<EntityRange>

getEncodedInlinesForType

Helper function for getting encoded styles for each inline style. Convert to UTF-8 character counts for storage.

Parameters

  • block ContentBlock
  • styleList List<DraftInlineStyle>
  • styleToEncode string

Returns Array<InlineStyleRange>

EntityRange

A plain object representation of an entity attribution.

The key value corresponds to the key of the entity in the entityMap of a ComposedText object, not for use with DraftEntity.get().

Type: {key: number, offset: number, length: number}

Properties

InlineStyleRange

A plain object representation of an inline style range.

Type: {style: string, offset: number, length: number}

Properties

RawDraftContentBlock

A plain object representation of a ContentBlock, with all style and entity attribution repackaged as range objects.

Type: {key: string?, type: DraftBlockType, text: string, depth: number?, inlineStyleRanges: Array<InlineStyleRange>?, entityRanges: Array<EntityRange>?, data: Object?}

Properties

RawDraftContentState

A type that represents a composed document as vanilla JavaScript objects, with all styles and entities represented as ranges. Corresponding entity objects are packaged as objects as well.

This object is especially useful when sending the document state to the server for storage, as its representation is more concise than our immutable objects.

Type: {blocks: Array<RawDraftContentBlock>, entityMap: {}}

Properties

RawDraftEntity

A plain object representation of an EntityInstance.

Type: {type: DraftEntityType, mutability: DraftEntityMutability, data: {}?}

Properties

DraftEntity

getLastCreatedEntityKey

WARNING: This method will be deprecated soon!

Please use 'contentState.getLastCreatedEntityKey' instead.

Get the random key string from whatever entity was last created. We need this to support the new API, as part of transitioning to put Entity storage in contentState.

Returns string

create

WARNING: This method will be deprecated soon!

Please use 'contentState.createEntity' instead.

Create a DraftEntityInstance and store it for later retrieval.

A random key string will be generated and returned. This key may be used to track the entity's usage in a ContentBlock, and for retrieving data about the entity at render time.

Parameters

Returns string

add

WARNING: This method will be deprecated soon!

Please use 'contentState.addEntity' instead.

Add an existing DraftEntityInstance to the DraftEntity map. This is useful when restoring instances from the server.

Parameters

Returns string

get

WARNING: This method will be deprecated soon!

Please use 'contentState.getEntity' instead.

Retrieve the entity corresponding to the supplied key string.

Parameters

Returns DraftEntityInstance

mergeData

WARNING: This method will be deprecated soon!

Please use 'contentState.mergeEntityData' instead.

Entity instances are immutable. If you need to update the data for an instance, this method will merge your data updates and return a new instance.

Parameters

Returns DraftEntityInstance

replaceData

WARNING: This method will be deprecated soon!

Please use 'contentState.replaceEntityData' instead.

Completely replace the data for a given instance.

Parameters

Returns DraftEntityInstance

__getLastCreatedEntityKey

Get the random key string from whatever entity was last created. We need this to support the new API, as part of transitioning to put Entity storage in contentState.

Returns string

__create

Create a DraftEntityInstance and store it for later retrieval.

A random key string will be generated and returned. This key may be used to track the entity's usage in a ContentBlock, and for retrieving data about the entity at render time.

Parameters

Returns string

__add

Add an existing DraftEntityInstance to the DraftEntity map. This is useful when restoring instances from the server.

Parameters

Returns string

__get

Retrieve the entity corresponding to the supplied key string.

Parameters

Returns DraftEntityInstance

__mergeData

Entity instances are immutable. If you need to update the data for an instance, this method will merge your data updates and return a new instance.

Parameters

Returns DraftEntityInstance

__replaceData

Completely replace the data for a given instance.

Parameters

Returns DraftEntityInstance

DraftEntity

A "document entity" is an object containing metadata associated with a piece of text in a ContentBlock.

For example, a link entity might include a uri property. When a ContentBlock is rendered in the browser, text that refers to that link entity may be rendered as an anchor, with the uri as the href value.

In a ContentBlock, every position in the text may correspond to zero or one entities. This correspondence is tracked using a key string, generated via DraftEntity.create() and used to obtain entity metadata via DraftEntity.get().

Type: DraftEntityMapObject

getLastCreatedEntityKey

WARNING: This method will be deprecated soon!

Please use 'contentState.getLastCreatedEntityKey' instead.

Get the random key string from whatever entity was last created. We need this to support the new API, as part of transitioning to put Entity storage in contentState.

Returns string

create

WARNING: This method will be deprecated soon!

Please use 'contentState.createEntity' instead.

Create a DraftEntityInstance and store it for later retrieval.

A random key string will be generated and returned. This key may be used to track the entity's usage in a ContentBlock, and for retrieving data about the entity at render time.

Parameters

Returns string

add

WARNING: This method will be deprecated soon!

Please use 'contentState.addEntity' instead.

Add an existing DraftEntityInstance to the DraftEntity map. This is useful when restoring instances from the server.

Parameters

Returns string

get

WARNING: This method will be deprecated soon!

Please use 'contentState.getEntity' instead.

Retrieve the entity corresponding to the supplied key string.

Parameters

Returns DraftEntityInstance

mergeData

WARNING: This method will be deprecated soon!

Please use 'contentState.mergeEntityData' instead.

Entity instances are immutable. If you need to update the data for an instance, this method will merge your data updates and return a new instance.

Parameters

Returns DraftEntityInstance

replaceData

WARNING: This method will be deprecated soon!

Please use 'contentState.replaceEntityData' instead.

Completely replace the data for a given instance.

Parameters

Returns DraftEntityInstance

__getLastCreatedEntityKey

Get the random key string from whatever entity was last created. We need this to support the new API, as part of transitioning to put Entity storage in contentState.

Returns string

__create

Create a DraftEntityInstance and store it for later retrieval.

A random key string will be generated and returned. This key may be used to track the entity's usage in a ContentBlock, and for retrieving data about the entity at render time.

Parameters

Returns string

__add

Add an existing DraftEntityInstance to the DraftEntity map. This is useful when restoring instances from the server.

Parameters

Returns string

__get

Retrieve the entity corresponding to the supplied key string.

Parameters

Returns DraftEntityInstance

__mergeData

Entity instances are immutable. If you need to update the data for an instance, this method will merge your data updates and return a new instance.

Parameters

Returns DraftEntityInstance

__replaceData

Completely replace the data for a given instance.

Parameters

Returns DraftEntityInstance

DraftEntityInstance

DraftEntityInstance

Extends DraftEntityInstanceRecord

An instance of a document entity, consisting of a type and relevant data, metadata about the entity.

For instance, a "link" entity might provide a URI, and a "mention" entity might provide the mentioned user's ID. These pieces of data may be used when rendering the entity as part of a ContentBlock DOM representation. For a link, the data would be used as an href for the rendered anchor. For a mention, the ID could be used to retrieve a hovercard.

logWarning

Temporary utility for generating the warnings

Parameters

  • oldMethodCall
  • newMethodCall

DraftEntityMutability

An enum representing the possible "mutability" options for an entity. This refers to the behavior that should occur when inserting or removing characters in a text range with an entity applied to it.

MUTABLE: The text range can be modified freely. Generally used in cases where the text content and the entity do not necessarily have a direct relationship. For instance, the text and URI for a link may be completely different. The user is allowed to edit the text as needed, and the entity is preserved and applied to any characters added within the range.

IMMUTABLE: Not to be confused with immutable data structures used to represent the state of the editor. Immutable entity ranges cannot be modified in any way. Adding characters within the range will remove the entity from the entire range. Deleting characters will delete the entire range. Example: Facebook Page mentions.

SEGMENTED: Segmented entities allow the removal of partial ranges of text, as separated by a delimiter. Adding characters wihin the range will remove the entity from the entire range. Deleting characters within a segmented entity will delete only the segments affected by the deletion. Example: Facebook User mentions.

Type: $Keys<any>

getEntityKeyForSelection

Return the entity key that should be used when inserting text for the specified target selection, only if the entity is MUTABLE. IMMUTABLE and SEGMENTED entities should not be used for insertion behavior.

Parameters

  • contentState ContentState
  • targetSelection SelectionState

Returns string?

filterKey

Determine whether an entity key corresponds to a MUTABLE entity. If so, return it. If not, return null.

Parameters

  • entityMap EntityMap
  • entityKey string?

Returns string?

getTextAfterNearestEntity

Find the string of text between the previous entity and the specified offset. This allows us to narrow down search areas for regex matching.

Parameters

  • block ContentBlock
  • offset number

Returns string

generate

Generate a block tree for a given ContentBlock/decorator pair.

Parameters

Returns List<DecoratorRange>

getFingerprint

Create a string representation of the given tree map. This allows us to rapidly determine whether a tree has undergone a significant structural change.

Parameters

  • tree List<DecoratorRange>

Returns string

generateLeaves

Generate LeafRange records for a given character list.

Parameters

  • characters List<CharacterMetadata>
  • offset number

Returns List<LeafRange>

create

Use this function instead of the CharacterMetadata constructor. Since most content generally uses only a very small number of style/entity permutations, we can reuse these objects as often as possible.

Parameters

  • config CharacterMetadataConfig

Returns CharacterMetadata

findStyleRanges

Execute a callback for every contiguous range of styles within the block.

Parameters

  • filterFn function (value: CharacterMetadata): boolean
  • callback function (start: number, end: number): void

Returns void

findEntityRanges

Execute a callback for every contiguous range of entities within the block.

Parameters

  • filterFn function (value: CharacterMetadata): boolean
  • callback function (start: number, end: number): void

Returns void

getInlineStyleOverride

While editing, the user may apply inline style commands with a collapsed cursor, intending to type text that adopts the specified style. In this case, we track the specified style as an "override" that takes precedence over the inline style of the text adjacent to the cursor.

If null, there is no override in place.

Returns DraftInlineStyle?

getCurrentInlineStyle

Get the appropriate inline style for the editor state. If an override is in place, use it. Otherwise, the current style is based on the location of the selection state.

Returns DraftInlineStyle

constructor

Not for public consumption.

Parameters

  • immutable EditorStateRecord

getImmutable

Not for public consumption.

Returns EditorStateRecord

acceptSelection

Incorporate native DOM selection changes into the EditorState. This method can be used when we simply want to accept whatever the DOM has given us to represent selection, and we do not need to re-render the editor.

To forcibly move the DOM selection, see EditorState.forceSelection.

Parameters

  • editorState EditorState
  • selection SelectionState

Returns EditorState

forceSelection

At times, we need to force the DOM selection to be where we need it to be. This can occur when the anchor or focus nodes are non-text nodes, for instance. In this case, we want to trigger a re-render of the editor, which in turn forces selection into the correct place in the DOM. The forceSelection method accomplishes this.

This method should be used in cases where you need to explicitly move the DOM selection from one place to another without a change in ContentState.

Parameters

  • editorState EditorState
  • selection SelectionState

Returns EditorState

moveSelectionToEnd

Move selection to the end of the editor without forcing focus.

Parameters

  • editorState EditorState

Returns EditorState

moveFocusToEnd

Force focus to the end of the editor. This is useful in scenarios where we want to programmatically focus the input and it makes sense to allow the user to continue working seamlessly.

Parameters

  • editorState EditorState

Returns EditorState

push

Push the current ContentState onto the undo stack if it should be considered a boundary state, and set the provided ContentState as the new current content.

Parameters

  • editorState EditorState
  • contentState ContentState
  • changeType EditorChangeType

Returns EditorState

undo

Make the top ContentState in the undo stack the new current content and push the current content onto the redo stack.

Parameters

  • editorState EditorState

Returns EditorState

redo

Make the top ContentState in the redo stack the new current content and push the current content onto the undo stack.

Parameters

  • editorState EditorState

Returns EditorState

updateSelection

Set the supplied SelectionState as the new current selection, and set the force flag to trigger manual selection placement by the view.

Parameters

  • editorState EditorState
  • selection SelectionState
  • forceSelection boolean

Returns EditorState

generateNewTreeMap

Regenerate the entire tree map for a given ContentState and decorator. Returns an OrderedMap that maps all available ContentBlock objects.

Parameters

Returns OrderedMap<string, List<any>>

regenerateTreeForNewBlocks

Regenerate tree map objects for all ContentBlocks that have changed between the current editorState and newContent. Returns an OrderedMap with only changed regenerated tree map objects.

Parameters

  • editorState EditorState
  • newBlockMap BlockMap
  • newEntityMap EntityMap
  • decorator DraftDecoratorType?

Returns OrderedMap<string, List<any>>

regenerateTreeForNewDecorator

Generate tree map objects for a new decorator object, preserving any decorations that are unchanged from the previous decorator.

Note that in order for this to perform optimally, decoration Lists for decorators should be preserved when possible to allow for direct immutable List comparison.

Parameters

Returns OrderedMap<string, List<any>>

mustBecomeBoundary

Return whether a change should be considered a boundary state, given the previous change type. Allows us to discard potential boundary states during standard typing or deletion behavior.

Parameters

  • editorState EditorState
  • changeType EditorChangeType

Returns boolean

findRangesImmutable

Search through an array to find contiguous stretches of elements that match a specified filter function.

When ranges are found, execute a specified found function to supply the values to the caller.

Parameters

  • haystack List<T>
  • areEqualFn function (a: T, b: T): boolean
  • filterFn function (value: T): boolean
  • foundFn function (start: number, end: number): void

Returns void

hasEdgeWithin

Return whether the specified range overlaps with an edge of the SelectionState.

Parameters

Returns boolean

DraftEntitySegments

Identify the range to delete from a segmented entity.

Rules:

Example: 'John F. Kennedy'

  • Deletion from within any non-whitespace (i.e. ['John', 'F.', 'Kennedy']) will return the range of that text.

    'John F. Kennedy' -> 'John F.' ^

  • Forward deletion of whitespace will remove the following section:

    'John F. Kennedy' -> 'John Kennedy' ^

  • Backward deletion of whitespace will remove the previous section:

    'John F. Kennedy' -> 'F. Kennedy' ^

DraftModifier

DraftModifier provides a set of convenience methods that apply modifications to a ContentState object based on a target SelectionState.

Any change to a ContentState should be decomposable into a series of transaction functions that apply the required changes and return output ContentState objects.

These functions encapsulate some of the most common transaction sequences.

getCharacterRemovalRange

Given a SelectionState and a removal direction, determine the entire range that should be removed from a ContentState. This is based on any entities within the target, with their mutability values taken into account.

For instance, if we are attempting to remove part of an "immutable" entity range, the entire entity must be removed. The returned SelectionState will be adjusted accordingly.

Parameters

  • entityMap EntityMap
  • startBlock ContentBlock
  • endBlock ContentBlock
  • selectionState SelectionState
  • direction DraftRemovalDirection

Returns SelectionState

getRangesForDraftEntity

Obtain the start and end positions of the range that has the specified entity applied to it.

Entity keys are applied only to contiguous stretches of text, so this method searches for the first instance of the entity key and returns the subsequent range.

Parameters

  • block ContentBlock
  • key string

Returns Array<DraftRange>

onBackspace

For collapsed selections at the start of styled blocks, backspace should just remove the existing style.

Parameters

  • editorState EditorState

Returns EditorState?

toggleInlineStyle

Toggle the specified inline style for the selection. If the user's selection is collapsed, apply or remove the style for the internal state. If it is not collapsed, apply the change directly to the document state.

Parameters

  • editorState EditorState
  • inlineStyle string

Returns EditorState

tryToRemoveBlockStyle

When a collapsed cursor is at the start of an empty styled block, allow certain key commands (newline, backspace) to simply change the style of the block instead of the default behavior.

Parameters

  • editorState EditorState

Returns ContentState?

getUnsafeBodyFromHTML

Parameters

  • html

it

todo: azelenskiy Changes to the mocked DOM appear to have broken this.

it('must suppress blocks nested inside other blocks', function() { var html = '

Some text here

more text here

'; var output = DraftPasteProcessor.processHTML(html, CUSTOM_BLOCK_MAP); assertBlockTypes(output, [ 'unstyled', ]); });

insertIntoList

Maintain persistence for target list when appending and prepending.

Parameters

  • targetList List<T>
  • toInsert List<T>
  • offset number

Returns List<T>

removeFromList

Maintain persistence for target list when removing characters on the head and tail of the character list.

Parameters

  • targetList List<CharacterMetadata>
  • startOffset number
  • endOffset number

Returns List<CharacterMetadata>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment