slate-react
Version:
Tools for building completely customizable richtext editors with React.
1,528 lines (1,300 loc) • 119 kB
JavaScript
import React, { useRef, useEffect, useLayoutEffect, useContext, createContext, useMemo, useCallback, useState } from 'react';
import { Path, Node, Editor, Text as Text$1, Range, Element as Element$1, Transforms } from 'slate';
import getDirection from 'direction';
import throttle from 'lodash/throttle';
import scrollIntoView from 'scroll-into-view-if-needed';
import { isKeyHotkey } from 'is-hotkey';
import invariant from 'tiny-invariant';
import ReactDOM from 'react-dom';
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
/**
* Leaf content strings.
*/
var String = props => {
var {
isLast,
leaf,
parent,
text
} = props;
var editor = useSlateStatic();
var path = ReactEditor.findPath(editor, text);
var parentPath = Path.parent(path); // COMPAT: Render text inside void nodes with a zero-width space.
// So the node can contain selection but the text is not visible.
if (editor.isVoid(parent)) {
return /*#__PURE__*/React.createElement(ZeroWidthString, {
length: Node.string(parent).length
});
} // COMPAT: If this is the last text node in an empty block, render a zero-
// width space that will convert into a line break when copying and pasting
// to support expected plain text.
if (leaf.text === '' && parent.children[parent.children.length - 1] === text && !editor.isInline(parent) && Editor.string(editor, parentPath) === '') {
return /*#__PURE__*/React.createElement(ZeroWidthString, {
isLineBreak: true
});
} // COMPAT: If the text is empty, it's because it's on the edge of an inline
// node, so we render a zero-width space so that the selection can be
// inserted next to it still.
if (leaf.text === '') {
return /*#__PURE__*/React.createElement(ZeroWidthString, null);
} // COMPAT: Browsers will collapse trailing new lines at the end of blocks,
// so we need to add an extra trailing new lines to prevent that.
if (isLast && leaf.text.slice(-1) === '\n') {
return /*#__PURE__*/React.createElement(TextString, {
isTrailing: true,
text: leaf.text
});
}
return /*#__PURE__*/React.createElement(TextString, {
text: leaf.text
});
};
/**
* Leaf strings with text in them.
*/
var TextString = props => {
var {
text,
isTrailing = false
} = props;
return /*#__PURE__*/React.createElement("span", {
"data-slate-string": true
}, text, isTrailing ? '\n' : null);
};
/**
* Leaf strings without text, render as zero-width strings.
*/
var ZeroWidthString = props => {
var {
length = 0,
isLineBreak = false
} = props;
return /*#__PURE__*/React.createElement("span", {
"data-slate-zero-width": isLineBreak ? 'n' : 'z',
"data-slate-length": length
}, '\uFEFF', isLineBreak ? /*#__PURE__*/React.createElement("br", null) : null);
};
/**
* Two weak maps that allow us rebuild a path given a node. They are populated
* at render time such that after a render occurs we can always backtrack.
*/
var NODE_TO_INDEX = new WeakMap();
var NODE_TO_PARENT = new WeakMap();
/**
* Weak maps that allow us to go between Slate nodes and DOM nodes. These
* are used to resolve DOM event-related logic into Slate actions.
*/
var EDITOR_TO_WINDOW = new WeakMap();
var EDITOR_TO_ELEMENT = new WeakMap();
var ELEMENT_TO_NODE = new WeakMap();
var KEY_TO_ELEMENT = new WeakMap();
var NODE_TO_ELEMENT = new WeakMap();
var NODE_TO_KEY = new WeakMap();
/**
* Weak maps for storing editor-related state.
*/
var IS_READ_ONLY = new WeakMap();
var IS_FOCUSED = new WeakMap();
/**
* Weak map for associating the context `onChange` context with the plugin.
*/
var EDITOR_TO_ON_CHANGE = new WeakMap();
var EDITOR_TO_RESTORE_DOM = new WeakMap();
/**
* Symbols.
*/
var PLACEHOLDER_SYMBOL = Symbol('placeholder');
// prevent inconsistent rendering by React with IME input
var keyForString = 0;
/**
* Individual leaves in a text node with unique formatting.
*/
var Leaf = props => {
var {
leaf,
isLast,
text,
parent,
renderPlaceholder,
renderLeaf = props => /*#__PURE__*/React.createElement(DefaultLeaf, Object.assign({}, props))
} = props;
var placeholderRef = useRef(null);
useEffect(() => {
var placeholderEl = placeholderRef === null || placeholderRef === void 0 ? void 0 : placeholderRef.current;
var editorEl = document.querySelector('[data-slate-editor="true"]');
if (!placeholderEl || !editorEl) {
return;
}
editorEl.style.minHeight = "".concat(placeholderEl.clientHeight, "px");
return () => {
editorEl.style.minHeight = 'auto';
};
}, [placeholderRef, leaf]);
var children = /*#__PURE__*/React.createElement(String, {
key: keyForString++,
isLast: isLast,
leaf: leaf,
parent: parent,
text: text
});
if (leaf[PLACEHOLDER_SYMBOL]) {
var placeholderProps = {
children: leaf.placeholder,
attributes: {
'data-slate-placeholder': true,
style: {
position: 'absolute',
pointerEvents: 'none',
width: '100%',
maxWidth: '100%',
display: 'block',
opacity: '0.333',
userSelect: 'none',
textDecoration: 'none'
},
contentEditable: false,
ref: placeholderRef
}
};
children = /*#__PURE__*/React.createElement(React.Fragment, null, renderPlaceholder(placeholderProps), children);
} // COMPAT: Having the `data-` attributes on these leaf elements ensures that
// in certain misbehaving browsers they aren't weirdly cloned/destroyed by
// contenteditable behaviors. (2019/05/08)
var attributes = {
'data-slate-leaf': true
};
return renderLeaf({
attributes,
children,
leaf,
text
});
};
var MemoizedLeaf = /*#__PURE__*/React.memo(Leaf, (prev, next) => {
return next.parent === prev.parent && next.isLast === prev.isLast && next.renderLeaf === prev.renderLeaf && next.renderPlaceholder === prev.renderPlaceholder && next.text === prev.text && next.leaf.text === prev.leaf.text && Text$1.matches(next.leaf, prev.leaf) && next.leaf[PLACEHOLDER_SYMBOL] === prev.leaf[PLACEHOLDER_SYMBOL];
});
var DefaultLeaf = props => {
var {
attributes,
children
} = props;
return /*#__PURE__*/React.createElement("span", Object.assign({}, attributes), children);
};
var IS_IOS = typeof navigator !== 'undefined' && typeof window !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
var IS_APPLE = typeof navigator !== 'undefined' && /Mac OS X/.test(navigator.userAgent);
var IS_ANDROID = typeof navigator !== 'undefined' && /Android/.test(navigator.userAgent);
var IS_FIREFOX = typeof navigator !== 'undefined' && /^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent);
var IS_SAFARI = typeof navigator !== 'undefined' && /Version\/[\d\.]+.*Safari/.test(navigator.userAgent); // "modern" Edge was released at 79.x
var IS_EDGE_LEGACY = typeof navigator !== 'undefined' && /Edge?\/(?:[0-6][0-9]|[0-7][0-8])/i.test(navigator.userAgent);
var IS_CHROME = typeof navigator !== 'undefined' && /Chrome/i.test(navigator.userAgent); // Native `beforeInput` events don't work well with react on Chrome 75
// and older, Chrome 76+ can use `beforeInput` though.
var IS_CHROME_LEGACY = typeof navigator !== 'undefined' && /Chrome?\/(?:[0-7][0-5]|[0-6][0-9])/i.test(navigator.userAgent); // Firefox did not support `beforeInput` until `v87`.
var IS_FIREFOX_LEGACY = typeof navigator !== 'undefined' && /^(?!.*Seamonkey)(?=.*Firefox\/(?:[0-7][0-9]|[0-8][0-6])).*/i.test(navigator.userAgent); // Check if DOM is available as React does internally.
// https://github.com/facebook/react/blob/master/packages/shared/ExecutionEnvironment.js
var CAN_USE_DOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); // COMPAT: Firefox/Edge Legacy don't support the `beforeinput` event
// Chrome Legacy doesn't support `beforeinput` correctly
var HAS_BEFORE_INPUT_SUPPORT = !IS_CHROME_LEGACY && !IS_EDGE_LEGACY && // globalThis is undefined in older browsers
typeof globalThis !== 'undefined' && globalThis.InputEvent && // @ts-ignore The `getTargetRanges` property isn't recognized.
typeof globalThis.InputEvent.prototype.getTargetRanges === 'function';
/**
* Prevent warning on SSR by falling back to useEffect when DOM isn't available
*/
var useIsomorphicLayoutEffect = CAN_USE_DOM ? useLayoutEffect : useEffect;
var shallowCompare = (obj1, obj2) => Object.keys(obj1).length === Object.keys(obj2).length && Object.keys(obj1).every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key]);
/**
* Check if a list of decorator ranges are equal to another.
*
* PERF: this requires the two lists to also have the ranges inside them in the
* same order, but this is an okay constraint for us since decorations are
* kept in order, and the odd case where they aren't is okay to re-render for.
*/
var isDecoratorRangeListEqual = (list, another) => {
if (list.length !== another.length) {
return false;
}
for (var i = 0; i < list.length; i++) {
var range = list[i];
var other = another[i];
var rangeOwnProps = _objectWithoutProperties(range, ["anchor", "focus"]);
var otherOwnProps = _objectWithoutProperties(other, ["anchor", "focus"]);
if (!Range.equals(range, other) || range[PLACEHOLDER_SYMBOL] !== other[PLACEHOLDER_SYMBOL] || !shallowCompare(rangeOwnProps, otherOwnProps)) {
return false;
}
}
return true;
};
/**
* Text.
*/
var Text = props => {
var {
decorations,
isLast,
parent,
renderPlaceholder,
renderLeaf,
text
} = props;
var editor = useSlateStatic();
var ref = useRef(null);
var leaves = Text$1.decorations(text, decorations);
var key = ReactEditor.findKey(editor, text);
var children = [];
for (var i = 0; i < leaves.length; i++) {
var leaf = leaves[i];
children.push( /*#__PURE__*/React.createElement(MemoizedLeaf, {
isLast: isLast && i === leaves.length - 1,
key: "".concat(key.id, "-").concat(i),
renderPlaceholder: renderPlaceholder,
leaf: leaf,
text: text,
parent: parent,
renderLeaf: renderLeaf
}));
} // Update element-related weak maps with the DOM element ref.
useIsomorphicLayoutEffect(() => {
if (ref.current) {
KEY_TO_ELEMENT.set(key, ref.current);
NODE_TO_ELEMENT.set(text, ref.current);
ELEMENT_TO_NODE.set(ref.current, text);
} else {
KEY_TO_ELEMENT.delete(key);
NODE_TO_ELEMENT.delete(text);
}
});
return /*#__PURE__*/React.createElement("span", {
"data-slate-node": "text",
ref: ref
}, children);
};
var MemoizedText = /*#__PURE__*/React.memo(Text, (prev, next) => {
return next.parent === prev.parent && next.isLast === prev.isLast && next.renderLeaf === prev.renderLeaf && next.text === prev.text && isDecoratorRangeListEqual(next.decorations, prev.decorations);
});
/**
* A React context for sharing the `selected` state of an element.
*/
var SelectedContext = /*#__PURE__*/createContext(false);
/**
* Get the current `selected` state of an element.
*/
var useSelected = () => {
return useContext(SelectedContext);
};
/**
* Element.
*/
var Element = props => {
var {
decorations,
element,
renderElement = p => /*#__PURE__*/React.createElement(DefaultElement, Object.assign({}, p)),
renderPlaceholder,
renderLeaf,
selection
} = props;
var ref = useRef(null);
var editor = useSlateStatic();
var readOnly = useReadOnly();
var isInline = editor.isInline(element);
var key = ReactEditor.findKey(editor, element);
var children = useChildren({
decorations,
node: element,
renderElement,
renderPlaceholder,
renderLeaf,
selection
}); // Attributes that the developer must mix into the element in their
// custom node renderer component.
var attributes = {
'data-slate-node': 'element',
ref
};
if (isInline) {
attributes['data-slate-inline'] = true;
} // If it's a block node with inline children, add the proper `dir` attribute
// for text direction.
if (!isInline && Editor.hasInlines(editor, element)) {
var text = Node.string(element);
var dir = getDirection(text);
if (dir === 'rtl') {
attributes.dir = dir;
}
} // If it's a void node, wrap the children in extra void-specific elements.
if (Editor.isVoid(editor, element)) {
attributes['data-slate-void'] = true;
if (!readOnly && isInline) {
attributes.contentEditable = false;
}
var Tag = isInline ? 'span' : 'div';
var [[_text]] = Node.texts(element);
children = readOnly ? null : /*#__PURE__*/React.createElement(Tag, {
"data-slate-spacer": true,
style: {
height: '0',
color: 'transparent',
outline: 'none',
position: 'absolute'
}
}, /*#__PURE__*/React.createElement(MemoizedText, {
renderPlaceholder: renderPlaceholder,
decorations: [],
isLast: false,
parent: element,
text: _text
}));
NODE_TO_INDEX.set(_text, 0);
NODE_TO_PARENT.set(_text, element);
} // Update element-related weak maps with the DOM element ref.
useIsomorphicLayoutEffect(() => {
if (ref.current) {
KEY_TO_ELEMENT.set(key, ref.current);
NODE_TO_ELEMENT.set(element, ref.current);
ELEMENT_TO_NODE.set(ref.current, element);
} else {
KEY_TO_ELEMENT.delete(key);
NODE_TO_ELEMENT.delete(element);
}
});
return /*#__PURE__*/React.createElement(SelectedContext.Provider, {
value: !!selection
}, renderElement({
attributes,
children,
element
}));
};
var MemoizedElement = /*#__PURE__*/React.memo(Element, (prev, next) => {
return prev.element === next.element && prev.renderElement === next.renderElement && prev.renderLeaf === next.renderLeaf && isDecoratorRangeListEqual(prev.decorations, next.decorations) && (prev.selection === next.selection || !!prev.selection && !!next.selection && Range.equals(prev.selection, next.selection));
});
/**
* The default element renderer.
*/
var DefaultElement = props => {
var {
attributes,
children,
element
} = props;
var editor = useSlateStatic();
var Tag = editor.isInline(element) ? 'span' : 'div';
return /*#__PURE__*/React.createElement(Tag, Object.assign({}, attributes, {
style: {
position: 'relative'
}
}), children);
};
/**
* A React context for sharing the editor object.
*/
var EditorContext = /*#__PURE__*/createContext(null);
/**
* Get the current editor object from the React context.
*/
var useSlateStatic = () => {
var editor = useContext(EditorContext);
if (!editor) {
throw new Error("The `useSlateStatic` hook must be used inside the <Slate> component's context.");
}
return editor;
};
/**
* A React context for sharing the `decorate` prop of the editable.
*/
var DecorateContext = /*#__PURE__*/createContext(() => []);
/**
* Get the current `decorate` prop of the editable.
*/
var useDecorate = () => {
return useContext(DecorateContext);
};
/**
* Children.
*/
var useChildren = props => {
var {
decorations,
node,
renderElement,
renderPlaceholder,
renderLeaf,
selection
} = props;
var decorate = useDecorate();
var editor = useSlateStatic();
var path = ReactEditor.findPath(editor, node);
var children = [];
var isLeafBlock = Element$1.isElement(node) && !editor.isInline(node) && Editor.hasInlines(editor, node);
for (var i = 0; i < node.children.length; i++) {
var p = path.concat(i);
var n = node.children[i];
var key = ReactEditor.findKey(editor, n);
var range = Editor.range(editor, p);
var sel = selection && Range.intersection(range, selection);
var ds = decorate([n, p]);
for (var dec of decorations) {
var d = Range.intersection(dec, range);
if (d) {
ds.push(d);
}
}
if (Element$1.isElement(n)) {
children.push( /*#__PURE__*/React.createElement(MemoizedElement, {
decorations: ds,
element: n,
key: key.id,
renderElement: renderElement,
renderPlaceholder: renderPlaceholder,
renderLeaf: renderLeaf,
selection: sel
}));
} else {
children.push( /*#__PURE__*/React.createElement(MemoizedText, {
decorations: ds,
key: key.id,
isLast: isLeafBlock && i === node.children.length - 1,
parent: node,
renderPlaceholder: renderPlaceholder,
renderLeaf: renderLeaf,
text: n
}));
}
NODE_TO_INDEX.set(n, i);
NODE_TO_PARENT.set(n, node);
}
return children;
};
/**
* Hotkey mappings for each platform.
*/
var HOTKEYS = {
bold: 'mod+b',
compose: ['down', 'left', 'right', 'up', 'backspace', 'enter'],
moveBackward: 'left',
moveForward: 'right',
moveWordBackward: 'ctrl+left',
moveWordForward: 'ctrl+right',
deleteBackward: 'shift?+backspace',
deleteForward: 'shift?+delete',
extendBackward: 'shift+left',
extendForward: 'shift+right',
italic: 'mod+i',
splitBlock: 'shift?+enter',
undo: 'mod+z'
};
var APPLE_HOTKEYS = {
moveLineBackward: 'opt+up',
moveLineForward: 'opt+down',
moveWordBackward: 'opt+left',
moveWordForward: 'opt+right',
deleteBackward: ['ctrl+backspace', 'ctrl+h'],
deleteForward: ['ctrl+delete', 'ctrl+d'],
deleteLineBackward: 'cmd+shift?+backspace',
deleteLineForward: ['cmd+shift?+delete', 'ctrl+k'],
deleteWordBackward: 'opt+shift?+backspace',
deleteWordForward: 'opt+shift?+delete',
extendLineBackward: 'opt+shift+up',
extendLineForward: 'opt+shift+down',
redo: 'cmd+shift+z',
transposeCharacter: 'ctrl+t'
};
var WINDOWS_HOTKEYS = {
deleteWordBackward: 'ctrl+shift?+backspace',
deleteWordForward: 'ctrl+shift?+delete',
redo: ['ctrl+y', 'ctrl+shift+z']
};
/**
* Create a platform-aware hotkey checker.
*/
var create = key => {
var generic = HOTKEYS[key];
var apple = APPLE_HOTKEYS[key];
var windows = WINDOWS_HOTKEYS[key];
var isGeneric = generic && isKeyHotkey(generic);
var isApple = apple && isKeyHotkey(apple);
var isWindows = windows && isKeyHotkey(windows);
return event => {
if (isGeneric && isGeneric(event)) return true;
if (IS_APPLE && isApple && isApple(event)) return true;
if (!IS_APPLE && isWindows && isWindows(event)) return true;
return false;
};
};
/**
* Hotkeys.
*/
var Hotkeys = {
isBold: create('bold'),
isCompose: create('compose'),
isMoveBackward: create('moveBackward'),
isMoveForward: create('moveForward'),
isDeleteBackward: create('deleteBackward'),
isDeleteForward: create('deleteForward'),
isDeleteLineBackward: create('deleteLineBackward'),
isDeleteLineForward: create('deleteLineForward'),
isDeleteWordBackward: create('deleteWordBackward'),
isDeleteWordForward: create('deleteWordForward'),
isExtendBackward: create('extendBackward'),
isExtendForward: create('extendForward'),
isExtendLineBackward: create('extendLineBackward'),
isExtendLineForward: create('extendLineForward'),
isItalic: create('italic'),
isMoveLineBackward: create('moveLineBackward'),
isMoveLineForward: create('moveLineForward'),
isMoveWordBackward: create('moveWordBackward'),
isMoveWordForward: create('moveWordForward'),
isRedo: create('redo'),
isSplitBlock: create('splitBlock'),
isTransposeCharacter: create('transposeCharacter'),
isUndo: create('undo')
};
/**
* A React context for sharing the `readOnly` state of the editor.
*/
var ReadOnlyContext = /*#__PURE__*/createContext(false);
/**
* Get the current `readOnly` state of the editor.
*/
var useReadOnly = () => {
return useContext(ReadOnlyContext);
};
/**
* A React context for sharing the editor object, in a way that re-renders the
* context whenever changes occur.
*/
var SlateContext = /*#__PURE__*/createContext(null);
/**
* Get the current editor object from the React context.
*/
var useSlate = () => {
var context = useContext(SlateContext);
if (!context) {
throw new Error("The `useSlate` hook must be used inside the <SlateProvider> component's context.");
}
var [editor] = context;
return editor;
};
/**
* Types.
*/
/**
* Returns the host window of a DOM node
*/
var getDefaultView = value => {
return value && value.ownerDocument && value.ownerDocument.defaultView || null;
};
/**
* Check if a DOM node is a comment node.
*/
var isDOMComment = value => {
return isDOMNode(value) && value.nodeType === 8;
};
/**
* Check if a DOM node is an element node.
*/
var isDOMElement = value => {
return isDOMNode(value) && value.nodeType === 1;
};
/**
* Check if a value is a DOM node.
*/
var isDOMNode = value => {
var window = getDefaultView(value);
return !!window && value instanceof window.Node;
};
/**
* Check if a value is a DOM selection.
*/
var isDOMSelection = value => {
var window = value && value.anchorNode && getDefaultView(value.anchorNode);
return !!window && value instanceof window.Selection;
};
/**
* Check if a DOM node is an element node.
*/
var isDOMText = value => {
return isDOMNode(value) && value.nodeType === 3;
};
/**
* Checks whether a paste event is a plaintext-only event.
*/
var isPlainTextOnlyPaste = event => {
return event.clipboardData && event.clipboardData.getData('text/plain') !== '' && event.clipboardData.types.length === 1;
};
/**
* Normalize a DOM point so that it always refers to a text node.
*/
var normalizeDOMPoint = domPoint => {
var [node, offset] = domPoint; // If it's an element node, its offset refers to the index of its children
// including comment nodes, so try to find the right text child node.
if (isDOMElement(node) && node.childNodes.length) {
var isLast = offset === node.childNodes.length;
var index = isLast ? offset - 1 : offset;
[node, index] = getEditableChildAndIndex(node, index, isLast ? 'backward' : 'forward'); // If the editable child found is in front of input offset, we instead seek to its end
isLast = index < offset; // If the node has children, traverse until we have a leaf node. Leaf nodes
// can be either text nodes, or other void DOM nodes.
while (isDOMElement(node) && node.childNodes.length) {
var i = isLast ? node.childNodes.length - 1 : 0;
node = getEditableChild(node, i, isLast ? 'backward' : 'forward');
} // Determine the new offset inside the text node.
offset = isLast && node.textContent != null ? node.textContent.length : 0;
} // Return the node and offset.
return [node, offset];
};
/**
* Determines wether the active element is nested within a shadowRoot
*/
var hasShadowRoot = () => {
return !!(window.document.activeElement && window.document.activeElement.shadowRoot);
};
/**
* Get the nearest editable child and index at `index` in a `parent`, preferring
* `direction`.
*/
var getEditableChildAndIndex = (parent, index, direction) => {
var {
childNodes
} = parent;
var child = childNodes[index];
var i = index;
var triedForward = false;
var triedBackward = false; // While the child is a comment node, or an element node with no children,
// keep iterating to find a sibling non-void, non-comment node.
while (isDOMComment(child) || isDOMElement(child) && child.childNodes.length === 0 || isDOMElement(child) && child.getAttribute('contenteditable') === 'false') {
if (triedForward && triedBackward) {
break;
}
if (i >= childNodes.length) {
triedForward = true;
i = index - 1;
direction = 'backward';
continue;
}
if (i < 0) {
triedBackward = true;
i = index + 1;
direction = 'forward';
continue;
}
child = childNodes[i];
index = i;
i += direction === 'forward' ? 1 : -1;
}
return [child, index];
};
/**
* Get the nearest editable child at `index` in a `parent`, preferring
* `direction`.
*/
var getEditableChild = (parent, index, direction) => {
var [child] = getEditableChildAndIndex(parent, index, direction);
return child;
};
/**
* Get a plaintext representation of the content of a node, accounting for block
* elements which get a newline appended.
*
* The domNode must be attached to the DOM.
*/
var getPlainText = domNode => {
var text = '';
if (isDOMText(domNode) && domNode.nodeValue) {
return domNode.nodeValue;
}
if (isDOMElement(domNode)) {
for (var childNode of Array.from(domNode.childNodes)) {
text += getPlainText(childNode);
}
var display = getComputedStyle(domNode).getPropertyValue('display');
if (display === 'block' || display === 'list' || domNode.tagName === 'BR') {
text += '\n';
}
}
return text;
};
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
/**
* Editable.
*/
var Editable = props => {
var {
autoFocus,
decorate = defaultDecorate,
onDOMBeforeInput: propsOnDOMBeforeInput,
placeholder,
readOnly = false,
renderElement,
renderLeaf,
renderPlaceholder = props => /*#__PURE__*/React.createElement(DefaultPlaceholder, Object.assign({}, props)),
style = {},
as: Component = 'div'
} = props,
attributes = _objectWithoutProperties(props, ["autoFocus", "decorate", "onDOMBeforeInput", "placeholder", "readOnly", "renderElement", "renderLeaf", "renderPlaceholder", "style", "as"]);
var editor = useSlate();
var ref = useRef(null); // Update internal state on each render.
IS_READ_ONLY.set(editor, readOnly); // Keep track of some state for the event handler logic.
var state = useMemo(() => ({
isComposing: false,
isDraggingInternally: false,
isUpdatingSelection: false,
latestElement: null
}), []); // Whenever the editor updates...
useIsomorphicLayoutEffect(() => {
// Update element-related weak maps with the DOM element ref.
var window;
if (ref.current && (window = getDefaultView(ref.current))) {
EDITOR_TO_WINDOW.set(editor, window);
EDITOR_TO_ELEMENT.set(editor, ref.current);
NODE_TO_ELEMENT.set(editor, ref.current);
ELEMENT_TO_NODE.set(ref.current, editor);
} else {
NODE_TO_ELEMENT.delete(editor);
} // Make sure the DOM selection state is in sync.
var {
selection
} = editor;
var root = ReactEditor.findDocumentOrShadowRoot(editor);
var domSelection = root.getSelection();
if (state.isComposing || !domSelection || !ReactEditor.isFocused(editor)) {
return;
}
var hasDomSelection = domSelection.type !== 'None'; // If the DOM selection is properly unset, we're done.
if (!selection && !hasDomSelection) {
return;
} // verify that the dom selection is in the editor
var editorElement = EDITOR_TO_ELEMENT.get(editor);
var hasDomSelectionInEditor = false;
if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
hasDomSelectionInEditor = true;
} // If the DOM selection is in the editor and the editor selection is already correct, we're done.
if (hasDomSelection && hasDomSelectionInEditor && selection) {
var slateRange = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: true
});
if (slateRange && Range.equals(slateRange, selection)) {
return;
}
} // when <Editable/> is being controlled through external value
// then its children might just change - DOM responds to it on its own
// but Slate's value is not being updated through any operation
// and thus it doesn't transform selection on its own
if (selection && !ReactEditor.hasRange(editor, selection)) {
editor.selection = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false
});
return;
} // Otherwise the DOM selection is out of sync, so update it.
var el = ReactEditor.toDOMNode(editor, editor);
state.isUpdatingSelection = true;
var newDomRange = selection && ReactEditor.toDOMRange(editor, selection);
if (newDomRange) {
if (Range.isBackward(selection)) {
domSelection.setBaseAndExtent(newDomRange.endContainer, newDomRange.endOffset, newDomRange.startContainer, newDomRange.startOffset);
} else {
domSelection.setBaseAndExtent(newDomRange.startContainer, newDomRange.startOffset, newDomRange.endContainer, newDomRange.endOffset);
}
var leafEl = newDomRange.startContainer.parentElement;
leafEl.getBoundingClientRect = newDomRange.getBoundingClientRect.bind(newDomRange);
scrollIntoView(leafEl, {
scrollMode: 'if-needed',
boundary: el
}); // @ts-ignore
delete leafEl.getBoundingClientRect;
} else {
domSelection.removeAllRanges();
}
setTimeout(() => {
// COMPAT: In Firefox, it's not enough to create a range, you also need
// to focus the contenteditable element too. (2016/11/16)
if (newDomRange && IS_FIREFOX) {
el.focus();
}
state.isUpdatingSelection = false;
});
}); // The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it
// needs to be manually focused.
useEffect(() => {
if (ref.current && autoFocus) {
ref.current.focus();
}
}, [autoFocus]); // Listen on the native `beforeinput` event to get real "Level 2" events. This
// is required because React's `beforeinput` is fake and never really attaches
// to the real event sadly. (2019/11/01)
// https://github.com/facebook/react/issues/11211
var onDOMBeforeInput = useCallback(event => {
if (!readOnly && hasEditableTarget(editor, event.target) && !isDOMEventHandled(event, propsOnDOMBeforeInput)) {
var {
selection
} = editor;
var {
inputType: type
} = event;
var data = event.dataTransfer || event.data || undefined; // These two types occur while a user is composing text and can't be
// cancelled. Let them through and wait for the composition to end.
if (type === 'insertCompositionText' || type === 'deleteCompositionText') {
return;
}
event.preventDefault(); // COMPAT: For the deleting forward/backward input types we don't want
// to change the selection because it is the range that will be deleted,
// and those commands determine that for themselves.
if (!type.startsWith('delete') || type.startsWith('deleteBy')) {
var [targetRange] = event.getTargetRanges();
if (targetRange) {
var range = ReactEditor.toSlateRange(editor, targetRange, {
exactMatch: false
});
if (!selection || !Range.equals(selection, range)) {
Transforms.select(editor, range);
}
}
} // COMPAT: If the selection is expanded, even if the command seems like
// a delete forward/backward command it should delete the selection.
if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
var direction = type.endsWith('Backward') ? 'backward' : 'forward';
Editor.deleteFragment(editor, {
direction
});
return;
}
switch (type) {
case 'deleteByComposition':
case 'deleteByCut':
case 'deleteByDrag':
{
Editor.deleteFragment(editor);
break;
}
case 'deleteContent':
case 'deleteContentForward':
{
Editor.deleteForward(editor);
break;
}
case 'deleteContentBackward':
{
Editor.deleteBackward(editor);
break;
}
case 'deleteEntireSoftLine':
{
Editor.deleteBackward(editor, {
unit: 'line'
});
Editor.deleteForward(editor, {
unit: 'line'
});
break;
}
case 'deleteHardLineBackward':
{
Editor.deleteBackward(editor, {
unit: 'block'
});
break;
}
case 'deleteSoftLineBackward':
{
Editor.deleteBackward(editor, {
unit: 'line'
});
break;
}
case 'deleteHardLineForward':
{
Editor.deleteForward(editor, {
unit: 'block'
});
break;
}
case 'deleteSoftLineForward':
{
Editor.deleteForward(editor, {
unit: 'line'
});
break;
}
case 'deleteWordBackward':
{
Editor.deleteBackward(editor, {
unit: 'word'
});
break;
}
case 'deleteWordForward':
{
Editor.deleteForward(editor, {
unit: 'word'
});
break;
}
case 'insertLineBreak':
case 'insertParagraph':
{
Editor.insertBreak(editor);
break;
}
case 'insertFromComposition':
case 'insertFromDrop':
case 'insertFromPaste':
case 'insertFromYank':
case 'insertReplacementText':
case 'insertText':
{
if (type === 'insertFromComposition') {
// COMPAT: in Safari, `compositionend` is dispatched after the
// `beforeinput` for "insertFromComposition". But if we wait for it
// then we will abort because we're still composing and the selection
// won't be updated properly.
// https://www.w3.org/TR/input-events-2/
state.isComposing = false;
}
var window = ReactEditor.getWindow(editor);
if (data instanceof window.DataTransfer) {
ReactEditor.insertData(editor, data);
} else if (typeof data === 'string') {
Editor.insertText(editor, data);
}
break;
}
}
}
}, [readOnly, propsOnDOMBeforeInput]); // Attach a native DOM event handler for `beforeinput` events, because React's
// built-in `onBeforeInput` is actually a leaky polyfill that doesn't expose
// real `beforeinput` events sadly... (2019/11/04)
// https://github.com/facebook/react/issues/11211
useIsomorphicLayoutEffect(() => {
if (ref.current && HAS_BEFORE_INPUT_SUPPORT) {
// @ts-ignore The `beforeinput` event isn't recognized.
ref.current.addEventListener('beforeinput', onDOMBeforeInput);
}
return () => {
if (ref.current && HAS_BEFORE_INPUT_SUPPORT) {
// @ts-ignore The `beforeinput` event isn't recognized.
ref.current.removeEventListener('beforeinput', onDOMBeforeInput);
}
};
}, [onDOMBeforeInput]); // Listen on the native `selectionchange` event to be able to update any time
// the selection changes. This is required because React's `onSelect` is leaky
// and non-standard so it doesn't fire until after a selection has been
// released. This causes issues in situations where another change happens
// while a selection is being dragged.
var onDOMSelectionChange = useCallback(throttle(() => {
if (!readOnly && !state.isComposing && !state.isUpdatingSelection && !state.isDraggingInternally) {
var root = ReactEditor.findDocumentOrShadowRoot(editor);
var {
activeElement
} = root;
var el = ReactEditor.toDOMNode(editor, editor);
var domSelection = root.getSelection();
if (activeElement === el) {
state.latestElement = activeElement;
IS_FOCUSED.set(editor, true);
} else {
IS_FOCUSED.delete(editor);
}
if (!domSelection) {
return Transforms.deselect(editor);
}
var {
anchorNode,
focusNode
} = domSelection;
var anchorNodeSelectable = hasEditableTarget(editor, anchorNode) || isTargetInsideVoid(editor, anchorNode);
var focusNodeSelectable = hasEditableTarget(editor, focusNode) || isTargetInsideVoid(editor, focusNode);
if (anchorNodeSelectable && focusNodeSelectable) {
var range = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false
});
Transforms.select(editor, range);
} else {
Transforms.deselect(editor);
}
}
}, 100), [readOnly]); // Attach a native DOM event handler for `selectionchange`, because React's
// built-in `onSelect` handler doesn't fire for all selection changes. It's a
// leaky polyfill that only fires on keypresses or clicks. Instead, we want to
// fire for any change to the selection inside the editor. (2019/11/04)
// https://github.com/facebook/react/issues/5785
useIsomorphicLayoutEffect(() => {
var window = ReactEditor.getWindow(editor);
window.document.addEventListener('selectionchange', onDOMSelectionChange);
return () => {
window.document.removeEventListener('selectionchange', onDOMSelectionChange);
};
}, [onDOMSelectionChange]);
var decorations = decorate([editor, []]);
if (placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
var start = Editor.start(editor, []);
decorations.push({
[PLACEHOLDER_SYMBOL]: true,
placeholder,
anchor: start,
focus: start
});
}
return /*#__PURE__*/React.createElement(ReadOnlyContext.Provider, {
value: readOnly
}, /*#__PURE__*/React.createElement(DecorateContext.Provider, {
value: decorate
}, /*#__PURE__*/React.createElement(Component // COMPAT: The Grammarly Chrome extension works by changing the DOM
// out from under `contenteditable` elements, which leads to weird
// behaviors so we have to disable it like editor. (2017/04/24)
, Object.assign({
"data-gramm": false,
role: readOnly ? undefined : 'textbox'
}, attributes, {
// COMPAT: Certain browsers don't support the `beforeinput` event, so we'd
// have to use hacks to make these replacement-based features work.
spellCheck: !HAS_BEFORE_INPUT_SUPPORT ? false : attributes.spellCheck,
autoCorrect: !HAS_BEFORE_INPUT_SUPPORT ? 'false' : attributes.autoCorrect,
autoCapitalize: !HAS_BEFORE_INPUT_SUPPORT ? 'false' : attributes.autoCapitalize,
"data-slate-editor": true,
"data-slate-node": "value",
contentEditable: readOnly ? undefined : true,
suppressContentEditableWarning: true,
ref: ref,
style: _objectSpread({
// Allow positioning relative to the editable element.
position: 'relative',
// Prevent the default outline styles.
outline: 'none',
// Preserve adjacent whitespace and new lines.
whiteSpace: 'pre-wrap',
// Allow words to break if they are too long.
wordWrap: 'break-word'
}, style),
onBeforeInput: useCallback(event => {
// COMPAT: Certain browsers don't support the `beforeinput` event, so we
// fall back to React's leaky polyfill instead just for it. It
// only works for the `insertText` input type.
if (!HAS_BEFORE_INPUT_SUPPORT && !readOnly && !isEventHandled(event, attributes.onBeforeInput) && hasEditableTarget(editor, event.target)) {
event.preventDefault();
if (!state.isComposing) {
var text = event.data;
Editor.insertText(editor, text);
}
}
}, [readOnly]),
onBlur: useCallback(event => {
if (readOnly || state.isUpdatingSelection || !hasEditableTarget(editor, event.target) || isEventHandled(event, attributes.onBlur)) {
return;
}
var window = ReactEditor.getWindow(editor); // COMPAT: If the current `activeElement` is still the previous
// one, this is due to the window being blurred when the tab
// itself becomes unfocused, so we want to abort early to allow to
// editor to stay focused when the tab becomes focused again.
var root = ReactEditor.findDocumentOrShadowRoot(editor);
if (state.latestElement === root.activeElement) {
return;
}
var {
relatedTarget
} = event;
var el = ReactEditor.toDOMNode(editor, editor); // COMPAT: The event should be ignored if the focus is returning
// to the editor from an embedded editable element (eg. an <input>
// element inside a void node).
if (relatedTarget === el) {
return;
} // COMPAT: The event should be ignored if the focus is moving from
// the editor to inside a void node's spacer element.
if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
return;
} // COMPAT: The event should be ignored if the focus is moving to a
// non- editable section of an element that isn't a void node (eg.
// a list item of the check list example).
if (relatedTarget != null && isDOMNode(relatedTarget) && ReactEditor.hasDOMNode(editor, relatedTarget)) {
var node = ReactEditor.toSlateNode(editor, relatedTarget);
if (Element$1.isElement(node) && !editor.isVoid(node)) {
return;
}
}
IS_FOCUSED.delete(editor);
}, [readOnly, attributes.onBlur]),
onClick: useCallback(event => {
if (!readOnly && hasTarget(editor, event.target) && !isEventHandled(event, attributes.onClick) && isDOMNode(event.target)) {
var node = ReactEditor.toSlateNode(editor, event.target);
var path = ReactEditor.findPath(editor, node);
var _start = Editor.start(editor, path);
var end = Editor.end(editor, path);
var startVoid = Editor.void(editor, {
at: _start
});
var endVoid = Editor.void(editor, {
at: end
});
if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
var range = Editor.range(editor, _start);
Transforms.select(editor, range);
}
}
}, [readOnly, attributes.onClick]),
onCompositionEnd: useCallback(event => {
if (hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onCompositionEnd)) {
state.isComposing = false; // COMPAT: In Chrome, `beforeinput` events for compositions
// aren't correct and never fire the "insertFromComposition"
// type that we need. So instead, insert whenever a composition
// ends since it will already have been committed to the DOM.
if (!IS_SAFARI && !IS_FIREFOX_LEGACY && event.data) {
Editor.insertText(editor, event.data);
}
}
}, [attributes.onCompositionEnd]),
onCompositionUpdate: useCallback(event => {
if (hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onCompositionUpdate)) {
state.isComposing = true;
}
}, [attributes.onCompositionUpdate]),
onCompositionStart: useCallback(event => {
if (hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onCompositionStart)) {
var {
selection
} = editor;
if (selection && Range.isExpanded(selection)) {
Editor.deleteFragment(editor);
}
}
}, [attributes.onCompositionStart]),
onCopy: useCallback(event => {
if (hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onCopy)) {
event.preventDefault();
ReactEditor.setFragmentData(editor, event.clipboardData);
}
}, [attributes.onCopy]),
onCut: useCallback(event => {
if (!readOnly && hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onCut)) {
event.preventDefault();
ReactEditor.setFragmentData(editor, event.clipboardData);
var {
selection
} = editor;
if (selection) {
if (Range.isExpanded(selection)) {
Editor.deleteFragment(editor);
} else {
var node = Node.parent(editor, selection.anchor.path);
if (Editor.isVoid(editor, node)) {
Transforms.delete(editor);
}
}
}
}
}, [readOnly, attributes.onCut]),
onDragOver: useCallback(event => {
if (hasTarget(editor, event.target) && !isEventHandled(event, attributes.onDragOver)) {
// Only when the target is void, call `preventDefault` to signal
// that drops are allowed. Editable content is droppable by
// default, and calling `preventDefault` hides the cursor.
var node = ReactEditor.toSlateNode(editor, event.target);
if (Editor.isVoid(editor, node)) {
event.preventDefault();
}
}
}, [attributes.onDragOver]),
onDragStart: useCallback(event => {
if (hasTarget(editor, event.target) && !isEventHandled(event, attributes.onDragStart)) {
var node = ReactEditor.toSlateNode(editor, event.target);
var path = ReactEditor.findPath(editor, node);
var voidMatch = Editor.isVoid(editor, node) || Editor.void(editor, {
at: path,
voids: true
}); // If starting a drag on a void node, make sure it is selected
// so that it shows up in the selection's fragment.
if (voidMatch) {
var range = Editor.range(editor, path);
Transforms.select(editor, range);
}
state.isDraggingInternally = true;
ReactEditor.setFragmentData(editor, event.dataTransfer);
}
}, [attributes.onDragStart]),
onDrop: useCallback(event => {
if (!readOnly && hasTarget(editor, event.target) && !isEventHandled(event, attributes.onDrop)) {
event.preventDefault(); // Keep a reference to the dragged range before updating selection
var draggedRange = editor.selection; // Find the range where the drop happened
var range = ReactEditor.findEventRange(editor, event);
var data = event.dataTransfer;
Transforms.select(editor, range);
if (state.isDraggingInternally) {
if (draggedRange) {
Transforms.delete(editor, {
at: draggedRange
});
}
state.isDraggingInternally = false;
}
ReactEditor.insertData(editor, data); // When dragging from another source into the editor, it's possible
// that the current editor does not have focus.
if (!ReactEditor.isFocused(editor)) {
ReactEditor.focus(editor);
}
}
}, [readOnly, attributes.onDrop]),
onDragEnd: useCallback(event => {
// When dropping on a different droppable element than the current editor,
// `onDrop` is not called. So we need to clean up in `onDragEnd` instead.
// Note: `onDragEnd` is only called when `onDrop` is not called
if (!readOnly && state.isDraggingInternally && hasTarget(editor, event.target) && !isEventHandled(event, attributes.onDragEnd)) {
state.isDraggingInternally = false;
}
}, [readOnly, attributes.onDragEnd]),
onFocus: useCallback(event => {
if (!readOnly && !state.isUpdatingSelection && hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onFocus)) {
var el = ReactEditor.toDOMNode(editor, editor);
var root = ReactEditor.findDocumentOrShadowRoot(editor);
state.latestElement = root.activeElement; // COMPAT: If the editor has nested editable elements, the focus
// can go to them. In Firefox, this must be prevented because it
// results in issues with keyboard navigation. (2017/03/30)
if (IS_FIREFOX && event.target !== el) {
el.focus();
return;
}
IS_FOCUSED.set(editor, true);
}
}, [readOnly, attributes.onFocus]),
onKeyDown: useCallback(event => {
if (!readOnly && hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onKeyDown)) {
var {
nativeEvent
} = event;
var {
selection