UNPKG

@atlaskit/editor-common

Version:

A package that contains common classes and components for editor and renderer

66 lines (64 loc) 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.computeSelectionOffsets = computeSelectionOffsets; exports.restoreSelection = restoreSelection; var _state = require("@atlaskit/editor-prosemirror/state"); var _selection = require("../selection"); /** * Compute the new selection offsets after list items have been moved/indented/outdented. * * Uses the content start offsets computed during fragment rebuild to map each * selection endpoint to its new absolute position, accounting for the change * in the list structure. */ function computeSelectionOffsets(_ref) { var items = _ref.items, startIndex = _ref.startIndex, endIndex = _ref.endIndex, originalFrom = _ref.originalFrom, originalTo = _ref.originalTo, contentStartOffsets = _ref.contentStartOffsets, rootListStart = _ref.rootListStart, docSize = _ref.docSize; // +1 shifts from the outer edge of the list item node to the start of the content within var fromContentStart = items[startIndex].pos + 1; var toContentStart = items[endIndex].pos + 1; var fromOffset = originalFrom - fromContentStart; var toOffset = originalTo - toContentStart; var clamp = function clamp(pos) { return Math.min(Math.max(0, pos), docSize); }; return { from: clamp(rootListStart + contentStartOffsets[startIndex] + fromOffset), to: clamp(rootListStart + contentStartOffsets[endIndex] + toOffset) }; } /** * Restore the transaction's selection after a list structural change * (indent/outdent of list items or task list items). * * Uses the content start offsets computed during fragment rebuild to * map each selection endpoint to its new absolute position. * * Handles NodeSelection, GapCursorSelection, and TextSelection. */ function restoreSelection(_ref2) { var tr = _ref2.tr, originalSelection = _ref2.originalSelection, from = _ref2.from, to = _ref2.to; var maxPos = tr.doc.content.size; if (originalSelection instanceof _state.NodeSelection) { try { tr.setSelection(_state.NodeSelection.create(tr.doc, Math.min(from, maxPos - 1))); } catch (_unused) { tr.setSelection(_state.Selection.near(tr.doc.resolve(from))); } } else if (originalSelection instanceof _selection.GapCursorSelection) { tr.setSelection(new _selection.GapCursorSelection(tr.doc.resolve(from), originalSelection.side)); } else { tr.setSelection(_state.TextSelection.create(tr.doc, from, to)); } }