Spaces:
Configuration error
Configuration error
File size: 21,929 Bytes
a7060a0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 | import { isDefined } from "./utilities";
export const isTextNode = (node) => node && node.nodeType === Node.TEXT_NODE;
const isText = (text) => text && /[\w']/i.test(text);
const isSpace = (text) => text && /[\s\t]/i.test(text);
const destructSelection = (selection) => {
const range = selection.getRangeAt(0);
const { startOffset, startContainer, endOffset, endContainer } = range;
const firstSymbol = startContainer.textContent[startOffset];
const prevSymbol = startContainer.textContent[startOffset - 1];
const lastSymbol = endContainer.textContent[endOffset - 1];
const nextSymbol = endContainer.textContent[endOffset];
return {
selection,
range,
startOffset,
startContainer,
endOffset,
endContainer,
firstSymbol,
prevSymbol,
lastSymbol,
nextSymbol,
};
};
const trimSelectionLeft = (selection) => {
const resultRange = selection.getRangeAt(0);
selection.removeAllRanges();
selection.collapse(resultRange.startContainer, resultRange.startOffset);
let currentRange = selection.getRangeAt(0);
do {
selection.collapse(currentRange.endContainer, currentRange.endOffset);
selection.modify("extend", "forward", "character");
currentRange = selection.getRangeAt(0);
} while (
!isTextNode(currentRange.startContainer) ||
isSpace(currentRange.startContainer.textContent[currentRange.startOffset])
);
resultRange.setStart(currentRange.startContainer, currentRange.startOffset);
selection.removeAllRanges();
selection.addRange(resultRange);
};
const trimSelectionRight = (selection) => {
const resultRange = selection.getRangeAt(0);
selection.removeAllRanges();
selection.collapse(resultRange.endContainer, resultRange.endOffset);
let currentRange = selection.getRangeAt(0);
do {
selection.collapse(currentRange.startContainer, currentRange.startOffset);
selection.modify("extend", "backward", "character");
currentRange = selection.getRangeAt(0);
} while (
!isTextNode(currentRange.startContainer) ||
isSpace(currentRange.startContainer.textContent[currentRange.startOffset])
);
resultRange.setEnd(currentRange.endContainer, currentRange.endOffset);
selection.removeAllRanges();
selection.addRange(resultRange);
};
/**
* Trims selection until both start and end are text nodes. We need this to make selection.move()
* work properly. With non-text nodes it jumps into inner/outer blocks instead of actually moving.
* Also removes leading and trailing spaces from selection.
* @param {Selection} selection
*/
export const trimSelection = (selection) => {
trimSelectionLeft(selection);
trimSelectionRight(selection);
};
/**
*
* @param {Selection} selection
*/
const findBoundarySelection = (selection, boundary) => {
const { range: originalRange, startOffset, startContainer, endOffset, endContainer } = destructSelection(selection);
const resultRange = {};
let currentRange;
// It's easier to operate the selection when it's collapsed
selection.collapse(endContainer, endOffset);
// Looking for maximum displacement
while (selection.getRangeAt(0).compareBoundaryPoints(Range.START_TO_START, originalRange) === 1) {
selection.modify("move", "backward", boundary);
}
// Going back to find minimum displacement
while (selection.getRangeAt(0).compareBoundaryPoints(Range.START_TO_START, originalRange) < 1) {
currentRange = selection.getRangeAt(0);
Object.assign(resultRange, {
startContainer: currentRange.startContainer,
startOffset: currentRange.startOffset,
});
selection.modify("move", "forward", boundary);
}
selection.collapse(startContainer, startOffset);
while (selection.getRangeAt(0).compareBoundaryPoints(Range.END_TO_END, originalRange) === -1) {
selection.modify("move", "forward", boundary);
}
while (selection.getRangeAt(0).compareBoundaryPoints(Range.END_TO_END, originalRange) > -1) {
currentRange = selection.getRangeAt(0);
Object.assign(resultRange, {
endContainer: currentRange.endContainer,
endOffset: currentRange.endOffset,
});
selection.modify("move", "backward", boundary);
}
selection.removeAllRanges();
const range = new Range();
range.setStart(resultRange.startContainer, resultRange.startOffset);
range.setEnd(resultRange.endContainer, resultRange.endOffset);
selection.addRange(range);
trimSelection(selection);
return selection;
};
const closestBoundarySelection = (selection, boundary) => {
const { range: originalRange, startOffset, startContainer, endOffset, endContainer } = destructSelection(selection);
const resultRange = {};
let currentRange;
// It's easier to operate the selection when it's collapsed
selection.collapse(startContainer, startOffset);
selection.modify("move", "forward", "character");
selection.modify("move", "backward", boundary);
if (selection.getRangeAt(0).compareBoundaryPoints(Range.START_TO_START, originalRange) === 1) {
selection.collapse(startContainer, startOffset);
selection.modify("move", "backward", boundary);
}
currentRange = selection.getRangeAt(0);
Object.assign(resultRange, {
startContainer: currentRange.startContainer,
startOffset: currentRange.startOffset,
});
selection.collapse(endContainer, endOffset);
selection.modify("move", "backward", "character");
selection.modify("move", "forward", boundary);
if (selection.getRangeAt(0).compareBoundaryPoints(Range.START_TO_START, originalRange) === -1) {
selection.collapse(endContainer, endOffset);
selection.modify("move", "forward", boundary);
}
currentRange = selection.getRangeAt(0);
Object.assign(resultRange, {
endContainer: currentRange.endContainer,
endOffset: currentRange.endOffset,
});
selection.removeAllRanges();
const range = new Range();
range.setStart(resultRange.startContainer, resultRange.startOffset);
range.setEnd(resultRange.endContainer, resultRange.endOffset);
selection.addRange(range);
return selection;
};
const boundarySelection = (selection, boundary) => {
const wordBoundary = boundary !== "symbol";
const { startOffset, startContainer, endOffset, endContainer, firstSymbol, prevSymbol, lastSymbol, nextSymbol } =
destructSelection(selection);
if (wordBoundary) {
if (boundary.endsWith("boundary")) {
closestBoundarySelection(selection, boundary);
} else {
findBoundarySelection(selection, boundary);
}
} else {
if (!isText(firstSymbol) || isText(prevSymbol)) {
const newRange = selection.getRangeAt(0);
newRange.setEnd(startContainer, startOffset);
selection.modify("move", "backward", boundary);
}
if (!isText(lastSymbol) || isText(nextSymbol)) {
const newRange = selection.getRangeAt(0);
newRange.setEnd(endContainer, endOffset);
selection.modify("extend", "forward", boundary);
}
}
};
/**
* Captures current selection
* @param {(response: {selectionText: string, range: Range}) => void} callback
*/
export const captureSelection = (
callback,
{ granularity, beforeCleanup, window } = {
granularity: "symbol",
},
) => {
const selection = window.getSelection();
if (selection.isCollapsed) return;
if (granularity !== "symbol") {
trimSelection(selection);
}
if (selection.isCollapsed) return;
applyTextGranularity(selection, granularity);
const selectionText = selection.toString().replace(/[\n\r]/g, "\\n");
for (let i = 0; i < selection.rangeCount; i++) {
const range = fixRange(selection.getRangeAt(i));
callback({ selectionText, range });
}
// eslint-disable-next-line no-unused-expressions
beforeCleanup?.();
selection.removeAllRanges();
};
/**
* *Experimental feature. Might nor work in Gecko browsers.*
*
* Updates selection's granularity.
* @param {Selection} selection
* @param {string} granularity
*/
export const applyTextGranularity = (selection, granularity) => {
if (!selection.modify || !granularity || granularity === "symbol") return;
try {
switch (granularity) {
case "word":
boundarySelection(selection, "word");
break;
case "sentence":
boundarySelection(selection, "sentenceboundary");
break;
case "paragraph":
boundarySelection(selection, "paragraphboundary");
break;
default:
// Handles "charater", "symbol", and any other unspecified granularities
break;
}
} catch {
console.warn("Probably, you're using browser that doesn't support granularity.");
}
};
/**
* Lookup closest text node
* @param {HTMLElement} commonContainer
* @param {HTMLElement} node
* @param {number} offset
* @param {string} direction forward, backward, forward-next, backward-next
* "-next" when we need to skip node if it's a text node
*/
const textNodeLookup = (commonContainer, node, offset, direction = "forward") => {
const startNode = node === commonContainer ? node.childNodes[offset] : node;
if (isTextNode(startNode) && !direction.endsWith("next")) return startNode;
const walker = commonContainer.ownerDocument.createTreeWalker(commonContainer, NodeFilter.SHOW_ALL);
let currentNode = walker.nextNode();
// tree walker can't go backward, so we go forward to startNode and record every text node
// to find the last one before startNode
let lastTextNode;
while (currentNode && currentNode !== startNode) {
if (isTextNode(currentNode)) lastTextNode = currentNode;
currentNode = walker.nextNode();
}
if (currentNode && direction.startsWith("backward")) return lastTextNode;
if (direction === "forward-next") currentNode = walker.nextNode();
while (currentNode) {
if (isTextNode(currentNode)) return currentNode;
currentNode = walker.nextNode();
}
};
/**
* Fix range if it contains non-text nodes and shrink it down to the better fit.
* The main goal here is to get the most relevant xpath+offset combination.
* i.e. `start` should point to the element, containing first char, not parent,
* not root, not some previous element with `startOffset` on the last char.
* @param {Range} range
*/
export const fixRange = (range) => {
const { endOffset, commonAncestorContainer: commonContainer } = range;
let { startOffset, startContainer, endContainer } = range;
if (!isTextNode(startContainer)) {
startContainer = textNodeLookup(commonContainer, startContainer, startOffset, "forward");
if (!startContainer) return null;
range.setStart(startContainer, 0);
startOffset = 0;
}
// if user started selection from the end of the tag, start could be this tag,
// so we should move it to more relevant one
const selectionFromTheEnd = startContainer.wholeText.length === startOffset;
// we skip ephemeral whitespace-only text nodes, like \n between tags in original html
const isBasicallyEmpty = (textNode) => /^\s*$/.test(textNode.wholeText);
if (selectionFromTheEnd || isBasicallyEmpty(startContainer)) {
do {
startContainer = textNodeLookup(commonContainer, startContainer, startOffset, "forward-next");
if (!startContainer) return null;
} while (isBasicallyEmpty(startContainer));
range.setStart(startContainer, 0);
startOffset = 0;
}
if (!isTextNode(endContainer)) {
endContainer = textNodeLookup(commonContainer, endContainer, endOffset, "backward");
if (!endContainer) return null;
while (/^\s*$/.test(endContainer.wholeText)) {
endContainer = textNodeLookup(commonContainer, endContainer, endOffset, "backward-next");
if (!endContainer) return null;
}
// we skip empty whitespace-only text nodes, so we need the found one to be included
range.setEnd(endContainer, endContainer.length);
}
return range;
};
/**
* Highlight given Range
* @param {Range} range
* @param {{label: string, index?: number, classNames: string[]}} param1
*/
export const highlightRange = (range, { index, label, classNames }) => {
const { startContainer, endContainer, commonAncestorContainer } = range;
const { startOffset, endOffset } = range;
const highlights = [];
/**
* Wrapper with predefined classNames and cssStyles
* @param {[Node, number, number]} args
*/
const applyStyledHighlight = (...args) => highlightRangePart(...args, classNames);
// If start and end nodes are equal, we don't need
// to perform any additional work, just highlighting as is
if (startContainer === endContainer) {
highlights.push(applyStyledHighlight(startContainer, startOffset, endOffset));
} else {
// When start and end are different we need to find all
// nodes between as they could contain text nodes
const nodesToHighlight = findNodesBetween(startContainer, endContainer, commonAncestorContainer);
// All nodes between start and end should be fully highlighted
nodesToHighlight.forEach((node) => {
let start = startOffset;
let end = endOffset;
if (node !== startContainer) start = 0;
if (node !== endContainer) end = node.length;
highlights.push(applyStyledHighlight(node, start, end));
});
}
const lastLabel = highlights[highlights.length - 1];
if (lastLabel) {
lastLabel.setAttribute("data-label", label ?? "");
lastLabel.setAttribute("data-index", index ? String(index) : "");
}
return highlights;
};
/**
* Takes original range and splits it into multiple text
* nodes highlighting a part of the text, then replaces
* original text node with highlighted one
* @param {Node} container
* @param {number} startOffset
* @param {number} endOffset
* @param {object} cssStyles
* @param {string[]} classNames
*/
export const highlightRangePart = (container, startOffset, endOffset, classNames) => {
let spanHighlight;
const text = container.textContent;
const parent = container.parentNode;
/**
* In case we're inside another region, move the selection outside
* to maintain proper nesting of highlight nodes
*/
if (
startOffset === 0 &&
container.length === endOffset &&
parent.classList.contains(classNames[0]) &&
parent.innerText === text
) {
const placeholder = container.ownerDocument.createElement("span");
const parentNode = parent.parentNode;
parentNode.replaceChild(placeholder, parent);
spanHighlight = wrapWithSpan(parent, classNames);
parentNode.replaceChild(spanHighlight, placeholder);
} else {
// Extract text content that matches offsets
const content = text.substring(startOffset, endOffset);
// Create text node that will be highlighted
const highlitedNode = container.ownerDocument.createTextNode(content);
// Split the container in three parts
const noseNode = container.cloneNode();
const tailNode = container.cloneNode();
// Add all the text BEFORE selection
noseNode.textContent = text.substring(0, startOffset);
tailNode.textContent = text.substring(endOffset, text.length);
// To avoid weird dom mutation we assemble replacement
// beforehands, it allows to replace original node
// directly without extra work
const textFragment = container.ownerDocument.createDocumentFragment();
spanHighlight = wrapWithSpan(highlitedNode, classNames);
if (noseNode.length) textFragment.appendChild(noseNode);
textFragment.appendChild(spanHighlight);
if (tailNode.length) textFragment.appendChild(tailNode);
// At this point we have three nodes in the tree
// one of them is our selected range
parent.replaceChild(textFragment, container);
}
return spanHighlight;
};
/**
* Wrap text node with stylized span
* @param {Text} node
* @param {string[]} classNames
* @param {object} cssStyles
* @param {string} [label]
* @todo all 2 usages of this method don't even get the label
*/
export const wrapWithSpan = (node, classNames, label) => {
const highlight = node.ownerDocument.createElement("span");
highlight.appendChild(node);
applySpanStyles(highlight, { classNames, label });
return highlight;
};
/**
* Apply classes and styles to a span. Optionally add or remove label
* @param {HTMLSpanElement} spanNode
* @param {{classNames?: string[], index?: number, label?: string}} param1
*/
export const applySpanStyles = (spanNode, { classNames, index, label }) => {
if (classNames) {
spanNode.className = "";
spanNode.classList.add(...classNames);
}
// label is array, string or null, so check for length
if (!label?.length) spanNode.removeAttribute("data-label");
else spanNode.setAttribute("data-label", label);
spanNode.setAttribute("data-index", index ? String(index) : "");
};
/**
* Look up all nodes between given `startNode` and `endNode` including ends
* @param {Node} startNode
* @param {Node} endNode
* @param {Node} root
*/
export const findNodesBetween = (startNode, endNode, root) => {
// Tree walker creates flat representation of DOM
// it allows to iterate over nodes more efficiently
// as we don't need to go up and down on a tree
// Also we iterate over Text nodes only natively. That's
// the only type of nodes we need to highlight.
// No additional checks, long live TreeWalker :)
const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_ALL);
// Flag indicates that we're somwhere between `startNode` and `endNode`
let inRange = false;
// Here we collect all nodes between start and end
// including ends
const nodes = [];
let { currentNode } = walker;
while (currentNode) {
if (currentNode === startNode) inRange = true;
if (inRange && currentNode.nodeType === Node.TEXT_NODE) nodes.push(currentNode);
if (inRange && currentNode === endNode) break;
currentNode = walker.nextNode();
}
return nodes;
};
/**
* Removes given range and restores DOM structure.
* @param {HTMLSpanElement[]} spans
*/
export const removeRange = (spans) => {
if (!spans) return;
spans.forEach((hl) => {
const fragment = hl.ownerDocument.createDocumentFragment();
const parent = hl.parentNode;
// Fill replacement fragment
// We need to copy childNodes because otherwise
// It will be changed during the loop
Array.from(hl.childNodes).forEach((node) => {
node.remove();
fragment.appendChild(node);
});
// Put back all text without spans
parent.replaceChild(fragment, hl);
// Join back all text nodes
Array.from(parent.childNodes).forEach((node) => {
const prev = node.previousSibling;
if (!isTextNode(prev) || !isTextNode(node)) return;
prev.data += node.data;
node.remove();
});
});
};
/**
* Fix position in node from chars count to code points count
* In python and other modern tools complex unicode symbols handled as code points, not UTF chars
* So for external usage js length should be converted to code points count
* string to array conversion splits string into code points array, that's the easiest way
* @param {{ node: Node, position: number }} container
* @return {{ node: Node, position: number }}
*/
export const charsToCodePoints = ({ node, position }) => {
const chars = node.textContent.substr(0, position);
const codePoints = [...chars].length;
return { node, position: codePoints };
};
/**
* Fix Range start/end offsets to code points count instead of chars count
* Alters given range
* @param {Range} range
* @return {Range} the same range
*/
export const fixCodePointsInRange = (range) => {
const start = charsToCodePoints({ node: range.startContainer, position: range.startOffset });
const end = charsToCodePoints({ node: range.endContainer, position: range.endOffset });
range.setStart(range.startContainer, start.position);
range.setEnd(range.endContainer, end.position);
return range;
};
/**
* Convert Range to global offsets relative to a root
* @param {Range} range
* @param {Node} root
*/
export const rangeToGlobalOffset = (range, root) => {
const globalOffsets = [
findGlobalOffset(range.startContainer, range.startOffset, root),
findGlobalOffset(range.endContainer, range.endOffset, root),
];
return globalOffsets;
};
/**
* Find text offset for given node and position relative to a root
* @param {Node} node
* @param {Number} position
* @param {Node} root
*/
const findGlobalOffset = (node, position, root) => {
const walker = (root.contentDocument ?? root.ownerDocument).createTreeWalker(root, NodeFilter.SHOW_ALL);
let globalPosition = 0;
let nodeReached = false;
let currentNode = walker.nextNode();
while (currentNode) {
// Indicates that we at or below desired node
nodeReached = nodeReached || node === currentNode;
const atTargetNode = node === currentNode || currentNode.contains(node);
const isText = currentNode.nodeType === Node.TEXT_NODE;
const isBR = currentNode.nodeName === "BR";
// Stop iteration
// Break if we passed target node and current node
// is not target, nor child of a target
if (nodeReached && atTargetNode === false) {
break;
}
if (isText || isBR) {
let length = isDefined(currentNode.length) ? [...currentNode.textContent].length : 1;
if (atTargetNode) {
length = Math.min(position, length);
}
globalPosition += length;
}
currentNode = walker.nextNode();
}
return globalPosition;
};
export const isSelectionContainsSpan = (spanNode) => {
const selection = window.getSelection();
const spanRange = document.createRange();
const textNode = spanNode.childNodes[0];
spanRange.setStart(textNode, 0);
spanRange.setEnd(textNode, textNode.length);
for (let i = selection.rangeCount; i--; ) {
const selRange = selection.getRangeAt(i);
if (
selRange.compareBoundaryPoints(Range.START_TO_START, spanRange) < 1 &&
selRange.compareBoundaryPoints(Range.END_TO_END, spanRange) > -1
)
return true;
}
return false;
};
|