(container: Element, node: Node, offset: number, isRangeEnd = false)
| 660 | } |
| 661 | |
| 662 | function getPosition(container: Element, node: Node, offset: number, isRangeEnd = false): Position { |
| 663 | if (node === container) { |
| 664 | return {index: offset, offset: 0}; |
| 665 | } |
| 666 | |
| 667 | let originalNode = node; |
| 668 | while (node.parentNode !== container) { |
| 669 | node = node.parentNode!; |
| 670 | } |
| 671 | |
| 672 | let index = indexOfNode(node); |
| 673 | if (node.nodeType === Node.ELEMENT_NODE) { |
| 674 | let tokenNode = node.childNodes[1]; |
| 675 | let atEnd: boolean; |
| 676 | let endOffset = 0; |
| 677 | if (originalNode === tokenNode) { |
| 678 | // Cursor is inside the token. |
| 679 | atEnd = isRangeEnd || offset > 0; |
| 680 | } else if (originalNode === node) { |
| 681 | // Cursor is inside the wrapper element. |
| 682 | atEnd = offset > 1; |
| 683 | } else { |
| 684 | // Cursor is on one of the zero width spaces. |
| 685 | atEnd = originalNode !== tokenNode.previousSibling; |
| 686 | // If the offset is greater than 1, the browser is trying to insert text into |
| 687 | // the zero width space node. This will actually end up in the next text node. |
| 688 | endOffset = atEnd && offset > 1 ? offset - 1 : 0; |
| 689 | } |
| 690 | |
| 691 | offset = atEnd ? (tokenNode?.textContent?.length ?? 0) : 0; |
| 692 | |
| 693 | // Several positions are equivalent due to the zero width spaces around tokens. |
| 694 | // Normalize offset to the end of the preceding text node, or the beginning of the following node. |
| 695 | if (offset === 0 && node.previousSibling?.nodeType === Node.TEXT_NODE) { |
| 696 | index--; |
| 697 | offset = node.previousSibling?.textContent?.length ?? 0; |
| 698 | } else if (atEnd) { |
| 699 | index++; |
| 700 | offset = endOffset; |
| 701 | } |
| 702 | } |
| 703 | return {index, offset}; |
| 704 | } |
| 705 | |
| 706 | let isProgrammaticSelectionChange = Symbol('isProgrammaticSelectionChange'); |
| 707 |
no test coverage detected