├── .gitignore ├── global.d.ts ├── package.json ├── tsconfig.json ├── CONTRIBUTING.md ├── README.md ├── demo.html ├── LICENSE └── shadow.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /global.d.ts: -------------------------------------------------------------------------------- 1 | declare interface Selection { 2 | modify( 3 | alter: 'move' | 'extend', 4 | direction: 'forward' | 'backward' | 'left' | 'right', 5 | granularity: 'character' | 'word' | 'sentence' | 'line' | 'paragraph' | 'lineboundary' | 'sentenceboundary' | 'paragraphboundary' | 'documentboundary', 6 | ): void; 7 | } 8 | 9 | declare interface Window { 10 | ShadyDOM?: {inUse: boolean}; 11 | } 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "shadow-selection-polyfill", 3 | "version": "1.1.0", 4 | "description": "Polyfill for shadowRoot.getSelection in Safari 10+", 5 | "main": "shadow.js", 6 | "jsnext:main": "shadow.js", 7 | "module": "shadow.js", 8 | "author": "The Chromium Authors", 9 | "bugs": { 10 | "url": "https://github.com/GoogleChromeLabs/shadow-selection-polyfill/issues" 11 | }, 12 | "homepage": "https://github.com/GoogleChromeLabs/shadow-selection-polyfill", 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/GoogleChromeLabs/shadow-selection-polyfill.git" 16 | }, 17 | "keywords": [ 18 | "shadowdom", 19 | "selection", 20 | "safari" 21 | ], 22 | "license": "Apache-2.0" 23 | } 24 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "checkJs": true, 4 | "noEmit": true, 5 | 6 | // if you'd like to warn if you're using modern features, change these 7 | // both to e.g., "es2017" 8 | "module": "esnext", 9 | "target": "esnext", 10 | 11 | // configure as you like: these are my preferred defaults! 12 | "strict": true, 13 | "skipLibCheck": true, 14 | "forceConsistentCasingInFileNames": true, 15 | 16 | // "strict" implies this, but you'll want to enable it when you're 17 | // ready: it's a huge reason your project will start complaining 18 | "noImplicitAny": false, 19 | }, 20 | "include": [ 21 | // include the JS files you'd like to check here 22 | "*.js", 23 | "global.d.ts", 24 | ], 25 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ⚠️ As of March 2021, it's not clear this polyfill will work on future versions of Safari. 2 | See [this issue](https://github.com/GoogleChromeLabs/shadow-selection-polyfill/issues/11) for an alternative implementation that provides selection on `contentEditable` areas. 3 | 4 | Polyfill for the `shadowRoot.getSelection()` method for Safari 10+. 5 | [See a demo](https://googlechromelabs.github.io/shadow-selection-polyfill/demo.html)! 6 | 7 | Safari supports `.attachShadow()` to create a Shadow Root, but does not support retrieving user selection within this root. 8 | You can safely use this code with other browsers (Firefox and Chromium), where it'll use the native version. 9 | 10 | ## Usage 11 | 12 | Include `./shadow.js` as an ES6 module, and call its `getRange` method, passing the shadow root you would like to check. 13 | This uses a native implementation where available (on Firefox and Chromium). 14 | 15 | Typically, you'd call this method in response to a `selectionchange` event, which is a global event on the document. 16 | However, this polyfill will cause additional `selectionchange` events to fire in the course of its work—possibly hundreds. 17 | Instead, you can listen to the `-shadow-selectionchange` event (exposed as `shadow.eventName`), which will safely fire only once. 18 | 19 | ```js 20 | import * as shadow from './node_modules/shadow-selection-polyfill/shadow.js'; 21 | 22 | const root = myElement.createShadowRoot({mode: 'open'}); 23 | root.innerHTML = `...`; 24 | 25 | document.addEventListener(shadow.eventName, () => { 26 | const range = shadow.getRange(root); 27 | if (range) { 28 | console.info('range selected within root element', range.toString()); 29 | } 30 | }); 31 | ``` 32 | 33 | Don't use this with `.attachShadow({mode: 'closed'})`, which is generally considered an antipattern anyway. 34 | 35 | ## Install 36 | 37 | Install via NPM as `shadow-selection-polyfill`, this has no dependencies. 38 | Depending on your transpiler, you might be able to include the polyfill with: 39 | 40 | ```js 41 | // naked imports 42 | import * as shadow from `shadow-selection-polyfill`; 43 | // require() compatibility 44 | const shadow = require('shadow-selection-polyfill'); 45 | ``` 46 | 47 | ## Implementation 48 | 49 | This polyfill basically rapidly splits `Text` nodes until it can find out just how many characters from the 'edge' of a Shadow Root that a user has selected. 50 | It uses this combined with a few other tricks to come up with a range. 51 | 52 | The algorithm is O(n) with respect to: 53 | 54 | * the maximum length of a text node that contains the start or end of a selection range 55 | * the depth of your nodes 56 | 57 | If speed is important to you, then keep individual text nodes small. 58 | 59 | ## Notes 60 | 61 | ### Native Versions 62 | 63 | As of February 2020, Firefox does not implement `getSelection()` on the Shadow Root ([issue](https://bugzilla.mozilla.org/show_bug.cgi?id=1430308)), but happily pierces the Shadow Root from the document globally. 64 | Chromium also implements `ShadowRoot.getSelection()` in an unofficial way. 65 | You can use this library to work around differences in browser implementations, as it'll use the native version when available. 66 | 67 | ### Other 68 | 69 | This isn't technically a polyfill, as it adds completely new functionality: it doesn't patch an existing method. 70 | There's nothing stopping us from emulating a faux-Selection, but it would probably make the code more complex than required. 71 | 72 | This is not an official Google product. 73 | -------------------------------------------------------------------------------- /demo.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 81 | 90 | 91 | 92 |

