- DraftEditor
- isIE
- DraftEditorPlaceholder
- editorState
- handleReturn
- onEscape
- DraftEditorBlock
- isBlockOnSelectionEdge
- DraftEditorContents
- getListItemClasses
- DraftEditorLeaf
- isNewline
- NEWLINE_A
- DraftEditorTextNode
- RESOLVE_DELAY
- resolved
- onCompositionStart
- onCompositionEnd
- onKeyDown
- onKeyPress
- resolveComposition
- getSelectionForEvent
- onDragEnd
- onDrop
- insertTextAtSelection
- keyCommandBackspaceWord
- keyCommandDeleteWord
- keyCommandMoveSelectionToEndOfBlock
- keyCommandMoveSelectionToStartOfBlock
- keyCommandPlainBackspace
- keyCommandPlainDelete
- keyCommandTransposeCharacters
- moveSelectionBackward
- moveSelectionForward
- removeTextWithStrategy
- SecondaryClipboard
- replaceText
- editOnBeforeInput
- editOnCompositionStart
- editOnCopy
- editOnCut
- editOnDragOver
- editOnDragStart
- editOnInput
- onKeyCommand
- editOnKeyDown
- editOnPaste
- describe
- describe
- describe
- describe
- UnicodeUtils
- getLineHeightPx
- areRectsOnOneLine
- getNodeLength
- expandRangeToStartOfLine
- findAncestorOffsetKey
- getDraftEditorSelection
- getDraftEditorSelectionWithNodes
- getFirstLeaf
- getLastLeaf
- getTextContentLength
- getRangeBoundingClientRect
- getRangeClientRects
- getSelectionOffsetKeyForNode
- getVisibleSelectionRect
- setDraftEditorSelection
- addFocusToSelection
- getZCommand
- getDefaultKeyBinding
- getTextContentFromFiles
- readFile
- isEventHandled
- isCtrlKeyCommand
- DraftBlockType
- DraftDragType
- DraftEditorCommand
- DraftHandleValue
- DraftInsertionType
- DraftRemovalDirection
- unmock
- CompositeDraftDecorator
- canOccupySlice
- occupySlice
- DraftDecorator
- DraftDecoratorType
- getDecorations
- getComponentForKey
- getPropsForKey
- disableAutomock
- disableAutomock
- disableAutomock
- containsSemanticBlockMarkup
- decodeEntityRanges
- decodeInlineStyleRanges
- encodeEntityRanges
- getEncodedInlinesForType
- EntityRange
- InlineStyleRange
- RawDraftContentBlock
- RawDraftContentState
- RawDraftEntity
- DraftEntity
- Please use 'contentState.getLastCreatedEntityKey' instead.
- Please use 'contentState.createEntity' instead.
- Please use 'contentState.addEntity' instead.
- Please use 'contentState.getEntity' instead.
- Please use 'contentState.mergeEntityData' instead.
- Please use 'contentState.replaceEntityData' instead.
- DraftEntity
- Please use 'contentState.getLastCreatedEntityKey' instead.
- Please use 'contentState.createEntity' instead.
- Please use 'contentState.addEntity' instead.
- Please use 'contentState.getEntity' instead.
- Please use 'contentState.mergeEntityData' instead.
- Please use 'contentState.replaceEntityData' instead.
- DraftEntityInstance
- DraftEntityInstance
- logWarning
- DraftEntityMutability
- getEntityKeyForSelection
- filterKey
- getTextAfterNearestEntity
- generate
- getFingerprint
- generateLeaves
- create
- findStyleRanges
- findEntityRanges
- getInlineStyleOverride
- getCurrentInlineStyle
- constructor
- getImmutable
- acceptSelection
- forceSelection
- moveSelectionToEnd
- moveFocusToEnd
- push
- undo
- redo
- updateSelection
- generateNewTreeMap
- regenerateTreeForNewBlocks
- regenerateTreeForNewDecorator
- mustBecomeBoundary
- findRangesImmutable
- hasEdgeWithin
- DraftEntitySegments
- DraftModifier
- getCharacterRemovalRange
- getRangesForDraftEntity
- onBackspace
- toggleInlineStyle
- tryToRemoveBlockStyle
- getUnsafeBodyFromHTML
- it
- insertIntoList
- removeFromList
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
Define proxies that can route events to the current handler.
Type: Function
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
eventName
string
Returns Function
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
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
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
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
Used via this.setClipboard(...)
.
Set the clipboard state for a cut/copy event.
Parameters
clipboard
BlockMap?
Returns void
Used via this.getClipboard()
.
Retrieve the clipboard state for a cut/copy event.
Returns BlockMap?
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
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
See _onDragEnter()
.
Returns void
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
Extends React.Component
This component is responsible for rendering placeholder text for the
DraftEditor
component.
Override placeholder style via CSS.
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.
Cancelable event handlers, handled from the top level down. A handler
that returns handled
will be the last handler to execute for that event.
Non-cancelable event triggers.
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.
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
Return whether a block overlaps with either edge of the SelectionState
.
Parameters
selection
SelectionStatekey
string
Returns boolean
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.
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
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.
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
Check whether the node should be considered a newline.
Parameters
node
Element
Returns boolean
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.
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
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
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.
A compositionstart
event has fired while we're still in composition
mode. Continue the current composition session to prevent a re-render.
Parameters
editor
DraftEditor
Returns void
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
editor
DraftEditor
Returns void
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
editor
DraftEditore
SyntheticKeyboardEvent
Returns void
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
editor
DraftEditore
SyntheticKeyboardEvent
Returns void
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
editor
DraftEditor
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 native
cut` operation on the DOM.
render
mode is the normal "null" mode, during which no edit behavior is
expected or observed.
Get a SelectionState for the supplied mouse event.
Parameters
event
ObjecteditorState
EditorState
Returns SelectionState?
Drag originating from input terminated.
Parameters
editor
DraftEditor
Returns void
Handle data being dropped.
Parameters
editor
DraftEditore
Object
Returns void
Insert text at a specified selection.
Parameters
editorState
EditorStateselection
SelectionStatetext
string
Returns EditorState
Delete the word that is left of the cursor, as well as any spaces or punctuation after the word.
Parameters
editorState
EditorState
Returns EditorState
Delete the word that is right of the cursor, as well as any spaces or punctuation before the word.
Parameters
editorState
EditorState
Returns EditorState
See comment for moveSelectionToStartOfBlock
.
Parameters
editorState
EditorState
Returns EditorState
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
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
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
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
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
EditorStatemaxDistance
number
Returns SelectionState
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
EditorStatemaxDistance
number
Returns SelectionState
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
EditorStatestrategy
function (editorState: EditorState): SelectionStatedirection
DraftRemovalDirection
Returns ContentState
Some systems offer a "secondary" clipboard to allow quick internal cut and paste behavior. For instance, Ctrl+K (cut) and Ctrl+Y (paste).
Replace the current selection with the specified text string, with the inline style and entity key applied to the newly inserted text.
Parameters
Returns EditorState
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
editor
DraftEditore
SyntheticInputEvent
Returns void
The user has begun using an IME input system. Switching to composite
mode
allows handling composition input and disables other edit behavior.
Parameters
editor
DraftEditore
SyntheticEvent
Returns void
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
editor
DraftEditore
SyntheticClipboardEvent
Returns void
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
editor
DraftEditore
SyntheticClipboardEvent
Returns void
Drag behavior has begun from outside the editor element.
Parameters
editor
DraftEditore
SyntheticDragEvent
Returns void
A dragstart
event has begun within the text editor component.
Parameters
editor
DraftEditor
Returns void
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
editor
DraftEditor
Returns void
Map a DraftEditorCommand
command value to a corresponding function.
Parameters
command
(DraftEditorCommand | string)editorState
EditorState
Returns EditorState
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
editor
DraftEditore
SyntheticKeyboardEvent
Returns void
Paste content.
Parameters
editor
DraftEditore
SyntheticClipboardEvent
Returns void
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.
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)
In some scenarios, the entire editor may be selected by command-A.
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.
Return the computed line height, in pixels, for the provided element.
Parameters
element
Element
Returns number
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
Return the length of a node, as used by Range offsets.
Parameters
node
Node
Returns number
Given a collapsed range, move the start position backwards as far as possible while the range still spans only a single line.
Parameters
range
Range
Returns Range
Get the key from the node's nearest offset-aware ancestor.
Parameters
node
Node
Returns string?
Convert the current selection range to an anchor/focus pair of offset keys and values that can be interpreted by components.
Parameters
editorState
EditorStateroot
HTMLElement
Returns DOMDerivedSelection
Convert the current selection range to an anchor/focus pair of offset keys and values that can be interpreted by components.
Parameters
editorState
EditorStateroot
HTMLElement?anchorNode
NodeanchorOffset
numberfocusNode
NodefocusOffset
number
Returns DOMDerivedSelection
Identify the first leaf descendant for the given node.
Parameters
node
Node
Returns Node
Identify the last leaf descendant for the given node.
Parameters
node
Node
Returns Node
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
node
Node
Returns number
Like range.getBoundingClientRect() but normalizes for browser bugs.
Parameters
range
Range
Returns FakeClientRect
Like range.getClientRects() but normalizes for browser bugs.
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
node
Node
Returns string?
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?
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
Extend selection towards focus point.
Parameters
Returns void
Copyright 2013-present, Facebook, Inc.
Get the appropriate undo/redo command for a Z key command.
Parameters
e
SyntheticKeyboardEvent
Returns DraftEditorCommand?
Retrieve a bound key command for the given event.
Parameters
e
SyntheticKeyboardEvent
Returns DraftEditorCommand?
Extract the text content from a file list.
Parameters
Returns void
todo isaac: Do work to turn html/rtf into a content fragment.
Parameters
file
Filecallback
function (contents: string): void
Returns void
Utility method for determining whether or not the value returned from a handler indicates that it was handled.
Parameters
value
DraftHandleValue
Returns boolean
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
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"
)
A type that allows us to avoid passing boolean arguments around to indicate whether a drag type is internal or external.
Type: ("internal"
| "external"
)
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.
A type that allows us to avoid returning boolean values to indicate whether an event was handled or not.
Type: ("handled"
| "not-handled"
)
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"
)
A type that allows us to avoid passing boolean arguments around to indicate whether a deletion is forward or backward.
Type: ("backward"
| "forward"
)
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
decorators
Array<DraftDecorator>
Determine whether we can occupy the specified slice of the decorations array.
Parameters
Returns boolean
Splice the specified component into our decoration array at the desired range.
Parameters
Returns void
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
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): FunctiongetPropsForKey
function (key: string): Object?
Given a ContentBlock
, return an immutable List of decorator keys.
Given a decorator key, return the component to use when rendering this decorated range.
Given a decorator key, optionally return the props to use when rendering this decorated range.
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
<div>
tags as meaningful (unstyled) blocks.
Parameters
Returns boolean
Convert to native JavaScript string lengths to determine ranges.
Parameters
Convert to native JavaScript string lengths to determine ranges.
Parameters
Returns Array<DraftInlineStyle>
Convert to UTF-8 character counts for storage.
Parameters
block
ContentBlockstorageMap
Object
Returns Array<EntityRange>
Helper function for getting encoded styles for each inline style. Convert to UTF-8 character counts for storage.
Parameters
block
ContentBlockstyleList
List<DraftInlineStyle>styleToEncode
string
Returns Array<InlineStyleRange>
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
A plain object representation of an inline style range.
Type: {style: string, offset: number, length: number}
Properties
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
key
string?type
DraftBlockTypetext
stringdepth
number?inlineStyleRanges
Array<InlineStyleRange>?entityRanges
Array<EntityRange>?data
Object?
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
blocks
Array<RawDraftContentBlock>entityMap
{}
A plain object representation of an EntityInstance.
Type: {type: DraftEntityType, mutability: DraftEntityMutability, data: {}?}
Properties
type
DraftEntityTypemutability
DraftEntityMutabilitydata
{}?
WARNING: This method will be deprecated soon!
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
WARNING: This method will be deprecated soon!
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
type
DraftEntityTypemutability
DraftEntityMutabilitydata
Object
Returns string
WARNING: This method will be deprecated soon!
Add an existing DraftEntityInstance to the DraftEntity map. This is useful when restoring instances from the server.
Parameters
instance
DraftEntityInstance
Returns string
WARNING: This method will be deprecated soon!
Retrieve the entity corresponding to the supplied key string.
Parameters
key
string
Returns DraftEntityInstance
WARNING: This method will be deprecated soon!
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
key
stringtoMerge
{}
Returns DraftEntityInstance
WARNING: This method will be deprecated soon!
Completely replace the data for a given instance.
Parameters
key
stringnewData
{}
Returns DraftEntityInstance
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 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
type
DraftEntityTypemutability
DraftEntityMutabilitydata
Object
Returns string
Add an existing DraftEntityInstance to the DraftEntity map. This is useful when restoring instances from the server.
Parameters
instance
DraftEntityInstance
Returns string
Retrieve the entity corresponding to the supplied key string.
Parameters
key
string
Returns DraftEntityInstance
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
key
stringtoMerge
{}
Returns DraftEntityInstance
Completely replace the data for a given instance.
Parameters
key
stringnewData
{}
Returns DraftEntityInstance
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
WARNING: This method will be deprecated soon!
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
WARNING: This method will be deprecated soon!
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
type
DraftEntityTypemutability
DraftEntityMutabilitydata
Object
Returns string
WARNING: This method will be deprecated soon!
Add an existing DraftEntityInstance to the DraftEntity map. This is useful when restoring instances from the server.
Parameters
instance
DraftEntityInstance
Returns string
WARNING: This method will be deprecated soon!
Retrieve the entity corresponding to the supplied key string.
Parameters
key
string
Returns DraftEntityInstance
WARNING: This method will be deprecated soon!
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
key
stringtoMerge
{}
Returns DraftEntityInstance
WARNING: This method will be deprecated soon!
Completely replace the data for a given instance.
Parameters
key
stringnewData
{}
Returns DraftEntityInstance
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 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
type
DraftEntityTypemutability
DraftEntityMutabilitydata
Object
Returns string
Add an existing DraftEntityInstance to the DraftEntity map. This is useful when restoring instances from the server.
Parameters
instance
DraftEntityInstance
Returns string
Retrieve the entity corresponding to the supplied key string.
Parameters
key
string
Returns DraftEntityInstance
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
key
stringtoMerge
{}
Returns DraftEntityInstance
Completely replace the data for a given instance.
Parameters
key
stringnewData
{}
Returns 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.
Temporary utility for generating the warnings
Parameters
oldMethodCall
newMethodCall
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>
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
ContentStatetargetSelection
SelectionState
Returns string?
Determine whether an entity key corresponds to a MUTABLE
entity. If so,
return it. If not, return null.
Parameters
entityMap
EntityMapentityKey
string?
Returns string?
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
ContentBlockoffset
number
Returns string
Generate a block tree for a given ContentBlock/decorator pair.
Parameters
contentState
ContentStateblock
ContentBlockdecorator
DraftDecoratorType?
Returns List<DecoratorRange>
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
Generate LeafRange records for a given character list.
Parameters
characters
List<CharacterMetadata>offset
number
Returns List<LeafRange>
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
Execute a callback for every contiguous range of styles within the block.
Parameters
filterFn
function (value: CharacterMetadata): booleancallback
function (start: number, end: number): void
Returns void
Execute a callback for every contiguous range of entities within the block.
Parameters
filterFn
function (value: CharacterMetadata): booleancallback
function (start: number, end: number): void
Returns void
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?
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
Not for public consumption.
Parameters
immutable
EditorStateRecord
Not for public consumption.
Returns EditorStateRecord
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
EditorStateselection
SelectionState
Returns EditorState
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
EditorStateselection
SelectionState
Returns EditorState
Move selection to the end of the editor without forcing focus.
Parameters
editorState
EditorState
Returns EditorState
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 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
EditorStatecontentState
ContentStatechangeType
EditorChangeType
Returns EditorState
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
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
Set the supplied SelectionState as the new current selection, and set
the force
flag to trigger manual selection placement by the view.
Parameters
editorState
EditorStateselection
SelectionStateforceSelection
boolean
Returns EditorState
Regenerate the entire tree map for a given ContentState and decorator. Returns an OrderedMap that maps all available ContentBlock objects.
Parameters
contentState
ContentStatedecorator
DraftDecoratorType?
Returns OrderedMap<string, List<any>>
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
EditorStatenewBlockMap
BlockMapnewEntityMap
EntityMapdecorator
DraftDecoratorType?
Returns OrderedMap<string, List<any>>
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
content
ContentStateblockMap
BlockMappreviousTreeMap
OrderedMap<string, List<any>>decorator
DraftDecoratorTypeexistingDecorator
DraftDecoratorType
Returns OrderedMap<string, List<any>>
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
EditorStatechangeType
EditorChangeType
Returns boolean
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): booleanfilterFn
function (value: T): booleanfoundFn
function (start: number, end: number): void
Returns void
Return whether the specified range overlaps with an edge of the SelectionState.
Parameters
Returns boolean
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
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.
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
EntityMapstartBlock
ContentBlockendBlock
ContentBlockselectionState
SelectionStatedirection
DraftRemovalDirection
Returns SelectionState
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
ContentBlockkey
string
Returns Array<DraftRange>
For collapsed selections at the start of styled blocks, backspace should just remove the existing style.
Parameters
editorState
EditorState
Returns EditorState?
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
EditorStateinlineStyle
string
Returns EditorState
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?
Parameters
html
todo: azelenskiy Changes to the mocked DOM appear to have broken this.
it('must suppress blocks nested inside other blocks', function() { var html = '
more text here '; var output = DraftPasteProcessor.processHTML(html, CUSTOM_BLOCK_MAP); assertBlockTypes(output, [ 'unstyled', ]); });Maintain persistence for target list when appending and prepending.
Parameters
targetList
List<T>toInsert
List<T>offset
number
Returns List<T>
Maintain persistence for target list when removing characters on the head and tail of the character list.
Parameters
Returns List<CharacterMetadata>