UNPKG

@atlaskit/renderer

Version:
57 lines 1.66 kB
import { TextSelection } from '@atlaskit/editor-prosemirror/state'; import { getFragmentsFromSelection, getLocalIdsFromSelection } from '@atlaskit/editor-common/selection'; import { getPosFromRange, getStartPos, findParent } from '../steps'; export var getSelectionContext = function getSelectionContext(_ref) { var doc = _ref.doc, schema = _ref.schema; if (!doc || !schema) { return null; } var selection = document.getSelection(); if (!selection || selection.type !== 'Range' || selection.rangeCount !== 1) { return null; } var range = selection.getRangeAt(0); if (range.collapsed) { return null; } var startNode = findParent(range.startContainer); var endNode = findParent(range.endContainer); if (!startNode || !endNode) { return null; } var startPos = getStartPos(startNode); var endPos = getStartPos(endNode); if (startPos === null || endPos === null) { return null; } var pos = getPosFromRange(range); if (!pos) { return null; } var from = Math.min(pos.from, pos.to); var to = Math.max(pos.from, pos.to); if (from === to) { return null; } var pmSelection; try { pmSelection = TextSelection.create(doc, from, to); } catch (_unused) { return null; } var startIndex = from - startPos; var endIndex = to - endPos; if (startIndex < 0 || endIndex < 0) { return null; } var selectionFragment = getFragmentsFromSelection(pmSelection); var localIds = getLocalIdsFromSelection(pmSelection); return { localIds: localIds, selectionFragment: selectionFragment, selectionMarkdown: null, startIndex: startIndex, endIndex: endIndex }; };