This repository has been archived by the owner on Oct 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathshadow.js
439 lines (366 loc) · 13.5 KB
/
shadow.js
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
/**
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
const debug = true;
const hasShadow = 'attachShadow' in Element.prototype && 'getRootNode' in Element.prototype;
const hasSelection = !!(hasShadow && document.createElement('div').attachShadow({ mode: 'open' }).getSelection);
const hasShady = window.ShadyDOM && window.ShadyDOM.inUse;
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) ||
/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
const useDocument = !hasShadow || hasShady || (!hasSelection && !isSafari);
const invalidPartialElements = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|script|source|style|template|track|wbr)$/;
export const eventName = '-shadow-selectionchange';
const validNodeTypes = [Node.ELEMENT_NODE, Node.TEXT_NODE, Node.DOCUMENT_FRAGMENT_NODE];
function isValidNode(node) {
return validNodeTypes.includes(node.nodeType);
}
/**
* @param {Selection} s selection to use
* @param {Node|null} node to find caret position within a shadow root
* @return {Node|ShadowRoot|null}
*/
export function findCaretFocus(s, node) {
if (!node) {
return null;
}
/** @type {ShadowRoot[]} */
const pending = [];
const pushAll = (nodeList) => {
for (let i = 0; i < nodeList.length; ++i) {
if (nodeList[i].shadowRoot) {
pending.push(nodeList[i].shadowRoot);
}
}
};
// We're told by Safari that a node containing a child with a Shadow Root is selected, but check
// the node directly too (just in case they change their mind later).
if (node instanceof Element && node.shadowRoot) {
pending.push(node.shadowRoot);
}
pushAll(node.childNodes);
for (;;) {
const root = pending.shift();
if (!root) {
break;
}
for (let i = 0; i < root.childNodes.length; ++i) {
if (s.containsNode(root.childNodes[i], true)) {
return root;
}
}
// The selection must be inside a further Shadow Root, but there's no good way to get a list of
// them. Safari won't tell you what regular node contains the root which has a selection. So,
// unfortunately if you stack them this will be slow(-ish).
pushAll(root.querySelectorAll('*'));
}
return null;
}
/**
* @param {Selection} s
* @param {Node} parentNode
* @param {boolean} isLeft
* @return {Node}
*/
function findNode(s, parentNode, isLeft) {
const nodes = parentNode.childNodes;
if (!nodes) {
return parentNode; // found it, probably text
}
for (let i = 0; i < nodes.length; ++i) {
const j = isLeft ? i : (nodes.length - 1 - i);
const childNode = nodes[j];
if (!isValidNode(childNode)) {
continue;
}
debug && console.debug('checking child', childNode, 'IsLeft', isLeft);
if (s.containsNode(childNode, true)) {
if (s.containsNode(childNode, false)) {
debug && console.info('found child', childNode);
return childNode;
}
// Special-case elements that cannot have feasible children.
const localName = childNode instanceof Element ? childNode.localName : '';
if (!localName || !invalidPartialElements.exec(localName)) {
debug && console.info('descending child', childNode);
return findNode(s, childNode, isLeft);
}
}
debug && console.info(parentNode, 'does NOT contain', childNode);
}
return parentNode;
}
let recentCaretRange = {node: null, offset: -1};
(function() {
if (hasSelection || useDocument) {
// getSelection exists or document API can be used
document.addEventListener('selectionchange', (ev) => {
document.dispatchEvent(new CustomEvent(eventName));
});
return () => {};
}
let withinInternals = false;
document.addEventListener('selectionchange', (ev) => {
if (withinInternals) {
return;
}
withinInternals = true;
const s = window.getSelection();
if (s && s.type === 'Caret') {
const root = findCaretFocus(s, s.anchorNode);
if (root instanceof window.ShadowRoot) {
const range = getRange(root);
if (range) {
const node = range.startContainer;
const offset = range.startOffset;
recentCaretRange = {node, offset};
}
}
}
document.dispatchEvent(new CustomEvent('-shadow-selectionchange'));
window.requestAnimationFrame(() => {
withinInternals = false;
});
});
})();
/**
* @param {Selection} s the window selection to use
* @param {Node?} node the node to walk from
* @param {boolean} walkForward should this walk in natural direction
* @return {boolean} whether the selection contains the following node (even partially)
*/
function containsNextElement(s, node, walkForward) {
const start = node;
while (node = walkFromNode(node, walkForward)) {
// walking (left) can contain our own parent, which we don't want
if (!node.contains(start)) {
break;
}
}
if (!node) {
return false;
}
// we look for Element as .containsNode says true for _every_ text node, and we only care about
// elements themselves
return node instanceof Element && s.containsNode(node, true);
}
/**
* @param {Selection} s the window selection to use
* @param {Node} leftNode the left node
* @param {Node} rightNode the right node
* @return {boolean|undefined} whether this has natural direction
*/
function getSelectionDirection(s, leftNode, rightNode) {
if (s.type !== 'Range') {
return undefined; // no direction
}
const measure = () => s.toString().length;
const initialSize = measure();
debug && console.info(`initial selection: "${s.toString()}"`)
let updatedSize;
// Try extending forward and seeing what happens.
s.modify('extend', 'forward', 'character');
updatedSize = measure();
debug && console.info(`forward selection: "${s.toString()}"`)
if (updatedSize > initialSize || containsNextElement(s, rightNode, true)) {
debug && console.info('got forward >, moving right')
s.modify('extend', 'backward', 'character');
return true;
} else if (updatedSize < initialSize || !s.containsNode(leftNode)) {
debug && console.info('got forward <, moving left')
s.modify('extend', 'backward', 'character');
return false;
}
// Maybe we were at the end of something. Extend backwards instead.
s.modify('extend', 'backward', 'character');
updatedSize = measure();
debug && console.info(`backward selection: "${s.toString()}"`)
if (updatedSize > initialSize || containsNextElement(s, leftNode, false)) {
debug && console.info('got backwards >, moving left')
s.modify('extend', 'forward', 'character');
return false;
} else if (updatedSize < initialSize || !s.containsNode(rightNode)) {
debug && console.info('got backwards <, moving right')
s.modify('extend', 'forward', 'character');
return true;
}
// This is likely a select-all.
return undefined;
}
/**
* Returns the next valid node (element or text). This is needed as Safari doesn't support
* TreeWalker inside Shadow DOM. Don't escape shadow roots.
*
* @param {Node?} node to start from
* @param {boolean} walkForward should this walk in natural direction
* @return {Node?} node found, if any
*/
function walkFromNode(node, walkForward) {
if (!walkForward && node) {
return node.previousSibling || node.parentNode || null;
}
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
return null;
}
const cachedRange = new Map();
export function getRange(root) {
if (hasShady) {
const s = document.getSelection();
return s && s.rangeCount ? s.getRangeAt(0) : null;
} else if (useDocument) {
// Document pierces Shadow Root for selection, so actively filter it down to the right node.
// This is only for Firefox, which does not allow selection across Shadow Root boundaries.
const s = document.getSelection();
if (s && s.containsNode(root, true)) {
return s.getRangeAt(0);
}
return null;
} else if (hasSelection) {
const s = root.getSelection();
return s.rangeCount ? s.getRangeAt(0) : null;
}
const thisFrame = cachedRange.get(root);
if (thisFrame) {
return thisFrame;
}
const result = internalGetShadowSelection(root);
cachedRange.set(root, result.range);
window.setTimeout(() => {
cachedRange.delete(root);
}, 0);
debug && console.debug('getRange got', result);
return result.range;
}
function internalGetShadowSelection(root) {
// nb. We used to check whether the selection contained the host, but this broke in Safari 13.
// This is "nicely formatted" whitespace as per the browser's renderer. This is fine, and we only
// provide selection information at this granularity.
const s = window.getSelection();
if (!s || s.type === 'None') {
return {range: null, type: 'none'};
} else if (!(s.type === 'Caret' || s.type === 'Range')) {
throw new TypeError('unexpected type: ' + s.type);
}
const leftNode = findNode(s, root, true);
if (leftNode === root) {
debug && console.warn('internal selection bail because leftNode=root');
return {range: null, mode: 'none'};
}
const range = document.createRange();
let rightNode = null;
let isNaturalDirection = undefined;
if (s.type === 'Range') {
rightNode = findNode(s, root, false); // get right node here _before_ getSelectionDirection
isNaturalDirection = getSelectionDirection(s, leftNode, rightNode);
// isNaturalDirection means "going right"
if (isNaturalDirection === undefined) {
// This occurs when we can't move because we can't extend left or right to measure the
// direction we're moving in... because it's the entire range. Hooray!
range.setStart(leftNode, 0);
let end = rightNode.childNodes.length;
if (rightNode instanceof Text) {
end = rightNode.length;
}
range.setEnd(rightNode, end);
return {range, mode: 'all'};
}
}
const initialSize = s.toString().length;
// Dumbest possible approach: remove characters from left side until no more selection,
// re-add.
// Try right side first, as we can trim characters until selection gets shorter.
let leftOffset = 0;
let rightOffset = 0;
if (rightNode === null) {
// This is a caret selection, do nothing.
} else if (rightNode.nodeType === Node.TEXT_NODE) {
const textRightNode = /** @type {Text} */ (rightNode);
const rightText = textRightNode.textContent || '';
const existingNextSibling = textRightNode.nextSibling;
for (let i = rightText.length - 1; i >= 0; --i) {
textRightNode.splitText(i);
const updatedSize = s.toString().length;
if (updatedSize !== initialSize) {
rightOffset = i + 1;
break;
}
}
// We don't use .normalize() here, as the user might already have a weird node arrangement
// they need to maintain.
textRightNode.insertData(textRightNode.length, rightText.substr(textRightNode.length));
while (textRightNode.nextSibling !== existingNextSibling) {
const s = /** @type {ChildNode} */ (textRightNode.nextSibling);
s.remove();
}
}
if (leftNode.nodeType === Node.TEXT_NODE) {
const textLeftNode = /** @type {Text} */ (leftNode);
if (textLeftNode !== rightNode) {
// If we're at the end of a text node, it's impossible to extend the selection, so add an
// extra character to select (that we delete later).
textLeftNode.appendData('?');
s.collapseToStart();
s.modify('extend', 'right', 'character');
}
const leftText = textLeftNode.textContent || '';
const existingNextSibling = textLeftNode.nextSibling;
const start = (textLeftNode === rightNode ? rightOffset : leftText.length - 1);
for (let i = start; i >= 0; --i) {
textLeftNode.splitText(i);
if (s.toString() === '') {
leftOffset = i;
break;
}
}
// As above, we don't want to use .normalize().
textLeftNode.insertData(textLeftNode.length, leftText.substr(textLeftNode.length));
while (textLeftNode.nextSibling !== existingNextSibling) {
const s = /** @type {ChildNode} */ (textLeftNode.nextSibling);
s.remove();
}
if (leftNode !== rightNode) {
textLeftNode.deleteData(textLeftNode.length - 1, 1);
}
if (rightNode === null) {
rightNode = leftNode;
rightOffset = leftOffset;
}
} else if (rightNode === null) {
rightNode = leftNode;
}
// Work around common browser bug. Single character selction is always seen as 'forward'. Check
// if it's actually supposed to be backward.
if (initialSize === 1 && recentCaretRange && recentCaretRange.node === leftNode) {
if (recentCaretRange.offset > leftOffset && isNaturalDirection) {
isNaturalDirection = false;
}
}
if (isNaturalDirection === true) {
s.collapse(leftNode, leftOffset);
s.extend(rightNode, rightOffset);
} else if (isNaturalDirection === false) {
s.collapse(rightNode, rightOffset);
s.extend(leftNode, leftOffset);
} else {
s.setPosition(leftNode, leftOffset);
}
range.setStart(leftNode, leftOffset);
range.setEnd(rightNode, rightOffset);
return {range, mode: 'normal'};
}