slate-react
Version:
Tools for building completely customizable richtext editors with React.
5,077 lines • 205 kB
JavaScript
import getDirection from 'direction';
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
import React, { useContext, createContext, useRef, useEffect, useLayoutEffect, useState, memo, forwardRef, useCallback, useReducer, useMemo, Fragment, Component } from 'react';
import scrollIntoView from 'scroll-into-view-if-needed';
import { Node, Range, Editor, Path, Point, Transforms, Location, Text as Text$1, Scrubber } from 'slate';
import { DOMEditor, isTrackedMutation, EDITOR_TO_FORCE_RENDER, IS_NODE_MAP_DIRTY, EDITOR_TO_PENDING_DIFFS, EDITOR_TO_PENDING_SELECTION, applyStringDiff, EDITOR_TO_PENDING_INSERTION_MARKS, isDOMSelection, isDOMNode, IS_COMPOSING, EDITOR_TO_PENDING_ACTION, EDITOR_TO_USER_MARKS, targetRange, verifyDiffState, EDITOR_TO_PLACEHOLDER_ELEMENT, normalizeStringDiff, mergeStringDiffs, IS_FIREFOX, normalizeRange, normalizePoint, CAN_USE_DOM, IS_ANDROID, EDITOR_TO_SCHEDULE_FLUSH, MARK_PLACEHOLDER_SYMBOL, PLACEHOLDER_SYMBOL, IS_WEBKIT, isTextDecorationsEqual, isElementDecorationsEqual, EDITOR_TO_KEY_TO_ELEMENT, NODE_TO_ELEMENT, ELEMENT_TO_NODE, NODE_TO_INDEX, NODE_TO_PARENT, Key, splitDecorationsByChild, isDOMElement, getSelection, IS_READ_ONLY, getActiveElement, IS_FOCUSED, getDefaultView, EDITOR_TO_WINDOW, EDITOR_TO_ELEMENT, containsShadowAware, IS_CHROME, EDITOR_TO_USER_SELECTION, HAS_BEFORE_INPUT_SUPPORT, isPlainTextOnlyPaste, Hotkeys, IS_FIREFOX_LEGACY, IS_IOS, IS_WECHATBROWSER, IS_UC_MOBILE, TRIPLE_CLICK, copyNodeInUse, EDITOR_TO_ON_CHANGE, withDOM } from 'slate-dom';
export { NODE_TO_INDEX, NODE_TO_PARENT } from 'slate-dom';
import ReactDOM from 'react-dom';
import { ResizeObserver } from '@juggle/resize-observer';
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (-1 !== e.indexOf(n)) continue;
t[n] = r[n];
}
return t;
}
function _objectWithoutProperties(e, t) {
if (null == e) return {};
var o,
r,
i = _objectWithoutPropertiesLoose(e, t);
if (Object.getOwnPropertySymbols) {
var n = Object.getOwnPropertySymbols(e);
for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
}
return i;
}
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r);
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: true,
configurable: true,
writable: true
}) : e[r] = t, e;
}
/**
* A React context for sharing the editor object.
*/
const EditorContext = /*#__PURE__*/createContext(null);
/**
* Get the current editor object from the React context.
*/
const useSlateStatic = () => {
const editor = useContext(EditorContext);
if (!editor) {
throw new Error(`The \`useSlateStatic\` hook must be used inside the <Slate> component's context.`);
}
return editor;
};
// eslint-disable-next-line no-redeclare
const ReactEditor = DOMEditor;
function ownKeys$8(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$8(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$8(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$8(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
// https://github.com/facebook/draft-js/blob/main/src/component/handlers/composition/DraftEditorCompositionHandler.js#L41
// When using keyboard English association function, conpositionEnd triggered too fast, resulting in after `insertText` still maintain association state.
const RESOLVE_DELAY = 25;
// Time with no user interaction before the current user action is considered as done.
const FLUSH_DELAY = 200;
// Time with no composition input after which a composition that never ended is
// treated as stale. Long enough that pausing mid-word does not cut a live
// composition short.
const COMPOSITION_IDLE_TIMEOUT = 5000;
// How often a deferred flush re-checks whether the composition is still live.
// Only bounds how quickly the value catches up with a composition that ended
// without firing `compositionend`; one that ends normally flushes immediately.
const COMPOSITION_RECHECK_DELAY = 50;
// Replace with `const debug = console.log` to debug
const debug = (..._) => {};
// Type guard to check if a value is a DataTransfer
const isDataTransfer = value => (value === null || value === void 0 ? void 0 : value.constructor.name) === 'DataTransfer';
const wordEndingAt = (editor, point, replacement) => {
var _replacement$;
const start = Editor.before(editor, point, {
unit: 'word'
});
if (!start || !Path.equals(start.path, point.path)) {
return null;
}
const typed = Editor.string(editor, {
anchor: start,
focus: point
});
return !/\s/.test(typed) && ((_replacement$ = replacement[0]) === null || _replacement$ === void 0 ? void 0 : _replacement$.toLowerCase()) === typed[0].toLowerCase() ? {
anchor: start,
focus: point
} : null;
};
const EDITOR_TO_FLUSH_DEFERRED_DIFFS = new WeakMap();
function createAndroidInputManager({
editor,
scheduleOnDOMSelectionChange,
onDOMSelectionChange
}) {
let flushing = false;
let flushingDeferredDiffs = false;
let compositionEndTimeoutId = null;
let flushTimeoutId = null;
let actionTimeoutId = null;
let lastCompositionActivity = 0;
let lastInsertText = 0;
let compositionCleared = false;
let hasUnrenderedMutations = false;
let idCounter = 0;
let insertPositionHint = false;
const applyPendingSelection = () => {
const pendingSelection = EDITOR_TO_PENDING_SELECTION.get(editor);
EDITOR_TO_PENDING_SELECTION.delete(editor);
if (pendingSelection) {
const {
selection
} = editor;
const normalized = normalizeRange(editor, pendingSelection);
if (normalized && (!selection || !Range.equals(normalized, selection))) {
Transforms.select(editor, normalized);
}
}
};
const performAction = () => {
const {
children
} = editor;
runPendingAction();
if (hasUnrenderedMutations && editor.children === children) {
var _EDITOR_TO_FORCE_REND;
(_EDITOR_TO_FORCE_REND = EDITOR_TO_FORCE_RENDER.get(editor)) === null || _EDITOR_TO_FORCE_REND === void 0 || _EDITOR_TO_FORCE_REND();
}
hasUnrenderedMutations = false;
};
const runPendingAction = () => {
const action = EDITOR_TO_PENDING_ACTION.get(editor);
EDITOR_TO_PENDING_ACTION.delete(editor);
if (!action) {
return;
}
if (action.at) {
const target = Location.isPoint(action.at) ? normalizePoint(editor, action.at) : normalizeRange(editor, action.at);
if (!target) {
return;
}
const targetRange = Editor.range(editor, target);
if (!editor.selection || !Range.equals(editor.selection, targetRange)) {
Transforms.select(editor, target);
}
}
action.run();
};
// `compositionend` is not fired reliably in every browser, which Slate
// already works around on keydown. Deferring flushes on a composition that
// never ends would strand the typed text outside the value, so a composition
// that has gone quiet, or that has lost focus, no longer holds flushes back.
const isCompositionLive = () => {
if (!IS_COMPOSING.get(editor) || compositionCleared) {
return false;
}
try {
const editable = ReactEditor.toDOMNode(editor, editor);
const {
activeElement
} = ReactEditor.getWindow(editor).document;
if (activeElement !== editable && !editable.contains(activeElement)) {
return false;
}
} catch (_unused) {
// Fall back to the idle check below if the editable can't be resolved.
}
return Date.now() - lastCompositionActivity < COMPOSITION_IDLE_TIMEOUT;
};
// A leaf that Slate models as empty renders as a zero-width string, which on
// Android is a `<br>` rather than a text node. When the IME composes the
// first character into such a leaf, the browser creates a text node for the
// composition. Applying the pending diffs re-renders that leaf as a text
// leaf, which unmounts the zero-width span and takes the text node the IME is
// composing in with it, silently cancelling the composition.
const hasPendingDiffsInEmptyLeaf = () => {
var _EDITOR_TO_PENDING_DI;
return !!((_EDITOR_TO_PENDING_DI = EDITOR_TO_PENDING_DIFFS.get(editor)) !== null && _EDITOR_TO_PENDING_DI !== void 0 && _EDITOR_TO_PENDING_DI.some(({
path
}) => {
try {
return Node.leaf(editor, path).text.length === 0;
} catch (_unused2) {
// The path may no longer resolve if the editor changed underneath us.
return false;
}
}));
};
const hasPendingDiffsInNewLeaf = () => hasPendingDiffsInEmptyLeaf() || hasPendingDiffs() && EDITOR_TO_PENDING_INSERTION_MARKS.get(editor) !== undefined;
const flush = () => {
if (flushTimeoutId) {
clearTimeout(flushTimeoutId);
flushTimeoutId = null;
}
if (actionTimeoutId) {
clearTimeout(actionTimeoutId);
actionTimeoutId = null;
}
// Defer flushing until the composition ends, so that the re-render that
// would replace the composing text node cannot happen mid-composition.
// Composing into a leaf that already has text is unaffected: applying the
// diff there only updates `textContent`, so the value still updates on
// every `compositionupdate`.
if (!flushingDeferredDiffs && isCompositionLive() && hasPendingDiffsInNewLeaf()) {
flushTimeoutId = setTimeout(flush, COMPOSITION_RECHECK_DELAY);
return;
}
if (!hasPendingDiffs() && !hasPendingAction()) {
applyPendingSelection();
return;
}
if (!flushing) {
flushing = true;
setTimeout(() => flushing = false);
}
if (hasPendingAction()) {
flushing = 'action';
}
const selectionRef = editor.selection && Editor.rangeRef(editor, editor.selection, {
affinity: 'forward'
});
EDITOR_TO_USER_MARKS.set(editor, editor.marks);
debug('flush', EDITOR_TO_PENDING_ACTION.get(editor), EDITOR_TO_PENDING_DIFFS.get(editor));
let scheduleSelectionChange = hasPendingDiffs();
let diff;
while (diff = (_EDITOR_TO_PENDING_DI2 = EDITOR_TO_PENDING_DIFFS.get(editor)) === null || _EDITOR_TO_PENDING_DI2 === void 0 ? void 0 : _EDITOR_TO_PENDING_DI2[0]) {
var _EDITOR_TO_PENDING_DI2, _EDITOR_TO_PENDING_DI3;
const pendingMarks = EDITOR_TO_PENDING_INSERTION_MARKS.get(editor);
if (pendingMarks !== undefined) {
EDITOR_TO_PENDING_INSERTION_MARKS.delete(editor);
editor.marks = pendingMarks;
}
if (pendingMarks && insertPositionHint === false) {
insertPositionHint = null;
}
const range = targetRange(diff);
if (!editor.selection || !Range.equals(editor.selection, range)) {
Transforms.select(editor, range);
}
if (diff.diff.text) {
Editor.insertText(editor, diff.diff.text);
} else {
Editor.deleteFragment(editor);
}
// Remove diff only after we have applied it to account for it when transforming
// pending ranges.
EDITOR_TO_PENDING_DIFFS.set(editor, (_EDITOR_TO_PENDING_DI3 = EDITOR_TO_PENDING_DIFFS.get(editor)) === null || _EDITOR_TO_PENDING_DI3 === void 0 ? void 0 : _EDITOR_TO_PENDING_DI3.filter(({
id
}) => id !== diff.id));
if (!verifyDiffState(editor, diff)) {
scheduleSelectionChange = false;
EDITOR_TO_PENDING_ACTION.delete(editor);
EDITOR_TO_USER_MARKS.delete(editor);
flushing = 'action';
// Ensure we don't restore the pending user (dom) selection
// since the document and dom state do not match.
EDITOR_TO_PENDING_SELECTION.delete(editor);
scheduleOnDOMSelectionChange.cancel();
onDOMSelectionChange.cancel();
selectionRef === null || selectionRef === void 0 || selectionRef.unref();
}
}
const selection = selectionRef === null || selectionRef === void 0 ? void 0 : selectionRef.unref();
if (selection && !EDITOR_TO_PENDING_SELECTION.get(editor) && (!editor.selection || !Range.equals(selection, editor.selection))) {
Transforms.select(editor, selection);
}
if (hasPendingAction()) {
performAction();
return;
}
// COMPAT: The selectionChange event is fired after the action is performed,
// so we have to manually schedule it to ensure we don't 'throw away' the selection
// while rendering if we have pending changes.
if (scheduleSelectionChange) {
scheduleOnDOMSelectionChange();
}
scheduleOnDOMSelectionChange.flush();
onDOMSelectionChange.flush();
applyPendingSelection();
const userMarks = EDITOR_TO_USER_MARKS.get(editor);
EDITOR_TO_USER_MARKS.delete(editor);
if (userMarks !== undefined && userMarks !== editor.marks) {
editor.marks = userMarks;
editor.onChange();
}
};
const flushDeferredDiffs = () => {
if (flushing || !isCompositionLive() || !hasPendingDiffsInNewLeaf()) {
return;
}
flushingDeferredDiffs = true;
try {
flush();
} finally {
flushingDeferredDiffs = false;
}
};
const handleCompositionEnd = _event => {
if (compositionEndTimeoutId) {
clearTimeout(compositionEndTimeoutId);
}
// Diffs deferred by `flush` have to be applied synchronously here. IMEs
// that compose one syllable at a time (Hangul, kana) start the next
// composition in the same tick as this event, so an asynchronous render
// would replace the text node that composition has already started in.
if (hasPendingDiffsInNewLeaf() && !flushing) {
ReactDOM.flushSync(() => {
IS_COMPOSING.set(editor, false);
flush();
});
updatePlaceholderVisibility();
return;
}
compositionEndTimeoutId = setTimeout(() => {
IS_COMPOSING.set(editor, false);
flush();
if (compositionCleared) {
var _EDITOR_TO_FORCE_REND2;
// A cancelled composition can take the empty leaf's text node with
// it. A forced render lets RestoreDOM put the leaf's DOM back, so the
// next composition starts from a clean state instead of a bare <br>.
(_EDITOR_TO_FORCE_REND2 = EDITOR_TO_FORCE_RENDER.get(editor)) === null || _EDITOR_TO_FORCE_REND2 === void 0 || _EDITOR_TO_FORCE_REND2();
}
updatePlaceholderVisibility();
}, RESOLVE_DELAY);
};
const handleCompositionStart = _event => {
IS_COMPOSING.set(editor, true);
lastCompositionActivity = Date.now();
compositionCleared = false;
if (compositionEndTimeoutId) {
clearTimeout(compositionEndTimeoutId);
compositionEndTimeoutId = null;
}
};
const updatePlaceholderVisibility = (forceHide = false) => {
const placeholderElement = EDITOR_TO_PLACEHOLDER_ELEMENT.get(editor);
if (!placeholderElement) {
return;
}
if (hasPendingDiffs() || forceHide) {
placeholderElement.style.display = 'none';
return;
}
placeholderElement.style.removeProperty('display');
};
const storeDiff = (path, diff) => {
var _EDITOR_TO_PENDING_DI4;
const pendingDiffs = (_EDITOR_TO_PENDING_DI4 = EDITOR_TO_PENDING_DIFFS.get(editor)) !== null && _EDITOR_TO_PENDING_DI4 !== void 0 ? _EDITOR_TO_PENDING_DI4 : [];
EDITOR_TO_PENDING_DIFFS.set(editor, pendingDiffs);
const target = Node.leaf(editor, path);
const idx = pendingDiffs.findIndex(change => Path.equals(change.path, path));
if (idx < 0) {
const normalized = normalizeStringDiff(target.text, diff);
if (normalized) {
pendingDiffs.push({
path,
diff,
id: idCounter++
});
}
updatePlaceholderVisibility();
return;
}
const merged = mergeStringDiffs(target.text, pendingDiffs[idx].diff, diff);
if (!merged) {
pendingDiffs.splice(idx, 1);
updatePlaceholderVisibility();
return;
}
pendingDiffs[idx] = _objectSpread$8(_objectSpread$8({}, pendingDiffs[idx]), {}, {
diff: merged
});
};
const scheduleAction = (run, {
at
} = {}) => {
insertPositionHint = false;
EDITOR_TO_PENDING_SELECTION.delete(editor);
scheduleOnDOMSelectionChange.cancel();
onDOMSelectionChange.cancel();
if (hasPendingAction()) {
flush();
}
if (actionTimeoutId) {
clearTimeout(actionTimeoutId);
}
EDITOR_TO_PENDING_ACTION.set(editor, {
at,
run
});
// COMPAT: When deleting before a non-contenteditable element chrome only fires a beforeinput,
// (no input) and doesn't perform any dom mutations. Without a flush timeout we would never flush
// in this case and thus never actually perform the action.
actionTimeoutId = setTimeout(flush);
};
const handleDOMBeforeInput = event => {
if (flushTimeoutId) {
clearTimeout(flushTimeoutId);
flushTimeoutId = null;
}
const isNodeMapDirty = IS_NODE_MAP_DIRTY.get(editor);
const {
inputType: type
} = event;
const continuesFirefoxInsert = IS_FIREFOX && type === 'insertText' && Date.now() - lastInsertText < RESOLVE_DELAY;
if (type === 'insertText') {
lastInsertText = Date.now();
}
if (type === 'insertCompositionText' || type === 'deleteCompositionText') {
lastCompositionActivity = Date.now();
if (event.data) {
compositionCleared = false;
} else {
// The IME threw away what it was composing. The deferred text never
// reached the value, so the value is already in the desired state -
// drop the deferral instead of applying and re-deleting it, which
// would churn the DOM mid-composition and can make Android close the
// keyboard.
compositionCleared = true;
const deferredDiffs = EDITOR_TO_PENDING_DIFFS.get(editor);
if (deferredDiffs !== null && deferredDiffs !== void 0 && deferredDiffs.length) {
const allInEmptyLeaves = deferredDiffs.every(({
path
}) => {
try {
return Node.leaf(editor, path).text.length === 0;
} catch (_unused3) {
return false;
}
});
if (allInEmptyLeaves) {
EDITOR_TO_PENDING_DIFFS.set(editor, []);
EDITOR_TO_PENDING_SELECTION.delete(editor);
}
}
}
}
let targetRange = null;
const data = event.dataTransfer || event.data || undefined;
if (insertPositionHint !== false && type !== 'insertText' && type !== 'insertCompositionText') {
insertPositionHint = false;
}
let [nativeTargetRange] = event.getTargetRanges();
const targetOutsideEditor = !!nativeTargetRange && !ReactEditor.hasDOMNode(editor, nativeTargetRange.startContainer);
if (nativeTargetRange && !isNodeMapDirty) {
targetRange = ReactEditor.toSlateRange(editor, nativeTargetRange, {
exactMatch: false,
suppressThrow: true
});
}
// COMPAT: SelectionChange event is fired after the action is performed, so we
// have to manually get the selection here to ensure it's up-to-date.
const window = ReactEditor.getWindow(editor);
const domSelection = window.getSelection();
if (!targetRange && domSelection && !isNodeMapDirty) {
nativeTargetRange = domSelection;
targetRange = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false,
suppressThrow: true
});
}
targetRange = targetRange !== null && targetRange !== void 0 ? targetRange : editor.selection;
if (!targetRange) {
return;
}
// By default, the input manager tries to store text diffs so that we can
// defer flushing them at a later point in time. We don't want to flush
// for every input event as this can be expensive. However, there are some
// scenarios where we cannot safely store the text diff and must instead
// schedule an action to let Slate normalize the editor state.
let canStoreDiff = true;
if (type.startsWith('delete')) {
const direction = type.endsWith('Backward') ? 'backward' : 'forward';
let [start, end] = Range.edges(targetRange);
let [leaf, path] = Editor.leaf(editor, start.path);
if (Range.isExpanded(targetRange)) {
if (leaf.text.length === start.offset && end.offset === 0) {
const next = Editor.next(editor, {
at: start.path,
match: Node.isText
});
if (next && Path.equals(next[1], end.path)) {
// when deleting a linebreak, targetRange will span across the break (ie start in the node before and end in the node after)
// if the node before is empty, this will look like a hanging range and get unhung later--which will take the break we want to remove out of the range
// so to avoid this we collapse the target range to default to single character deletion
if (direction === 'backward') {
targetRange = {
anchor: end,
focus: end
};
start = end;
[leaf, path] = next;
} else {
targetRange = {
anchor: start,
focus: start
};
end = start;
}
}
}
}
const diff = {
text: '',
start: start.offset,
end: end.offset
};
const pendingDiffs = EDITOR_TO_PENDING_DIFFS.get(editor);
const relevantPendingDiffs = pendingDiffs === null || pendingDiffs === void 0 ? void 0 : pendingDiffs.find(change => Path.equals(change.path, path));
const diffs = relevantPendingDiffs ? [relevantPendingDiffs.diff, diff] : [diff];
const text = applyStringDiff(leaf.text, ...diffs);
if (text.length === 0) {
// Text leaf will be removed, so we need to schedule an
// action to remove it so that Slate can normalize instead
// of storing as a diff
canStoreDiff = false;
}
if (Range.isExpanded(targetRange)) {
if (canStoreDiff && Path.equals(targetRange.anchor.path, targetRange.focus.path)) {
const point = {
path: targetRange.anchor.path,
offset: start.offset
};
const range = Editor.range(editor, point, point);
handleUserSelect(range);
storeDiff(targetRange.anchor.path, {
text: '',
end: end.offset,
start: start.offset
});
if (type === 'deleteContentBackward') {
scheduleFlush();
}
return;
}
return scheduleAction(() => Editor.deleteFragment(editor, {
direction
}), {
at: targetRange
});
}
}
switch (type) {
case 'deleteByComposition':
case 'deleteByCut':
case 'deleteByDrag':
{
return scheduleAction(() => Editor.deleteFragment(editor), {
at: targetRange
});
}
case 'deleteContent':
case 'deleteContentForward':
{
const {
anchor
} = targetRange;
if (canStoreDiff && Range.isCollapsed(targetRange)) {
const targetNode = Node.leaf(editor, anchor.path);
if (anchor.offset < targetNode.text.length) {
return storeDiff(anchor.path, {
text: '',
start: anchor.offset,
end: anchor.offset + 1
});
}
}
return scheduleAction(() => Editor.deleteForward(editor), {
at: targetRange
});
}
case 'deleteContentBackward':
{
var _nativeTargetRange;
const {
anchor
} = targetRange;
// If we have a mismatch between the native and slate selection being collapsed
// we are most likely deleting a zero-width placeholder and thus should perform it
// as an action to ensure correct behavior (mostly happens with mark placeholders)
const nativeCollapsed = isDOMSelection(nativeTargetRange) ? nativeTargetRange.isCollapsed : !!((_nativeTargetRange = nativeTargetRange) !== null && _nativeTargetRange !== void 0 && _nativeTargetRange.collapsed);
if (canStoreDiff && nativeCollapsed && Range.isCollapsed(targetRange) && anchor.offset > 0) {
storeDiff(anchor.path, {
text: '',
start: anchor.offset - 1,
end: anchor.offset
});
scheduleFlush();
return;
}
return scheduleAction(() => Editor.deleteBackward(editor), {
at: targetRange
});
}
case 'deleteEntireSoftLine':
{
return scheduleAction(() => {
Editor.deleteBackward(editor, {
unit: 'line'
});
Editor.deleteForward(editor, {
unit: 'line'
});
}, {
at: targetRange
});
}
case 'deleteHardLineBackward':
{
return scheduleAction(() => Editor.deleteBackward(editor, {
unit: 'block'
}), {
at: targetRange
});
}
case 'deleteSoftLineBackward':
{
return scheduleAction(() => Editor.deleteBackward(editor, {
unit: 'line'
}), {
at: targetRange
});
}
case 'deleteHardLineForward':
{
return scheduleAction(() => Editor.deleteForward(editor, {
unit: 'block'
}), {
at: targetRange
});
}
case 'deleteSoftLineForward':
{
return scheduleAction(() => Editor.deleteForward(editor, {
unit: 'line'
}), {
at: targetRange
});
}
case 'deleteWordBackward':
{
return scheduleAction(() => Editor.deleteBackward(editor, {
unit: 'word'
}), {
at: targetRange
});
}
case 'deleteWordForward':
{
return scheduleAction(() => Editor.deleteForward(editor, {
unit: 'word'
}), {
at: targetRange
});
}
case 'insertLineBreak':
{
return scheduleAction(() => Editor.insertSoftBreak(editor), {
at: targetRange
});
}
case 'insertParagraph':
{
return scheduleAction(() => Editor.insertBreak(editor), {
at: targetRange
});
}
case 'insertCompositionText':
case 'deleteCompositionText':
case 'insertFromComposition':
case 'insertFromDrop':
case 'insertFromPaste':
case 'insertFromYank':
case 'insertReplacementText':
case 'insertText':
{
if (isDataTransfer(data)) {
return scheduleAction(() => ReactEditor.insertData(editor, data), {
at: targetRange
});
}
let text = data !== null && data !== void 0 ? data : '';
// COMPAT: If we are writing inside a placeholder, the ime inserts the text inside
// the placeholder itself and thus includes the zero-width space inside edit events.
if (EDITOR_TO_PENDING_INSERTION_MARKS.get(editor)) {
text = text.replace('\uFEFF', '');
}
if (continuesFirefoxInsert && editor.selection && !Range.equals(targetRange, editor.selection)) {
event.preventDefault();
return scheduleAction(() => Editor.insertText(editor, text));
}
if (targetOutsideEditor && Range.isCollapsed(targetRange)) {
var _wordEndingAt;
event.preventDefault();
return scheduleAction(() => Editor.insertText(editor, text), {
at: (_wordEndingAt = wordEndingAt(editor, targetRange.anchor, text)) !== null && _wordEndingAt !== void 0 ? _wordEndingAt : targetRange
});
}
// Pastes from the Android clipboard will generate `insertText` events.
// If the copied text contains any newlines, Android will append an
// extra newline to the end of the copied text.
if (type === 'insertText' && /.*\n.*\n$/.test(text)) {
text = text.slice(0, -1);
}
// If the text includes a newline, split it at newlines and paste each component
// string, with soft breaks in between each.
if (text.includes('\n')) {
return scheduleAction(() => {
const parts = text.split('\n');
parts.forEach((line, i) => {
if (line) {
Editor.insertText(editor, line);
}
if (i !== parts.length - 1) {
Editor.insertSoftBreak(editor);
}
});
}, {
at: targetRange
});
}
if (type === 'insertText' && !ReactEditor.isComposing(editor) && Range.isCollapsed(targetRange) && typeof Editor.insertionPoint === 'function' && !Point.equals(Editor.insertionPoint(editor, targetRange.anchor), targetRange.anchor)) {
var _nativeTargetRange2;
const node = isDOMSelection(nativeTargetRange) ? nativeTargetRange.anchorNode : (_nativeTargetRange2 = nativeTargetRange) === null || _nativeTargetRange2 === void 0 ? void 0 : _nativeTargetRange2.startContainer;
const snapshot = isDOMNode(node) && node.nodeType === 3 ? {
node,
text: node.textContent
} : null;
event.preventDefault();
return scheduleAction(() => {
if (snapshot && snapshot.node.isConnected && snapshot.node.textContent !== snapshot.text) {
snapshot.node.textContent = snapshot.text;
}
Editor.insertText(editor, text);
}, {
at: targetRange
});
}
if (Path.equals(targetRange.anchor.path, targetRange.focus.path)) {
const [start, end] = Range.edges(targetRange);
const diff = {
start: start.offset,
end: end.offset,
text
};
// COMPAT: Swiftkey has a weird bug where the target range of the 2nd word
// inserted after a mark placeholder is inserted with an anchor offset off by 1.
// So writing 'some text' will result in 'some ttext'. Luckily all 'normal' insert
// text events are fired with the correct target ranges, only the final 'insertComposition'
// isn't, so we can adjust the target range start offset if we are confident this is the
// swiftkey insert causing the issue.
if (text && insertPositionHint && type === 'insertCompositionText') {
const hintPosition = insertPositionHint.start + insertPositionHint.text.search(/\S|$/);
const diffPosition = diff.start + diff.text.search(/\S|$/);
if (diffPosition === hintPosition + 1 && diff.end === insertPositionHint.start + insertPositionHint.text.length) {
diff.start -= 1;
insertPositionHint = null;
scheduleFlush();
} else {
insertPositionHint = false;
}
} else if (type === 'insertText') {
if (insertPositionHint === null) {
insertPositionHint = diff;
} else if (insertPositionHint && Range.isCollapsed(targetRange) && insertPositionHint.end + insertPositionHint.text.length === start.offset) {
insertPositionHint = _objectSpread$8(_objectSpread$8({}, insertPositionHint), {}, {
text: insertPositionHint.text + text
});
} else {
insertPositionHint = false;
}
} else {
insertPositionHint = false;
}
if (canStoreDiff) {
const currentSelection = editor.selection;
storeDiff(start.path, diff);
if (currentSelection) {
const newPoint = {
path: start.path,
offset: start.offset + text.length
};
scheduleAction(() => {}, {
at: newPoint
});
}
return;
}
}
return scheduleAction(() => Editor.insertText(editor, text), {
at: targetRange
});
}
}
};
const hasPendingAction = () => {
return !!EDITOR_TO_PENDING_ACTION.get(editor);
};
const hasPendingDiffs = () => {
var _EDITOR_TO_PENDING_DI5;
return !!((_EDITOR_TO_PENDING_DI5 = EDITOR_TO_PENDING_DIFFS.get(editor)) !== null && _EDITOR_TO_PENDING_DI5 !== void 0 && _EDITOR_TO_PENDING_DI5.length);
};
const hasPendingChanges = () => {
return hasPendingAction() || hasPendingDiffs();
};
const isFlushing = () => {
return flushing;
};
const handleUserSelect = range => {
EDITOR_TO_PENDING_SELECTION.set(editor, range);
if (flushTimeoutId) {
clearTimeout(flushTimeoutId);
flushTimeoutId = null;
}
const {
selection
} = editor;
if (!range) {
return;
}
const pathChanged = !selection || !Path.equals(selection.anchor.path, range.anchor.path);
const parentPathChanged = !selection || !Path.equals(selection.anchor.path.slice(0, -1), range.anchor.path.slice(0, -1));
if (pathChanged && insertPositionHint || parentPathChanged) {
insertPositionHint = false;
}
if (pathChanged || hasPendingDiffs()) {
flushTimeoutId = setTimeout(flush, FLUSH_DELAY);
}
};
const handleInput = () => {
if (hasPendingAction() || !hasPendingDiffs()) {
flush();
}
};
const handleKeyDown = _ => {
// COMPAT: Swiftkey closes the keyboard when typing inside a empty node
// directly next to a non-contenteditable element (= the placeholder).
// The only event fired soon enough for us to allow hiding the placeholder
// without swiftkey picking it up is the keydown event, so we have to hide it
// here. See https://github.com/ianstormtaylor/slate/pull/4988#issuecomment-1201050535
if (!hasPendingDiffs()) {
updatePlaceholderVisibility(true);
setTimeout(updatePlaceholderVisibility);
}
};
const scheduleFlush = () => {
if (!hasPendingAction()) {
if (actionTimeoutId) {
clearTimeout(actionTimeoutId);
}
actionTimeoutId = setTimeout(flush);
}
};
const handleDomMutations = mutations => {
var _EDITOR_TO_FORCE_REND3;
if (hasPendingDiffs()) {
return;
}
if (!mutations.some(mutation => isTrackedMutation(editor, mutation, mutations))) {
return;
}
if (hasPendingAction()) {
hasUnrenderedMutations = true;
return;
}
// Cause a re-render to restore the dom state if we encounter tracked mutations without
// a corresponding pending action.
(_EDITOR_TO_FORCE_REND3 = EDITOR_TO_FORCE_RENDER.get(editor)) === null || _EDITOR_TO_FORCE_REND3 === void 0 || _EDITOR_TO_FORCE_REND3();
};
return {
flush,
flushDeferredDiffs,
scheduleFlush,
hasPendingDiffs,
hasPendingAction,
hasPendingChanges,
isFlushing,
handleUserSelect,
handleCompositionEnd,
handleCompositionStart,
handleDOMBeforeInput,
handleKeyDown,
handleDomMutations,
handleInput
};
}
function useIsMounted() {
const isMountedRef = useRef(false);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
return isMountedRef.current;
}
/**
* Prevent warning on SSR by falling back to useEffect when DOM isn't available
*/
const useIsomorphicLayoutEffect = CAN_USE_DOM ? useLayoutEffect : useEffect;
function useMutationObserver(node, callback, options) {
const [mutationObserver] = useState(() => new MutationObserver(callback));
useIsomorphicLayoutEffect(() => {
// Discard mutations caused during render phase. This works due to react calling
// useLayoutEffect synchronously after the render phase before the next tick.
mutationObserver.takeRecords();
});
useEffect(() => {
if (!node.current) {
throw new Error('Failed to attach MutationObserver, `node` is undefined');
}
mutationObserver.observe(node.current, options);
return () => mutationObserver.disconnect();
}, [mutationObserver, node, options]);
}
const _excluded$2 = ["node"];
function ownKeys$7(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$7(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$7(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const MUTATION_OBSERVER_CONFIG$1 = {
subtree: true,
childList: true,
characterData: true
};
const useAndroidInputManager = !IS_ANDROID ? () => null : _ref => {
let {
node
} = _ref,
options = _objectWithoutProperties(_ref, _excluded$2);
if (!IS_ANDROID) {
return null;
}
const editor = useSlateStatic();
const isMounted = useIsMounted();
const [inputManager] = useState(() => createAndroidInputManager(_objectSpread$7({
editor
}, options)));
useMutationObserver(node, inputManager.handleDomMutations, MUTATION_OBSERVER_CONFIG$1);
EDITOR_TO_SCHEDULE_FLUSH.set(editor, inputManager.scheduleFlush);
EDITOR_TO_FLUSH_DEFERRED_DIFFS.set(editor, inputManager.flushDeferredDiffs);
if (isMounted) {
inputManager.flush();
}
return inputManager;
};
function ownKeys$6(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$6(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$6(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
/**
* Leaf content strings.
*/
const String$1 = props => {
const {
isLast,
leaf,
parent,
text
} = props;
const editor = useSlateStatic();
const path = ReactEditor.findPath(editor, text);
const parentPath = Path.parent(path);
const isMarkPlaceholder = Boolean(leaf[MARK_PLACEHOLDER_SYMBOL]);
// 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,
isMarkPlaceholder: isMarkPlaceholder
});
}
// 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, {
isMarkPlaceholder: isMarkPlaceholder
});
}
// 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.
*/
const TextString = props => {
const {
text,
isTrailing = false
} = props;
const editor = useSlateStatic();
const ref = useRef(null);
const getTextContent = () => {
return `${text !== null && text !== void 0 ? text : ''}${isTrailing ? '\n' : ''}`;
};
const [initialText] = useState(getTextContent);
// This is the actual text rendering boundary where we interface with the DOM
// The text is not rendered as part of the virtual DOM, as since we handle basic character insertions natively,
// updating the DOM is not a one way dataflow anymore. What we need here is not reconciliation and diffing
// with previous version of the virtual DOM, but rather diffing with the actual DOM element, and replace the DOM <span> content
// exactly if and only if its current content does not match our current virtual DOM.
// Otherwise the DOM TextNode would always be replaced by React as the user types, which interferes with native text features,
// eg makes native spellcheck opt out from checking the text node.
// useLayoutEffect: updating our span before browser paint
useIsomorphicLayoutEffect(() => {
var _ref$current2, _ref$current3;
// null coalescing text to make sure we're not outputing "null" as a string in the extreme case it is nullish at runtime
const textWithTrailing = getTextContent();
if (ref.current && ref.current.textContent !== textWithTrailing) {
// On Android the DOM intentionally runs ahead of the value while the IME
// composes, since input is buffered as pending diffs. Writing
// `textContent` here would replace the text node the composition lives in
// and cancel it; the pending diffs reconcile this span when the
// composition ends.
if (IS_ANDROID && IS_COMPOSING.get(editor)) {
var _ReactEditor$getWindo;
const composingNode = (_ReactEditor$getWindo = ReactEditor.getWindow(editor).getSelection()) === null || _ReactEditor$getWindo === void 0 ? void 0 : _ReactEditor$getWindo.anchorNode;
if (composingNode && ref.current.contains(composingNode)) {
return;
}
}
ref.current.textContent = textWithTrailing;
}
if (IS_FIREFOX) {
var _ref$current;
(_ref$current = ref.current) === null || _ref$current === void 0 || _ref$current.toggleAttribute('data-slate-trailing', isTrailing);
}
const textNode = (_ref$current2 = ref.current) === null || _ref$current2 === void 0 ? void 0 : _ref$current2.firstChild;
if (IS_FIREFOX && isTrailing && ((_ref$current3 = ref.current) === null || _ref$current3 === void 0 ? void 0 : _ref$current3.childNodes.length) === 1 && (textNode === null || textNode === void 0 ? void 0 : textNode.nodeType) === 3) {
textNode.splitText(text.length);
}
// intentionally not specifying dependencies, so that this effect runs on every render
// as this effectively replaces "specifying the text in the virtual DOM under the <span> below" on each render
});
// We intentionally render a memoized <span> that only receives the initial text content when the component is mounted.
// We defer to the layout effect above to update the `textContent` of the span element when needed.
return /*#__PURE__*/React.createElement(MemoizedText$1, {
ref: ref
}, initialText);
};
const MemoizedText$1 = /*#__PURE__*/memo(/*#__PURE__*/forwardRef((props, ref) => {
return /*#__PURE__*/React.createElement("span", {
"data-slate-string": true,
ref: ref
}, props.children);
}));
/**
* Leaf strings without text, render as zero-width strings.
*/
const ZeroWidthString = props => {
const {
length = 0,
isLineBreak = false,
isMarkPlaceholder = false
} = props;
const attributes = {
'data-slate-zero-width': isLineBreak ? 'n' : 'z',
'data-slate-length': length
};
if (isMarkPlaceholder) {
attributes['data-slate-mark-placeholder'] = true;
}
// FIXME: Inserting the \uFEFF on iOS breaks capitalization at the start of an
// empty editor (https://github.com/ianstormtaylor/slate/issues/5199).
//
// However, not inserting the \uFEFF on iOS causes the editor to crash when
// inserting any text using an IME at the start of a block. This appears to
// be because accepting an IME suggestion when at the start of a block (no
// preceding \uFEFF) removes one or more DOM elements that `toSlateRange`
// depends on. (https://github.com/ianstormtaylor/slate/issues/5703)
// A leaf with no text node at all forces the IME to create one when the
// first character is composed there, and no re-render can then touch the
// leaf without cancelling the composition. Rendering the zero-width space on
// Android too gives the composition a React-owned text node to live in; the
// wrapper keeps its data-slate-zero-width attributes, so selection mapping
// is unchanged.
return /*#__PURE__*/React.createElement("span", _objectSpread$6({}, attributes), '\uFEFF', isLineBreak ? /*#__PURE__*/React.createElement("br", null) : null);
};
const hasSameProperties = (prev, next) => {
const prevKeys = Object.keys(prev).filter(key => key !== 'children');
const nextKeys = Object.keys(next).filter(key => key !== 'children');
return prevKeys.length === nextKeys.length && prevKeys.every(key => key in next && prev[key] === next[key]);
};
const isLastChild = (parent, text) => parent.children[parent.children.length - 1] === text;
const isTextParentEquivalent = (prevParent, nextParent, prevText, nextText) => {
if (prevParent === nextParent) {
return true;
}
return hasSameProperties(prevParent, nextParent) && isLastChild(prevParent, prevText) === isLastChild(nextParent, nextText) && (nextText.text !== '' || Node.string(prevParent) === '' === (Node.string(nextParent) === ''));
};
function ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
// Delay the placeholder on Android to prevent the keyboard from closing.
// (https://github.com/ianstormtaylor/slate/pull/5368)
const PLACEHOLDER_DELAY = IS_ANDROID ? 300 : 0;
function disconnectPlaceholderResizeObserver(placeholderResizeObserver, releaseObserver) {
if (placeholderResizeObserver.current) {
placeholderResizeObserver.current.disconnect();
if (releaseObserver) {
placeholderResizeObserver.current = null;
}
}
}
function clearTimeoutRef(timeoutRef) {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
}
const defaultRenderLeaf = props => /*#__PURE__*/React.createElement(DefaultLeaf, _objectSpread$5({}, props));
/**
* Individual leaves in a text node with unique formatting.
*/
const Leaf = props => {
const {
leaf,
isLast,
text,
parent,
renderPlaceholder,
renderLeaf = defaultRenderLeaf,
leafPosition
} = props;
const editor = useSlateStatic();
const placeholderResizeObserver = useRef(null);
const placeholderRef = useRef(null);
const [showPlaceholder, setShowPlaceholder] = useState(false);
const showPlaceholderTimeoutRef = useRef(null);
const callbackPlaceholderRef = useCallback(placeholderEl => {
disconnectPlaceholderResizeObserver(placeholderResizeObserver, placeholderEl == null);
if (placeholderEl == null) {
var _leaf$onPlaceholderRe;
EDITOR_TO_PLACEHOLDER_ELEMENT.delete(editor);
(_leaf$onPlaceholderRe = leaf.onPlaceholderResize) === null || _leaf$onPlaceholderRe === void 0 || _leaf$onPlaceholderRe.call(leaf, null);
} else {
EDITOR_TO_PLACEHOLDER_ELEMENT.set(editor, placeholderEl);
if (!placeholderResizeObserver.current) {
// Create a new observer and observe the placeholder element.
const ResizeObserver$1 = window.ResizeObserver || ResizeObserver;
placeholderResizeObserver.current = new ResizeObserver$1(() => {
var _leaf$onPlaceholderRe2;
(_leaf$onPlaceholderRe2 = leaf.onPlaceholderResize) === null || _leaf$onPlaceholderRe2 === void 0 || _leaf$onPlaceholderRe2.call(leaf, placeholderEl);
});
}
placeholderResizeObserver.current.observe(placeholderEl);
placeholderRef.current = placeholderEl;
}
}, [placeholderRef, leaf, editor]);
let children = /*#__PURE__*/React.createElement(String$1, {
isLast: isLast,
leaf: leaf,
parent: parent,
text: text
});
const leafIsPlaceholder = Boolean(leaf[PLACEHOLDER_SYMBOL]);
useEffect(() => {
if (leafIsPlaceholder) {
if (!showPlaceholderTimeoutRef.current) {
// Delay the placeholder, so it will not render in a selection
showPlaceholderTimeoutRef.current = setTimeout(() => {
setShowPlaceholder(true);
showPlaceholderTimeoutRef.current = null;
}, PLACEHOLDER_DELAY);
}
} else {
clearTimeoutRef(showPlaceholderTimeoutRef);
setShowPlaceholder(false);
}
return () => clearTimeoutRef(showPlaceholderTimeoutRef);
}, [leafIsPlaceholder, setShowPlaceholder]);
if (leafIsPlaceholder && showPlaceholder) {
const placeholderProps = {
children: leaf.placeholder,
attributes: {
'data-slate-placeholder': true,
'aria-hidden': true,
style: {
position: 'absolute',
top: 0,
pointerEvents: 'none',
width: '100%',
maxWidth: '100%',
display: 'block',
opacity: '0.333',
userSelect: 'none',
WebkitUserSelect: 'none',
textDecoration: 'none',
// Fixes https://github.com/udecode/plate/issues/2315
WebkitUserModify: IS_WEBKIT ? 'inherit' : undefined
},
contentEditable: false,
ref: callbackPlaceholderRef
}
};
children = /*#__PURE__*/React.createElement(React.Fragment, null, children, renderPlaceholder(placeholderProps));
}
// 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)
const attributes = {
'data-slate-leaf': true
};
return renderLeaf({
attributes,
children,
leaf,
text,
leafPosition
});
};
const MemoizedLeaf = /*#__PURE__*/React.memo(Leaf, (prev, next) => {
return isTextParentEquivalent(prev.parent, next.parent, prev.text, next.text) && next.isLast === prev.isLast && next.renderLeaf === prev.renderLeaf && next.renderPlaceholder === prev.renderPlaceholder && next.text === prev.text && Text$1.equals(next.leaf, prev.leaf) && next.leaf[PLACEHOLDER_SYMBOL] === prev.leaf[PLACEHOLDER_SYMBOL];
});
const DefaultLeaf = props => {
const {
attributes,
children
} = props;
return /*#__PURE__*/React.createElement("span", _objectSpread$5({}, attributes), children);
};
/**
* Create a selector that updates when an `update` function is called, and
* which only causes the component to render when the result of `selector`
* differs from the previous result according to `equalityFn`.
*
* If `selector` is memoized using `useCallback`, then it will only be called
* when it changes or when `update` is called. Otherwise, `selector` will be
* called every time the component renders.
*
* @example
* const [state, update] = useGenericSelector(selector, equalityFn)
*
* useIsomorphicLayoutEffect(() => {
* return addEventListener(update)
* }, [addEventListener, update])
*
* return state
*/
function useGenericSelector(selector, equalityFn) {
const [, forceRender] = useReducer(s => s + 1, 0);
const latestSubscriptionCallbackError = useRef(undefined);
const latestSelector = useRef(() => null);
const latestSelectedState = useRef(null);
let selectedState;
try {
if (selector !== latestSelector.current || latestSubscriptionCallbackError.current) {
const selectorResult = selector();
if (equalityFn(latestSelectedState.current, selectorResult)) {
selectedState = latestSelectedState.current;
} else {
selectedState = selectorResult;
}
} else {
selectedState = latestSelectedState.current;
}
} catch (err) {
if (latestSubscriptionCallbackError.current && isError(err)) {
err.message += `\nThe error may be correlated with this previous error:\n${latestSubscriptionCallbackError.current.stack}\n\n`;
}
throw err;
}
latestSelector.current = selector;
latestSelectedState.current = selectedState;
latestSubscriptionCallbackError.current = undefined;
const update = useCallback(() => {
try {
const newSelectedState = latestSelector.current();
if (equalityFn(latestSelectedState.current, newSelectedState)) {
return;
}
latestSelectedState.current = newSelectedState;
} catch (err) {
// we ignore all errors here, since when the component
// is re-rendered, the selectors are called again, and
// will throw again, if neither props nor store state
// changed
if (err instanceof Error) {
latestSubscriptionCallbackError.current = err;
} else {
latestSubscriptionCallbackError.current = new Error(String(err));
}
}
forceRender();
// don't rerender on equalityFn change since we want to be able to define it inline
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return [selectedState, update];
}
function isError(error) {
return error instanceof Error;
}
/**
* A React context for sharing the `decorate` prop of the editable and
* subscribing to changes on this prop.
*/
const DecorateContext = /*#__PURE__*/createContext({});
const useDecorations = (node, parentDecorations) => {
const editor = useSlateStatic();
const {
decorate,
addEventListener
} = useContext(DecorateContext);
// Not memoized since we want nodes to be decorated on each render
const selector = () => {
const path = ReactEditor.findPath(editor, node);
const decorations = decorate([node, path]);
if (Node.isText(node)) {
const range = Editor.range(editor, path);
return decorations.flatMap(decoration => {
const intersection = Range.intersection(decoration, range);
return intersection ? [intersection] : [];
});
}
return decorations;
};
const equalityFn = Node.isText(node) ? isTextDecorationsEqual : isElementDecorationsEqual;
const [decorations, update] = useGenericSelector(selector, equalityFn);
useIsomorphicLayoutEffect(() => {
const unsubscribe = addEventListener(update);
update();
return unsubscribe;
}, [addEventListener, update]);
return useMemo(() => [...decorations, ...parentDecorations], [decorations, parentDecorations]);
};
const useDecorateContext = decorateProp => {
const [, forceUpdate] = useReducer(s => s + 1, 0);
const eventListeners = useRef(new Set());
const hasMounted = useRef(false);
const latestDecorate = useRef(decorateProp);
useIsomorphicLayoutEffect(() => {
latestDecorate.current = decorateProp;
eventListeners.current.forEach(listener => listener());
// Skip the forced re-render on the initial mount: there is no committed
// DOM to restore the selection against yet, and forcing an extra render
// here breaks contenteditable input in Firefox. Only later decoration
// changes need to re-render Editable in the same batch as the text
// components notified above, so its selection-restoration layout effect
// runs after the decoration-induced DOM changes are committed. Without
// that, the text components restructure the DOM in a separate pass where
// Editable's layout effect never fires, potentially leaving the caret at
// a wrong position.
if (!hasMounted.current) {
hasMounted.current = true;
return;
}
forceUpdate();
}, [decorateProp]);
const decorate = useCallback(entry => latestDecorate.current(entry), []);
const addEventListener = useCallback(callback => {
eventListeners.current.add(callback);
return () => {
eventListeners.current.delete(callback);
};
}, []);
return useMemo(() => ({
decorate,
addEventListener
}), [decorate, addEventListener]);
};
function ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const defaultRenderText = props => /*#__PURE__*/React.createElement(DefaultText, _objectSpread$4({}, props));
/**
* Text.
*/
const Text = props => {
const {
decorations: parentDecorations,
isLast,
parent,
renderPlaceholder,
renderLeaf,
renderText = defaultRenderText,
text
} = props;
const editor = useSlateStatic();
const ref = useRef(null);
const decorations = useDecorations(text, parentDecorations);
const decoratedLeaves = Text$1.decorations(text, decorations);
const key = ReactEditor.findKey(editor, text);
const children = [];
for (let i = 0; i < decoratedLeaves.length; i++) {
const {
leaf,
position
} = decoratedLeaves[i];
children.push(/*#__PURE__*/React.createElement(MemoizedLeaf, {
isLast: isLast && i === decoratedLeaves.length - 1,
key: `${key.id}-${i}`,
renderPlaceholder: renderPlaceholder,
leaf: leaf,
leafPosition: position,
text: text,
parent: parent,
renderLeaf: renderLeaf
}));
}
// Update element-related weak maps with the DOM element ref.
const callbackRef = useCallback(span => {
const KEY_TO_ELEMENT = EDITOR_TO_KEY_TO_ELEMENT.get(editor);
if (span) {
KEY_TO_ELEMENT === null || KEY_TO_ELEMENT === void 0 || KEY_TO_ELEMENT.set(key, span);
NODE_TO_ELEMENT.set(text, span);
ELEMENT_TO_NODE.set(span, text);
} else {
KEY_TO_ELEMENT === null || KEY_TO_ELEMENT === void 0 || KEY_TO_ELEMENT.delete(key);
NODE_TO_ELEMENT.delete(text);
if (ref.current) {
ELEMENT_TO_NODE.delete(ref.current);
}
}
ref.current = span;
}, [ref, editor, key, text]);
const attributes = {
'data-slate-node': 'text',
ref: callbackRef
};
return renderText({
text,
children,
attributes
});
};
const MemoizedText = /*#__PURE__*/React.memo(Text, (prev, next) => {
return isTextParentEquivalent(prev.parent, next.parent, prev.text, next.text) && next.isLast === prev.isLast && next.renderText === prev.renderText && next.renderLeaf === prev.renderLeaf && next.renderPlaceholder === prev.renderPlaceholder && next.text === prev.text && isTextDecorationsEqual(next.decorations, prev.decorations);
});
const DefaultText = props => {
const {
attributes,
children
} = props;
return /*#__PURE__*/React.createElement("span", _objectSpread$4({}, attributes), children);
};
function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const findSiblingDirection = siblings => {
for (const sibling of siblings) {
const dir = getDirection(Node.string(sibling));
if (dir !== 'neutral') {
return dir;
}
}
};
const getEmptyBlockDirection = element => {
var _findSiblingDirection;
const parent = NODE_TO_PARENT.get(element);
const index = NODE_TO_INDEX.get(element);
if (!parent || index === undefined) {
return;
}
const before = parent.children.slice(0, index).reverse();
const after = parent.children.slice(index + 1);
return (_findSiblingDirection = findSiblingDirection(before)) !== null && _findSiblingDirection !== void 0 ? _findSiblingDirection : findSiblingDirection(after);
};
const getMountedChildren = (editor, element) => Editor.isVoid(editor, element) ? [Node.texts(element).next().value[0]] : element.children;
const findUnmountedChild = (editor, element) => getMountedChildren(editor, element).findIndex(child => !NODE_TO_ELEMENT.has(child));
const defaultRenderElement = props => (/*#__PURE__*/React.createElement(DefaultElement, _objectSpread$3({}, props)));
/**
* Element.
*/
const Element = props => {
const {
decorations: parentDecorations,
element,
renderElement = defaultRenderElement,
renderChunk,
renderPlaceholder,
renderLeaf,
renderText
} = props;
const editor = useSlateStatic();
const readOnly = useReadOnly();
const isInline = editor.isInline(element);
const decorations = useDecorations(element, parentDecorations);
const key = ReactEditor.findKey(editor, element);
const ref = useCallback(ref => {
// Update element-related weak maps with the DOM element ref.
const KEY_TO_ELEMENT = EDITOR_TO_KEY_TO_ELEMENT.get(editor);
if (ref) {
KEY_TO_ELEMENT === null || KEY_TO_ELEMENT === void 0 || KEY_TO_ELEMENT.set(key, ref);
NODE_TO_ELEMENT.set(element, ref);
ELEMENT_TO_NODE.set(ref, element);
} else {
KEY_TO_ELEMENT === null || KEY_TO_ELEMENT === void 0 || KEY_TO_ELEMENT.delete(key);
NODE_TO_ELEMENT.delete(element);
}
}, [editor, key, element]);
useIsomorphicLayoutEffect(() => {
const index = findUnmountedChild(editor, element);
if (index !== -1) {
const type = element.type;
const path = ReactEditor.findPath(editor, element);
editor.onDOMError(new Error(`renderElement didn't render the children of the ${typeof type === 'string' ? `"${type}" ` : ''}element at path ${JSON.stringify(path)}: child ${index} has no DOM node. Render the \`children\` prop inside the element.`));
}
}, [editor, element]);
let children = useChildren({
decorations,
node: element,
renderElement,
renderChunk,
renderPlaceholder,
renderLeaf,
renderText
});
// Attributes that the developer must mix into the element in their
// custom node renderer component.
const 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)) {
const text = Node.string(element);
const dir = text === '' ? getEmptyBlockDirection(element) : 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;
}
const Tag = isInline ? 'span' : 'div';
const [[text]] = Node.texts(element);
children = /*#__PURE__*/React.createElement(Tag, {
"data-slate-spacer": true,
style: {
height: '0',
color: 'transparent',
outline: 'none',
position: 'absolute',
userSelect: 'none',
WebkitUserSelect: 'none'
}
}, /*#__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);
}
return renderElement({
attributes,
children,
element
});
};
const MemoizedElement = /*#__PURE__*/React.memo(Element, (prev, next) => {
return prev.element === next.element && prev.renderElement === next.renderElement && prev.renderChunk === next.renderChunk && prev.renderText === next.renderText && prev.renderLeaf === next.renderLeaf && prev.renderPlaceholder === next.renderPlaceholder && isElementDecorationsEqual(prev.decorations, next.decorations);
});
/**
* The default element renderer.
*/
const DefaultElement = props => {
const {
attributes,
children,
element
} = props;
const editor = useSlateStatic();
const Tag = editor.isInline(element) ? 'span' : 'div';
return /*#__PURE__*/React.createElement(Tag, _objectSpread$3(_objectSpread$3({}, attributes), {}, {
style: {
position: 'relative'
}
}), children);
};
/**
* Traverse and modify a chunk tree
*/
class ChunkTreeHelper {
constructor(chunkTree, {
chunkSize,
debug
}) {
/**
* The root of the chunk tree
*/
_defineProperty(this, "root", void 0);
/**
* The ideal size of a chunk
*/
_defineProperty(this, "chunkSize", void 0);
/**
* Whether debug mode is enabled
*
* If enabled, the pointer state will be checked for internal consistency
* after each mutating operation.
*/
_defineProperty(this, "debug", void 0);
/**
* Whether the traversal has reached the end of the chunk tree
*
* When this is true, the pointerChunk and pointerIndex point to the last
* top-level node in the chunk tree, although pointerNode returns null.
*/
_defineProperty(this, "reachedEnd", void 0);
/**
* The chunk containing the current node
*/
_defineProperty(this, "pointerChunk", void 0);
/**
* The index of the current node within pointerChunk
*
* Can be -1 to indicate that the pointer is before the start of the tree.
*/
_defineProperty(this, "pointerIndex", void 0);
/**
* Similar to a Slate path; tracks the path of pointerChunk relative to the
* root.
*
* Used to move the pointer from the current chunk to the parent chunk more
* efficiently.
*/
_defineProperty(this, "pointerIndexStack", void 0);
/**
* Indexing the current chunk's children has a slight time cost, which adds up
* when traversing very large trees, so the current node is cached.
*
* A value of undefined means that the current node is not cached. This
* property must be set to undefined whenever the pointer is moved, unless
* the pointer is guaranteed to point to the same node that it did previously.
*/
_defineProperty(this, "cachedPointerNode", void 0);
this.root = chunkTree;
this.chunkSize = chunkSize;
// istanbul ignore next
this.debug = debug !== null && debug !== void 0 ? debug : false;
this.pointerChunk = chunkTree;
this.pointerIndex = -1;
this.pointerIndexStack = [];
this.reachedEnd = false;
this.validateState();
}
/**
* Move the pointer to the next leaf in the chunk tree
*/
readLeaf() {
// istanbul ignore next
if (this.reachedEnd) return null;
// Get the next sibling or aunt node
while (true) {
if (this.pointerIndex + 1 < this.pointerSiblings.length) {
this.pointerIndex++;
this.cachedPointerNode = undefined;
break;
} else if (this.pointerChunk.type === 'root') {
this.reachedEnd = true;
return null;
} else {
this.exitChunk();
}
}
this.validateState();
// If the next sibling or aunt is a chunk, descend into it
this.enterChunkUntilLeaf(false);
return this.pointerNode;
}
/**
* Move the pointer to the previous leaf in the chunk tree
*/
returnToPreviousLeaf() {
// If we were at the end of the tree, descend into the end of the last
// chunk in the tree
if (this.reachedEnd) {
this.reachedEnd = false;
this.enterChunkUntilLeaf(true);
return;
}
// Get the previous sibling or aunt node
while (true) {
if (this.pointerIndex >= 1) {
this.pointerIndex--;
this.cachedPointerNode = undefined;
break;
} else if (this.pointerChunk.type === 'root') {
this.pointerIndex = -1;
return;
} else {
this.exitChunk();
}
}
this.validateState();
// If the previous sibling or aunt is a chunk, descend into it
this.enterChunkUntilLeaf(true);
}
/**
* Insert leaves before the current leaf, leaving the pointer unchanged
*/
insertBefore(leaves) {
this.returnToPreviousLeaf();
this.insertAfter(leaves);
this.readLeaf();
}
/**
* Insert leaves after the current leaf, leaving the pointer on the last
* inserted leaf
*
* The insertion algorithm first checks for any chunk we're currently at the
* end of that can receive additional leaves. Next, it tries to insert leaves
* at the starts of any subsequent chunks.
*
* Any remaining leaves are passed to rawInsertAfter to be chunked and
* inserted at the highest possible level.
*/
insertAfter(leaves) {
// istanbul ignore next
if (leaves.length === 0) return;
let beforeDepth = 0;
let afterDepth = 0;
// While at the end of a chunk, insert any leaves that will fit, and then
// exit the chunk
while (this.pointerChunk.type === 'chunk' && this.pointerIndex === this.pointerSiblings.length - 1) {
const remainingCapacity = this.chunkSize - this.pointerSiblings.length;
const toInsertCount = Math.min(remainingCapacity, leaves.length);
if (toInsertCount > 0) {
const leavesToInsert = leaves.splice(0, toInsertCount);
this.rawInsertAfter(leavesToInsert, beforeDepth);
}
this.exitChunk();
beforeDepth++;
}
if (leaves.length === 0) return;
// Save the pointer so that we can come back here after inserting leaves
// into the starts of subsequent blocks
const rawInsertPointer = this.savePointer();
// If leaves are inserted into the start of a subsequent block, then we
// eventually need to restore the pointer to the last such inserted leaf
let finalPointer = null;
// Move the pointer into the chunk containing the next leaf, if it exists
if (this.readLeaf()) {
// While at the start of a chunk, insert any leaves that will fit, and
// then exit the chunk
while (this.pointerChunk.type === 'chunk' && this.pointerIndex === 0) {
const remainingCapacity = this.chunkSize - this.pointerSiblings.length;
const toInsertCount = Math.min(remainingCapacity, leaves.length);
if (toInsertCount > 0) {
const leavesToInsert = leaves.splice(-toInsertCount, toInsertCount);
// Insert the leaves at the start of the chunk
this.pointerIndex = -1;
this.cachedPointerNode = undefined;
this.rawInsertAfter(leavesToInsert, afterDepth);
// If this is the first batch of insertions at the start of a
// subsequent chunk, set the final pointer to the last inserted leaf
if (!finalPointer) {
finalPointer = this.savePointer();
}
}
this.exitChunk();
afterDepth++;
}
}
this.restorePointer(rawInsertPointer);
// If there are leaves left to insert, insert them between the end of the
// previous chunk and the start of the first subsequent chunk, or wherever
// the pointer ended up after the first batch of insertions
const minDepth = Math.max(beforeDepth, afterDepth);
this.rawInsertAfter(leaves, minDepth);
if (finalPointer) {
this.restorePointer(finalPointer);
}
this.validateState();
}
/**
* Remove the current node and decrement the pointer, deleting any ancestor
* chunk that becomes empty as a result
*/
remove() {
this.pointerSiblings.splice(this.pointerIndex--, 1);
this.cachedPointerNode = undefined;
if (this.pointerSiblings.length === 0 && this.pointerChunk.type === 'chunk') {
this.exitChunk();
this.remove();
} else {
this.invalidateChunk();
}
this.validateState();
}
/**
* Add the current chunk and all ancestor chunks to the list of modified
* chunks
*/
invalidateChunk() {
for (let c = this.pointerChunk; c.type === 'chunk'; c = c.parent) {
this.root.modifiedChunks.add(c);
}
}
/**
* Whether the pointer is at the start of the tree
*/
get atStart() {
return this.pointerChunk.type === 'root' && this.pointerIndex === -1;
}
/**
* The siblings of the current node
*/
get pointerSiblings() {
return this.pointerChunk.children;
}
/**
* Get the current node (uncached)
*
* If the pointer is at the start or end of the document, returns null.
*
* Usually, the current node is a chunk leaf, although it can be a chunk
* while insertions are in progress.
*/
getPointerNode() {
if (this.reachedEnd || this.pointerIndex === -1) {
return null;
}
return this.pointerSiblings[this.pointerIndex];
}
/**
* Cached getter for the current node
*/
get pointerNode() {
if (this.cachedPointerNode !== undefined) return this.cachedPointerNode;
const pointerNode = this.getPointerNode();
this.cachedPointerNode = pointerNode;
return pointerNode;
}
/**
* Get the path of a chunk relative to the root, returning null if the chunk
* is not connected to the root
*/
getChunkPath(chunk) {
const path = [];
for (let c = chunk; c.type === 'chunk'; c = c.parent) {
const index = c.parent.children.indexOf(c);
// istanbul ignore next
if (index === -1) {
return null;
}
path.unshift(index);
}
return path;
}
/**
* Save the current pointer to be restored later
*/
savePointer() {
if (this.atStart) return 'start';
// istanbul ignore next
if (!this.pointerNode) {
throw new Error('Cannot save pointer when pointerNode is null');
}
return {
chunk: this.pointerChunk,
node: this.pointerNode
};
}
/**
* Restore the pointer to a previous state
*/
restorePointer(savedPointer) {
if (savedPointer === 'start') {
this.pointerChunk = this.root;
this.pointerIndex = -1;
this.pointerIndexStack = [];
this.reachedEnd = false;
this.cachedPointerNode = undefined;
return;
}
// Since nodes may have been inserted or removed prior to the saved
// pointer since it was saved, the index and index stack must be
// recomputed. This is slow, but this is fine since restoring a pointer is
// not a frequent operation.
const {
chunk,
node
} = savedPointer;
const index = chunk.children.indexOf(node);
// istanbul ignore next
if (index === -1) {
throw new Error('Cannot restore point because saved node is no longer in saved chunk');
}
const indexStack = this.getChunkPath(chunk);
// istanbul ignore next
if (!indexStack) {
throw new Error('Cannot restore point because saved chunk is no longer connected to root');
}
this.pointerChunk = chunk;
this.pointerIndex = index;
this.pointerIndexStack = indexStack;
this.reachedEnd = false;
this.cachedPointerNode = node;
this.validateState();
}
/**
* Assuming the current node is a chunk, move the pointer into that chunk
*
* @param end If true, place the pointer on the last node of the chunk.
* Otherwise, place the pointer on the first node.
*/
enterChunk(end) {
var _this$pointerNode;
// istanbul ignore next
if (((_this$pointerNode = this.pointerNode) === null || _this$pointerNode === void 0 ? void 0 : _this$pointerNode.type) !== 'chunk') {
throw new Error('Cannot enter non-chunk');
}
this.pointerIndexStack.push(this.pointerIndex);
this.pointerChunk = this.pointerNode;
this.pointerIndex = end ? this.pointerSiblings.length - 1 : 0;
this.cachedPointerNode = undefined;
this.validateState();
// istanbul ignore next
if (this.pointerChunk.children.length === 0) {
throw new Error('Cannot enter empty chunk');
}
}
/**
* Assuming the current node is a chunk, move the pointer into that chunk
* repeatedly until the current node is a leaf
*
* @param end If true, place the pointer on the last node of the chunk.
* Otherwise, place the pointer on the first node.
*/
enterChunkUntilLeaf(end) {
while (((_this$pointerNode2 = this.pointerNode) === null || _this$pointerNode2 === void 0 ? void 0 : _this$pointerNode2.type) === 'chunk') {
var _this$pointerNode2;
this.enterChunk(end);
}
}
/**
* Move the pointer to the parent chunk
*/
exitChunk() {
// istanbul ignore next
if (this.pointerChunk.type === 'root') {
throw new Error('Cannot exit root');
}
const previousPointerChunk = this.pointerChunk;
this.pointerChunk = previousPointerChunk.parent;
this.pointerIndex = this.pointerIndexStack.pop();
this.cachedPointerNode = undefined;
this.validateState();
}
/**
* Insert leaves immediately after the current node, leaving the pointer on
* the last inserted leaf
*
* Leaves are chunked according to the number of nodes already in the parent
* plus the number of nodes being inserted, or the minimum depth if larger
*/
rawInsertAfter(leaves, minDepth) {
if (leaves.length === 0) return;
const groupIntoChunks = (leaves, parent, perChunk) => {
if (perChunk === 1) return leaves;
const chunks = [];
for (let i = 0; i < this.chunkSize; i++) {
const chunkNodes = leaves.slice(i * perChunk, (i + 1) * perChunk);
if (chunkNodes.length === 0) break;
const chunk = {
type: 'chunk',
key: new Key(),
parent,
children: []
};
chunk.children = groupIntoChunks(chunkNodes, chunk, perChunk / this.chunkSize);
chunks.push(chunk);
}
return chunks;
};
// Determine the chunking depth based on the number of existing nodes in
// the chunk and the number of nodes being inserted
const newTotal = this.pointerSiblings.length + leaves.length;
let depthForTotal = 0;
for (let i = this.chunkSize; i < newTotal; i *= this.chunkSize) {
depthForTotal++;
}
// A depth of 0 means no chunking
const depth = Math.max(depthForTotal, minDepth);
const perTopLevelChunk = Math.pow(this.chunkSize, depth);
const chunks = groupIntoChunks(leaves, this.pointerChunk, perTopLevelChunk);
this.pointerSiblings.splice(this.pointerIndex + 1, 0, ...chunks);
this.pointerIndex += chunks.length;
this.cachedPointerNode = undefined;
this.invalidateChunk();
this.validateState();
}
/**
* If debug mode is enabled, ensure that the state is internally consistent
*/
// istanbul ignore next
validateState() {
if (!this.debug) return;
const validateDescendant = node => {
if (node.type === 'chunk') {
const {
parent,
children
} = node;
if (!parent.children.includes(node)) {
throw new Error(`Debug: Chunk ${node.key.id} has an incorrect parent property`);
}
children.forEach(validateDescendant);
}
};
this.root.children.forEach(validateDescendant);
if (this.cachedPointerNode !== undefined && this.cachedPointerNode !== this.getPointerNode()) {
throw new Error('Debug: The cached pointer is incorrect and has not been invalidated');
}
const actualIndexStack = this.getChunkPath(this.pointerChunk);
if (!actualIndexStack) {
throw new Error('Debug: The pointer chunk is not connected to the root');
}
if (!Path.equals(this.pointerIndexStack, actualIndexStack)) {
throw new Error(`Debug: The cached index stack [${this.pointerIndexStack.join(', ')}] does not match the path of the pointer chunk [${actualIndexStack.join(', ')}]`);
}
}
}
/**
* Traverse an array of children, providing helpers useful for reconciling the
* children array with a chunk tree
*/
class ChildrenHelper {
constructor(editor, children) {
_defineProperty(this, "editor", void 0);
_defineProperty(this, "children", void 0);
/**
* Sparse array of Slate node keys, each index corresponding to an index in
* the children array
*
* Fetching the key for a Slate node is expensive, so we cache them here.
*/
_defineProperty(this, "cachedKeys", void 0);
/**
* The index of the next node to be read in the children array
*/
_defineProperty(this, "pointerIndex", void 0);
this.editor = editor;
this.children = children;
this.cachedKeys = new Array(children.length);
this.pointerIndex = 0;
}
/**
* Read a given number of nodes, advancing the pointer by that amount
*/
read(n) {
// PERF: If only one child was requested (the most common case), use array
// indexing instead of slice
if (n === 1) {
return [this.children[this.pointerIndex++]];
}
const slicedChildren = this.remaining(n);
this.pointerIndex += n;
return slicedChildren;
}
/**
* Get the remaining children without advancing the pointer
*
* @param [maxChildren] Limit the number of children returned.
*/
remaining(maxChildren) {
if (maxChildren === undefined) {
return this.children.slice(this.pointerIndex);
}
return this.children.slice(this.pointerIndex, this.pointerIndex + maxChildren);
}
/**
* Whether all children have been read
*/
get reachedEnd() {
return this.pointerIndex >= this.children.length;
}
/**
* Determine whether a node with a given key appears in the unread part of the
* children array, and return its index relative to the current pointer if so
*
* Searching for the node object itself using indexOf is most efficient, but
* will fail to locate nodes that have been modified. In this case, nodes
* should be identified by their keys instead.
*
* Searching an array of keys using indexOf is very inefficient since fetching
* the keys for all children in advance is very slow. Insead, if the node
* search fails to return a value, fetch the keys of each remaining child one
* by one and compare it to the known key.
*/
lookAhead(node, key) {
const elementResult = this.children.indexOf(node, this.pointerIndex);
if (elementResult > -1) return elementResult - this.pointerIndex;
for (let i = this.pointerIndex; i < this.children.length; i++) {
const candidateNode = this.children[i];
const candidateKey = this.findKey(candidateNode, i);
if (candidateKey === key) return i - this.pointerIndex;
}
return -1;
}
/**
* Convert an array of Slate nodes to an array of chunk leaves, each
* containing the node and its key
*/
toChunkLeaves(nodes, startIndex) {
return nodes.map((node, i) => ({
type: 'leaf',
node,
key: this.findKey(node, startIndex + i),
index: startIndex + i
}));
}
/**
* Get the key for a Slate node, cached using the node's index
*/
findKey(node, index) {
const cachedKey = this.cachedKeys[index];
if (cachedKey) return cachedKey;
const key = ReactEditor.findKey(this.editor, node);
this.cachedKeys[index] = key;
return key;
}
}
/**
* Update the chunk tree to match the children array, inserting, removing and
* updating differing nodes
*/
const reconcileChildren = (editor, {
chunkTree,
children,
chunkSize,
rerenderChildren: _rerenderChildren = [],
onInsert,
onUpdate,
onIndexChange,
debug
}) => {
const chunkTreeHelper = new ChunkTreeHelper(chunkTree, {
chunkSize,
debug
});
const childrenHelper = new ChildrenHelper(editor, children);
let treeLeaf;
// Read leaves from the tree one by one, each one representing a single Slate
// node. Each leaf from the tree is compared to the current node in the
// children array to determine whether nodes have been inserted, removed or
// updated.
while (treeLeaf = chunkTreeHelper.readLeaf()) {
// Check where the tree node appears in the children array. In the most
// common case (where no insertions or removals have occurred), this will be
// 0. If the node has been removed, this will be -1. If new nodes have been
// inserted before the node, or if the node has been moved to a later
// position in the same children array, this will be a positive number.
const lookAhead = childrenHelper.lookAhead(treeLeaf.node, treeLeaf.key);
// If the node was moved, we want to remove it and insert it later, rather
// then re-inserting all intermediate nodes before it.
const wasMoved = lookAhead > 0 && chunkTree.movedNodeKeys.has(treeLeaf.key);
// If the tree leaf was moved or removed, remove it
if (lookAhead === -1 || wasMoved) {
chunkTreeHelper.remove();
continue;
}
// Get the matching Slate node and any nodes that may have been inserted
// prior to it. Insert these into the chunk tree.
const insertedChildrenStartIndex = childrenHelper.pointerIndex;
const insertedChildren = childrenHelper.read(lookAhead + 1);
const matchingChild = insertedChildren.pop();
if (insertedChildren.length) {
const leavesToInsert = childrenHelper.toChunkLeaves(insertedChildren, insertedChildrenStartIndex);
chunkTreeHelper.insertBefore(leavesToInsert);
insertedChildren.forEach((node, relativeIndex) => {
onInsert === null || onInsert === void 0 || onInsert(node, insertedChildrenStartIndex + relativeIndex);
});
}
const matchingChildIndex = childrenHelper.pointerIndex - 1;
// Make sure the chunk tree contains the most recent version of the Slate
// node
if (treeLeaf.node !== matchingChild) {
treeLeaf.node = matchingChild;
chunkTreeHelper.invalidateChunk();
onUpdate === null || onUpdate === void 0 || onUpdate(matchingChild, matchingChildIndex);
}
// Update the index if it has changed
if (treeLeaf.index !== matchingChildIndex) {
treeLeaf.index = matchingChildIndex;
onIndexChange === null || onIndexChange === void 0 || onIndexChange(matchingChild, matchingChildIndex);
}
// Manually invalidate chunks containing specific children that we want to
// re-render
if (_rerenderChildren.includes(matchingChildIndex)) {
chunkTreeHelper.invalidateChunk();
}
}
// If there are still Slate nodes remaining from the children array that were
// not matched to nodes in the tree, insert them at the end of the tree
if (!childrenHelper.reachedEnd) {
const remainingChildren = childrenHelper.remaining();
const leavesToInsert = childrenHelper.toChunkLeaves(remainingChildren, childrenHelper.pointerIndex);
// Move the pointer back to the final leaf in the tree, or the start of the
// tree if the tree is currently empty
chunkTreeHelper.returnToPreviousLeaf();
chunkTreeHelper.insertAfter(leavesToInsert);
remainingChildren.forEach((node, relativeIndex) => {
onInsert === null || onInsert === void 0 || onInsert(node, childrenHelper.pointerIndex + relativeIndex);
});
}
chunkTree.movedNodeKeys.clear();
};
function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const KEY_TO_CHUNK_TREE = new WeakMap();
/**
* Get or create the chunk tree for a Slate node
*
* If the reconcile option is provided, the chunk tree will be updated to
* match the current children of the node. The children are chunked
* automatically using the given chunk size.
*/
const getChunkTreeForNode = (editor, node,
// istanbul ignore next
options = {}) => {
const key = ReactEditor.findKey(editor, node);
let chunkTree = KEY_TO_CHUNK_TREE.get(key);
if (!chunkTree) {
chunkTree = {
type: 'root',
movedNodeKeys: new Set(),
modifiedChunks: new Set(),
children: []
};
KEY_TO_CHUNK_TREE.set(key, chunkTree);
}
if (options.reconcile) {
reconcileChildren(editor, _objectSpread$2({
chunkTree,
children: node.children
}, options.reconcile));
}
return chunkTree;
};
function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const defaultRenderChunk = ({
children
}) => children;
const ChunkAncestor = props => {
const {
root,
ancestor,
renderElement,
renderChunk = defaultRenderChunk
} = props;
return ancestor.children.map(chunkNode => {
if (chunkNode.type === 'chunk') {
const key = chunkNode.key.id;
const renderedChunk = renderChunk({
highest: ancestor === root,
lowest: chunkNode.children.some(c => c.type === 'leaf'),
attributes: {
'data-slate-chunk': true
},
children: (/*#__PURE__*/React.createElement(MemoizedChunk, {
root: root,
ancestor: chunkNode,
renderElement: renderElement,
renderChunk: renderChunk
}))
});
return /*#__PURE__*/React.createElement(Fragment, {
key: key
}, renderedChunk);
}
// Only blocks containing no inlines are chunked
const element = chunkNode.node;
return renderElement(element, chunkNode.index, chunkNode.key);
});
};
const ChunkTree = props => {
// Clear the set of modified chunks only when React finishes rendering. The
// timing of this is important in strict mode because if the chunks are
// cleared during rendering (such as in reconcileChildren), strict mode's
// second render won't include them.
useEffect(() => {
props.root.modifiedChunks.clear();
});
return /*#__PURE__*/React.createElement(ChunkAncestor, _objectSpread$1({}, props));
};
const MemoizedChunk = /*#__PURE__*/React.memo(ChunkAncestor, (prev, next) => prev.root === next.root && prev.renderElement === next.renderElement && prev.renderChunk === next.renderChunk && !next.root.modifiedChunks.has(next.ancestor));
const ElementContext = /*#__PURE__*/createContext(null);
/**
* Get the current element.
*/
const useElement = () => {
const context = useContext(ElementContext);
if (!context) {
throw new Error('The `useElement` hook must be used inside `renderElement`.');
}
return context;
};
/**
* Get the current element, or return null if not inside `renderElement`.
*/
const useElementIf = () => useContext(ElementContext);
/**
* Children.
*/
const useChildren = props => {
const {
decorations,
node,
renderElement,
renderChunk,
renderPlaceholder,
renderText,
renderLeaf
} = props;
const editor = useSlateStatic();
IS_NODE_MAP_DIRTY.set(editor, false);
const isBlock = Node.isElement(node) && !editor.isInline(node);
const isLeafBlock = isBlock && Editor.hasInlines(editor, node);
const chunkSize = isLeafBlock ? null : editor.getChunkSize(node);
const chunking = !!chunkSize;
const {
decorationsByChild,
childrenToRedecorate
} = useDecorationsByChild(editor, node, decorations);
// Update the index and parent of each child.
// PERF: If chunking is enabled, this is done while traversing the chunk tree
// instead to eliminate unnecessary weak map operations.
if (!chunking) {
node.children.forEach((n, i) => {
NODE_TO_INDEX.set(n, i);
NODE_TO_PARENT.set(n, node);
});
}
const renderElementComponent = useCallback((n, i, cachedKey) => {
const key = cachedKey !== null && cachedKey !== void 0 ? cachedKey : ReactEditor.findKey(editor, n);
return /*#__PURE__*/React.createElement(ElementContext.Provider, {
key: `provider-${key.id}`,
value: n
}, /*#__PURE__*/React.createElement(MemoizedElement, {
decorations: decorationsByChild[i],
element: n,
key: key.id,
renderElement: renderElement,
renderChunk: renderChunk,
renderPlaceholder: renderPlaceholder,
renderLeaf: renderLeaf,
renderText: renderText
}));
}, [editor, decorationsByChild, renderElement, renderChunk, renderPlaceholder, renderLeaf, renderText]);
const renderTextComponent = (n, i) => {
const key = ReactEditor.findKey(editor, n);
return /*#__PURE__*/React.createElement(MemoizedText, {
decorations: decorationsByChild[i],
key: key.id,
isLast: i === node.children.length - 1,
parent: node,
renderPlaceholder: renderPlaceholder,
renderLeaf: renderLeaf,
renderText: renderText,
text: n
});
};
if (!chunking) {
return node.children.map((n, i) => Node.isText(n) ? renderTextComponent(n, i) : renderElementComponent(n, i));
}
const chunkTree = getChunkTreeForNode(editor, node, {
reconcile: {
chunkSize,
rerenderChildren: childrenToRedecorate,
onInsert: (n, i) => {
NODE_TO_INDEX.set(n, i);
NODE_TO_PARENT.set(n, node);
},
onUpdate: (n, i) => {
NODE_TO_INDEX.set(n, i);
NODE_TO_PARENT.set(n, node);
},
onIndexChange: (n, i) => {
NODE_TO_INDEX.set(n, i);
}
}
});
return /*#__PURE__*/React.createElement(ChunkTree, {
root: chunkTree,
ancestor: chunkTree,
renderElement: renderElementComponent,
renderChunk: renderChunk
});
};
const useDecorationsByChild = (editor, node, decorations) => {
const decorationsByChild = splitDecorationsByChild(editor, node, decorations);
// The value we return is a mutable array of `DecoratedRange[]` arrays. This
// lets us avoid passing an immutable array of decorations for each child into
// `ChunkTree` using props. Each `DecoratedRange[]` is only updated if the
// decorations at that index have changed, which speeds up the equality check
// for the `decorations` prop in the memoized `Element` and `Text` components.
const mutableDecorationsByChild = useRef(decorationsByChild).current;
// Track the list of child indices whose decorations have changed, so that we
// can tell the chunk tree to re-render these children.
const childrenToRedecorate = [];
// Resize the mutable array to match the latest result
mutableDecorationsByChild.length = decorationsByChild.length;
for (let i = 0; i < decorationsByChild.length; i++) {
var _mutableDecorationsBy;
const _decorations = decorationsByChild[i];
const previousDecorations = (_mutableDecorationsBy = mutableDecorationsByChild[i]) !== null && _mutableDecorationsBy !== void 0 ? _mutableDecorationsBy : null;
if (!isElementDecorationsEqual(previousDecorations, _decorations)) {
mutableDecorationsByChild[i] = _decorations;
childrenToRedecorate.push(i);
}
}
return {
decorationsByChild: mutableDecorationsByChild,
childrenToRedecorate
};
};
/**
* A React context for sharing the `readOnly` state of the editor.
*/
const ReadOnlyContext = /*#__PURE__*/createContext(false);
/**
* Get the current `readOnly` state of the editor.
*/
const useReadOnly = () => {
return useContext(ReadOnlyContext);
};
/**
* A React context for sharing the editor selector context in a way to control
* re-renders.
*/
const SlateSelectorContext = /*#__PURE__*/createContext({});
const refEquality = (a, b) => a === b;
/**
* Use redux style selectors to prevent re-rendering on every keystroke.
*
* Bear in mind re-rendering can only prevented if the returned value is a value
* type or for reference types (e.g. objects and arrays) add a custom equality
* function.
*
* If `selector` is memoized using `useCallback`, then it will only be called
* when it or the editor state changes. Otherwise, `selector` will be called
* every time the component renders.
*
* @example
* const isSelectionActive = useSlateSelector(editor => Boolean(editor.selection))
*/
function useSlateSelector(selector, equalityFn = refEquality, {
deferred
} = {}) {
const context = useContext(SlateSelectorContext);
if (!context) {
throw new Error(`The \`useSlateSelector\` hook must be used inside the <Slate> component's context.`);
}
const {
addEventListener
} = context;
const editor = useSlateStatic();
const genericSelector = useCallback(() => selector(editor), [editor, selector]);
const [selectedState, update] = useGenericSelector(genericSelector, equalityFn);
useIsomorphicLayoutEffect(() => {
const unsubscribe = addEventListener(update, {
deferred
});
update();
return unsubscribe;
}, [addEventListener, update, deferred]);
return selectedState;
}
/**
* Create selector context with editor updating on every editor change
*/
function useSelectorContext() {
const eventListeners = useRef(new Set());
const deferredEventListeners = useRef(new Set());
const onChange = useCallback(() => {
eventListeners.current.forEach(listener => listener());
}, []);
const flushDeferred = useCallback(() => {
deferredEventListeners.current.forEach(listener => listener());
deferredEventListeners.current.clear();
}, []);
const addEventListener = useCallback((callbackProp, {
deferred: _deferred = false
} = {}) => {
const callback = _deferred ? () => deferredEventListeners.current.add(callbackProp) : callbackProp;
eventListeners.current.add(callback);
return () => {
eventListeners.current.delete(callback);
};
}, []);
const selectorContext = useMemo(() => ({
addEventListener,
flushDeferred
}), [addEventListener, flushDeferred]);
return {
selectorContext,
onChange
};
}
function useFlushDeferredSelectorsOnRender() {
const {
flushDeferred
} = useContext(SlateSelectorContext);
useIsomorphicLayoutEffect(flushDeferred);
}
/**
* Get the current editor object and re-render whenever it changes.
*/
const useSlate = () => {
const {
addEventListener
} = useContext(SlateSelectorContext);
const [, forceRender] = useReducer(s => s + 1, 0);
if (!addEventListener) {
throw new Error(`The \`useSlate\` hook must be used inside the <Slate> component's context.`);
}
useIsomorphicLayoutEffect(() => addEventListener(forceRender), [addEventListener]);
return useSlateStatic();
};
const EDITOR_TO_V = new WeakMap();
const getEditorVersionRef = editor => {
let v = EDITOR_TO_V.get(editor);
if (v) {
return v;
}
v = {
current: 0
};
EDITOR_TO_V.set(editor, v);
// Register the `onChange` handler exactly once per editor
const {
onChange
} = editor;
editor.onChange = options => {
v.current++;
onChange(options);
};
return v;
};
/**
* Get the current editor object and its version, which increments on every
* change.
*
* @deprecated The `v` counter is no longer used except for this hook, and may
* be removed in a future version.
*/
const useSlateWithV = () => {
const editor = useSlate();
const vRef = useMemo(() => getEditorVersionRef(editor), [editor]);
return {
editor,
v: vRef.current
};
};
function useTrackUserInput() {
const editor = useSlateStatic();
const receivedUserInput = useRef(false);
const animationFrameIdRef = useRef(0);
const onUserInput = useCallback(() => {
if (receivedUserInput.current) {
return;
}
receivedUserInput.current = true;
const window = ReactEditor.getWindow(editor);
window.cancelAnimationFrame(animationFrameIdRef.current);
animationFrameIdRef.current = window.requestAnimationFrame(() => {
receivedUserInput.current = false;
});
}, [editor]);
useEffect(() => () => cancelAnimationFrame(animationFrameIdRef.current), []);
return {
receivedUserInput,
onUserInput
};
}
const isPlaceholderNode = node => isDOMElement(node) && node.hasAttribute('data-slate-placeholder');
const changesOnlyPlaceholders = ({
addedNodes,
removedNodes
}) => {
const nodes = [...Array.from(addedNodes), ...Array.from(removedNodes)];
return nodes.length > 0 && nodes.every(isPlaceholderNode);
};
const createRestoreDomManager = (editor, receivedUserInput) => {
let bufferedMutations = [];
const clear = () => {
bufferedMutations = [];
};
const registerMutations = mutations => {
if (!receivedUserInput.current) {
return;
}
const trackedMutations = mutations.filter(mutation => !changesOnlyPlaceholders(mutation) && isTrackedMutation(editor, mutation, mutations));
bufferedMutations.push(...trackedMutations);
};
function restoreDOM() {
if (bufferedMutations.length > 0) {
bufferedMutations.reverse().forEach(mutation => {
if (mutation.type === 'characterData') {
// We don't want to restore the DOM for characterData mutations
// because this interrupts the composition.
return;
}
mutation.removedNodes.forEach(node => {
mutation.target.insertBefore(node, mutation.nextSibling);
});
mutation.addedNodes.forEach(node => {
mutation.target.removeChild(node);
});
});
// Clear buffered mutations to ensure we don't undo them twice
clear();
}
}
return {
registerMutations,
restoreDOM,
clear
};
};
const useCompositionDOM = editor => {
const compositionDOM = useMemo(() => {
const manager = createRestoreDomManager(editor, {
current: true
});
let observer = null;
const clear = () => {
var _observer;
(_observer = observer) === null || _observer === void 0 || _observer.disconnect();
observer = null;
manager.clear();
};
const observe = () => {
observer !== null && observer !== void 0 ? observer : observer = new MutationObserver(manager.registerMutations);
observer.observe(ReactEditor.toDOMNode(editor, editor), {
childList: true,
subtree: true
});
};
const track = text => {
if (!observer && !(text !== null && text !== void 0 && text.includes('\n'))) return;
observe();
};
const pause = () => {
if (!observer) return;
manager.registerMutations(observer.takeRecords());
observer.disconnect();
};
const restore = () => {
pause();
manager.restoreDOM();
};
return {
observe,
track,
pause,
restore,
clear
};
}, [editor]);
useEffect(() => () => compositionDOM.clear(), [compositionDOM]);
return compositionDOM;
};
const revertMutation = mutation => {
const {
target
} = mutation;
if (mutation.type === 'characterData') {
target.nodeValue = mutation.oldValue;
} else if (mutation.type === 'attributes' && isDOMElement(target)) {
const name = mutation.attributeName;
if (mutation.oldValue === null) {
target.removeAttribute(name);
} else {
target.setAttribute(name, mutation.oldValue);
}
} else {
mutation.addedNodes.forEach(node => {
var _node$parentNode;
return (_node$parentNode = node.parentNode) === null || _node$parentNode === void 0 ? void 0 : _node$parentNode.removeChild(node);
});
mutation.removedNodes.forEach(node => target.insertBefore(node, mutation.nextSibling));
}
};
const useNativeFormatDOM = editor => {
const nativeFormatDOM = useMemo(() => {
let delivered = [];
let observer = null;
const deliver = mutations => {
if (delivered.length === 0) {
setTimeout(() => {
delivered = [];
});
}
delivered.push(...mutations);
};
const observe = () => {
observer !== null && observer !== void 0 ? observer : observer = new MutationObserver(deliver);
observer.observe(ReactEditor.toDOMNode(editor, editor), {
attributes: true,
attributeOldValue: true,
characterData: true,
characterDataOldValue: true,
childList: true,
subtree: true
});
};
const disconnect = () => {
var _observer;
(_observer = observer) === null || _observer === void 0 || _observer.disconnect();
delivered = [];
};
const revert = () => {
var _observer$takeRecords, _observer2;
const mutations = [...delivered, ...((_observer$takeRecords = (_observer2 = observer) === null || _observer2 === void 0 ? void 0 : _observer2.takeRecords()) !== null && _observer$takeRecords !== void 0 ? _observer$takeRecords : [])];
delivered = [];
mutations.reverse().forEach(revertMutation);
};
return {
observe,
disconnect,
revert
};
}, [editor]);
useEffect(() => {
nativeFormatDOM.observe();
return nativeFormatDOM.disconnect;
}, [nativeFormatDOM]);
return nativeFormatDOM;
};
const caretTop = (editor, point) => {
const range = ReactEditor.resolveDOMRange(editor, {
anchor: point,
focus: point
});
if (!range) {
return null;
}
const [rect] = Array.from(range.getClientRects());
return (rect !== null && rect !== void 0 ? rect : range.getBoundingClientRect()).top;
};
const getPointAboveTrailingNewline = (editor, point) => {
const block = Editor.above(editor, {
at: point,
match: n => Node.isElement(n) && Editor.isBlock(editor, n)
});
if (!block) {
return null;
}
const blockStart = Editor.start(editor, block[1]);
const before = Editor.before(editor, blockStart);
if (!before || !Editor.leaf(editor, before)[0].text.endsWith('\n')) {
return null;
}
if (Point.equals(point, blockStart)) {
return before;
}
const pointTop = caretTop(editor, point);
const blockStartTop = caretTop(editor, blockStart);
if (pointTop === null || blockStartTop === null) {
return null;
}
return Math.abs(pointTop - blockStartTop) > 2 ? null : before;
};
const getCharacterMoveUnit = (editor, point, reverse) => {
const inline = Editor.above(editor, {
at: point,
match: node => Node.isElement(node) && editor.isInline(node)
});
if (!inline || editor.isVoid(inline[0]) || editor.isElementReadOnly(inline[0]) || !(reverse ? Editor.isStart(editor, point, inline[1]) : Editor.isEnd(editor, point, inline[1]))) {
return 'character';
}
if (reverse && !Path.hasPrevious(inline[1])) {
return 'character';
}
const siblingPath = reverse ? Path.previous(inline[1]) : Path.next(inline[1]);
if (!Editor.hasPath(editor, siblingPath)) {
return 'character';
}
const sibling = Node.get(editor, siblingPath);
return Node.isText(sibling) && sibling.text === '' ? 'offset' : 'character';
};
const isTextNode = node => isDOMNode(node) && node.nodeType === node.TEXT_NODE;
const removeStrayComposition = (editor, data) => {
const {
selection
} = editor;
if (!selection || !Range.isCollapsed(selection)) return;
const domSelection = getSelection(ReactEditor.findDocumentOrShadowRoot(editor));
const node = domSelection === null || domSelection === void 0 ? void 0 : domSelection.anchorNode;
if (!domSelection || !isTextNode(node)) return;
const end = domSelection.anchorOffset;
const start = end - data.length;
if (start < 0 || node.data.slice(start, end) !== data) return;
if (!ReactEditor.hasDOMNode(editor, node, {
editable: true
})) return;
const leafPath = ReactEditor.findPath(editor, ReactEditor.toSlateNode(editor, node));
const insertsIntoLeaf = Path.equals(leafPath, selection.anchor.path) && !Editor.void(editor, {
at: selection
});
if (insertsIntoLeaf) return;
node.deleteData(start, data.length);
};
const blockPathAt = (editor, point) => {
var _Editor$above;
return (_Editor$above = Editor.above(editor, {
at: point,
match: n => Node.isElement(n) && Editor.isBlock(editor, n)
})) === null || _Editor$above === void 0 ? void 0 : _Editor$above[1];
};
const getWholeTopLevelBlockPaths = (editor, range) => {
const [start, end] = Range.edges(range);
const startBlock = blockPathAt(editor, start);
const endBlock = blockPathAt(editor, end);
if (!startBlock || !endBlock || startBlock.length !== 1 || endBlock.length !== 1 || startBlock[0] >= endBlock[0] || !Editor.isStart(editor, start, startBlock) || !Editor.isStart(editor, end, endBlock)) {
return null;
}
return Array.from({
length: endBlock[0] - startBlock[0]
}, (_, offset) => [startBlock[0] + offset]);
};
const getMovableRange = (editor, range) => getWholeTopLevelBlockPaths(editor, range) ? range : Editor.unhangRange(editor, range);
const deleteMovedRange = (editor, range) => {
if (Range.isCollapsed(range)) {
const voidEntry = Editor.void(editor, {
at: range
});
if (voidEntry) {
Transforms.removeNodes(editor, {
at: voidEntry[1],
voids: true
});
}
return;
}
const blockPaths = getWholeTopLevelBlockPaths(editor, range);
if (!blockPaths) {
Transforms.select(editor, range);
Editor.deleteFragment(editor);
return;
}
const followingBlockRef = Editor.pathRef(editor, Path.next(blockPaths[blockPaths.length - 1]));
Editor.withoutNormalizing(editor, () => {
for (const path of [...blockPaths].reverse()) {
Transforms.removeNodes(editor, {
at: path
});
}
});
const followingBlock = followingBlockRef.unref();
if (followingBlock) {
Transforms.select(editor, Editor.start(editor, followingBlock));
}
};
const MUTATION_OBSERVER_CONFIG = {
subtree: true,
childList: true,
characterData: true,
characterDataOldValue: true
};
// We have to use a class component here since we rely on `getSnapshotBeforeUpdate` which has no FC equivalent
// to run code synchronously immediately before react commits the component update to the DOM.
class RestoreDOMComponent extends Component {
constructor(...args) {
super(...args);
_defineProperty(this, "context", null);
_defineProperty(this, "manager", null);
_defineProperty(this, "mutationObserver", null);
}
observe() {
var _this$mutationObserve;
const {
node
} = this.props;
if (!node.current) {
throw new Error('Failed to attach MutationObserver, `node` is undefined');
}
(_this$mutationObserve = this.mutationObserver) === null || _this$mutationObserve === void 0 || _this$mutationObserve.observe(node.current, MUTATION_OBSERVER_CONFIG);
}
componentDidMount() {
const {
receivedUserInput
} = this.props;
const editor = this.context;
this.manager = createRestoreDomManager(editor, receivedUserInput);
this.mutationObserver = new MutationObserver(this.manager.registerMutations);
this.observe();
}
getSnapshotBeforeUpdate() {
var _this$mutationObserve2, _this$mutationObserve3, _this$manager2;
const pendingMutations = (_this$mutationObserve2 = this.mutationObserver) === null || _this$mutationObserve2 === void 0 ? void 0 : _this$mutationObserve2.takeRecords();
if (pendingMutations !== null && pendingMutations !== void 0 && pendingMutations.length) {
var _this$manager;
(_this$manager = this.manager) === null || _this$manager === void 0 || _this$manager.registerMutations(pendingMutations);
}
(_this$mutationObserve3 = this.mutationObserver) === null || _this$mutationObserve3 === void 0 || _this$mutationObserve3.disconnect();
(_this$manager2 = this.manager) === null || _this$manager2 === void 0 || _this$manager2.restoreDOM();
return null;
}
componentDidUpdate() {
var _this$manager3;
(_this$manager3 = this.manager) === null || _this$manager3 === void 0 || _this$manager3.clear();
this.observe();
}
componentWillUnmount() {
var _this$mutationObserve4;
(_this$mutationObserve4 = this.mutationObserver) === null || _this$mutationObserve4 === void 0 || _this$mutationObserve4.disconnect();
}
render() {
return this.props.children;
}
}
_defineProperty(RestoreDOMComponent, "contextType", EditorContext);
const RestoreDOM = IS_ANDROID ? RestoreDOMComponent : ({
children
}) => /*#__PURE__*/React.createElement(React.Fragment, null, children);
const EDITOR_TO_COMPOSING = new WeakMap();
/**
* A React context for sharing the `composing` state of the editor.
*/
const ComposingContext = /*#__PURE__*/createContext(false);
/**
* Get the current `composing` state of the editor.
*/
const useComposing = () => {
return useContext(ComposingContext);
};
const _excluded$1 = ["autoFocus", "decorate", "onDOMBeforeInput", "placeholder", "readOnly", "renderElement", "renderChunk", "renderLeaf", "renderText", "renderPlaceholder", "scrollSelectionIntoView", "style", "as", "disableDefaultStyles"],
_excluded2 = ["text"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const isTextDOMNode = node => isDOMNode(node) && node.nodeType === 3;
const isSameCaretPosition = (editor, a, b) => {
if (!Range.isCollapsed(a) || !Range.isCollapsed(b)) {
return false;
}
const [first, second] = Path.isBefore(a.anchor.path, b.anchor.path) ? [a.anchor, b.anchor] : [b.anchor, a.anchor];
if (second.offset !== 0 || !Path.equals(Path.next(first.path), second.path)) {
return false;
}
const node = Node.get(editor, first.path);
return Node.isText(node) && first.offset === node.text.length;
};
const Children = props => (/*#__PURE__*/React.createElement(React.Fragment, null, useChildren(props)));
/**
* Editable.
*/
const Editable = /*#__PURE__*/forwardRef((props, forwardedRef) => {
const defaultRenderPlaceholder = useCallback(props => /*#__PURE__*/React.createElement(DefaultPlaceholder, _objectSpread({}, props)), []);
const {
autoFocus,
decorate = defaultDecorate,
onDOMBeforeInput: propsOnDOMBeforeInput,
placeholder,
readOnly = false,
renderElement,
renderChunk,
renderLeaf,
renderText,
renderPlaceholder = defaultRenderPlaceholder,
scrollSelectionIntoView = defaultScrollSelectionIntoView,
style: userStyle = {},
as: Component = 'div',
disableDefaultStyles = false
} = props,
attributes = _objectWithoutProperties(props, _excluded$1);
const editor = useSlate();
// Rerender editor when composition status changed
const [isComposing, setIsComposing] = useState(false);
const setComposing = useCallback(composing => {
setIsComposing(composing);
IS_COMPOSING.set(editor, composing);
}, [editor]);
useIsomorphicLayoutEffect(() => {
EDITOR_TO_COMPOSING.set(editor, isComposing);
return () => {
EDITOR_TO_COMPOSING.delete(editor);
};
}, [editor, isComposing]);
const ref = useRef(null);
const previousChildren = useRef(editor.children);
const previousSelection = useRef(editor.selection);
const pendingInputScroll = useRef(false);
const pendingNavigationScroll = useRef(false);
const deferredOperations = useRef([]);
const lastNativeInsertion = useRef(null);
const [placeholderHeight, setPlaceholderHeight] = useState();
const processing = useRef(false);
const compositionDOM = useCompositionDOM(editor);
const nativeFormatDOM = useNativeFormatDOM(editor);
const deleteOnCompositionEndRef = useRef(false);
const {
onUserInput,
receivedUserInput
} = useTrackUserInput();
const [, forceRender] = useReducer(s => s + 1, 0);
EDITOR_TO_FORCE_RENDER.set(editor, forceRender);
// Update internal state on each render.
IS_READ_ONLY.set(editor, readOnly);
// Keep track of some state for the event handler logic.
const state = useMemo(() => ({
isBlurring: false,
isDraggingInternally: false,
isTabbing: false,
pendingSelection: null,
isUpdatingSelection: false,
latestElement: null,
hasMarkPlaceholder: false
}), []);
// The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it
// needs to be manually focused.
//
// If this stops working in Firefox, make sure nothing is causing this
// component to re-render during the initial mount. If the DOM selection is
// set by `useIsomorphicLayoutEffect` before `onDOMSelectionChange` updates
// `editor.selection`, the DOM selection can be removed accidentally.
useEffect(() => {
if (!ref.current || !autoFocus) {
return;
}
if (editor.children.length > 0) {
ReactEditor.focus(editor);
} else {
ref.current.focus();
}
}, [autoFocus, editor]);
/**
* The AndroidInputManager object has a cyclical dependency on onDOMSelectionChange
*
* It is defined as a reference to simplify hook dependencies and clarify that
* it needs to be initialized.
*/
const androidInputManagerRef = useRef(undefined);
// 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.
const onDOMSelectionChange = useMemo(() => throttle(() => {
if (IS_NODE_MAP_DIRTY.get(editor)) {
onDOMSelectionChange();
return;
}
state.pendingSelection = null;
const el = ReactEditor.toDOMNode(editor, editor);
const root = el.getRootNode();
if (!processing.current && IS_WEBKIT && root instanceof ShadowRoot) {
processing.current = true;
const active = getActiveElement();
if (active) {
document.execCommand('indent');
} else {
Transforms.deselect(editor);
}
processing.current = false;
return;
}
const androidInputManager = androidInputManagerRef.current;
if ((IS_ANDROID || !ReactEditor.isComposing(editor)) && (!state.isUpdatingSelection || androidInputManager !== null && androidInputManager !== void 0 && androidInputManager.isFlushing()) && !state.isDraggingInternally) {
const _root = ReactEditor.findDocumentOrShadowRoot(editor);
const {
activeElement
} = _root;
const _el = ReactEditor.toDOMNode(editor, editor);
const domSelection = getSelection(_root);
if (activeElement === _el) {
state.latestElement = activeElement;
IS_FOCUSED.set(editor, true);
} else {
IS_FOCUSED.delete(editor);
}
if (!domSelection) {
return Transforms.deselect(editor);
}
const {
anchorNode,
focusNode
} = domSelection;
const anchorNodeSelectable = ReactEditor.hasEditableTarget(editor, anchorNode) || ReactEditor.isTargetInsideNonReadonlyVoid(editor, anchorNode);
const focusNodeInEditor = ReactEditor.hasTarget(editor, focusNode);
const isFocusInEditor = isDOMNode(activeElement) && _el.contains(activeElement);
if (anchorNodeSelectable && focusNodeInEditor && (readOnly || isFocusInEditor || state.isBlurring)) {
const range = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false,
suppressThrow: true
});
if (range) {
if (!ReactEditor.isComposing(editor) && !(androidInputManager !== null && androidInputManager !== void 0 && androidInputManager.hasPendingChanges()) && !(androidInputManager !== null && androidInputManager !== void 0 && androidInputManager.isFlushing())) {
const isCaretOutsideText = domSelection.isCollapsed && !isInSlateText(anchorNode);
if (isCaretOutsideText && editor.selection && Range.equals(range, editor.selection)) {
restoreDomSelection(editor, domSelection, state);
} else {
Transforms.select(editor, range);
}
} else {
androidInputManager === null || androidInputManager === void 0 || androidInputManager.handleUserSelect(range);
}
}
}
// Deselect the editor if the dom selection is not selectable in readonly mode
if (readOnly && (!anchorNodeSelectable || !focusNodeInEditor)) {
Transforms.deselect(editor);
}
}
}, 100), [editor, readOnly, state]);
const scheduleOnDOMSelectionChange = useMemo(() => debounce(onDOMSelectionChange, 0), [onDOMSelectionChange]);
const flushDOMSelectionChange = useCallback(() => {
const root = ReactEditor.toDOMNode(editor, editor).getRootNode();
scheduleOnDOMSelectionChange.flush();
if (!(IS_WEBKIT && root instanceof ShadowRoot)) {
onDOMSelectionChange();
}
onDOMSelectionChange.flush();
}, [editor, onDOMSelectionChange, scheduleOnDOMSelectionChange]);
androidInputManagerRef.current = useAndroidInputManager({
node: ref,
onDOMSelectionChange,
scheduleOnDOMSelectionChange
});
useIsomorphicLayoutEffect(() => {
var _androidInputManagerR, _androidInputManagerR2;
// Update element-related weak maps with the DOM element ref.
let 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.
const {
selection
} = editor;
const scrollForInput = pendingInputScroll.current;
pendingInputScroll.current = false;
const scrollForNavigation = pendingNavigationScroll.current;
pendingNavigationScroll.current = false;
const selectionChangedByInput = (scrollForInput && previousChildren.current !== editor.children || scrollForNavigation) && !!selection && (!previousSelection.current || !Range.equals(previousSelection.current, selection));
previousChildren.current = editor.children;
previousSelection.current = selection;
const root = ReactEditor.findDocumentOrShadowRoot(editor);
const domSelection = getSelection(root);
if (!domSelection || !ReactEditor.isFocused(editor) || (_androidInputManagerR = androidInputManagerRef.current) !== null && _androidInputManagerR !== void 0 && _androidInputManagerR.hasPendingAction()) {
return;
}
const setDomSelection = forceChange => {
const hasDomSelection = domSelection.type !== 'None';
// If the DOM selection is properly unset, we're done.
if (!selection && !hasDomSelection) {
return;
}
// Get anchorNode and focusNode
const focusNode = domSelection.focusNode;
let anchorNode;
// COMPAT: In firefox the normal selection way does not work
// (https://github.com/ianstormtaylor/slate/pull/5486#issue-1820720223)
if (IS_FIREFOX && domSelection.rangeCount > 1) {
const firstRange = domSelection.getRangeAt(0);
const lastRange = domSelection.getRangeAt(domSelection.rangeCount - 1);
// Right to left
if (firstRange.startContainer === focusNode) {
anchorNode = lastRange.endContainer;
} else {
// Left to right
anchorNode = firstRange.startContainer;
}
} else {
anchorNode = domSelection.anchorNode;
}
// verify that the dom selection is in the editor
const editorElement = EDITOR_TO_ELEMENT.get(editor);
let hasDomSelectionInEditor = false;
if (containsShadowAware(editorElement, anchorNode) && containsShadowAware(editorElement, 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 && !forceChange) {
var _anchorNode;
const slateRange = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: true,
// domSelection is not necessarily a valid Slate range
// (e.g. when clicking on contentEditable:false element)
suppressThrow: true
});
if (slateRange && Range.equals(slateRange, selection) && (!state.hasMarkPlaceholder || (_anchorNode = anchorNode) !== null && _anchorNode !== void 0 && (_anchorNode = _anchorNode.parentElement) !== null && _anchorNode !== void 0 && _anchorNode.hasAttribute('data-slate-mark-placeholder'))) {
if (selectionChangedByInput) {
scrollSelectionIntoView(editor, domSelection.getRangeAt(0));
}
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,
suppressThrow: true
});
return;
}
const pending = state.pendingSelection;
state.pendingSelection = null;
if (pending && !forceChange && pending.basedOn === selection && !(selection && Range.equals(pending.range, selection))) {
Transforms.select(editor, pending.range);
return;
}
// Otherwise the DOM selection is out of sync, so update it.
state.isUpdatingSelection = true;
const newDomRange = selection && ReactEditor.resolveDOMRange(editor, selection);
if (newDomRange) {
if (ReactEditor.isComposing(editor) && !IS_ANDROID) {
if (domSelection.rangeCount > 0) {
domSelection.collapseToEnd();
}
} else 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);
}
scrollSelectionIntoView(editor, newDomRange);
} else {
domSelection.removeAllRanges();
}
return newDomRange;
};
// In firefox if there is more then 1 range and we call setDomSelection we remove the ability to select more cells in a table
if (domSelection.rangeCount <= 1) {
setDomSelection();
}
const ensureSelection = ((_androidInputManagerR2 = androidInputManagerRef.current) === null || _androidInputManagerR2 === void 0 ? void 0 : _androidInputManagerR2.isFlushing()) === 'action';
if (!IS_ANDROID || !ensureSelection) {
setTimeout(() => {
state.isUpdatingSelection = false;
});
return;
}
let timeoutId = null;
const animationFrameId = requestAnimationFrame(() => {
if (ensureSelection) {
const ensureDomSelection = forceChange => {
const el = EDITOR_TO_ELEMENT.get(editor);
if (!el) {
return;
}
el.focus();
setDomSelection(forceChange);
};
// Compat: Android IMEs try to force their selection by manually re-applying it even after we set it.
// This essentially would make setting the slate selection during an update meaningless, so we force it
// again here. We can't only do it in the setTimeout after the animation frame since that would cause a
// visible flicker.
ensureDomSelection();
timeoutId = setTimeout(() => {
// COMPAT: While setting the selection in an animation frame visually correctly sets the selection,
// it doesn't update GBoards spellchecker state. We have to manually trigger a selection change after
// the animation frame to ensure it displays the correct state.
ensureDomSelection(true);
state.isUpdatingSelection = false;
});
}
});
return () => {
cancelAnimationFrame(animationFrameId);
if (timeoutId) {
clearTimeout(timeoutId);
}
};
});
// 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
const onDOMBeforeInput = useCallback(event => {
if (readOnly) {
isDOMEventHandled(event, propsOnDOMBeforeInput);
return;
}
if (!ReactEditor.hasEditableTarget(editor, event.target)) {
return;
}
handleNativeHistoryEvents(editor, event);
const el = ReactEditor.toDOMNode(editor, editor);
const root = el.getRootNode();
if (processing !== null && processing !== void 0 && processing.current && IS_WEBKIT && root instanceof ShadowRoot) {
const ranges = event.getTargetRanges();
const range = ranges[0];
const newRange = new window.Range();
newRange.setStart(range.startContainer, range.startOffset);
newRange.setEnd(range.endContainer, range.endOffset);
// Unresolvable ranges would throw out of the handler (#3556); suppress and skip the move.
const slateRange = ReactEditor.toSlateRange(editor, newRange, {
exactMatch: false,
suppressThrow: true
});
if (slateRange) {
Transforms.select(editor, slateRange);
}
event.preventDefault();
event.stopImmediatePropagation();
return;
}
onUserInput();
pendingInputScroll.current = true;
if (!isDOMEventHandled(event, propsOnDOMBeforeInput)) {
var _EDITOR_TO_USER_SELEC;
// COMPAT: BeforeInput events aren't cancelable on android, so we have to handle them differently using the android input manager.
if (androidInputManagerRef.current) {
return androidInputManagerRef.current.handleDOMBeforeInput(event);
}
// Some IMEs/Chrome extensions like e.g. Grammarly set the selection immediately before
// triggering a `beforeinput` expecting the change to be applied to the immediately before
// set selection.
flushDOMSelectionChange();
const {
selection
} = editor;
const {
inputType: type
} = event;
const data = event.dataTransfer || event.data || undefined;
const isCompositionChange = type === 'insertCompositionText' || type === 'deleteCompositionText';
// COMPAT: use composition change events as a hint to where we should insert
// composition text if we aren't composing to work around https://github.com/ianstormtaylor/slate/issues/5038
if (isCompositionChange && ReactEditor.isComposing(editor)) {
if (IS_CHROME || deleteOnCompositionEndRef.current) {
compositionDOM.track(event.data);
}
return;
}
let native = false;
let nativePoint = null;
if (type === 'insertText' && selection && Range.isCollapsed(selection) &&
// Only use native character insertion for single characters a-z or space for now.
// Long-press events (hold a + press 4 = ä) to choose a special character otherwise
// causes duplicate inserts.
event.data && event.data.length === 1 && /[a-z ]/i.test(event.data) &&
// Chrome has issues correctly editing the start of nodes: https://bugs.chromium.org/p/chromium/issues/detail?id=1249405
// When there is an inline element, e.g. a link, and you select
// right after it (the start of the next node).
selection.anchor.offset !== 0) {
native = true;
// Skip native if there are marks, as
// `insertText` will insert a node, not just text.
if (editor.marks || typeof Editor.insertionPoint === 'function' && !Point.equals(Editor.insertionPoint(editor, selection.anchor), selection.anchor)) {
native = false;
}
const domSelection = getSelection(ReactEditor.findDocumentOrShadowRoot(editor));
const domAnchor = domSelection === null || domSelection === void 0 ? void 0 : domSelection.anchorNode;
if (!isInSlateText(domAnchor)) {
native = false;
}
// If the NODE_MAP is dirty, we can't trust the selection anchor (eg ReactEditor.toDOMPoint)
if (!IS_NODE_MAP_DIRTY.get(editor)) {
// Chrome also has issues correctly editing the end of anchor elements: https://bugs.chromium.org/p/chromium/issues/detail?id=1259100
// Therefore we don't allow native events to insert text at the end of anchor nodes.
const {
anchor
} = selection;
const domPoint = ReactEditor.resolveDOMPoint(editor, anchor);
if (!domPoint) {
native = false;
} else {
var _node$parentElement, _window$getComputedSt;
const [node, offset] = domPoint;
const anchorNode = (_node$parentElement = node.parentElement) === null || _node$parentElement === void 0 ? void 0 : _node$parentElement.closest('a');
const window = ReactEditor.getWindow(editor);
if (native && anchorNode && ReactEditor.hasDOMNode(editor, anchorNode)) {
var _lastText$textContent;
// Find the last text node inside the anchor.
const lastText = window === null || window === void 0 ? void 0 : window.document.createTreeWalker(anchorNode, NodeFilter.SHOW_TEXT).lastChild();
if (lastText === node && ((_lastText$textContent = lastText.textContent) === null || _lastText$textContent === void 0 ? void 0 : _lastText$textContent.length) === offset) {
native = false;
}
}
// Chrome has issues with the presence of tab characters inside elements with whiteSpace = 'pre'
// causing abnormal insert behavior: https://bugs.chromium.org/p/chromium/issues/detail?id=1219139
if (native && node.parentElement && (window === null || window === void 0 || (_window$getComputedSt = window.getComputedStyle(node.parentElement)) === null || _window$getComputedSt === void 0 ? void 0 : _window$getComputedSt.whiteSpace) === 'pre') {
const block = Editor.above(editor, {
at: anchor.path,
match: n => Node.isElement(n) && Editor.isBlock(editor, n)
});
if (block && Node.string(block[0]).includes('\t')) {
native = false;
}
}
if (native && isTextDOMNode(node)) {
nativePoint = domSelection !== null && domSelection !== void 0 && domSelection.isCollapsed && isTextDOMNode(domAnchor) ? [domAnchor, domSelection.anchorOffset] : [node, offset];
}
}
}
}
// 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 the NODE_MAP is dirty, we can't trust the selection anchor (eg ReactEditor.toDOMPoint via ReactEditor.toSlateRange)
if ((!type.startsWith('delete') || type.startsWith('deleteBy')) && !IS_NODE_MAP_DIRTY.get(editor)) {
const [targetRange] = event.getTargetRanges();
if (targetRange) {
// Unresolvable ranges would throw out of the handler (#3556); suppress and fall back to synthetic handling.
const range = ReactEditor.toSlateRange(editor, targetRange, {
exactMatch: false,
suppressThrow: true
});
if (!range) {
native = false;
} else if (!selection || !Range.equals(selection, range)) {
native = false;
const selectionRef = !isCompositionChange && editor.selection && !isSameCaretPosition(editor, editor.selection, range) && Editor.rangeRef(editor, editor.selection);
Transforms.select(editor, range);
if (selectionRef) {
EDITOR_TO_USER_SELECTION.set(editor, selectionRef);
}
}
if (native && isTextDOMNode(targetRange.startContainer)) {
nativePoint = [targetRange.startContainer, targetRange.startOffset];
}
}
}
// Composition change types occur while a user is composing text and can't be
// cancelled. Let them through and wait for the composition to end.
if (isCompositionChange) {
return;
}
if (!native) {
lastNativeInsertion.current = null;
event.preventDefault();
}
// 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')) {
const 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':
Editor.insertSoftBreak(editor);
break;
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/
if (ReactEditor.isComposing(editor)) {
setComposing(false);
}
}
// use a weak comparison instead of 'instanceof' to allow
// programmatic access of paste events coming from external windows
// like cypress where cy.window does not work realibly
if ((data === null || data === void 0 ? void 0 : data.constructor.name) === 'DataTransfer') {
ReactEditor.insertData(editor, data);
} else if (typeof data === 'string') {
// Only insertText operations use the native functionality, for now.
// Potentially expand to single character deletes, as well.
if (native) {
lastNativeInsertion.current = null;
if (nativePoint && selection) {
const [node] = Editor.leaf(editor, selection.anchor);
const [domNode, domOffset] = nativePoint;
lastNativeInsertion.current = {
point: selection.anchor,
text: node.text,
domNode,
domOffset,
domText: domNode.data,
char: data
};
}
deferredOperations.current.push(() => Editor.insertText(editor, data));
} else {
Editor.insertText(editor, data);
}
}
break;
}
}
// Restore the actual user section if nothing manually set it.
const toRestore = (_EDITOR_TO_USER_SELEC = EDITOR_TO_USER_SELECTION.get(editor)) === null || _EDITOR_TO_USER_SELEC === void 0 ? void 0 : _EDITOR_TO_USER_SELEC.unref();
EDITOR_TO_USER_SELECTION.delete(editor);
if (toRestore && (!editor.selection || !Range.equals(editor.selection, toRestore))) {
Transforms.select(editor, toRestore);
}
}
}, [editor, onUserInput, propsOnDOMBeforeInput, compositionDOM, flushDOMSelectionChange, readOnly, setComposing]);
const callbackRef = useCallback(node => {
if (node == null) {
onDOMSelectionChange.cancel();
scheduleOnDOMSelectionChange.cancel();
EDITOR_TO_ELEMENT.delete(editor);
NODE_TO_ELEMENT.delete(editor);
if (ref.current && HAS_BEFORE_INPUT_SUPPORT) {
// @ts-ignore The `beforeinput` event isn't recognized.
ref.current.removeEventListener('beforeinput', onDOMBeforeInput);
}
} else {
// 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
if (HAS_BEFORE_INPUT_SUPPORT) {
// @ts-ignore The `beforeinput` event isn't recognized.
node.addEventListener('beforeinput', onDOMBeforeInput);
}
}
ref.current = node;
if (typeof forwardedRef === 'function') {
forwardedRef(node);
} else if (forwardedRef) {
forwardedRef.current = node;
}
}, [onDOMSelectionChange, scheduleOnDOMSelectionChange, editor, onDOMBeforeInput, forwardedRef]);
useIsomorphicLayoutEffect(() => {
const window = ReactEditor.getWindow(editor);
// COMPAT: In Chrome, `selectionchange` events can fire when <input> and
// <textarea> elements are appended to the DOM, causing
// `editor.selection` to be overwritten in some circumstances.
// (2025/01/16) https://issues.chromium.org/issues/389368412
const readUnsyncedSelection = () => {
const androidInputManager = androidInputManagerRef.current;
if (state.isUpdatingSelection || state.isDraggingInternally || ReactEditor.isComposing(editor) || androidInputManager !== null && androidInputManager !== void 0 && androidInputManager.hasPendingChanges() || androidInputManager !== null && androidInputManager !== void 0 && androidInputManager.isFlushing() || IS_NODE_MAP_DIRTY.get(editor)) {
return null;
}
const domSelection = getSelection(ReactEditor.findDocumentOrShadowRoot(editor));
if (!domSelection || !(ReactEditor.hasEditableTarget(editor, domSelection.anchorNode) || ReactEditor.isTargetInsideNonReadonlyVoid(editor, domSelection.anchorNode)) || !ReactEditor.hasTarget(editor, domSelection.focusNode)) {
return null;
}
const range = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false,
suppressThrow: true
});
return range ? {
range,
basedOn: editor.selection
} : null;
};
const onSelectionChange = ({
target
}) => {
const targetElement = target instanceof HTMLElement ? target : null;
const targetTagName = targetElement === null || targetElement === void 0 ? void 0 : targetElement.tagName;
if (targetTagName === 'INPUT' || targetTagName === 'TEXTAREA') {
return;
}
state.pendingSelection = readUnsyncedSelection();
scheduleOnDOMSelectionChange();
};
// 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
window.document.addEventListener('selectionchange', onSelectionChange);
const onKeyDown = event => {
state.isTabbing = event.key === 'Tab';
};
const clearTabbing = () => {
state.isTabbing = false;
};
window.document.addEventListener('keydown', onKeyDown, true);
window.document.addEventListener('keyup', clearTabbing, true);
window.document.addEventListener('pointerdown', clearTabbing, true);
// Listen for dragend and drop globally. In Firefox, if a drop handler
// initiates an operation that causes the originally dragged element to
// unmount, that element will not emit a dragend event. (2024/06/21)
const stoppedDragging = () => {
state.isDraggingInternally = false;
};
window.document.addEventListener('dragend', stoppedDragging);
window.document.addEventListener('drop', stoppedDragging);
return () => {
window.document.removeEventListener('selectionchange', onSelectionChange);
window.document.removeEventListener('keydown', onKeyDown, true);
window.document.removeEventListener('keyup', clearTabbing, true);
window.document.removeEventListener('pointerdown', clearTabbing, true);
window.document.removeEventListener('dragend', stoppedDragging);
window.document.removeEventListener('drop', stoppedDragging);
};
}, [editor, scheduleOnDOMSelectionChange, state]);
const decorations = decorate([editor, []]);
const decorateContext = useDecorateContext(decorate);
const showPlaceholder = placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '' && !isComposing;
const placeHolderResizeHandler = useCallback(placeholderEl => {
if (placeholderEl && showPlaceholder) {
var _placeholderEl$getBou;
setPlaceholderHeight((_placeholderEl$getBou = placeholderEl.getBoundingClientRect()) === null || _placeholderEl$getBou === void 0 ? void 0 : _placeholderEl$getBou.height);
} else {
setPlaceholderHeight(undefined);
}
}, [showPlaceholder]);
if (showPlaceholder) {
const start = Editor.start(editor, []);
decorations.push({
[PLACEHOLDER_SYMBOL]: true,
placeholder,
onPlaceholderResize: placeHolderResizeHandler,
anchor: start,
focus: start
});
}
const {
marks
} = editor;
state.hasMarkPlaceholder = false;
if (editor.selection && Range.isCollapsed(editor.selection) && marks) {
const {
anchor
} = editor.selection;
const leaf = Node.leaf(editor, anchor.path);
const {
text
} = leaf,
rest = _objectWithoutProperties(leaf, _excluded2);
// While marks isn't a 'complete' text, we can still use loose Text.equals
// here which only compares marks anyway.
if (!Text$1.equals(leaf, marks, {
loose: true
})) {
state.hasMarkPlaceholder = true;
const unset = Object.fromEntries(Object.keys(rest).map(mark => [mark, null]));
decorations.push(_objectSpread(_objectSpread(_objectSpread({
[MARK_PLACEHOLDER_SYMBOL]: true
}, unset), marks), {}, {
anchor,
focus: anchor
}));
}
}
// Update EDITOR_TO_MARK_PLACEHOLDER_MARKS in setTimeout useEffect to ensure we don't set it
// before we receive the composition end event.
useEffect(() => {
setTimeout(() => {
const {
selection
} = editor;
if (selection) {
const {
anchor
} = selection;
const text = Node.leaf(editor, anchor.path);
// While marks isn't a 'complete' text, we can still use loose Text.equals
// here which only compares marks anyway.
if (marks && !Text$1.equals(text, marks, {
loose: true
})) {
EDITOR_TO_PENDING_INSERTION_MARKS.set(editor, marks);
return;
}
}
EDITOR_TO_PENDING_INSERTION_MARKS.delete(editor);
});
});
useFlushDeferredSelectorsOnRender();
return /*#__PURE__*/React.createElement(ReadOnlyContext.Provider, {
value: readOnly
}, /*#__PURE__*/React.createElement(ComposingContext.Provider, {
value: isComposing
}, /*#__PURE__*/React.createElement(DecorateContext.Provider, {
value: decorateContext
}, /*#__PURE__*/React.createElement(RestoreDOM, {
node: ref,
receivedUserInput: receivedUserInput
}, /*#__PURE__*/React.createElement(Component, _objectSpread(_objectSpread({
role: readOnly ? undefined : 'textbox',
"aria-multiline": readOnly ? undefined : true,
"aria-placeholder": showPlaceholder ? placeholder : undefined,
translate: "no"
}, attributes), {}, {
// COMPAT: Certain browsers don't support the `beforeinput` event, so we'd
// have to use hacks to make these replacement-based features work.
// For SSR situations HAS_BEFORE_INPUT_SUPPORT is false and results in prop
// mismatch warning app moves to browser. Pass-through consumer props when
// not CAN_USE_DOM (SSR) and default to falsy value
spellCheck: HAS_BEFORE_INPUT_SUPPORT || !CAN_USE_DOM ? attributes.spellCheck : false,
autoCorrect: HAS_BEFORE_INPUT_SUPPORT || !CAN_USE_DOM ? attributes.autoCorrect : 'false',
autoCapitalize: HAS_BEFORE_INPUT_SUPPORT || !CAN_USE_DOM ? attributes.autoCapitalize : 'false',
"data-slate-editor": true,
"data-slate-node": "value",
// explicitly set this
contentEditable: !readOnly,
// in some cases, a decoration needs access to the range / selection to decorate a text node,
// then you will select the whole text node when you select part the of text
// this magic zIndex="-1" will fix it
zindex: -1,
suppressContentEditableWarning: true,
ref: callbackRef,
style: _objectSpread(_objectSpread({}, disableDefaultStyles ? {} : _objectSpread({
// Allow positioning relative to the editable element.
position: 'relative',
// Preserve adjacent whitespace and new lines.
whiteSpace: 'pre-wrap',
// Allow words to break if they are too long.
wordWrap: 'break-word'
}, placeholderHeight ? {
minHeight: placeholderHeight
} : {})), userStyle),
onBeforeInput: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onBeforeInput);
return;
}
// 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 && !isEventHandled(event, attributes.onBeforeInput) && ReactEditor.hasSelectableTarget(editor, event.target)) {
event.preventDefault();
if (!ReactEditor.isComposing(editor)) {
const text = event.data;
Editor.insertText(editor, text);
}
}
}, [attributes.onBeforeInput, editor, readOnly]),
onInput: useCallback(event => {
var _event$nativeEvent$in;
if (readOnly) {
isEventHandled(event, attributes.onInput);
return;
}
if (!ReactEditor.hasEditableTarget(editor, event.target)) {
return;
}
compositionDOM.pause();
if (isEventHandled(event, attributes.onInput)) {
return;
}
if (androidInputManagerRef.current) {
androidInputManagerRef.current.handleInput();
return;
}
if ((_event$nativeEvent$in = event.nativeEvent.inputType) !== null && _event$nativeEvent$in !== void 0 && _event$nativeEvent$in.startsWith('format')) {
const domSelection = getSelection(ReactEditor.findDocumentOrShadowRoot(editor));
const range = domSelection && ReactEditor.resolveSlateRange(editor, domSelection);
nativeFormatDOM.revert();
if (domSelection && range) {
Transforms.select(editor, range);
restoreDomSelection(editor, domSelection, state);
}
return;
}
// Flush native operations, as native events will have propogated
// and we can correctly compare DOM text values in components
// to stop rendering, so that browser functions like autocorrect
// and spellcheck work as expected.
for (const op of deferredOperations.current) {
op();
}
deferredOperations.current = [];
const nativeInsertion = lastNativeInsertion.current;
lastNativeInsertion.current = null;
if (nativeInsertion) {
const {
point,
text,
domNode,
domOffset,
domText,
char
} = nativeInsertion;
const node = Node.getIf(editor, point.path);
if (Text$1.isText(node) && node.text === text && domNode.isConnected && domNode.data === domText.slice(0, domOffset) + char + domText.slice(domOffset)) {
domNode.deleteData(domOffset, char.length);
if (editor.selection && Range.isCollapsed(editor.selection) && Point.equals(editor.selection.anchor, point)) {
var _getSelection;
(_getSelection = getSelection(ReactEditor.findDocumentOrShadowRoot(editor))) === null || _getSelection === void 0 || _getSelection.collapse(domNode, domOffset);
}
}
}
// COMPAT: Since `beforeinput` doesn't fully `preventDefault`,
// there's a chance that content might be placed in the browser's undo stack.
// This means undo can be triggered even when the div is not focused,
// and it only triggers the input event for the node. (2024/10/09)
if (!ReactEditor.isFocused(editor)) {
handleNativeHistoryEvents(editor, event.nativeEvent);
}
}, [readOnly, attributes.onInput, editor, compositionDOM, nativeFormatDOM, state]),
onBlur: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onBlur);
return;
}
if (state.isUpdatingSelection || !ReactEditor.hasSelectableTarget(editor, event.target) || isEventHandled(event, attributes.onBlur)) {
return;
}
// 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.
const root = ReactEditor.findDocumentOrShadowRoot(editor);
if (state.latestElement === root.activeElement) {
return;
}
const {
relatedTarget
} = event;
const 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)) {
const node = ReactEditor.toSlateNode(editor, relatedTarget);
if (Node.isElement(node) && !editor.isVoid(node)) {
return;
}
}
state.isBlurring = true;
try {
flushDOMSelectionChange();
} finally {
state.isBlurring = false;
}
// COMPAT: Safari doesn't always remove the selection even if the content-
// editable element no longer has focus. Refer to:
// https://stackoverflow.com/questions/12353247/force-contenteditable-div-to-stop-accepting-input-after-it-loses-focus-under-web
if (IS_WEBKIT) {
const domSelection = getSelection(root);
domSelection === null || domSelection === void 0 || domSelection.removeAllRanges();
}
IS_FOCUSED.delete(editor);
}, [readOnly, state, editor, attributes.onBlur, flushDOMSelectionChange]),
onClick: useCallback(event => {
if (ReactEditor.hasTarget(editor, event.target)) {
flushDOMSelectionChange();
}
if (ReactEditor.hasTarget(editor, event.target) && !isEventHandled(event, attributes.onClick) && isDOMNode(event.target)) {
const node = ReactEditor.toSlateNode(editor, event.target);
let path;
try {
path = ReactEditor.findPath(editor, node);
} catch (_unused) {
return;
}
// At this time, the Slate document may be arbitrarily different,
// because onClick handlers can change the document before we get here.
// Therefore we must check that this path actually exists,
// and that it still refers to the same node.
if (!Editor.hasPath(editor, path) || Node.get(editor, path) !== node) {
return;
}
if (event.detail === TRIPLE_CLICK && path.length >= 1) {
let blockPath = path;
if (!(Node.isElement(node) && Editor.isBlock(editor, node))) {
var _block$;
const block = Editor.above(editor, {
match: n => Node.isElement(n) && Editor.isBlock(editor, n),
at: path
});
blockPath = (_block$ = block === null || block === void 0 ? void 0 : block[1]) !== null && _block$ !== void 0 ? _block$ : path.slice(0, 1);
}
const isIsolated = Editor.above(editor, {
at: Editor.start(editor, blockPath),
match: n => {
var _editor$isIsolated;
return Node.isElement(n) && !!((_editor$isIsolated = editor.isIsolated) !== null && _editor$isIsolated !== void 0 && _editor$isIsolated.call(editor, n));
}
});
if (blockPath.length > 1 || isIsolated) {
const range = Editor.range(editor, blockPath);
Transforms.select(editor, range);
return;
}
}
if (readOnly) {
return;
}
const start = Editor.start(editor, path);
const end = Editor.end(editor, path);
const startVoid = Editor.void(editor, {
at: start
});
const endVoid = Editor.void(editor, {
at: end
});
const selectedVoid = editor.selection && Range.isCollapsed(editor.selection) && Editor.void(editor, {
at: editor.selection.anchor
});
if (event.shiftKey && selectedVoid && !Path.isAncestor(selectedVoid[1], path) && !(startVoid && Path.equals(startVoid[1], selectedVoid[1]))) {
const clicked = ReactEditor.resolveEventRange(editor, event);
if (!clicked) {
return;
}
const voidStart = Editor.start(editor, selectedVoid[1]);
const voidEnd = Editor.end(editor, selectedVoid[1]);
const anchor = Point.isBefore(clicked.anchor, voidStart) ? voidEnd : voidStart;
Transforms.select(editor, {
anchor,
focus: clicked.anchor
});
return;
}
if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
if (event.shiftKey && editor.selection) {
const {
anchor
} = editor.selection;
const focus = Point.isBefore(anchor, start) ? end : start;
Transforms.select(editor, {
anchor,
focus
});
return;
}
const range = Editor.range(editor, start);
Transforms.select(editor, range);
}
}
}, [editor, attributes.onClick, readOnly, flushDOMSelectionChange]),
onCompositionEnd: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onCompositionEnd);
return;
}
if (isDOMEventTargetInput(event)) {
return;
}
if (ReactEditor.hasSelectableTarget(editor, event.target)) {
var _androidInputManagerR3;
Promise.resolve().then(() => {
setComposing(false);
});
(_androidInputManagerR3 = androidInputManagerRef.current) === null || _androidInputManagerR3 === void 0 || _androidInputManagerR3.handleCompositionEnd(event);
const deleteOnCompositionEnd = deleteOnCompositionEndRef.current;
deleteOnCompositionEndRef.current = false;
if (isEventHandled(event, attributes.onCompositionEnd) || IS_ANDROID) {
compositionDOM.clear();
return;
}
if (deleteOnCompositionEnd && !event.data) {
compositionDOM.restore();
Editor.deleteFragment(editor);
}
// 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_WEBKIT && !IS_FIREFOX_LEGACY && !IS_IOS && !IS_WECHATBROWSER && !IS_UC_MOBILE && event.data) {
const placeholderMarks = EDITOR_TO_PENDING_INSERTION_MARKS.get(editor);
EDITOR_TO_PENDING_INSERTION_MARKS.delete(editor);
// Ensure we insert text with the marks the user was actually seeing
if (placeholderMarks !== undefined) {
EDITOR_TO_USER_MARKS.set(editor, editor.marks);
editor.marks = placeholderMarks;
}
compositionDOM.restore();
removeStrayComposition(editor, event.data);
Editor.insertText(editor, event.data);
const userMarks = EDITOR_TO_USER_MARKS.get(editor);
EDITOR_TO_USER_MARKS.delete(editor);
if (userMarks !== undefined) {
editor.marks = userMarks;
}
}
compositionDOM.clear();
}
}, [readOnly, attributes.onCompositionEnd, editor, compositionDOM, setComposing]),
onCompositionUpdate: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onCompositionUpdate);
return;
}
if (ReactEditor.hasSelectableTarget(editor, event.target) && !isEventHandled(event, attributes.onCompositionUpdate) && !isDOMEventTargetInput(event)) {
if (!ReactEditor.isComposing(editor)) {
setComposing(true);
}
}
}, [readOnly, attributes.onCompositionUpdate, editor, setComposing]),
onCompositionStart: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onCompositionStart);
return;
}
if (isDOMEventTargetInput(event)) {
return;
}
if (ReactEditor.hasSelectableTarget(editor, event.target)) {
var _androidInputManagerR4;
(_androidInputManagerR4 = androidInputManagerRef.current) === null || _androidInputManagerR4 === void 0 || _androidInputManagerR4.handleCompositionStart(event);
if (isEventHandled(event, attributes.onCompositionStart) || IS_ANDROID) {
return;
}
compositionDOM.clear();
setIsComposing(true);
flushDOMSelectionChange();
const {
selection
} = editor;
if (selection && Range.isExpanded(selection)) {
if (IS_FIREFOX && !IS_FIREFOX_LEGACY) {
compositionDOM.observe();
deleteOnCompositionEndRef.current = true;
return;
}
Editor.deleteFragment(editor);
return;
}
}
}, [readOnly, attributes.onCompositionStart, editor, compositionDOM, flushDOMSelectionChange]),
onCopy: useCallback(event => {
if (ReactEditor.hasSelectableTarget(editor, event.target) && !isDOMEventTargetInput(event)) {
flushDOMSelectionChange();
}
if (ReactEditor.hasSelectableTarget(editor, event.target) && !isEventHandled(event, attributes.onCopy) && !isDOMEventTargetInput(event)) {
event.preventDefault();
ReactEditor.setFragmentData(editor, event.clipboardData, 'copy');
}
}, [attributes.onCopy, editor, flushDOMSelectionChange]),
onCut: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onCut);
return;
}
if (ReactEditor.hasSelectableTarget(editor, event.target) && !isDOMEventTargetInput(event)) {
flushDOMSelectionChange();
}
if (ReactEditor.hasSelectableTarget(editor, event.target) && !isEventHandled(event, attributes.onCut) && !isDOMEventTargetInput(event)) {
event.preventDefault();
selectMovableRange(editor);
ReactEditor.setFragmentData(editor, event.clipboardData, 'cut');
const {
selection
} = editor;
if (selection) {
if (Range.isExpanded(selection)) {
deleteMovedRange(editor, selection);
} else {
const node = Node.parent(editor, selection.anchor.path);
if (Editor.isVoid(editor, node)) {
Transforms.delete(editor);
}
}
}
}
}, [readOnly, editor, attributes.onCut, flushDOMSelectionChange]),
onDragOver: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onDragOver);
return;
}
if (ReactEditor.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.
const node = ReactEditor.toSlateNode(editor, event.target);
if (Node.isElement(node) && Editor.isVoid(editor, node)) {
event.preventDefault();
}
}
}, [readOnly, attributes.onDragOver, editor]),
onDragStart: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onDragStart);
return;
}
if (ReactEditor.hasTarget(editor, event.target) && !isEventHandled(event, attributes.onDragStart)) {
const node = ReactEditor.toSlateNode(editor, event.target);
const path = ReactEditor.findPath(editor, node);
const voidMatch = Node.isElement(node) && 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) {
const range = Editor.range(editor, path);
Transforms.select(editor, range);
}
selectMovableRange(editor);
state.isDraggingInternally = true;
ReactEditor.setFragmentData(editor, event.dataTransfer, 'drag');
}
}, [readOnly, editor, attributes.onDragStart, state]),
onDrop: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onDrop);
return;
}
if (ReactEditor.hasTarget(editor, event.target) && !isEventHandled(event, attributes.onDrop)) {
event.preventDefault();
// Keep a reference to the dragged range before updating selection
const draggedRange = editor.selection;
// Find the range where the drop happened. It is resolved from
// the drop coordinates, which can point outside of the editor
// even though the event's target is inside it (e.g. when the
// page scrolled during the drag), leaving no range to drop at.
const range = ReactEditor.findEventRange(editor, event, {
suppressThrow: true
});
const data = event.dataTransfer;
if (!range && state.isDraggingInternally) {
// The dragged content already sits in the editor, so without
// a target it stays where it is.
return;
}
if (range) {
Transforms.select(editor, range);
if (state.isDraggingInternally && draggedRange) {
if (Range.includes(draggedRange, range.anchor)) {
return;
}
if (!Editor.void(editor, {
at: range,
voids: true
})) {
const dropRef = Editor.rangeRef(editor, range);
deleteMovedRange(editor, draggedRange);
const dropRange = dropRef.unref();
if (dropRange) {
Transforms.select(editor, dropRange);
}
}
}
} else if (!editor.selection && editor.children.length > 0) {
// Without a drop position the data goes to the current
// selection, or to the end of the document if there is none.
Transforms.select(editor, Editor.end(editor, []));
}
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, editor, attributes.onDrop, state]),
onDragEnd: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onDragEnd);
return;
}
if (state.isDraggingInternally && attributes.onDragEnd && ReactEditor.hasTarget(editor, event.target)) {
attributes.onDragEnd(event);
}
}, [readOnly, state, attributes, editor]),
onFocus: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onFocus);
return;
}
if (!state.isUpdatingSelection && ReactEditor.hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onFocus)) {
const el = ReactEditor.toDOMNode(editor, editor);
const 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);
if (state.isTabbing && event.target === el) {
const domSelection = getSelection(root);
if (domSelection && editor.selection) {
state.pendingSelection = null;
restoreDomSelection(editor, domSelection, state);
}
state.isTabbing = false;
}
}
}, [readOnly, state, editor, attributes.onFocus]),
onKeyDown: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onKeyDown);
return;
}
if (ReactEditor.hasEditableTarget(editor, event.target)) {
var _androidInputManagerR5;
(_androidInputManagerR5 = androidInputManagerRef.current) === null || _androidInputManagerR5 === void 0 || _androidInputManagerR5.handleKeyDown(event);
const {
nativeEvent
} = event;
// COMPAT: The composition end event isn't fired reliably in all browsers,
// so we sometimes might end up stuck in a composition state even though we
// aren't composing any more.
if (ReactEditor.isComposing(editor) && (nativeEvent.isComposing === false || isDeletingInVoid(editor, nativeEvent))) {
setComposing(false);
}
if (isEventHandled(event, attributes.onKeyDown) || ReactEditor.isComposing(editor)) {
return;
}
pendingNavigationScroll.current = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown'].includes(nativeEvent.key);
const {
selection
} = editor;
const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
const isRTL = getDirection(Node.string(element)) === 'rtl';
// COMPAT: Since we prevent the default behavior on
// `beforeinput` events, the browser doesn't think there's ever
// any history stack to undo or redo, so we have to manage these
// hotkeys ourselves. (2019/11/06)
if (Hotkeys.isRedo(nativeEvent)) {
event.preventDefault();
const maybeHistoryEditor = editor;
if (typeof maybeHistoryEditor.redo === 'function') {
maybeHistoryEditor.redo();
}
return;
}
if (Hotkeys.isUndo(nativeEvent)) {
event.preventDefault();
const maybeHistoryEditor = editor;
if (typeof maybeHistoryEditor.undo === 'function') {
maybeHistoryEditor.undo();
}
return;
}
if ((IS_CHROME || IS_WEBKIT) && nativeEvent.key === 'ArrowUp' && !nativeEvent.altKey && !nativeEvent.ctrlKey && !nativeEvent.metaKey && selection && (nativeEvent.shiftKey || Range.isCollapsed(selection))) {
const above = getPointAboveTrailingNewline(editor, selection.focus);
if (above) {
event.preventDefault();
Transforms.select(editor, nativeEvent.shiftKey ? {
anchor: selection.anchor,
focus: above
} : above);
return;
}
}
// COMPAT: Certain browsers don't handle the selection updates
// properly. In Chrome, the selection isn't properly extended.
// And in Firefox, the selection isn't properly collapsed.
// (2017/10/17)
if (Hotkeys.isMoveLineBackward(nativeEvent)) {
event.preventDefault();
Transforms.move(editor, {
unit: 'line',
reverse: true
});
return;
}
if (Hotkeys.isMoveLineForward(nativeEvent)) {
event.preventDefault();
Transforms.move(editor, {
unit: 'line'
});
return;
}
if (Hotkeys.isExtendLineBackward(nativeEvent)) {
event.preventDefault();
Transforms.move(editor, {
unit: 'line',
edge: 'focus',
reverse: true
});
return;
}
if (Hotkeys.isExtendLineForward(nativeEvent)) {
event.preventDefault();
Transforms.move(editor, {
unit: 'line',
edge: 'focus'
});
return;
}
// COMPAT: If a void node is selected, or a zero-width text node
// adjacent to an inline is selected, we need to handle these
// hotkeys manually because browsers won't be able to skip over
// the void node with the zero-width space not being an empty
// string.
if (Hotkeys.isMoveBackward(nativeEvent)) {
event.preventDefault();
if (selection && Range.isCollapsed(selection)) {
Transforms.move(editor, {
reverse: !isRTL,
unit: getCharacterMoveUnit(editor, selection.focus, !isRTL)
});
} else {
Transforms.collapse(editor, {
edge: isRTL ? 'end' : 'start'
});
}
return;
}
if (Hotkeys.isMoveForward(nativeEvent)) {
event.preventDefault();
if (selection && Range.isCollapsed(selection)) {
Transforms.move(editor, {
reverse: isRTL,
unit: getCharacterMoveUnit(editor, selection.focus, isRTL)
});
} else {
Transforms.collapse(editor, {
edge: isRTL ? 'start' : 'end'
});
}
return;
}
const wordBackward = Hotkeys.isMoveWordBackward(nativeEvent);
if (wordBackward || Hotkeys.isMoveWordForward(nativeEvent)) {
event.preventDefault();
const root = ReactEditor.findDocumentOrShadowRoot(editor);
const domSelection = getSelection(root);
if (domSelection !== null && domSelection !== void 0 && domSelection.modify) {
domSelection.modify('move', wordBackward ? 'left' : 'right', 'word');
const range = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false,
suppressThrow: true
});
if (range) {
Transforms.select(editor, range);
return;
}
}
if (selection && Range.isExpanded(selection)) {
Transforms.collapse(editor, {
edge: 'focus'
});
}
Transforms.move(editor, {
unit: 'word',
reverse: wordBackward ? !isRTL : isRTL
});
return;
}
// COMPAT: Certain browsers don't support the `beforeinput` event, so we
// fall back to guessing at the input intention for hotkeys.
// COMPAT: In iOS, some of these hotkeys are handled in the
if (!HAS_BEFORE_INPUT_SUPPORT) {
// We don't have a core behavior for these, but they change the
// DOM if we don't prevent them, so we have to.
if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
event.preventDefault();
return;
}
if (Hotkeys.isSoftBreak(nativeEvent)) {
event.preventDefault();
Editor.insertSoftBreak(editor);
return;
}
if (Hotkeys.isSplitBlock(nativeEvent)) {
event.preventDefault();
Editor.insertBreak(editor);
return;
}
if (Hotkeys.isDeleteBackward(nativeEvent)) {
event.preventDefault();
if (selection && Range.isExpanded(selection)) {
Editor.deleteFragment(editor, {
direction: 'backward'
});
} else {
Editor.deleteBackward(editor);
}
return;
}
if (Hotkeys.isDeleteForward(nativeEvent)) {
event.preventDefault();
if (selection && Range.isExpanded(selection)) {
Editor.deleteFragment(editor, {
direction: 'forward'
});
} else {
Editor.deleteForward(editor);
}
return;
}
if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
event.preventDefault();
if (selection && Range.isExpanded(selection)) {
Editor.deleteFragment(editor, {
direction: 'backward'
});
} else {
Editor.deleteBackward(editor, {
unit: 'line'
});
}
return;
}
if (Hotkeys.isDeleteLineForward(nativeEvent)) {
event.preventDefault();
if (selection && Range.isExpanded(selection)) {
Editor.deleteFragment(editor, {
direction: 'forward'
});
} else {
Editor.deleteForward(editor, {
unit: 'line'
});
}
return;
}
if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
event.preventDefault();
if (selection && Range.isExpanded(selection)) {
Editor.deleteFragment(editor, {
direction: 'backward'
});
} else {
Editor.deleteBackward(editor, {
unit: 'word'
});
}
return;
}
if (Hotkeys.isDeleteWordForward(nativeEvent)) {
event.preventDefault();
if (selection && Range.isExpanded(selection)) {
Editor.deleteFragment(editor, {
direction: 'forward'
});
} else {
Editor.deleteForward(editor, {
unit: 'word'
});
}
return;
}
} else {
if (IS_CHROME || IS_WEBKIT) {
// COMPAT: Chrome and Safari support `beforeinput` event but do not fire
// an event when deleting backwards in a selected void inline node
if (selection && (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) && Range.isCollapsed(selection)) {
const currentNode = Node.parent(editor, selection.anchor.path);
if (Node.isElement(currentNode) && Editor.isVoid(editor, currentNode) && (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))) {
event.preventDefault();
if (Hotkeys.isDeleteForward(nativeEvent)) {
Editor.deleteForward(editor, {
unit: 'block'
});
} else {
Editor.deleteBackward(editor, {
unit: 'block'
});
}
return;
}
}
}
if (IS_WEBKIT && selection && Range.isCollapsed(selection)) {
if (Hotkeys.isDeleteBackward(nativeEvent) && Editor.isStart(editor, selection.anchor, [])) {
event.preventDefault();
Editor.deleteBackward(editor);
return;
}
if (Hotkeys.isDeleteForward(nativeEvent) && Editor.isEnd(editor, selection.anchor, [])) {
event.preventDefault();
Editor.deleteForward(editor);
return;
}
}
}
}
}, [readOnly, editor, attributes.onKeyDown, setComposing]),
onPaste: useCallback(event => {
if (readOnly) {
isEventHandled(event, attributes.onPaste);
return;
}
if (ReactEditor.hasEditableTarget(editor, event.target) && !isEventHandled(event, attributes.onPaste)) {
// COMPAT: Certain browsers don't support the `beforeinput` event, so we
// fall back to React's `onPaste` here instead.
// COMPAT: Firefox, Chrome and Safari don't emit `beforeinput` events
// when "paste without formatting" is used, so fallback. (2020/02/20)
// COMPAT: Safari InputEvents generated by pasting won't include
// application/x-slate-fragment items, so use the
// ClipboardEvent here. (2023/03/15)
if (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event.nativeEvent) || IS_WEBKIT) {
event.preventDefault();
ReactEditor.insertData(editor, event.clipboardData);
}
}
}, [readOnly, editor, attributes.onPaste])
}), /*#__PURE__*/React.createElement(Children, {
decorations: decorations,
node: editor,
renderElement: renderElement,
renderChunk: renderChunk,
renderPlaceholder: renderPlaceholder,
renderLeaf: renderLeaf,
renderText: renderText
}))))));
});
/**
* The default placeholder element
*/
const isDeletingInVoid = (editor, event) => {
const {
selection
} = editor;
return !!selection && Range.isCollapsed(selection) && (Hotkeys.isDeleteBackward(event) || Hotkeys.isDeleteForward(event)) && !!Editor.void(editor, {
at: selection
});
};
const isInSlateText = node => {
var _node$parentElement2;
return isDOMNode(node) && node.nodeType === node.TEXT_NODE && !!((_node$parentElement2 = node.parentElement) !== null && _node$parentElement2 !== void 0 && _node$parentElement2.closest('[data-slate-string], [data-slate-zero-width]'));
};
const restoreDomSelection = (editor, domSelection, state) => {
if (!editor.selection) {
return;
}
const domRange = ReactEditor.resolveDOMRange(editor, editor.selection);
if (!domRange) {
return;
}
const backward = Range.isBackward(editor.selection);
state.isUpdatingSelection = true;
domSelection.setBaseAndExtent(backward ? domRange.endContainer : domRange.startContainer, backward ? domRange.endOffset : domRange.startOffset, backward ? domRange.startContainer : domRange.endContainer, backward ? domRange.startOffset : domRange.endOffset);
setTimeout(() => {
state.isUpdatingSelection = false;
});
};
const selectMovableRange = editor => {
const {
selection
} = editor;
if (selection && Range.isExpanded(selection)) {
const movableRange = getMovableRange(editor, selection);
if (!Range.equals(movableRange, selection)) {
Transforms.select(editor, movableRange);
}
}
};
const DefaultPlaceholder = ({
attributes,
children
}) => (/*#__PURE__*/React.createElement("span", _objectSpread({}, attributes), children, IS_ANDROID && /*#__PURE__*/React.createElement("br", null)));
/**
* A default memoized decorate function.
*/
const defaultDecorate = () => [];
/**
* A default implement to scroll dom range into view.
*/
const defaultScrollSelectionIntoView = (editor, domRange) => {
var _ReactEditor$resolveD;
// Scroll to the focus point of the selection, in case the selection is expanded
const {
selection
} = editor;
const isBackward = !!selection && Range.isBackward(selection);
const unhung = selection && !isBackward && Range.isExpanded(selection) ? Editor.unhangRange(editor, selection) : selection;
const domFocusPoint = unhung && selection && !Range.equals(unhung, selection) ? (_ReactEditor$resolveD = ReactEditor.resolveDOMRange(editor, unhung)) !== null && _ReactEditor$resolveD !== void 0 ? _ReactEditor$resolveD : domRange.cloneRange() : domRange.cloneRange();
domFocusPoint.collapse(isBackward);
if (domFocusPoint.getBoundingClientRect) {
const leafEl = domFocusPoint.startContainer.parentElement;
// COMPAT: In Chrome, domFocusPoint.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
// When this happens, do not scroll like most editors do.
const domRect = domFocusPoint.getBoundingClientRect();
const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
if (isZeroDimensionRect) {
const leafRect = leafEl.getBoundingClientRect();
const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
if (leafHasDimensions) {
return;
}
}
// Default behavior: use domFocusPoint's getBoundingClientRect
leafEl.getBoundingClientRect = domFocusPoint.getBoundingClientRect.bind(domFocusPoint);
scrollIntoView(leafEl, {
scrollMode: 'if-needed',
block: 'nearest',
inline: 'nearest'
});
// @ts-expect-error an unorthodox delete D:
delete leafEl.getBoundingClientRect;
}
};
/**
* Check if an event is overrided by a handler.
*/
const isEventHandled = (event, handler) => {
if (!handler) {
return false;
}
// The custom event handler may return a boolean to specify whether the event
// shall be treated as being handled or not.
const shouldTreatEventAsHandled = handler(event);
if (shouldTreatEventAsHandled != null) {
return shouldTreatEventAsHandled;
}
return event.isDefaultPrevented() || event.isPropagationStopped();
};
/**
* Check if the event's target is an input element
*/
const isDOMEventTargetInput = event => {
return isDOMNode(event.target) && (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement);
};
/**
* Check if a DOM event is overrided by a handler.
*/
const isDOMEventHandled = (event, handler) => {
if (!handler) {
return false;
}
// The custom event handler may return a boolean to specify whether the event
// shall be treated as being handled or not.
const shouldTreatEventAsHandled = handler(event);
if (shouldTreatEventAsHandled != null) {
return shouldTreatEventAsHandled;
}
return event.defaultPrevented;
};
const handleNativeHistoryEvents = (editor, event) => {
const maybeHistoryEditor = editor;
if (event.inputType === 'historyUndo' && typeof maybeHistoryEditor.undo === 'function') {
maybeHistoryEditor.undo();
return;
}
if (event.inputType === 'historyRedo' && typeof maybeHistoryEditor.redo === 'function') {
maybeHistoryEditor.redo();
return;
}
};
/**
* A React context for sharing the `focused` state of the editor.
*/
const FocusedContext = /*#__PURE__*/createContext(false);
/**
* Get the current `focused` state of the editor.
*/
const useFocused = () => {
return useContext(FocusedContext);
};
const REACT_MAJOR_VERSION = parseInt(React.version.split('.')[0], 10);
const _excluded = ["editor", "children", "onChange", "onSelectionChange", "onValueChange", "initialValue", "value"];
/**
* A wrapper around the provider to handle `onChange` events, because the editor
* is a mutable singleton so it won't ever register as "changed" otherwise.
*/
const Slate = props => {
const {
editor,
children,
onChange,
onSelectionChange,
onValueChange,
initialValue,
value: controlledValue
} = props,
rest = _objectWithoutProperties(props, _excluded);
const initializedEditor = useRef(null);
const lastEmittedValue = useRef(undefined);
const lastAppliedValue = useRef(undefined);
const appliedChildren = useRef(undefined);
if (controlledValue !== undefined && initialValue !== undefined) {
throw new Error('[Slate] value and initialValue cannot be used together.');
}
if (controlledValue !== undefined && !Node.isNodeList(controlledValue)) {
throw new Error(`[Slate] value is invalid! Expected a list of elements but got: ${Scrubber.stringify(controlledValue)}`);
}
if (initializedEditor.current !== editor) {
var _ref;
if (!Editor.isEditor(editor)) {
throw new Error(`[Slate] editor is invalid! You passed: ${Scrubber.stringify(editor)}`);
}
if (initialValue === undefined && controlledValue === undefined && editor.children.length === 0) {
throw new Error('[Slate] editor.children is empty and no initialValue was provided. If this is intentional, pass initialValue={[]} to the Slate component.');
}
const value = (_ref = initialValue !== null && initialValue !== void 0 ? initialValue : controlledValue) !== null && _ref !== void 0 ? _ref : editor.children;
if (!Node.isNodeList(value)) {
throw new Error(`[Slate] initialValue is invalid! Expected a list of elements but got: ${Scrubber.stringify(value)}`);
}
const copied = initialValue === undefined && controlledValue === undefined ? value : value.map(copyNodeInUse);
const _children = copied.every((node, i) => node === value[i]) ? value : copied;
editor.children = _children.length > 0 ? _children : [{
children: [{
text: ''
}]
}];
Object.assign(editor, rest);
initializedEditor.current = editor;
lastEmittedValue.current = undefined;
lastAppliedValue.current = controlledValue;
}
const {
selectorContext,
onChange: handleSelectorChange
} = useSelectorContext();
const onContextChange = useCallback(() => {
const changed = editor.operations.some(op => op.type !== 'set_selection');
const external = changed && editor.children === appliedChildren.current;
appliedChildren.current = undefined;
if (changed && !external) {
lastEmittedValue.current = editor.children;
}
if (onChange) {
onChange(editor.children);
}
if (onSelectionChange && editor.operations.find(op => op.type === 'set_selection')) {
onSelectionChange(editor.selection);
}
if (onValueChange && changed && !external) {
onValueChange(editor.children);
}
handleSelectorChange();
}, [editor, handleSelectorChange, onChange, onSelectionChange, onValueChange]);
const controlled = controlledValue !== undefined;
const registerOnChange = useCallback(() => {
const callback = () => onContextChange();
EDITOR_TO_ON_CHANGE.set(editor, callback);
return () => {
if (EDITOR_TO_ON_CHANGE.get(editor) === callback) {
EDITOR_TO_ON_CHANGE.delete(editor);
}
};
}, [editor, onContextChange]);
useEffect(() => {
if (!controlled) return registerOnChange();
}, [controlled, registerOnChange]);
useIsomorphicLayoutEffect(() => {
if (controlled) return registerOnChange();
}, [controlled, registerOnChange]);
useIsomorphicLayoutEffect(() => {
let frame;
const apply = () => {
var _EDITOR_TO_PENDING_DI;
if (controlledValue === undefined) return;
if (controlledValue === lastEmittedValue.current) {
lastAppliedValue.current = controlledValue;
return;
}
if (controlledValue === lastAppliedValue.current) return;
if (ReactEditor.isComposing(editor) || EDITOR_TO_COMPOSING.get(editor) || EDITOR_TO_PENDING_ACTION.get(editor) || (_EDITOR_TO_PENDING_DI = EDITOR_TO_PENDING_DIFFS.get(editor)) !== null && _EDITOR_TO_PENDING_DI !== void 0 && _EDITOR_TO_PENDING_DI.length) {
frame = window.requestAnimationFrame(apply);
return;
}
const previous = editor.children;
lastAppliedValue.current = controlledValue;
Transforms.setChildren(editor, controlledValue);
if (previous !== editor.children) {
appliedChildren.current = editor.children;
handleSelectorChange();
}
};
apply();
return () => {
if (frame !== undefined) window.cancelAnimationFrame(frame);
};
}, [editor, controlledValue, handleSelectorChange]);
const [isFocused, setIsFocused] = useState(ReactEditor.isFocused(editor));
useEffect(() => {
setIsFocused(ReactEditor.isFocused(editor));
}, [editor]);
useIsomorphicLayoutEffect(() => {
const fn = () => setIsFocused(ReactEditor.isFocused(editor));
if (REACT_MAJOR_VERSION >= 17) {
// In React >= 17 onFocus and onBlur listen to the focusin and focusout events during the bubbling phase.
// Therefore in order for <Editable />'s handlers to run first, which is necessary for ReactEditor.isFocused(editor)
// to return the correct value, we have to listen to the focusin and focusout events without useCapture here.
document.addEventListener('focusin', fn);
document.addEventListener('focusout', fn);
return () => {
document.removeEventListener('focusin', fn);
document.removeEventListener('focusout', fn);
};
} else {
document.addEventListener('focus', fn, true);
document.addEventListener('blur', fn, true);
return () => {
document.removeEventListener('focus', fn, true);
document.removeEventListener('blur', fn, true);
};
}
}, [editor]);
return /*#__PURE__*/React.createElement(SlateSelectorContext.Provider, {
value: selectorContext
}, /*#__PURE__*/React.createElement(EditorContext.Provider, {
value: editor
}, /*#__PURE__*/React.createElement(FocusedContext.Provider, {
value: isFocused
}, children)));
};
/**
* Get the current editor object from the React context.
* @deprecated Use useSlateStatic instead.
*/
const useEditor = () => {
const editor = useContext(EditorContext);
if (!editor) {
throw new Error(`The \`useEditor\` hook must be used inside the <Slate> component's context.`);
}
return editor;
};
/**
* Get the current `selected` state of an element.
*
* Set `suppressThrow` to return `false` instead of throwing when the element
* can no longer be found in the editor.
*/
const useSelected = ({
suppressThrow: _suppressThrow = false
} = {}) => {
const element = useElementIf();
// Breaking the rules of hooks is fine here since `!element` will remain true
// or false for the entire lifetime of the component this hook is called from.
// TODO: Decide if we want to throw an error instead when calling
// `useSelected` outside of an element (potentially a breaking change).
if (!element) return false;
// eslint-disable-next-line react-hooks/rules-of-hooks
const selector = useCallback(editor => {
if (!editor.selection) return false;
try {
const path = ReactEditor.findPath(editor, element);
const range = Editor.range(editor, path);
return !!Range.intersection(range, editor.selection);
} catch (e) {
if (_suppressThrow) {
return false;
}
throw e;
}
}, [element, _suppressThrow]);
// eslint-disable-next-line react-hooks/rules-of-hooks
return useSlateSelector(selector, undefined, {
// Defer the selector until after `Editable` has rendered so that the path
// will be accurate.
deferred: true
});
};
/**
* Get the current slate selection.
* Only triggers a rerender when the selection actually changes
*/
const useSlateSelection = () => {
return useSlateSelector(editor => editor.selection, isSelectionEqual);
};
const isSelectionEqual = (a, b) => {
if (!a && !b) return true;
if (!a || !b) return false;
return Range.equals(a, b);
};
const RERENDERING_OPERATIONS = new Set(['insert_node', 'move_node', 'remove_node', 'set_node']);
/**
* `withReact` adds React and DOM specific behaviors to the editor.
*
* If you are using TypeScript, you must extend Slate's CustomTypes to use
* this plugin.
*
* See https://docs.slatejs.org/concepts/11-typescript to learn how.
*/
const withReact = (editor, clipboardFormatKey = 'x-slate-fragment') => {
let e = editor;
e = withDOM(e, clipboardFormatKey);
const {
onChange,
apply,
insertText
} = e;
e.getChunkSize = () => null;
if (IS_ANDROID) {
e.insertText = (text, options) => {
// COMPAT: Android devices, specifically Samsung devices, experience cursor jumping.
// This issue occurs when the insertText function is called immediately after typing.
// The problem arises because typing schedules a selection change.
// However, this selection change is only executed after the insertText function.
// As a result, the already obsolete selection is applied, leading to incorrect
// final cursor position.
EDITOR_TO_PENDING_SELECTION.delete(e);
return insertText(text, options);
};
}
e.onChange = options => {
// COMPAT: React < 18 doesn't batch `setState` hook calls, which means
// that the children and selection can get out of sync for one render
// pass. So we have to use this unstable API to ensure it batches them.
// (2019/12/03)
// https://github.com/facebook/react/issues/14259#issuecomment-439702367
const maybeBatchUpdates = REACT_MAJOR_VERSION < 18 ? ReactDOM.unstable_batchedUpdates : callback => callback();
maybeBatchUpdates(() => {
onChange(options);
});
};
// On move_node, if the chunking optimization is enabled for the parent of the
// node being moved, add the moved node to the movedNodeKeys set of the
// parent's chunk tree.
e.apply = operation => {
if (IS_ANDROID && RERENDERING_OPERATIONS.has(operation.type)) {
var _EDITOR_TO_FLUSH_DEFE;
(_EDITOR_TO_FLUSH_DEFE = EDITOR_TO_FLUSH_DEFERRED_DIFFS.get(e)) === null || _EDITOR_TO_FLUSH_DEFE === void 0 || _EDITOR_TO_FLUSH_DEFE();
}
if (operation.type === 'move_node') {
const parent = Node.parent(e, operation.path);
const chunking = !!e.getChunkSize(parent);
if (chunking) {
const node = Node.get(e, operation.path);
const chunkTree = getChunkTreeForNode(e, parent);
const key = ReactEditor.findKey(e, node);
chunkTree.movedNodeKeys.add(key);
}
}
apply(operation);
};
return e;
};
export { DefaultElement, DefaultLeaf, DefaultPlaceholder, DefaultText, Editable, ReactEditor, Slate, defaultScrollSelectionIntoView, useComposing, useEditor, useElement, useElementIf, useFocused, useReadOnly, useSelected, useSlate, useSlateSelection, useSlateSelector, useSlateStatic, useSlateWithV, withReact };
//# sourceMappingURL=index.es.js.map