* In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Th
(node, offsets)
| 6973 | */ |
| 6974 | |
| 6975 | function setOffsets(node, offsets) { |
| 6976 | var doc = node.ownerDocument || document; |
| 6977 | var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios. |
| 6978 | // (For instance: TinyMCE editor used in a list component that supports pasting to add more, |
| 6979 | // fails when pasting 100+ items) |
| 6980 | |
| 6981 | if (!win.getSelection) { |
| 6982 | return; |
| 6983 | } |
| 6984 | |
| 6985 | var selection = win.getSelection(); |
| 6986 | var length = node.textContent.length; |
| 6987 | var start = Math.min(offsets.start, length); |
| 6988 | var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. |
| 6989 | // Flip backward selections, so we can set with a single range. |
| 6990 | |
| 6991 | if (!selection.extend && start > end) { |
| 6992 | var temp = end; |
| 6993 | end = start; |
| 6994 | start = temp; |
| 6995 | } |
| 6996 | |
| 6997 | var startMarker = getNodeForCharacterOffset(node, start); |
| 6998 | var endMarker = getNodeForCharacterOffset(node, end); |
| 6999 | |
| 7000 | if (startMarker && endMarker) { |
| 7001 | if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) { |
| 7002 | return; |
| 7003 | } |
| 7004 | |
| 7005 | var range = doc.createRange(); |
| 7006 | range.setStart(startMarker.node, startMarker.offset); |
| 7007 | selection.removeAllRanges(); |
| 7008 | |
| 7009 | if (start > end) { |
| 7010 | selection.addRange(range); |
| 7011 | selection.extend(endMarker.node, endMarker.offset); |
| 7012 | } else { |
| 7013 | range.setEnd(endMarker.node, endMarker.offset); |
| 7014 | selection.addRange(range); |
| 7015 | } |
| 7016 | } |
| 7017 | } |
| 7018 | |
| 7019 | function isTextNode(node) { |
| 7020 | return node && node.nodeType === TEXT_NODE; |
no test coverage detected