@portabletext/editor
Version:
Portable Text Editor made in React
1,393 lines (1,392 loc) • 421 kB
JavaScript
import { c } from "react-compiler-runtime";
import React, { useEffect, createContext, useContext, useState, useRef, Component, useMemo, startTransition, useCallback, forwardRef, useImperativeHandle } from "react";
import { useEffectEvent } from "use-effect-event";
import { useEditor, EditorContext } from "./_chunks-es/use-editor.js";
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { useSelector, useActorRef } from "@xstate/react";
import noop from "lodash/noop.js";
import { Element as Element$1, Text, Range, Editor, Node, Transforms, Path, Operation, Point, createEditor } from "slate";
import { useSelected, useSlateSelector, useSlateStatic, withReact, ReactEditor, Slate, useSlate, Editable } from "slate-react";
import debug$f from "debug";
import { DOMEditor, isDOMNode } from "slate-dom";
import { getBlockStartPoint, getBlockKeyFromSelectionPoint, isTextBlock, getChildKeyFromSelectionPoint, blockOffsetToSpanSelectionPoint, isSpan, parseBlock, parseAnnotation, parseInlineObject, isKeyedSegment, isListBlock, isTypedObject, getSelectionStartPoint, getSelectionEndPoint, getTextBlockText, parseBlocks } from "./_chunks-es/util.slice-blocks.js";
import { getBlockEndPoint, isSelectionCollapsed, isEqualSelectionPoints, isEmptyTextBlock } from "./_chunks-es/util.is-selection-collapsed.js";
import isEqual from "lodash/isEqual.js";
import { isSelectionCollapsed as isSelectionCollapsed$1, getFocusTextBlock, getFocusSpan as getFocusSpan$1, isSelectionExpanded, getFocusBlock as getFocusBlock$1, getSelectedValue, getFocusChild as getFocusChild$1 } from "./_chunks-es/selector.is-selection-expanded.js";
import { getFocusInlineObject, getSelectedBlocks, getSelectionStartBlock as getSelectionStartBlock$1, getSelectionEndBlock as getSelectionEndBlock$1, isOverlappingSelection, isSelectingEntireBlocks, getMarkState, getActiveDecorators, getActiveAnnotationsMarks, getTrimmedSelection, getCaretWordSelection, getFocusBlockObject, getPreviousBlock, getNextBlock, isAtTheEndOfBlock, isAtTheStartOfBlock, getFirstBlock as getFirstBlock$1, getLastBlock as getLastBlock$1, getFocusListBlock, isActiveAnnotation, isActiveDecorator, getSelectedTextBlocks, isActiveListItem, isActiveStyle, getActiveAnnotations } from "./_chunks-es/selector.is-selecting-entire-blocks.js";
import getRandomValues from "get-random-values-esm";
import { defineBehavior, forward, raise, effect } from "./behaviors/index.js";
import uniq from "lodash/uniq.js";
import { Subject } from "rxjs";
import { setup, assign, enqueueActions, emit, assertEvent, stateIn, fromCallback, and, not, raise as raise$1, createActor } from "xstate";
import { htmlToBlocks } from "@portabletext/block-tools";
import { toHTML } from "@portabletext/to-html";
import { Schema } from "@sanity/schema";
import flatten from "lodash/flatten.js";
import omit from "lodash/omit.js";
import { applyAll, unset, insert, set, setIfMissing, diffMatchPatch as diffMatchPatch$1 } from "@portabletext/patches";
import { blockOffsetsToSelection } from "./_chunks-es/util.child-selection-point-to-block-offset.js";
import { selectionPointToBlockOffset, sliceTextBlock } from "./_chunks-es/util.slice-text-block.js";
import get from "lodash/get.js";
import isUndefined from "lodash/isUndefined.js";
import omitBy from "lodash/omitBy.js";
import { createDraft, finishDraft } from "immer";
import { createKeyboardShortcut, code, underline, italic, bold, undo, redo } from "@portabletext/keyboard-shortcuts";
import { defineType, defineField } from "@sanity/types";
import startCase from "lodash.startcase";
import isPlainObject from "lodash/isPlainObject.js";
function EditorEventListener(props) {
const $ = c(5), editor = useEditor(), on = useEffectEvent(props.on);
let t0;
$[0] !== editor || $[1] !== on ? (t0 = () => {
const subscription = editor.on("*", on);
return () => {
subscription.unsubscribe();
};
}, $[0] = editor, $[1] = on, $[2] = t0) : t0 = $[2];
let t1;
return $[3] !== editor ? (t1 = [editor], $[3] = editor, $[4] = t1) : t1 = $[4], useEffect(t0, t1), null;
}
const rootName = "sanity-pte:";
debug$f(rootName);
function debugWithName(name) {
const namespace = `${rootName}${name}`;
return debug$f && debug$f.enabled(namespace) ? debug$f(namespace) : debug$f(rootName);
}
const VOID_CHILD_KEY = "void-child";
function keepObjectEquality(object, keyMap) {
const value = keyMap[object._key];
return value && isEqual(object, value) ? value : (keyMap[object._key] = object, object);
}
function toSlateValue(value, {
schemaTypes
}, keyMap = {}) {
return value && Array.isArray(value) ? value.map((block) => {
const {
_type,
_key,
...rest
} = block;
if (block && block._type === schemaTypes.block.name) {
const textBlock = block;
let hasInlines = !1;
const hasMissingStyle = typeof textBlock.style > "u", hasMissingMarkDefs = typeof textBlock.markDefs > "u", hasMissingChildren = typeof textBlock.children > "u", children = (textBlock.children || []).map((child) => {
const {
_type: cType,
_key: cKey,
...cRest
} = child;
return cType !== "span" ? (hasInlines = !0, keepObjectEquality({
_type: cType,
_key: cKey,
children: [{
_key: VOID_CHILD_KEY,
_type: "span",
text: "",
marks: []
}],
value: cRest,
__inline: !0
}, keyMap)) : child;
});
return !hasMissingStyle && !hasMissingMarkDefs && !hasMissingChildren && !hasInlines && Element$1.isElement(block) ? block : (hasMissingStyle && (rest.style = schemaTypes.styles[0].name), keepObjectEquality({
_type,
_key,
...rest,
children
}, keyMap));
}
return keepObjectEquality({
_type,
_key,
children: [{
_key: VOID_CHILD_KEY,
_type: "span",
text: "",
marks: []
}],
value: rest
}, keyMap);
}) : [];
}
function fromSlateValue(value, textBlockType, keyMap = {}) {
return value.map((block) => {
const {
_key,
_type
} = block;
if (!_key || !_type)
throw new Error("Not a valid block");
if (_type === textBlockType && "children" in block && Array.isArray(block.children) && _key) {
let hasInlines = !1;
const children = block.children.map((child) => {
const {
_type: _cType
} = child;
if ("value" in child && _cType !== "span") {
hasInlines = !0;
const {
value: v,
_key: k,
_type: t,
__inline: _i,
children: _c,
...rest
} = child;
return keepObjectEquality({
...rest,
...v,
_key: k,
_type: t
}, keyMap);
}
return child;
});
return hasInlines ? keepObjectEquality({
...block,
children,
_key,
_type
}, keyMap) : block;
}
const blockValue = "value" in block && block.value;
return keepObjectEquality({
_key,
_type,
...typeof blockValue == "object" ? blockValue : {}
}, keyMap);
});
}
function isEqualToEmptyEditor(children, schemaTypes) {
return children === void 0 || children && Array.isArray(children) && children.length === 0 || children && Array.isArray(children) && children.length === 1 && Element$1.isElement(children[0]) && children[0]._type === schemaTypes.block.name && "style" in children[0] && children[0].style === schemaTypes.styles[0].name && !("listItem" in children[0]) && Array.isArray(children[0].children) && children[0].children.length === 1 && Text.isText(children[0].children[0]) && children[0].children[0]._type === "span" && !children[0].children[0].marks?.join("") && children[0].children[0].text === "";
}
function getBlockPath({
editor,
_key
}) {
const [, blockPath] = Array.from(Editor.nodes(editor, {
at: [],
match: (n) => n._key === _key
})).at(0) ?? [void 0, void 0], blockIndex = blockPath?.at(0);
if (blockIndex !== void 0)
return [blockIndex];
}
function getFocusBlock({
editor
}) {
if (!editor.selection)
return [void 0, void 0];
try {
return Editor.node(editor, editor.selection.focus.path.slice(0, 1)) ?? [void 0, void 0];
} catch {
return [void 0, void 0];
}
}
function getFocusSpan({
editor
}) {
if (!editor.selection)
return [void 0, void 0];
try {
const [node, path] = Editor.node(editor, editor.selection.focus.path);
if (editor.isTextSpan(node))
return [node, path];
} catch {
return [void 0, void 0];
}
return [void 0, void 0];
}
function getSelectionStartBlock({
editor
}) {
if (!editor.selection)
return [void 0, void 0];
const selectionStartPoint = Range.start(editor.selection);
return getPointBlock({
editor,
point: selectionStartPoint
});
}
function getSelectionEndBlock({
editor
}) {
if (!editor.selection)
return [void 0, void 0];
const selectionEndPoint = Range.end(editor.selection);
return getPointBlock({
editor,
point: selectionEndPoint
});
}
function getPointBlock({
editor,
point
}) {
try {
const [block] = Editor.node(editor, point.path.slice(0, 1)) ?? [void 0, void 0];
return block ? [block, point.path.slice(0, 1)] : [void 0, void 0];
} catch {
return [void 0, void 0];
}
}
function getFocusChild({
editor
}) {
const [focusBlock, focusBlockPath] = getFocusBlock({
editor
}), childIndex = editor.selection?.focus.path.at(1);
if (!focusBlock || !focusBlockPath || childIndex === void 0)
return [void 0, void 0];
try {
const focusChild = Node.child(focusBlock, childIndex);
return focusChild ? [focusChild, [...focusBlockPath, childIndex]] : [void 0, void 0];
} catch {
return [void 0, void 0];
}
}
function getPointChild({
editor,
point
}) {
const [block, blockPath] = getPointBlock({
editor,
point
}), childIndex = point.path.at(1);
if (!block || !blockPath || childIndex === void 0)
return [void 0, void 0];
try {
const pointChild = Node.child(block, childIndex);
return pointChild ? [pointChild, [...blockPath, childIndex]] : [void 0, void 0];
} catch {
return [void 0, void 0];
}
}
function getFirstBlock({
editor
}) {
if (editor.children.length === 0)
return [void 0, void 0];
const firstBlockPath = Editor.start(editor, []).path.at(0);
try {
return firstBlockPath !== void 0 ? Editor.node(editor, [firstBlockPath]) ?? [void 0, void 0] : [void 0, void 0];
} catch {
return [void 0, void 0];
}
}
function getLastBlock({
editor
}) {
if (editor.children.length === 0)
return [void 0, void 0];
const lastBlockPath = Editor.end(editor, []).path.at(0);
try {
return lastBlockPath !== void 0 ? Editor.node(editor, [lastBlockPath]) ?? [void 0, void 0] : [void 0, void 0];
} catch {
return [void 0, void 0];
}
}
function getNodeBlock({
editor,
schema,
node
}) {
if (Editor.isEditor(node))
return;
if (isBlockElement({
editor,
schema
}, node))
return elementToBlock({
schema,
element: node
});
const parent = Array.from(Editor.nodes(editor, {
mode: "highest",
at: [],
match: (n) => isBlockElement({
editor,
schema
}, n) && n.children.some((child) => child._key === node._key)
})).at(0)?.at(0);
return Element$1.isElement(parent) ? elementToBlock({
schema,
element: parent
}) : void 0;
}
function elementToBlock({
schema,
element
}) {
return fromSlateValue([element], schema.block.name)?.at(0);
}
function isBlockElement({
editor,
schema
}, node) {
return Element$1.isElement(node) && !editor.isInline(node) && (schema.block.name === node._type || schema.blockObjects.some((blockObject) => blockObject.name === node._type));
}
function isListItemActive({
editor,
listItem
}) {
if (!editor.selection)
return !1;
const selectedBlocks = [...Editor.nodes(editor, {
at: editor.selection,
match: (node) => editor.isTextBlock(node)
})];
return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => editor.isListBlock(node) && node.listItem === listItem) : !1;
}
function isStyleActive({
editor,
style
}) {
if (!editor.selection)
return !1;
const selectedBlocks = [...Editor.nodes(editor, {
at: editor.selection,
match: (node) => editor.isTextBlock(node)
})];
return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => node.style === style) : !1;
}
function slateRangeToSelection({
schema,
editor,
range
}) {
const [anchorBlock] = getPointBlock({
editor,
point: range.anchor
}), [focusBlock] = getPointBlock({
editor,
point: range.focus
});
if (!anchorBlock || !focusBlock)
return null;
const [anchorChild] = anchorBlock._type === schema.block.name ? getPointChild({
editor,
point: range.anchor
}) : [void 0, void 0], [focusChild] = focusBlock._type === schema.block.name ? getPointChild({
editor,
point: range.focus
}) : [void 0, void 0], selection = {
anchor: {
path: [{
_key: anchorBlock._key
}],
offset: range.anchor.offset
},
focus: {
path: [{
_key: focusBlock._key
}],
offset: range.focus.offset
},
backward: Range.isBackward(range)
};
return anchorChild && (selection.anchor.path.push("children"), selection.anchor.path.push({
_key: anchorChild._key
})), focusChild && (selection.focus.path.push("children"), selection.focus.path.push({
_key: focusChild._key
})), selection;
}
function getEventPosition({
editorActor,
slateEditor,
event
}) {
if (editorActor.getSnapshot().matches({
setup: "setting up"
}))
return;
const eventNode = getEventNode({
slateEditor,
event
});
if (!eventNode)
return;
const eventBlock = getNodeBlock({
editor: slateEditor,
schema: editorActor.getSnapshot().context.schema,
node: eventNode
}), eventPositionBlock = getEventPositionBlock({
node: eventNode,
slateEditor,
event
}), eventSelection = getEventSelection({
schema: editorActor.getSnapshot().context.schema,
slateEditor,
event
});
if (eventBlock && eventPositionBlock && !eventSelection && !Editor.isEditor(eventNode))
return {
block: eventPositionBlock,
isEditor: !1,
selection: {
anchor: getBlockStartPoint({
context: editorActor.getSnapshot().context,
block: {
node: eventBlock,
path: [{
_key: eventBlock._key
}]
}
}),
focus: getBlockEndPoint({
context: editorActor.getSnapshot().context,
block: {
node: eventBlock,
path: [{
_key: eventBlock._key
}]
}
})
}
};
if (!eventPositionBlock || !eventSelection)
return;
const eventSelectionFocusBlockKey = getBlockKeyFromSelectionPoint(eventSelection.focus);
if (eventSelectionFocusBlockKey !== void 0)
return isSelectionCollapsed(eventSelection) && eventBlock && eventSelectionFocusBlockKey !== eventBlock._key ? {
block: eventPositionBlock,
isEditor: !1,
selection: {
anchor: getBlockStartPoint({
context: editorActor.getSnapshot().context,
block: {
node: eventBlock,
path: [{
_key: eventBlock._key
}]
}
}),
focus: getBlockEndPoint({
context: editorActor.getSnapshot().context,
block: {
node: eventBlock,
path: [{
_key: eventBlock._key
}]
}
})
}
} : {
block: eventPositionBlock,
isEditor: Editor.isEditor(eventNode),
selection: eventSelection
};
}
function getEventNode({
slateEditor,
event
}) {
return DOMEditor.hasTarget(slateEditor, event.target) ? DOMEditor.toSlateNode(slateEditor, event.target) : void 0;
}
function getEventPositionBlock({
node,
slateEditor,
event
}) {
const [firstBlock] = getFirstBlock({
editor: slateEditor
});
if (!firstBlock)
return;
const firstBlockRect = DOMEditor.toDOMNode(slateEditor, firstBlock).getBoundingClientRect();
if (event.pageY < firstBlockRect.top)
return "start";
const [lastBlock] = getLastBlock({
editor: slateEditor
});
if (!lastBlock)
return;
const lastBlockRef = DOMEditor.toDOMNode(slateEditor, lastBlock).getBoundingClientRect();
if (event.pageY > lastBlockRef.bottom)
return "end";
const elementRect = DOMEditor.toDOMNode(slateEditor, node).getBoundingClientRect(), top = elementRect.top, height = elementRect.height;
return Math.abs(top - event.pageY) < height / 2 ? "start" : "end";
}
function getEventSelection({
schema,
slateEditor,
event
}) {
const range = getSlateRangeFromEvent(slateEditor, event);
return range ? slateRangeToSelection({
schema,
editor: slateEditor,
range
}) : null;
}
function getSlateRangeFromEvent(editor, event) {
if (!event.target || !isDOMNode(event.target))
return;
const window2 = DOMEditor.getWindow(editor);
let domRange;
if (window2.document.caretPositionFromPoint !== void 0) {
const position = window2.document.caretPositionFromPoint(event.clientX, event.clientY);
if (position)
try {
domRange = window2.document.createRange(), domRange.setStart(position.offsetNode, position.offset), domRange.setEnd(position.offsetNode, position.offset);
} catch {
}
} else if (window2.document.caretRangeFromPoint !== void 0)
domRange = window2.document.caretRangeFromPoint(event.clientX, event.clientY) ?? void 0;
else {
console.warn("Neither caretPositionFromPoint nor caretRangeFromPoint is supported");
return;
}
if (!domRange)
return;
let range;
try {
range = DOMEditor.toSlateRange(editor, domRange, {
exactMatch: !1,
// It can still throw even with this option set to true
suppressThrow: !1
});
} catch {
}
return range;
}
function normalizePoint(point, value) {
if (!point || !value)
return null;
const newPath = [];
let newOffset = point.offset || 0;
const blockKey = typeof point.path[0] == "object" && "_key" in point.path[0] && point.path[0]._key, childKey = typeof point.path[2] == "object" && "_key" in point.path[2] && point.path[2]._key, block = value.find((blk) => blk._key === blockKey);
if (block)
newPath.push({
_key: block._key
});
else
return null;
if (block && point.path[1] === "children") {
if (!block.children || Array.isArray(block.children) && block.children.length === 0)
return null;
const child = Array.isArray(block.children) && block.children.find((cld) => cld._key === childKey);
if (child)
newPath.push("children"), newPath.push({
_key: child._key
}), newOffset = child.text && child.text.length >= point.offset ? point.offset : child.text && child.text.length || 0;
else
return null;
}
return {
path: newPath,
offset: newOffset
};
}
function normalizeSelection(selection, value) {
if (!selection || !value || value.length === 0)
return null;
let newAnchor = null, newFocus = null;
const {
anchor,
focus
} = selection;
return anchor && value.find((blk) => isEqual({
_key: blk._key
}, anchor.path[0])) && (newAnchor = normalizePoint(anchor, value)), focus && value.find((blk) => isEqual({
_key: blk._key
}, focus.path[0])) && (newFocus = normalizePoint(focus, value)), newAnchor && newFocus ? {
anchor: newAnchor,
focus: newFocus,
backward: selection.backward
} : null;
}
function toSlateRange(snapshot) {
if (!snapshot.context.selection)
return null;
if (isEqualSelectionPoints(snapshot.context.selection.anchor, snapshot.context.selection.focus)) {
const anchorPoint2 = toSlateSelectionPoint(snapshot, snapshot.context.selection.anchor, snapshot.context.selection.backward ? "forward" : "backward");
return anchorPoint2 ? {
anchor: anchorPoint2,
focus: anchorPoint2
} : null;
}
const anchorPoint = toSlateSelectionPoint(snapshot, snapshot.context.selection.anchor, snapshot.context.selection.backward ? "forward" : "backward"), focusPoint = toSlateSelectionPoint(snapshot, snapshot.context.selection.focus, snapshot.context.selection.backward ? "backward" : "forward");
return !anchorPoint || !focusPoint ? null : {
anchor: anchorPoint,
focus: focusPoint
};
}
function toSlateSelectionPoint(snapshot, selectionPoint, direction) {
const blockKey = getBlockKeyFromSelectionPoint(selectionPoint);
if (!blockKey)
return;
const blockIndex = snapshot.blockIndexMap.get(blockKey);
if (blockIndex === void 0)
return;
const block = snapshot.context.value.at(blockIndex);
if (!block)
return;
if (!isTextBlock(snapshot.context, block))
return {
path: [blockIndex, 0],
offset: 0
};
let childKey = getChildKeyFromSelectionPoint({
path: selectionPoint.path
});
const spanSelectionPoint = childKey ? void 0 : blockOffsetToSpanSelectionPoint({
context: {
schema: snapshot.context.schema,
value: [block]
},
blockOffset: {
path: [{
_key: blockKey
}],
offset: selectionPoint.offset
},
direction
});
if (childKey = spanSelectionPoint ? getChildKeyFromSelectionPoint(spanSelectionPoint) : childKey, !childKey)
return {
path: [blockIndex, 0],
offset: 0
};
let offset = spanSelectionPoint?.offset ?? selectionPoint.offset, childPath = [], childIndex = -1, pathChild;
for (const child of block.children)
if (childIndex++, child._key === childKey) {
pathChild = child, isSpan(snapshot.context, child) ? childPath = [childIndex] : (childPath = [childIndex, 0], offset = 0);
break;
}
return childPath.length === 0 ? {
path: [blockIndex, 0],
offset: 0
} : {
path: [blockIndex].concat(childPath),
offset: isSpan(snapshot.context, pathChild) ? Math.min(pathChild.text.length, offset) : offset
};
}
const IS_PROCESSING_REMOTE_CHANGES = /* @__PURE__ */ new WeakMap(), KEY_TO_SLATE_ELEMENT = /* @__PURE__ */ new WeakMap(), KEY_TO_VALUE_ELEMENT = /* @__PURE__ */ new WeakMap(), SLATE_TO_PORTABLE_TEXT_RANGE = /* @__PURE__ */ new WeakMap(), EditorActorContext = createContext({});
function DropIndicator() {
const $ = c(1);
let t0;
return $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = /* @__PURE__ */ jsx("div", { contentEditable: !1, className: "pt-drop-indicator", style: {
position: "absolute",
width: "100%",
height: 1,
borderBottom: "1px solid currentColor",
zIndex: 5
}, children: /* @__PURE__ */ jsx("span", {}) }), $[0] = t0) : t0 = $[0], t0;
}
function RenderDefaultBlockObject(props) {
const $ = c(4);
let t0;
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {
userSelect: "none"
}, $[0] = t0) : t0 = $[0];
let t1;
return $[1] !== props.blockObject._key || $[2] !== props.blockObject._type ? (t1 = /* @__PURE__ */ jsxs("div", { style: t0, children: [
"[",
props.blockObject._type,
": ",
props.blockObject._key,
"]"
] }), $[1] = props.blockObject._key, $[2] = props.blockObject._type, $[3] = t1) : t1 = $[3], t1;
}
function RenderDefaultInlineObject(props) {
const $ = c(4);
let t0;
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {
userSelect: "none"
}, $[0] = t0) : t0 = $[0];
let t1;
return $[1] !== props.inlineObject._key || $[2] !== props.inlineObject._type ? (t1 = /* @__PURE__ */ jsxs("span", { style: t0, children: [
"[",
props.inlineObject._type,
": ",
props.inlineObject._key,
"]"
] }), $[1] = props.inlineObject._key, $[2] = props.inlineObject._type, $[3] = t1) : t1 = $[3], t1;
}
function getDragSelection({
eventSelection,
snapshot
}) {
let dragSelection = eventSelection;
if (getFocusInlineObject({
...snapshot,
context: {
...snapshot.context,
selection: eventSelection
}
}))
return dragSelection;
const draggingCollapsedSelection = isSelectionCollapsed$1({
context: {
...snapshot.context,
selection: eventSelection
}
}), draggedTextBlock = getFocusTextBlock({
...snapshot,
context: {
...snapshot.context,
selection: eventSelection
}
}), draggedSpan = getFocusSpan$1({
...snapshot,
context: {
...snapshot.context,
selection: eventSelection
}
});
draggingCollapsedSelection && draggedTextBlock && draggedSpan && (dragSelection = {
anchor: getBlockStartPoint({
context: snapshot.context,
block: draggedTextBlock
}),
focus: getBlockEndPoint({
context: snapshot.context,
block: draggedTextBlock
})
});
const selectedBlocks = getSelectedBlocks(snapshot);
if (snapshot.context.selection && isSelectionExpanded(snapshot) && selectedBlocks.length > 1) {
const selectionStartBlock = getSelectionStartBlock$1(snapshot), selectionEndBlock = getSelectionEndBlock$1(snapshot);
if (!selectionStartBlock || !selectionEndBlock)
return dragSelection;
const selectionStartPoint = getBlockStartPoint({
context: snapshot.context,
block: selectionStartBlock
}), selectionEndPoint = getBlockEndPoint({
context: snapshot.context,
block: selectionEndBlock
});
isOverlappingSelection(eventSelection)({
...snapshot,
context: {
...snapshot.context,
selection: {
anchor: selectionStartPoint,
focus: selectionEndPoint
}
}
}) && (dragSelection = {
anchor: selectionStartPoint,
focus: selectionEndPoint
});
}
return dragSelection;
}
const defaultKeyGenerator = () => randomKey(12), getByteHexTable = /* @__PURE__ */ (() => {
let table;
return () => {
if (table)
return table;
table = [];
for (let i = 0; i < 256; ++i)
table[i] = (i + 256).toString(16).slice(1);
return table;
};
})();
function whatwgRNG(length = 16) {
const rnds8 = new Uint8Array(length);
return getRandomValues(rnds8), rnds8;
}
function randomKey(length) {
const table = getByteHexTable();
return whatwgRNG(length).reduce((str, n) => str + table[n], "").slice(0, length);
}
function createEditorPriority(config) {
return {
id: defaultKeyGenerator(),
name: config?.name,
reference: config?.reference
};
}
const corePriority = createEditorPriority({
name: "core"
});
function createCoreBlockElementBehaviorsConfig({
key,
onSetDragPositionBlock
}) {
return [{
behavior: defineBehavior({
on: "drag.dragover",
guard: ({
snapshot,
event
}) => {
const dropFocusBlock = getFocusBlock$1({
...snapshot,
context: {
...snapshot.context,
selection: event.position.selection
}
});
if (!dropFocusBlock || dropFocusBlock.node._key !== key)
return !1;
const dragOrigin = event.dragOrigin;
if (!dragOrigin)
return !1;
const dragSelection = getDragSelection({
eventSelection: dragOrigin.selection,
snapshot
});
return getSelectedBlocks({
...snapshot,
context: {
...snapshot.context,
selection: dragSelection
}
}).some((draggedBlock) => draggedBlock.node._key === key) ? !1 : isSelectingEntireBlocks({
...snapshot,
context: {
...snapshot.context,
selection: dragSelection
}
});
},
actions: [({
event
}) => [{
type: "effect",
effect: () => {
onSetDragPositionBlock(event.position.block);
}
}]]
}),
priority: createEditorPriority({
reference: {
priority: corePriority,
importance: "lower"
}
})
}, {
behavior: defineBehavior({
on: "drag.*",
guard: ({
event
}) => event.type !== "drag.dragover",
actions: [({
event
}) => [{
type: "effect",
effect: () => {
onSetDragPositionBlock(void 0);
}
}, forward(event)]]
}),
priority: createEditorPriority({
reference: {
priority: corePriority,
importance: "lower"
}
})
}];
}
function useCoreBlockElementBehaviors(t0) {
const $ = c(5), {
key,
onSetDragPositionBlock
} = t0, editorActor = useContext(EditorActorContext);
let t1, t2;
$[0] !== editorActor || $[1] !== key || $[2] !== onSetDragPositionBlock ? (t1 = () => {
const behaviorConfigs = createCoreBlockElementBehaviorsConfig({
key,
onSetDragPositionBlock
});
for (const behaviorConfig of behaviorConfigs)
editorActor.send({
type: "add behavior",
behaviorConfig
});
return () => {
for (const behaviorConfig_0 of behaviorConfigs)
editorActor.send({
type: "remove behavior",
behaviorConfig: behaviorConfig_0
});
};
}, t2 = [editorActor, key, onSetDragPositionBlock], $[0] = editorActor, $[1] = key, $[2] = onSetDragPositionBlock, $[3] = t1, $[4] = t2) : (t1 = $[3], t2 = $[4]), useEffect(t1, t2);
}
function RenderBlockObject(props) {
const [dragPositionBlock, setDragPositionBlock] = useState(), blockObjectRef = useRef(null), selected = useSelected(), focused = useSlateSelector((editor) => selected && editor.selection !== null && Range.isCollapsed(editor.selection));
useCoreBlockElementBehaviors({
key: props.element._key,
onSetDragPositionBlock: setDragPositionBlock
});
const legacySchemaType = props.legacySchema.blockObjects.find((schemaType) => schemaType.name === props.element._type);
legacySchemaType || console.error(`Unable to find Block Object "${props.element._type}" in Schema`);
const blockObject = props.blockObject ?? {
_key: props.element._key,
_type: props.element._type
};
return /* @__PURE__ */ jsxs("div", { ...props.attributes, className: "pt-block pt-object-block", "data-block-key": props.element._key, "data-block-name": props.element._type, "data-block-type": "object", children: [
dragPositionBlock === "start" ? /* @__PURE__ */ jsx(DropIndicator, {}) : null,
props.children,
/* @__PURE__ */ jsx("div", { ref: blockObjectRef, contentEditable: !1, draggable: !props.readOnly, children: props.renderBlock && legacySchemaType ? props.renderBlock({
children: /* @__PURE__ */ jsx(RenderDefaultBlockObject, { blockObject }),
editorElementRef: blockObjectRef,
focused,
path: [{
_key: props.element._key
}],
schemaType: legacySchemaType,
selected,
type: legacySchemaType,
value: blockObject
}) : /* @__PURE__ */ jsx(RenderDefaultBlockObject, { blockObject }) }),
dragPositionBlock === "end" ? /* @__PURE__ */ jsx(DropIndicator, {}) : null
] });
}
function RenderInlineObject(props) {
const inlineObjectRef = useRef(null), slateEditor = useSlateStatic(), selected = useSelected(), focused = useSlateSelector((editor) => selected && editor.selection !== null && Range.isCollapsed(editor.selection)), legacySchemaType = props.legacySchema.inlineObjects.find((inlineObject) => inlineObject.name === props.element._type);
legacySchemaType || console.error(`Unable to find Inline Object "${props.element._type}" in Schema`);
const path = DOMEditor.findPath(slateEditor, props.element), [block] = getPointBlock({
editor: slateEditor,
point: {
path,
offset: 0
}
});
block || console.error(`Unable to find parent block of inline object ${props.element._key}`);
const inlineObject_0 = {
_key: props.element._key,
_type: props.element._type,
..."value" in props.element && typeof props.element.value == "object" ? props.element.value : {}
};
return /* @__PURE__ */ jsxs("span", { ...props.attributes, draggable: !props.readOnly, className: "pt-inline-object", "data-child-key": inlineObject_0._key, "data-child-name": inlineObject_0._type, "data-child-type": "object", children: [
props.children,
/* @__PURE__ */ jsx("span", { ref: inlineObjectRef, style: {
display: "inline-block"
}, children: props.renderChild && block && legacySchemaType ? props.renderChild({
annotations: [],
children: /* @__PURE__ */ jsx(RenderDefaultInlineObject, { inlineObject: inlineObject_0 }),
editorElementRef: inlineObjectRef,
selected,
focused,
path: [{
_key: block._key
}, "children", {
_key: props.element._key
}],
schemaType: legacySchemaType,
value: inlineObject_0,
type: legacySchemaType
}) : /* @__PURE__ */ jsx(RenderDefaultInlineObject, { inlineObject: inlineObject_0 }) })
] });
}
function RenderTextBlock(props) {
const [dragPositionBlock, setDragPositionBlock] = useState(), blockRef = useRef(null), selected = useSelected(), focused = useSlateSelector((editor) => selected && editor.selection !== null && Range.isCollapsed(editor.selection));
useCoreBlockElementBehaviors({
key: props.element._key,
onSetDragPositionBlock: setDragPositionBlock
});
const listIndex = useSlateSelector((editor_0) => editor_0.listIndexMap.get(props.textBlock._key));
let children = props.children;
if (props.renderStyle && props.textBlock.style) {
const legacyStyleSchemaType = props.textBlock.style !== void 0 ? props.legacySchema.styles.find((style) => style.value === props.textBlock.style) : void 0;
legacyStyleSchemaType ? children = props.renderStyle({
block: props.textBlock,
children,
editorElementRef: blockRef,
focused,
path: [{
_key: props.textBlock._key
}],
schemaType: legacyStyleSchemaType,
selected,
value: props.textBlock.style
}) : console.error(`Unable to find Schema type for text block style ${props.textBlock.style}`);
}
if (props.renderListItem && props.textBlock.listItem) {
const legacyListItemSchemaType = props.legacySchema.lists.find((list) => list.value === props.textBlock.listItem);
legacyListItemSchemaType ? children = props.renderListItem({
block: props.textBlock,
children,
editorElementRef: blockRef,
focused,
level: props.textBlock.level ?? 1,
path: [{
_key: props.textBlock._key
}],
selected,
value: props.textBlock.listItem,
schemaType: legacyListItemSchemaType
}) : console.error(`Unable to find Schema type for text block list item ${props.textBlock.listItem}`);
}
return /* @__PURE__ */ jsxs("div", { ...props.attributes, className: ["pt-block", "pt-text-block", ...props.textBlock.style ? [`pt-text-block-style-${props.textBlock.style}`] : [], ...props.textBlock.listItem ? ["pt-list-item", `pt-list-item-${props.textBlock.listItem}`, `pt-list-item-level-${props.textBlock.level ?? 1}`] : []].join(" "), spellCheck: props.spellCheck, "data-block-key": props.textBlock._key, "data-block-name": props.textBlock._type, "data-block-type": "text", ...props.textBlock.listItem !== void 0 ? {
"data-list-item": props.textBlock.listItem
} : {}, ...props.textBlock.level !== void 0 ? {
"data-level": props.textBlock.level
} : {}, ...props.textBlock.style !== void 0 ? {
"data-style": props.textBlock.style
} : {}, ...listIndex !== void 0 ? {
"data-list-index": listIndex
} : {}, children: [
dragPositionBlock === "start" ? /* @__PURE__ */ jsx(DropIndicator, {}) : null,
/* @__PURE__ */ jsx("div", { ref: blockRef, children: props.renderBlock ? props.renderBlock({
children,
editorElementRef: blockRef,
focused,
level: props.textBlock.level,
listItem: props.textBlock.listItem,
path: [{
_key: props.textBlock._key
}],
selected,
schemaType: props.legacySchema.block,
style: props.textBlock.style,
type: props.legacySchema.block,
value: props.textBlock
}) : children }),
dragPositionBlock === "end" ? /* @__PURE__ */ jsx(DropIndicator, {}) : null
] });
}
function RenderElement(props) {
const $ = c(34), editorActor = useContext(EditorActorContext), schema = useSelector(editorActor, _temp$1), legacySchema = useSelector(editorActor, _temp2), slateStatic = useSlateStatic();
if ("__inline" in props.element && props.element.__inline === !0) {
let t02;
return $[0] !== legacySchema || $[1] !== props.attributes || $[2] !== props.children || $[3] !== props.element || $[4] !== props.readOnly || $[5] !== props.renderChild || $[6] !== schema ? (t02 = /* @__PURE__ */ jsx(RenderInlineObject, { attributes: props.attributes, element: props.element, legacySchema, readOnly: props.readOnly, renderChild: props.renderChild, schema, children: props.children }), $[0] = legacySchema, $[1] = props.attributes, $[2] = props.children, $[3] = props.element, $[4] = props.readOnly, $[5] = props.renderChild, $[6] = schema, $[7] = t02) : t02 = $[7], t02;
}
let block, t0;
if ($[8] !== props.element._key || $[9] !== schema || $[10] !== slateStatic.blockIndexMap || $[11] !== slateStatic.value) {
const blockIndex = slateStatic.blockIndexMap.get(props.element._key);
block = blockIndex !== void 0 ? slateStatic.value.at(blockIndex) : void 0, t0 = isTextBlock({
schema
}, block), $[8] = props.element._key, $[9] = schema, $[10] = slateStatic.blockIndexMap, $[11] = slateStatic.value, $[12] = block, $[13] = t0;
} else
block = $[12], t0 = $[13];
if (t0) {
let t12;
return $[14] !== block || $[15] !== legacySchema || $[16] !== props.attributes || $[17] !== props.children || $[18] !== props.element || $[19] !== props.readOnly || $[20] !== props.renderBlock || $[21] !== props.renderListItem || $[22] !== props.renderStyle || $[23] !== props.spellCheck ? (t12 = /* @__PURE__ */ jsx(RenderTextBlock, { attributes: props.attributes, element: props.element, legacySchema, readOnly: props.readOnly, renderBlock: props.renderBlock, renderListItem: props.renderListItem, renderStyle: props.renderStyle, spellCheck: props.spellCheck, textBlock: block, children: props.children }), $[14] = block, $[15] = legacySchema, $[16] = props.attributes, $[17] = props.children, $[18] = props.element, $[19] = props.readOnly, $[20] = props.renderBlock, $[21] = props.renderListItem, $[22] = props.renderStyle, $[23] = props.spellCheck, $[24] = t12) : t12 = $[24], t12;
}
let t1;
return $[25] !== block || $[26] !== legacySchema || $[27] !== props.attributes || $[28] !== props.children || $[29] !== props.element || $[30] !== props.readOnly || $[31] !== props.renderBlock || $[32] !== schema ? (t1 = /* @__PURE__ */ jsx(RenderBlockObject, { attributes: props.attributes, blockObject: block, element: props.element, legacySchema, readOnly: props.readOnly, renderBlock: props.renderBlock, schema, children: props.children }), $[25] = block, $[26] = legacySchema, $[27] = props.attributes, $[28] = props.children, $[29] = props.element, $[30] = props.readOnly, $[31] = props.renderBlock, $[32] = schema, $[33] = t1) : t1 = $[33], t1;
}
function _temp2(s_0) {
return s_0.context.getLegacySchema();
}
function _temp$1(s) {
return s.context.schema;
}
const PortableTextEditorContext = createContext(null), usePortableTextEditor = () => {
const editor = useContext(PortableTextEditorContext);
if (!editor)
throw new Error("The `usePortableTextEditor` hook must be used inside the <PortableTextEditor> component's context.");
return editor;
}, forEachActor = (actorRef, callback) => {
callback(actorRef);
const children = actorRef.getSnapshot().children;
children && Object.values(children).forEach((child) => {
forEachActor(child, callback);
});
};
function stopActor(actorRef) {
const persistedSnapshots = [];
forEachActor(actorRef, (ref) => {
persistedSnapshots.push([ref, ref.getSnapshot()]), ref.observers = /* @__PURE__ */ new Set();
});
const systemSnapshot = actorRef.system.getSnapshot?.();
actorRef.stop(), actorRef.system._snapshot = systemSnapshot, persistedSnapshots.forEach(([ref, snapshot]) => {
ref._processingStatus = 0, ref._snapshot = snapshot;
});
}
const converterJson = {
mimeType: "application/json",
serialize: ({
snapshot,
event
}) => {
const portableTextConverter = snapshot.context.converters.find((converter) => converter.mimeType === "application/x-portable-text");
return portableTextConverter ? {
...portableTextConverter.serialize({
snapshot,
event
}),
mimeType: "application/json",
originEvent: event.originEvent
} : {
type: "serialization.failure",
mimeType: "application/json",
originEvent: event.originEvent,
reason: "No application/x-portable-text Converter found"
};
},
deserialize: ({
snapshot,
event
}) => {
const portableTextConverter = snapshot.context.converters.find((converter) => converter.mimeType === "application/x-portable-text");
return portableTextConverter ? {
...portableTextConverter.deserialize({
snapshot,
event
}),
mimeType: "application/json"
} : {
type: "deserialization.failure",
mimeType: "application/json",
reason: "No application/x-portable-text Converter found"
};
}
}, converterPortableText = {
mimeType: "application/x-portable-text",
serialize: ({
snapshot,
event
}) => {
if (!snapshot.context.selection)
return {
type: "serialization.failure",
mimeType: "application/x-portable-text",
originEvent: event.originEvent,
reason: "No selection"
};
const blocks = getSelectedValue(snapshot);
return blocks.length === 0 ? {
type: "serialization.failure",
mimeType: "application/x-portable-text",
reason: "No blocks serialized",
originEvent: event.originEvent
} : {
type: "serialization.success",
data: JSON.stringify(blocks),
mimeType: "application/x-portable-text",
originEvent: event.originEvent
};
},
deserialize: ({
snapshot,
event
}) => {
const blocks = JSON.parse(event.data);
if (!Array.isArray(blocks))
return {
type: "deserialization.failure",
mimeType: "application/x-portable-text",
reason: "Data is not an array"
};
const parsedBlocks = blocks.flatMap((block) => {
const parsedBlock = parseBlock({
context: snapshot.context,
block,
options: {
refreshKeys: !0,
validateFields: !1
}
});
return parsedBlock ? [parsedBlock] : [];
});
return parsedBlocks.length === 0 && blocks.length > 0 ? {
type: "deserialization.failure",
mimeType: "application/x-portable-text",
reason: "No blocks were parsed"
} : {
type: "deserialization.success",
data: parsedBlocks,
mimeType: "application/x-portable-text"
};
}
};
function createConverterTextHtml(legacySchema) {
return {
mimeType: "text/html",
serialize: ({
snapshot,
event
}) => {
if (!snapshot.context.selection)
return {
type: "serialization.failure",
mimeType: "text/html",
originEvent: event.originEvent,
reason: "No selection"
};
const blocks = getSelectedValue(snapshot), html = toHTML(blocks, {
onMissingComponent: !1,
components: {
unknownType: ({
children
}) => children !== void 0 ? `${children}` : ""
}
});
return html === "" ? {
type: "serialization.failure",
mimeType: "text/html",
originEvent: event.originEvent,
reason: "Serialized HTML is empty"
} : {
type: "serialization.success",
data: html,
mimeType: "text/html",
originEvent: event.originEvent
};
},
deserialize: ({
snapshot,
event
}) => {
const parsedBlocks = htmlToBlocks(event.data, legacySchema.portableText, {
keyGenerator: snapshot.context.keyGenerator,
unstable_whitespaceOnPasteMode: legacySchema.block.options.unstable_whitespaceOnPasteMode
}).flatMap((block) => {
const parsedBlock = parseBlock({
context: snapshot.context,
block,
options: {
refreshKeys: !1,
validateFields: !0
}
});
return parsedBlock ? [parsedBlock] : [];
});
return parsedBlocks.length === 0 ? {
type: "deserialization.failure",
mimeType: "text/html",
reason: "No blocks deserialized"
} : {
type: "deserialization.success",
data: parsedBlocks,
mimeType: "text/html"
};
}
};
}
function createConverterTextPlain(legacySchema) {
return {
mimeType: "text/plain",
serialize: ({
snapshot,
event
}) => snapshot.context.selection ? {
type: "serialization.success",
data: getSelectedValue(snapshot).map((block) => isTextBlock(snapshot.context, block) ? block.children.map((child) => child._type === snapshot.context.schema.span.name ? child.text : event.originEvent === "drag.dragstart" ? `[${snapshot.context.schema.inlineObjects.find((inlineObjectType) => inlineObjectType.name === child._type)?.title ?? "Object"}]` : "").join("") : event.originEvent === "drag.dragstart" ? `[${snapshot.context.schema.blockObjects.find((blockObjectType) => blockObjectType.name === block._type)?.title ?? "Object"}]` : "").filter((block) => block !== "").join(`
`),
mimeType: "text/plain",
originEvent: event.originEvent
} : {
type: "serialization.failure",
mimeType: "text/plain",
originEvent: event.originEvent,
reason: "No selection"
},
deserialize: ({
snapshot,
event
}) => {
const textToHtml = `<html><body>${escapeHtml(event.data).split(/\n{2,}/).map((line) => line ? `<p>${line.replace(/(?:\r\n|\r|\n)/g, "<br/>")}</p>` : "<p></p>").join("")}</body></html>`, parsedBlocks = htmlToBlocks(textToHtml, legacySchema.portableText, {
keyGenerator: snapshot.context.keyGenerator
}).flatMap((block) => {
const parsedBlock = parseBlock({
context: snapshot.context,
block,
options: {
refreshKeys: !1,
validateFields: !0
}
});
return parsedBlock ? [parsedBlock] : [];
});
return parsedBlocks.length === 0 ? {
type: "deserialization.failure",
mimeType: "text/plain",
reason: "No blocks deserialized"
} : {
type: "deserialization.success",
data: parsedBlocks,
mimeType: "text/plain"
};
}
};
}
const entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/",
"`": "`",
"=": "="
};
function escapeHtml(str) {
return String(str).replace(/[&<>"'`=/]/g, (s) => entityMap[s]);
}
function createCoreConverters(legacySchema) {
return [converterJson, converterPortableText, createConverterTextHtml(legacySchema), createConverterTextPlain(legacySchema)];
}
function compileType(rawType) {
return Schema.compile({
name: "blockTypeSchema",
types: [rawType]
}).get(rawType.name);
}
const levelIndexMap = /* @__PURE__ */ new Map();
function buildIndexMaps(context, {
blockIndexMap,
listIndexMap
}) {
blockIndexMap.clear(), listIndexMap.clear(), levelIndexMap.clear();
let previousListItem;
for (let blockIndex = 0; blockIndex < context.value.length; blockIndex++) {
const block = context.value.at(blockIndex);
if (block !== void 0) {
if (blockIndexMap.set(block._key, blockIndex), !isTextBlock(context, block)) {
levelIndexMap.clear(), previousListItem = void 0;
continue;
}
if (block.listItem === void 0 || block.level === void 0) {
levelIndexMap.clear(), previousListItem = void 0;
continue;
}
if (!previousListItem) {
previousListItem = {
listItem: block.listItem,
level: block.level
}, levelIndexMap.set(block.level, 1), listIndexMap.set(block._key, 1);
continue;
}
if (previousListItem.listItem !== block.listItem) {
levelIndexMap.clear(), previousListItem = {
listItem: block.listItem,
level: block.level
}, levelIndexMap.set(block.level, 1), listIndexMap.set(block._key, 1);
continue;
}
if (previousListItem.level === block.level) {
const levelCounter = levelIndexMap.get(block.level) ?? 0;
levelIndexMap.set(block.level, levelCounter + 1), previousListItem = {
listItem: block.listItem,
level: block.level
}, listIndexMap.set(block._key, levelCounter + 1);
continue;
}
if (previousListItem.level < block.level) {
levelIndexMap.set(block.level, 1), previousListItem = {
listItem: block.listItem,
level: block.level
}, listIndexMap.set(block._key, 1);
continue;
}
if (previousListItem.level > block.level) {
const levelCounter = levelIndexMap.get(block.level) ?? 0;
levelIndexMap.set(block.level, levelCounter + 1), previousListItem = {
listItem: block.listItem,
level: block.level
}, listIndexMap.set(block._key, levelCounter + 1);
}
}
}
}
function createPlaceholderBlock(context) {
return {
_type: context.schema.block.name,
_key: context.keyGenerator(),
style: context.schema.styles[0].name ?? "normal",
markDefs: [],
children: [{
_type: context.schema.span.name,
_key: context.keyGenerator(),
text: "",
marks: []
}]
};
}
const insertTextOperationImplementat