Shadow DOM selection page

93 | 94 |

This page demos detecting the selection range within a shadow root, for Safari, which does not yet support ShadowRoot.getSelection. 95 | (It still works in Chromium and Firefox, it just uses the native versions.)

96 | 97 |

Note that Chromium and Safari allow selection across Shadow DOM boundaries, sometimes with unpredictable results. 98 | Please provide feedback if you have opinions or real-world experience with this problem.

99 | 100 |

Selection

101 | 105 | 106 | 107 | 108 | 109 |
110 |
111 | Content is below me
112 |
113 |
114 | I'm some content in the DOM 115 |
116 | ^^ That's my host above 117 |
118 | 119 | 120 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /shadow.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 | * use this file except in compliance with the License. You may obtain a copy of 6 | * the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations under 14 | * the License. 15 | */ 16 | 17 | const debug = true; 18 | 19 | const hasShadow = 'attachShadow' in Element.prototype && 'getRootNode' in Element.prototype; 20 | const hasSelection = !!(hasShadow && document.createElement('div').attachShadow({ mode: 'open' }).getSelection); 21 | const hasShady = window.ShadyDOM && window.ShadyDOM.inUse; 22 | const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) || 23 | /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; 24 | const useDocument = !hasShadow || hasShady || (!hasSelection && !isSafari); 25 | 26 | const invalidPartialElements = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|script|source|style|template|track|wbr)$/; 27 | 28 | export const eventName = '-shadow-selectionchange'; 29 | 30 | 31 | const validNodeTypes = [Node.ELEMENT_NODE, Node.TEXT_NODE, Node.DOCUMENT_FRAGMENT_NODE]; 32 | function isValidNode(node) { 33 | return validNodeTypes.includes(node.nodeType); 34 | } 35 | 36 | 37 | /** 38 | * @param {Selection} s selection to use 39 | * @param {Node|null} node to find caret position within a shadow root 40 | * @return {Node|ShadowRoot|null} 41 | */ 42 | export function findCaretFocus(s, node) { 43 | if (!node) { 44 | return null; 45 | } 46 | 47 | /** @type {ShadowRoot[]} */ 48 | const pending = []; 49 | const pushAll = (nodeList) => { 50 | for (let i = 0; i < nodeList.length; ++i) { 51 | if (nodeList[i].shadowRoot) { 52 | pending.push(nodeList[i].shadowRoot); 53 | } 54 | } 55 | }; 56 | 57 | // We're told by Safari that a node containing a child with a Shadow Root is selected, but check 58 | // the node directly too (just in case they change their mind later). 59 | if (node instanceof Element && node.shadowRoot) { 60 | pending.push(node.shadowRoot); 61 | } 62 | pushAll(node.childNodes); 63 | 64 | for (;;) { 65 | const root = pending.shift(); 66 | if (!root) { 67 | break; 68 | } 69 | 70 | for (let i = 0; i < root.childNodes.length; ++i) { 71 | if (s.containsNode(root.childNodes[i], true)) { 72 | return root; 73 | } 74 | } 75 | 76 | // The selection must be inside a further Shadow Root, but there's no good way to get a list of 77 | // them. Safari won't tell you what regular node contains the root which has a selection. So, 78 | // unfortunately if you stack them this will be slow(-ish). 79 | pushAll(root.querySelectorAll('*')); 80 | } 81 | 82 | return null; 83 | } 84 | 85 | 86 | /** 87 | * @param {Selection} s 88 | * @param {Node} parentNode 89 | * @param {boolean} isLeft 90 | * @return {Node} 91 | */ 92 | function findNode(s, parentNode, isLeft) { 93 | const nodes = parentNode.childNodes; 94 | if (!nodes) { 95 | return parentNode; // found it, probably text 96 | } 97 | 98 | for (let i = 0; i < nodes.length; ++i) { 99 | const j = isLeft ? i : (nodes.length - 1 - i); 100 | const childNode = nodes[j]; 101 | if (!isValidNode(childNode)) { 102 | continue; 103 | } 104 | 105 | debug && console.debug('checking child', childNode, 'IsLeft', isLeft); 106 | if (s.containsNode(childNode, true)) { 107 | if (s.containsNode(childNode, false)) { 108 | debug && console.info('found child', childNode); 109 | return childNode; 110 | } 111 | // Special-case elements that cannot have feasible children. 112 | const localName = childNode instanceof Element ? childNode.localName : ''; 113 | if (!localName || !invalidPartialElements.exec(localName)) { 114 | debug && console.info('descending child', childNode); 115 | return findNode(s, childNode, isLeft); 116 | } 117 | } 118 | debug && console.info(parentNode, 'does NOT contain', childNode); 119 | } 120 | return parentNode; 121 | } 122 | 123 | 124 | let recentCaretRange = {node: null, offset: -1}; 125 | 126 | 127 | (function() { 128 | if (hasSelection || useDocument) { 129 | // getSelection exists or document API can be used 130 | document.addEventListener('selectionchange', (ev) => { 131 | document.dispatchEvent(new CustomEvent(eventName)); 132 | }); 133 | return () => {}; 134 | } 135 | 136 | let withinInternals = false; 137 | 138 | document.addEventListener('selectionchange', (ev) => { 139 | if (withinInternals) { 140 | return; 141 | } 142 | 143 | withinInternals = true; 144 | 145 | const s = window.getSelection(); 146 | if (s && s.type === 'Caret') { 147 | const root = findCaretFocus(s, s.anchorNode); 148 | if (root instanceof window.ShadowRoot) { 149 | const range = getRange(root); 150 | if (range) { 151 | const node = range.startContainer; 152 | const offset = range.startOffset; 153 | recentCaretRange = {node, offset}; 154 | } 155 | } 156 | } 157 | 158 | document.dispatchEvent(new CustomEvent('-shadow-selectionchange')); 159 | window.requestAnimationFrame(() => { 160 | withinInternals = false; 161 | }); 162 | }); 163 | })(); 164 | 165 | 166 | /** 167 | * @param {Selection} s the window selection to use 168 | * @param {Node?} node the node to walk from 169 | * @param {boolean} walkForward should this walk in natural direction 170 | * @return {boolean} whether the selection contains the following node (even partially) 171 | */ 172 | function containsNextElement(s, node, walkForward) { 173 | const start = node; 174 | while (node = walkFromNode(node, walkForward)) { 175 | // walking (left) can contain our own parent, which we don't want 176 | if (!node.contains(start)) { 177 | break; 178 | } 179 | } 180 | if (!node) { 181 | return false; 182 | } 183 | // we look for Element as .containsNode says true for _every_ text node, and we only care about 184 | // elements themselves 185 | return node instanceof Element && s.containsNode(node, true); 186 | } 187 | 188 | 189 | /** 190 | * @param {Selection} s the window selection to use 191 | * @param {Node} leftNode the left node 192 | * @param {Node} rightNode the right node 193 | * @return {boolean|undefined} whether this has natural direction 194 | */ 195 | function getSelectionDirection(s, leftNode, rightNode) { 196 | if (s.type !== 'Range') { 197 | return undefined; // no direction 198 | } 199 | const measure = () => s.toString().length; 200 | 201 | const initialSize = measure(); 202 | debug && console.info(`initial selection: "${s.toString()}"`) 203 | 204 | let updatedSize; 205 | 206 | // Try extending forward and seeing what happens. 207 | s.modify('extend', 'forward', 'character'); 208 | updatedSize = measure(); 209 | debug && console.info(`forward selection: "${s.toString()}"`) 210 | 211 | if (updatedSize > initialSize || containsNextElement(s, rightNode, true)) { 212 | debug && console.info('got forward >, moving right') 213 | s.modify('extend', 'backward', 'character'); 214 | return true; 215 | } else if (updatedSize < initialSize || !s.containsNode(leftNode)) { 216 | debug && console.info('got forward <, moving left') 217 | s.modify('extend', 'backward', 'character'); 218 | return false; 219 | } 220 | 221 | // Maybe we were at the end of something. Extend backwards instead. 222 | s.modify('extend', 'backward', 'character'); 223 | updatedSize = measure(); 224 | debug && console.info(`backward selection: "${s.toString()}"`) 225 | 226 | if (updatedSize > initialSize || containsNextElement(s, leftNode, false)) { 227 | debug && console.info('got backwards >, moving left') 228 | s.modify('extend', 'forward', 'character'); 229 | return false; 230 | } else if (updatedSize < initialSize || !s.containsNode(rightNode)) { 231 | debug && console.info('got backwards <, moving right') 232 | s.modify('extend', 'forward', 'character'); 233 | return true; 234 | } 235 | 236 | // This is likely a select-all. 237 | return undefined; 238 | } 239 | 240 | /** 241 | * Returns the next valid node (element or text). This is needed as Safari doesn't support 242 | * TreeWalker inside Shadow DOM. Don't escape shadow roots. 243 | * 244 | * @param {Node?} node to start from 245 | * @param {boolean} walkForward should this walk in natural direction 246 | * @return {Node?} node found, if any 247 | */ 248 | function walkFromNode(node, walkForward) { 249 | if (!walkForward && node) { 250 | return node.previousSibling || node.parentNode || null; 251 | } 252 | while (node) { 253 | if (node.nextSibling) { 254 | return node.nextSibling; 255 | } 256 | node = node.parentNode; 257 | } 258 | return null; 259 | } 260 | 261 | 262 | const cachedRange = new Map(); 263 | export function getRange(root) { 264 | if (hasShady) { 265 | const s = document.getSelection(); 266 | return s && s.rangeCount ? s.getRangeAt(0) : null; 267 | } else if (useDocument) { 268 | // Document pierces Shadow Root for selection, so actively filter it down to the right node. 269 | // This is only for Firefox, which does not allow selection across Shadow Root boundaries. 270 | const s = document.getSelection(); 271 | if (s && s.containsNode(root, true)) { 272 | return s.getRangeAt(0); 273 | } 274 | return null; 275 | } else if (hasSelection) { 276 | const s = root.getSelection(); 277 | return s.rangeCount ? s.getRangeAt(0) : null; 278 | } 279 | 280 | const thisFrame = cachedRange.get(root); 281 | if (thisFrame) { 282 | return thisFrame; 283 | } 284 | 285 | const result = internalGetShadowSelection(root); 286 | 287 | cachedRange.set(root, result.range); 288 | window.setTimeout(() => { 289 | cachedRange.delete(root); 290 | }, 0); 291 | debug && console.debug('getRange got', result); 292 | return result.range; 293 | } 294 | 295 | 296 | function internalGetShadowSelection(root) { 297 | // nb. We used to check whether the selection contained the host, but this broke in Safari 13. 298 | // This is "nicely formatted" whitespace as per the browser's renderer. This is fine, and we only 299 | // provide selection information at this granularity. 300 | const s = window.getSelection(); 301 | 302 | if (!s || s.type === 'None') { 303 | return {range: null, type: 'none'}; 304 | } else if (!(s.type === 'Caret' || s.type === 'Range')) { 305 | throw new TypeError('unexpected type: ' + s.type); 306 | } 307 | 308 | const leftNode = findNode(s, root, true); 309 | if (leftNode === root) { 310 | debug && console.warn('internal selection bail because leftNode=root'); 311 | return {range: null, mode: 'none'}; 312 | } 313 | 314 | const range = document.createRange(); 315 | 316 | let rightNode = null; 317 | let isNaturalDirection = undefined; 318 | if (s.type === 'Range') { 319 | rightNode = findNode(s, root, false); // get right node here _before_ getSelectionDirection 320 | isNaturalDirection = getSelectionDirection(s, leftNode, rightNode); 321 | 322 | // isNaturalDirection means "going right" 323 | 324 | if (isNaturalDirection === undefined) { 325 | // This occurs when we can't move because we can't extend left or right to measure the 326 | // direction we're moving in... because it's the entire range. Hooray! 327 | range.setStart(leftNode, 0); 328 | 329 | let end = rightNode.childNodes.length; 330 | if (rightNode instanceof Text) { 331 | end = rightNode.length; 332 | } 333 | range.setEnd(rightNode, end); 334 | return {range, mode: 'all'}; 335 | } 336 | } 337 | 338 | const initialSize = s.toString().length; 339 | 340 | // Dumbest possible approach: remove characters from left side until no more selection, 341 | // re-add. 342 | 343 | // Try right side first, as we can trim characters until selection gets shorter. 344 | 345 | let leftOffset = 0; 346 | let rightOffset = 0; 347 | 348 | if (rightNode === null) { 349 | // This is a caret selection, do nothing. 350 | } else if (rightNode.nodeType === Node.TEXT_NODE) { 351 | const textRightNode = /** @type {Text} */ (rightNode); 352 | 353 | const rightText = textRightNode.textContent || ''; 354 | const existingNextSibling = textRightNode.nextSibling; 355 | 356 | for (let i = rightText.length - 1; i >= 0; --i) { 357 | textRightNode.splitText(i); 358 | const updatedSize = s.toString().length; 359 | if (updatedSize !== initialSize) { 360 | rightOffset = i + 1; 361 | break; 362 | } 363 | } 364 | 365 | // We don't use .normalize() here, as the user might already have a weird node arrangement 366 | // they need to maintain. 367 | textRightNode.insertData(textRightNode.length, rightText.substr(textRightNode.length)); 368 | while (textRightNode.nextSibling !== existingNextSibling) { 369 | const s = /** @type {ChildNode} */ (textRightNode.nextSibling); 370 | s.remove(); 371 | } 372 | } 373 | 374 | if (leftNode.nodeType === Node.TEXT_NODE) { 375 | const textLeftNode = /** @type {Text} */ (leftNode); 376 | 377 | if (textLeftNode !== rightNode) { 378 | // If we're at the end of a text node, it's impossible to extend the selection, so add an 379 | // extra character to select (that we delete later). 380 | textLeftNode.appendData('?'); 381 | s.collapseToStart(); 382 | s.modify('extend', 'right', 'character'); 383 | } 384 | 385 | const leftText = textLeftNode.textContent || ''; 386 | const existingNextSibling = textLeftNode.nextSibling; 387 | 388 | const start = (textLeftNode === rightNode ? rightOffset : leftText.length - 1); 389 | 390 | for (let i = start; i >= 0; --i) { 391 | textLeftNode.splitText(i); 392 | if (s.toString() === '') { 393 | leftOffset = i; 394 | break; 395 | } 396 | } 397 | 398 | // As above, we don't want to use .normalize(). 399 | textLeftNode.insertData(textLeftNode.length, leftText.substr(textLeftNode.length)); 400 | while (textLeftNode.nextSibling !== existingNextSibling) { 401 | const s = /** @type {ChildNode} */ (textLeftNode.nextSibling); 402 | s.remove(); 403 | } 404 | 405 | if (leftNode !== rightNode) { 406 | textLeftNode.deleteData(textLeftNode.length - 1, 1); 407 | } 408 | 409 | if (rightNode === null) { 410 | rightNode = leftNode; 411 | rightOffset = leftOffset; 412 | } 413 | 414 | } else if (rightNode === null) { 415 | rightNode = leftNode; 416 | } 417 | 418 | // Work around common browser bug. Single character selction is always seen as 'forward'. Check 419 | // if it's actually supposed to be backward. 420 | if (initialSize === 1 && recentCaretRange && recentCaretRange.node === leftNode) { 421 | if (recentCaretRange.offset > leftOffset && isNaturalDirection) { 422 | isNaturalDirection = false; 423 | } 424 | } 425 | 426 | if (isNaturalDirection === true) { 427 | s.collapse(leftNode, leftOffset); 428 | s.extend(rightNode, rightOffset); 429 | } else if (isNaturalDirection === false) { 430 | s.collapse(rightNode, rightOffset); 431 | s.extend(leftNode, leftOffset); 432 | } else { 433 | s.setPosition(leftNode, leftOffset); 434 | } 435 | 436 | range.setStart(leftNode, leftOffset); 437 | range.setEnd(rightNode, rightOffset); 438 | return {range, mode: 'normal'}; 439 | } 440 | --------------------------------------------------------------------------------