UNPKG

@portabletext/editor

Version:

Portable Text Editor made in React

1,324 lines (1,323 loc) 437 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var reactCompilerRuntime = require("react-compiler-runtime"), React = require("react"), useEffectEvent = require("use-effect-event"), useEditor = require("./_chunks-cjs/use-editor.cjs"), jsxRuntime = require("react/jsx-runtime"), react = require("@xstate/react"), noop = require("lodash/noop.js"), slate = require("slate"), slateReact = require("slate-react"), debug$f = require("debug"), slateDom = require("slate-dom"), util_sliceBlocks = require("./_chunks-cjs/util.slice-blocks.cjs"), util_isSelectionCollapsed = require("./_chunks-cjs/util.is-selection-collapsed.cjs"), isEqual = require("lodash/isEqual.js"), selector_isSelectionExpanded = require("./_chunks-cjs/selector.is-selection-expanded.cjs"), selector_isSelectingEntireBlocks = require("./_chunks-cjs/selector.is-selecting-entire-blocks.cjs"), getRandomValues = require("get-random-values-esm"), behaviors_index = require("./behaviors/index.cjs"), uniq = require("lodash/uniq.js"), rxjs = require("rxjs"), xstate = require("xstate"), blockTools = require("@portabletext/block-tools"), toHtml = require("@portabletext/to-html"), schema = require("@sanity/schema"), flatten = require("lodash/flatten.js"), omit = require("lodash/omit.js"), patches = require("@portabletext/patches"), util_childSelectionPointToBlockOffset = require("./_chunks-cjs/util.child-selection-point-to-block-offset.cjs"), util_sliceTextBlock = require("./_chunks-cjs/util.slice-text-block.cjs"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), immer = require("immer"), keyboardShortcuts = require("@portabletext/keyboard-shortcuts"), types = require("@sanity/types"), startCase = require("lodash.startcase"), isPlainObject = require("lodash/isPlainObject.js"); function _interopDefaultCompat(e) { return e && typeof e == "object" && "default" in e ? e : { default: e }; } var React__default = /* @__PURE__ */ _interopDefaultCompat(React), noop__default = /* @__PURE__ */ _interopDefaultCompat(noop), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$f), isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), getRandomValues__default = /* @__PURE__ */ _interopDefaultCompat(getRandomValues), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten), omit__default = /* @__PURE__ */ _interopDefaultCompat(omit), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy), startCase__default = /* @__PURE__ */ _interopDefaultCompat(startCase), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject); function EditorEventListener(props) { const $ = reactCompilerRuntime.c(5), editor = useEditor.useEditor(), on = useEffectEvent.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], React.useEffect(t0, t1), null; } const rootName = "sanity-pte:"; debug__default.default(rootName); function debugWithName(name) { const namespace = `${rootName}${name}`; return debug__default.default && debug__default.default.enabled(namespace) ? debug__default.default(namespace) : debug__default.default(rootName); } const VOID_CHILD_KEY = "void-child"; function keepObjectEquality(object, keyMap) { const value = keyMap[object._key]; return value && isEqual__default.default(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 && slate.Element.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 && slate.Element.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 && slate.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(slate.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 slate.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] = slate.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 = slate.Range.start(editor.selection); return getPointBlock({ editor, point: selectionStartPoint }); } function getSelectionEndBlock({ editor }) { if (!editor.selection) return [void 0, void 0]; const selectionEndPoint = slate.Range.end(editor.selection); return getPointBlock({ editor, point: selectionEndPoint }); } function getPointBlock({ editor, point }) { try { const [block] = slate.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 = slate.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 = slate.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 = slate.Editor.start(editor, []).path.at(0); try { return firstBlockPath !== void 0 ? slate.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 = slate.Editor.end(editor, []).path.at(0); try { return lastBlockPath !== void 0 ? slate.Editor.node(editor, [lastBlockPath]) ?? [void 0, void 0] : [void 0, void 0]; } catch { return [void 0, void 0]; } } function getNodeBlock({ editor, schema: schema2, node }) { if (slate.Editor.isEditor(node)) return; if (isBlockElement({ editor, schema: schema2 }, node)) return elementToBlock({ schema: schema2, element: node }); const parent = Array.from(slate.Editor.nodes(editor, { mode: "highest", at: [], match: (n) => isBlockElement({ editor, schema: schema2 }, n) && n.children.some((child) => child._key === node._key) })).at(0)?.at(0); return slate.Element.isElement(parent) ? elementToBlock({ schema: schema2, element: parent }) : void 0; } function elementToBlock({ schema: schema2, element }) { return fromSlateValue([element], schema2.block.name)?.at(0); } function isBlockElement({ editor, schema: schema2 }, node) { return slate.Element.isElement(node) && !editor.isInline(node) && (schema2.block.name === node._type || schema2.blockObjects.some((blockObject) => blockObject.name === node._type)); } function isListItemActive({ editor, listItem }) { if (!editor.selection) return !1; const selectedBlocks = [...slate.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 = [...slate.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: schema2, editor, range }) { const [anchorBlock] = getPointBlock({ editor, point: range.anchor }), [focusBlock] = getPointBlock({ editor, point: range.focus }); if (!anchorBlock || !focusBlock) return null; const [anchorChild] = anchorBlock._type === schema2.block.name ? getPointChild({ editor, point: range.anchor }) : [void 0, void 0], [focusChild] = focusBlock._type === schema2.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: slate.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 && !slate.Editor.isEditor(eventNode)) return { block: eventPositionBlock, isEditor: !1, selection: { anchor: util_sliceBlocks.getBlockStartPoint({ context: editorActor.getSnapshot().context, block: { node: eventBlock, path: [{ _key: eventBlock._key }] } }), focus: util_isSelectionCollapsed.getBlockEndPoint({ context: editorActor.getSnapshot().context, block: { node: eventBlock, path: [{ _key: eventBlock._key }] } }) } }; if (!eventPositionBlock || !eventSelection) return; const eventSelectionFocusBlockKey = util_sliceBlocks.getBlockKeyFromSelectionPoint(eventSelection.focus); if (eventSelectionFocusBlockKey !== void 0) return util_isSelectionCollapsed.isSelectionCollapsed(eventSelection) && eventBlock && eventSelectionFocusBlockKey !== eventBlock._key ? { block: eventPositionBlock, isEditor: !1, selection: { anchor: util_sliceBlocks.getBlockStartPoint({ context: editorActor.getSnapshot().context, block: { node: eventBlock, path: [{ _key: eventBlock._key }] } }), focus: util_isSelectionCollapsed.getBlockEndPoint({ context: editorActor.getSnapshot().context, block: { node: eventBlock, path: [{ _key: eventBlock._key }] } }) } } : { block: eventPositionBlock, isEditor: slate.Editor.isEditor(eventNode), selection: eventSelection }; } function getEventNode({ slateEditor, event }) { return slateDom.DOMEditor.hasTarget(slateEditor, event.target) ? slateDom.DOMEditor.toSlateNode(slateEditor, event.target) : void 0; } function getEventPositionBlock({ node, slateEditor, event }) { const [firstBlock] = getFirstBlock({ editor: slateEditor }); if (!firstBlock) return; const firstBlockRect = slateDom.DOMEditor.toDOMNode(slateEditor, firstBlock).getBoundingClientRect(); if (event.pageY < firstBlockRect.top) return "start"; const [lastBlock] = getLastBlock({ editor: slateEditor }); if (!lastBlock) return; const lastBlockRef = slateDom.DOMEditor.toDOMNode(slateEditor, lastBlock).getBoundingClientRect(); if (event.pageY > lastBlockRef.bottom) return "end"; const elementRect = slateDom.DOMEditor.toDOMNode(slateEditor, node).getBoundingClientRect(), top = elementRect.top, height = elementRect.height; return Math.abs(top - event.pageY) < height / 2 ? "start" : "end"; } function getEventSelection({ schema: schema2, slateEditor, event }) { const range = getSlateRangeFromEvent(slateEditor, event); return range ? slateRangeToSelection({ schema: schema2, editor: slateEditor, range }) : null; } function getSlateRangeFromEvent(editor, event) { if (!event.target || !slateDom.isDOMNode(event.target)) return; const window2 = slateDom.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 = slateDom.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__default.default({ _key: blk._key }, anchor.path[0])) && (newAnchor = normalizePoint(anchor, value)), focus && value.find((blk) => isEqual__default.default({ _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 (util_isSelectionCollapsed.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 = util_sliceBlocks.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 (!util_sliceBlocks.isTextBlock(snapshot.context, block)) return { path: [blockIndex, 0], offset: 0 }; let childKey = util_sliceBlocks.getChildKeyFromSelectionPoint({ path: selectionPoint.path }); const spanSelectionPoint = childKey ? void 0 : util_sliceBlocks.blockOffsetToSpanSelectionPoint({ context: { schema: snapshot.context.schema, value: [block] }, blockOffset: { path: [{ _key: blockKey }], offset: selectionPoint.offset }, direction }); if (childKey = spanSelectionPoint ? util_sliceBlocks.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, util_sliceBlocks.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: util_sliceBlocks.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 = React.createContext({}); function DropIndicator() { const $ = reactCompilerRuntime.c(1); let t0; return $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = /* @__PURE__ */ jsxRuntime.jsx("div", { contentEditable: !1, className: "pt-drop-indicator", style: { position: "absolute", width: "100%", height: 1, borderBottom: "1px solid currentColor", zIndex: 5 }, children: /* @__PURE__ */ jsxRuntime.jsx("span", {}) }), $[0] = t0) : t0 = $[0], t0; } function RenderDefaultBlockObject(props) { const $ = reactCompilerRuntime.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__ */ jsxRuntime.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 $ = reactCompilerRuntime.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__ */ jsxRuntime.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 (selector_isSelectingEntireBlocks.getFocusInlineObject({ ...snapshot, context: { ...snapshot.context, selection: eventSelection } })) return dragSelection; const draggingCollapsedSelection = selector_isSelectionExpanded.isSelectionCollapsed({ context: { ...snapshot.context, selection: eventSelection } }), draggedTextBlock = selector_isSelectionExpanded.getFocusTextBlock({ ...snapshot, context: { ...snapshot.context, selection: eventSelection } }), draggedSpan = selector_isSelectionExpanded.getFocusSpan({ ...snapshot, context: { ...snapshot.context, selection: eventSelection } }); draggingCollapsedSelection && draggedTextBlock && draggedSpan && (dragSelection = { anchor: util_sliceBlocks.getBlockStartPoint({ context: snapshot.context, block: draggedTextBlock }), focus: util_isSelectionCollapsed.getBlockEndPoint({ context: snapshot.context, block: draggedTextBlock }) }); const selectedBlocks = selector_isSelectingEntireBlocks.getSelectedBlocks(snapshot); if (snapshot.context.selection && selector_isSelectionExpanded.isSelectionExpanded(snapshot) && selectedBlocks.length > 1) { const selectionStartBlock = selector_isSelectingEntireBlocks.getSelectionStartBlock(snapshot), selectionEndBlock = selector_isSelectingEntireBlocks.getSelectionEndBlock(snapshot); if (!selectionStartBlock || !selectionEndBlock) return dragSelection; const selectionStartPoint = util_sliceBlocks.getBlockStartPoint({ context: snapshot.context, block: selectionStartBlock }), selectionEndPoint = util_isSelectionCollapsed.getBlockEndPoint({ context: snapshot.context, block: selectionEndBlock }); selector_isSelectingEntireBlocks.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__default.default(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: behaviors_index.defineBehavior({ on: "drag.dragover", guard: ({ snapshot, event }) => { const dropFocusBlock = selector_isSelectionExpanded.getFocusBlock({ ...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 selector_isSelectingEntireBlocks.getSelectedBlocks({ ...snapshot, context: { ...snapshot.context, selection: dragSelection } }).some((draggedBlock) => draggedBlock.node._key === key) ? !1 : selector_isSelectingEntireBlocks.isSelectingEntireBlocks({ ...snapshot, context: { ...snapshot.context, selection: dragSelection } }); }, actions: [({ event }) => [{ type: "effect", effect: () => { onSetDragPositionBlock(event.position.block); } }]] }), priority: createEditorPriority({ reference: { priority: corePriority, importance: "lower" } }) }, { behavior: behaviors_index.defineBehavior({ on: "drag.*", guard: ({ event }) => event.type !== "drag.dragover", actions: [({ event }) => [{ type: "effect", effect: () => { onSetDragPositionBlock(void 0); } }, behaviors_index.forward(event)]] }), priority: createEditorPriority({ reference: { priority: corePriority, importance: "lower" } }) }]; } function useCoreBlockElementBehaviors(t0) { const $ = reactCompilerRuntime.c(5), { key, onSetDragPositionBlock } = t0, editorActor = React.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]), React.useEffect(t1, t2); } function RenderBlockObject(props) { const [dragPositionBlock, setDragPositionBlock] = React.useState(), blockObjectRef = React.useRef(null), selected = slateReact.useSelected(), focused = slateReact.useSlateSelector((editor) => selected && editor.selection !== null && slate.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__ */ jsxRuntime.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__ */ jsxRuntime.jsx(DropIndicator, {}) : null, props.children, /* @__PURE__ */ jsxRuntime.jsx("div", { ref: blockObjectRef, contentEditable: !1, draggable: !props.readOnly, children: props.renderBlock && legacySchemaType ? props.renderBlock({ children: /* @__PURE__ */ jsxRuntime.jsx(RenderDefaultBlockObject, { blockObject }), editorElementRef: blockObjectRef, focused, path: [{ _key: props.element._key }], schemaType: legacySchemaType, selected, type: legacySchemaType, value: blockObject }) : /* @__PURE__ */ jsxRuntime.jsx(RenderDefaultBlockObject, { blockObject }) }), dragPositionBlock === "end" ? /* @__PURE__ */ jsxRuntime.jsx(DropIndicator, {}) : null ] }); } function RenderInlineObject(props) { const inlineObjectRef = React.useRef(null), slateEditor = slateReact.useSlateStatic(), selected = slateReact.useSelected(), focused = slateReact.useSlateSelector((editor) => selected && editor.selection !== null && slate.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 = slateDom.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__ */ jsxRuntime.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__ */ jsxRuntime.jsx("span", { ref: inlineObjectRef, style: { display: "inline-block" }, children: props.renderChild && block && legacySchemaType ? props.renderChild({ annotations: [], children: /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsx(RenderDefaultInlineObject, { inlineObject: inlineObject_0 }) }) ] }); } function RenderTextBlock(props) { const [dragPositionBlock, setDragPositionBlock] = React.useState(), blockRef = React.useRef(null), selected = slateReact.useSelected(), focused = slateReact.useSlateSelector((editor) => selected && editor.selection !== null && slate.Range.isCollapsed(editor.selection)); useCoreBlockElementBehaviors({ key: props.element._key, onSetDragPositionBlock: setDragPositionBlock }); const listIndex = slateReact.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__ */ jsxRuntime.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__ */ jsxRuntime.jsx(DropIndicator, {}) : null, /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsx(DropIndicator, {}) : null ] }); } function RenderElement(props) { const $ = reactCompilerRuntime.c(34), editorActor = React.useContext(EditorActorContext), schema2 = react.useSelector(editorActor, _temp$1), legacySchema = react.useSelector(editorActor, _temp2), slateStatic = slateReact.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] !== schema2 ? (t02 = /* @__PURE__ */ jsxRuntime.jsx(RenderInlineObject, { attributes: props.attributes, element: props.element, legacySchema, readOnly: props.readOnly, renderChild: props.renderChild, schema: schema2, children: props.children }), $[0] = legacySchema, $[1] = props.attributes, $[2] = props.children, $[3] = props.element, $[4] = props.readOnly, $[5] = props.renderChild, $[6] = schema2, $[7] = t02) : t02 = $[7], t02; } let block, t0; if ($[8] !== props.element._key || $[9] !== schema2 || $[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 = util_sliceBlocks.isTextBlock({ schema: schema2 }, block), $[8] = props.element._key, $[9] = schema2, $[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__ */ jsxRuntime.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] !== schema2 ? (t1 = /* @__PURE__ */ jsxRuntime.jsx(RenderBlockObject, { attributes: props.attributes, blockObject: block, element: props.element, legacySchema, readOnly: props.readOnly, renderBlock: props.renderBlock, schema: schema2, children: props.children }), $[25] = block, $[26] = legacySchema, $[27] = props.attributes, $[28] = props.children, $[29] = props.element, $[30] = props.readOnly, $[31] = props.renderBlock, $[32] = schema2, $[33] = t1) : t1 = $[33], t1; } function _temp2(s_0) { return s_0.context.getLegacySchema(); } function _temp$1(s) { return s.context.schema; } const PortableTextEditorContext = React.createContext(null), usePortableTextEditor = () => { const editor = React.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 = selector_isSelectionExpanded.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 = util_sliceBlocks.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 = selector_isSelectionExpanded.getSelectedValue(snapshot), html = toHtml.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 = blockTools.htmlToBlocks(event.data, legacySchema.portableText, { keyGenerator: snapshot.context.keyGenerator, unstable_whitespaceOnPasteMode: legacySchema.block.options.unstable_whitespaceOnPasteMode }).flatMap((block) => { const parsedBlock = util_sliceBlocks.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: selector_isSelectionExpanded.getSelectedValue(snapshot).map((block) => util_sliceBlocks.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 = blockTools.htmlToBlocks(textToHtml, legacySchema.portableText, { keyGenerator: snapshot.context.keyGenerator }).flatMap((block) => { const parsedBlock = util_sliceBlocks.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 = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;", "/": "&#x2F;", "`": "&#x60;", "=": "&#x3D;" }; 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.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), !util_sliceBlocks.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 (pre