@atlaskit/editor-plugin-selection-extension
Version:
editor-plugin-selection-extension plugin for @atlaskit/editor-core
84 lines (81 loc) • 3.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getOffsetByPath = getOffsetByPath;
var _model = require("@atlaskit/editor-prosemirror/model");
// TODO: ED-28434 - move this to a shared package
// mirror code from https://bitbucket.org/atlassian/pf-adf-service/src/master/src/lib/update/get-offset.ts
function getOffsetByPath(root, pos, pointer) {
var from = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var to = arguments.length > 4 ? arguments[4] : undefined;
var parts = pointer.split('/');
var ref = root;
var len = parts.length;
// -1 to account for the root node (usually doc)
// The start of the document, right before the first content, is position 0.
var offset = pos; //-1;
for (var i = 1; i < len; i++) {
var key = parts[i];
// @ts-ignore - TS1501 TypeScript 5.9.2 upgrade
if (ref instanceof _model.Fragment && /^[0-9]+$/.test(key)) {
var index = parseInt(key, 10);
if (index >= ref.childCount) {
throw new Error("JSON pointer \"".concat(pointer, "\" points to non-existing location."));
}
var nextRef = ref.child(index);
while (index--) {
offset += ref.child(index).nodeSize;
}
ref = nextRef;
} else if (ref instanceof _model.Node) {
/**
* Reference: https://prosemirror.net/docs/guide/#doc.data_structures
* +----------------------------------+
* | Node |
* | ^^^^ |
* | type: NodeType |
* | content: Fragment |
* | [ Node, Node, ...] |
* | attrs: Object |
* | marks: Mark |
* | [ |
* | type: MarkType |
* | attrs: Object |
* | ] |
* +----------------------------------+
*/
switch (key) {
case 'content':
// Entering or leaving a node that is not a leaf node (i.e. supports content) counts as one token.
offset++;
ref = ref.content;
break;
case 'attrs':
return {
type: 'attrs',
from: offset + from,
path: parts.slice(i + 1)
};
case 'text':
if (!ref.isText) {
throw new Error("\"".concat(parts.slice(0, i).join('/'), "\" doesn't have any \"text\" node!"));
}
continue;
default:
throw new Error("JSON pointer \"".concat(pointer, "\" points to an unsupported location."));
}
} else {
throw new Error("JSON pointer \"".concat(pointer, "\" points to an unsupported entity."));
}
}
if (ref instanceof _model.Fragment) {
throw new Error("Expected a Node, but the JSON pointer \"".concat(pointer, "\" points to a Fragment."));
}
return {
type: 'node',
from: offset + from,
to: offset + (to !== null && to !== void 0 ? to : ref.nodeSize),
matches: [to ? ref.textBetween(from, to) : ref.textContent]
};
}