UNPKG

@portabletext/editor

Version:

Portable Text Editor made in React

97 lines (96 loc) 2.51 kB
import { blockOffsetToSpanSelectionPoint, isKeyedSegment } from "./util.slice-blocks.js"; import { isPortableTextTextBlock, isPortableTextSpan } from "@sanity/types"; function blockOffsetToBlockSelectionPoint({ value, blockOffset }) { let selectionPoint; for (const block of value) if (block._key === blockOffset.path[0]._key) { selectionPoint = { path: [{ _key: block._key }], offset: blockOffset.offset }; break; } return selectionPoint; } function blockOffsetToSelectionPoint({ value, blockOffset, direction }) { return blockOffsetToSpanSelectionPoint({ value, blockOffset, direction }) || blockOffsetToBlockSelectionPoint({ value, blockOffset }); } function blockOffsetsToSelection({ value, offsets, backward }) { const anchor = blockOffsetToSelectionPoint({ value, blockOffset: offsets.anchor, direction: backward ? "backward" : "forward" }), focus = blockOffsetToSelectionPoint({ value, blockOffset: offsets.focus, direction: backward ? "forward" : "backward" }); return !anchor || !focus ? null : { anchor, focus, backward }; } function childSelectionPointToBlockOffset({ value, selectionPoint }) { let offset = 0; const blockKey = isKeyedSegment(selectionPoint.path[0]) ? selectionPoint.path[0]._key : void 0, childKey = isKeyedSegment(selectionPoint.path[2]) ? selectionPoint.path[2]._key : void 0; if (!(!blockKey || !childKey)) { for (const block of value) if (block._key === blockKey && isPortableTextTextBlock(block)) for (const child of block.children) { if (child._key === childKey) return { path: [{ _key: block._key }], offset: offset + selectionPoint.offset }; isPortableTextSpan(child) && (offset += child.text.length); } } } function selectionPointToBlockOffset({ value, selectionPoint }) { return selectionPoint.path.length === 1 && isKeyedSegment(selectionPoint.path[0]) ? { path: [{ _key: selectionPoint.path[0]._key }], offset: selectionPoint.offset } : childSelectionPointToBlockOffset({ value, selectionPoint }); } export { blockOffsetToBlockSelectionPoint, blockOffsetToSelectionPoint, blockOffsetsToSelection, childSelectionPointToBlockOffset, selectionPointToBlockOffset }; //# sourceMappingURL=util.selection-point-to-block-offset.js.map