-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
dom.js
668 lines (567 loc) · 18.7 KB
/
dom.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
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
668
/**
* External dependencies
*/
import { includes } from 'lodash';
/**
* Browser dependencies
*/
const { getComputedStyle } = window;
const {
TEXT_NODE,
ELEMENT_NODE,
DOCUMENT_POSITION_PRECEDING,
DOCUMENT_POSITION_FOLLOWING,
} = window.Node;
/**
* Returns true if the given selection object is in the forward direction, or
* false otherwise.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
*
* @param {Selection} selection Selection object to check.
*
* @return {boolean} Whether the selection is forward.
*/
function isSelectionForward( selection ) {
const {
anchorNode,
focusNode,
anchorOffset,
focusOffset,
} = selection;
const position = anchorNode.compareDocumentPosition( focusNode );
// Disable reason: `Node#compareDocumentPosition` returns a bitmask value,
// so bitwise operators are intended.
/* eslint-disable no-bitwise */
// Compare whether anchor node precedes focus node. If focus node (where
// end of selection occurs) is after the anchor node, it is forward.
if ( position & DOCUMENT_POSITION_PRECEDING ) {
return false;
}
if ( position & DOCUMENT_POSITION_FOLLOWING ) {
return true;
}
/* eslint-enable no-bitwise */
// `compareDocumentPosition` returns 0 when passed the same node, in which
// case compare offsets.
if ( position === 0 ) {
return anchorOffset <= focusOffset;
}
// This should never be reached, but return true as default case.
return true;
}
/**
* Check whether the selection is horizontally at the edge of the container.
*
* @param {Element} container Focusable element.
* @param {boolean} isReverse Set to true to check left, false for right.
*
* @return {boolean} True if at the horizontal edge, false if not.
*/
export function isHorizontalEdge( container, isReverse ) {
if ( includes( [ 'INPUT', 'TEXTAREA' ], container.tagName ) ) {
if ( container.selectionStart !== container.selectionEnd ) {
return false;
}
if ( isReverse ) {
return container.selectionStart === 0;
}
return container.value.length === container.selectionStart;
}
if ( ! container.isContentEditable ) {
return true;
}
const selection = window.getSelection();
// Create copy of range for setting selection to find effective offset.
const range = selection.getRangeAt( 0 ).cloneRange();
// Collapse in direction of selection.
if ( ! selection.isCollapsed ) {
range.collapse( ! isSelectionForward( selection ) );
}
let node = range.startContainer;
let extentOffset;
if ( isReverse ) {
// When in reverse, range node should be first.
extentOffset = 0;
} else if ( node.nodeValue ) {
// Otherwise, vary by node type. A text node has no children. Its range
// offset reflects its position in nodeValue.
//
// "If the startContainer is a Node of type Text, Comment, or
// CDATASection, then the offset is the number of characters from the
// start of the startContainer to the boundary point of the Range."
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Range/startOffset
// See: https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeValue
extentOffset = node.nodeValue.length;
} else {
// "For other Node types, the startOffset is the number of child nodes
// between the start of the startContainer and the boundary point of
// the Range."
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Range/startOffset
extentOffset = node.childNodes.length;
}
// Offset of range should be at expected extent.
const position = isReverse ? 'start' : 'end';
const offset = range[ `${ position }Offset` ];
if ( offset !== extentOffset ) {
return false;
}
// If confirmed to be at extent, traverse up through DOM, verifying that
// the node is at first or last child for reverse or forward respectively
// (ignoring empty text nodes). Continue until container is reached.
const order = isReverse ? 'previous' : 'next';
while ( node !== container ) {
let next = node[ `${ order }Sibling` ];
// Skip over empty text nodes.
while ( next && next.nodeType === TEXT_NODE && next.data === '' ) {
next = next[ `${ order }Sibling` ];
}
if ( next ) {
return false;
}
node = node.parentNode;
}
// If reached, range is assumed to be at edge.
return true;
}
/**
* Check whether the selection is vertically at the edge of the container.
*
* @param {Element} container Focusable element.
* @param {boolean} isReverse Set to true to check top, false for bottom.
*
* @return {boolean} True if at the edge, false if not.
*/
export function isVerticalEdge( container, isReverse ) {
if ( includes( [ 'INPUT', 'TEXTAREA' ], container.tagName ) ) {
return isHorizontalEdge( container, isReverse );
}
if ( ! container.isContentEditable ) {
return true;
}
const selection = window.getSelection();
const range = selection.rangeCount ? selection.getRangeAt( 0 ) : null;
if ( ! range ) {
return false;
}
const rangeRect = getRectangleFromRange( range );
if ( ! rangeRect ) {
return false;
}
const buffer = rangeRect.height / 2;
const editableRect = container.getBoundingClientRect();
// Too low.
if ( isReverse && rangeRect.top - buffer > editableRect.top ) {
return false;
}
// Too high.
if ( ! isReverse && rangeRect.bottom + buffer < editableRect.bottom ) {
return false;
}
return true;
}
/**
* Get the rectangle of a given Range.
*
* @param {Range} range The range.
*
* @return {DOMRect} The rectangle.
*/
export function getRectangleFromRange( range ) {
// For uncollapsed ranges, get the rectangle that bounds the contents of the
// range; this a rectangle enclosing the union of the bounding rectangles
// for all the elements in the range.
if ( ! range.collapsed ) {
return range.getBoundingClientRect();
}
let rect = range.getClientRects()[ 0 ];
// If the collapsed range starts (and therefore ends) at an element node,
// `getClientRects` can be empty in some browsers. This can be resolved
// by adding a temporary text node with zero-width space to the range.
//
// See: https://stackoverflow.com/a/6847328/995445
if ( ! rect ) {
const padNode = document.createTextNode( '\u200b' );
range.insertNode( padNode );
rect = range.getClientRects()[ 0 ];
padNode.parentNode.removeChild( padNode );
}
return rect;
}
/**
* Get the rectangle for the selection in a container.
*
* @param {Element} container Editable container.
*
* @return {?DOMRect} The rectangle.
*/
export function computeCaretRect( container ) {
if ( ! container.isContentEditable ) {
return;
}
const selection = window.getSelection();
const range = selection.rangeCount ? selection.getRangeAt( 0 ) : null;
if ( ! range ) {
return;
}
return getRectangleFromRange( range );
}
/**
* Places the caret at start or end of a given element.
*
* @param {Element} container Focusable element.
* @param {boolean} isReverse True for end, false for start.
*/
export function placeCaretAtHorizontalEdge( container, isReverse ) {
if ( ! container ) {
return;
}
if ( includes( [ 'INPUT', 'TEXTAREA' ], container.tagName ) ) {
container.focus();
if ( isReverse ) {
container.selectionStart = container.value.length;
container.selectionEnd = container.value.length;
} else {
container.selectionStart = 0;
container.selectionEnd = 0;
}
return;
}
container.focus();
if ( ! container.isContentEditable ) {
return;
}
// Select on extent child of the container, not the container itself. This
// avoids the selection always being `endOffset` of 1 when placed at end,
// where `startContainer`, `endContainer` would always be container itself.
const rangeTarget = container[ isReverse ? 'lastChild' : 'firstChild' ];
// If no range target, it implies that the container is empty. Focusing is
// sufficient for caret to be placed correctly.
if ( ! rangeTarget ) {
return;
}
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents( rangeTarget );
range.collapse( ! isReverse );
selection.removeAllRanges();
selection.addRange( range );
}
/**
* Polyfill.
* Get a collapsed range for a given point.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Document/caretRangeFromPoint
*
* @param {Document} doc The document of the range.
* @param {number} x Horizontal position within the current viewport.
* @param {number} y Vertical position within the current viewport.
*
* @return {?Range} The best range for the given point.
*/
function caretRangeFromPoint( doc, x, y ) {
if ( doc.caretRangeFromPoint ) {
return doc.caretRangeFromPoint( x, y );
}
if ( ! doc.caretPositionFromPoint ) {
return null;
}
const point = doc.caretPositionFromPoint( x, y );
// If x or y are negative, outside viewport, or there is no text entry node.
// https://developer.mozilla.org/en-US/docs/Web/API/Document/caretRangeFromPoint
if ( ! point ) {
return null;
}
const range = doc.createRange();
range.setStart( point.offsetNode, point.offset );
range.collapse( true );
return range;
}
/**
* Get a collapsed range for a given point.
* Gives the container a temporary high z-index (above any UI).
* This is preferred over getting the UI nodes and set styles there.
*
* @param {Document} doc The document of the range.
* @param {number} x Horizontal position within the current viewport.
* @param {number} y Vertical position within the current viewport.
* @param {Element} container Container in which the range is expected to be found.
*
* @return {?Range} The best range for the given point.
*/
function hiddenCaretRangeFromPoint( doc, x, y, container ) {
container.style.zIndex = '10000';
const range = caretRangeFromPoint( doc, x, y );
container.style.zIndex = null;
return range;
}
/**
* Places the caret at the top or bottom of a given element.
*
* @param {Element} container Focusable element.
* @param {boolean} isReverse True for bottom, false for top.
* @param {DOMRect} [rect] The rectangle to position the caret with.
* @param {boolean} [mayUseScroll=true] True to allow scrolling, false to disallow.
*/
export function placeCaretAtVerticalEdge( container, isReverse, rect, mayUseScroll = true ) {
if ( ! container ) {
return;
}
if ( ! rect || ! container.isContentEditable ) {
placeCaretAtHorizontalEdge( container, isReverse );
return;
}
// Offset by a buffer half the height of the caret rect. This is needed
// because caretRangeFromPoint may default to the end of the selection if
// offset is too close to the edge. It's unclear how to precisely calculate
// this threshold; it may be the padded area of some combination of line
// height, caret height, and font size. The buffer offset is effectively
// equivalent to a point at half the height of a line of text.
const buffer = rect.height / 2;
const editableRect = container.getBoundingClientRect();
const x = rect.left;
const y = isReverse ? ( editableRect.bottom - buffer ) : ( editableRect.top + buffer );
let range = hiddenCaretRangeFromPoint( document, x, y, container );
if ( ! range || ! container.contains( range.startContainer ) ) {
if ( mayUseScroll && (
( ! range || ! range.startContainer ) ||
! range.startContainer.contains( container ) ) ) {
// Might be out of view.
// Easier than attempting to calculate manually.
container.scrollIntoView( isReverse );
placeCaretAtVerticalEdge( container, isReverse, rect, false );
return;
}
placeCaretAtHorizontalEdge( container, isReverse );
return;
}
// Check if the closest text node is actually further away.
// If so, attempt to get the range again with the y position adjusted to get the right offset.
if ( range.startContainer.nodeType === TEXT_NODE ) {
const parentNode = range.startContainer.parentNode;
const parentRect = parentNode.getBoundingClientRect();
const side = isReverse ? 'bottom' : 'top';
const padding = parseInt( getComputedStyle( parentNode ).getPropertyValue( `padding-${ side }` ), 10 ) || 0;
const actualY = isReverse ? ( parentRect.bottom - padding - buffer ) : ( parentRect.top + padding + buffer );
if ( y !== actualY ) {
range = hiddenCaretRangeFromPoint( document, x, actualY, container );
}
}
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange( range );
container.focus();
// Editable was already focussed, it goes back to old range...
// This fixes it.
selection.removeAllRanges();
selection.addRange( range );
}
/**
* Check whether the given element is a text field, where text field is defined
* by the ability to select within the input, or that it is contenteditable.
*
* See: https://html.spec.whatwg.org/#textFieldSelection
*
* @param {HTMLElement} element The HTML element.
*
* @return {boolean} True if the element is an text field, false if not.
*/
export function isTextField( element ) {
try {
const { nodeName, selectionStart, contentEditable } = element;
return (
( nodeName === 'INPUT' && selectionStart !== null ) ||
( nodeName === 'TEXTAREA' ) ||
contentEditable === 'true'
);
} catch ( error ) {
// Safari throws an exception when trying to get `selectionStart`
// on non-text <input> elements (which, understandably, don't
// have the text selection API). We catch this via a try/catch
// block, as opposed to a more explicit check of the element's
// input types, because of Safari's non-standard behavior. This
// also means we don't have to worry about the list of input
// types that support `selectionStart` changing as the HTML spec
// evolves over time.
return false;
}
}
/**
* Check wether the current document has a selection.
* This checks both for focus in an input field and general text selection.
*
* @return {boolean} True if there is selection, false if not.
*/
export function documentHasSelection() {
if ( isTextField( document.activeElement ) ) {
return true;
}
const selection = window.getSelection();
const range = selection.rangeCount ? selection.getRangeAt( 0 ) : null;
return range && ! range.collapsed;
}
/**
* Check whether the contents of the element have been entirely selected.
* Returns true if there is no possibility of selection.
*
* @param {Element} element The element to check.
*
* @return {boolean} True if entirely selected, false if not.
*/
export function isEntirelySelected( element ) {
if ( includes( [ 'INPUT', 'TEXTAREA' ], element.nodeName ) ) {
return element.selectionStart === 0 && element.value.length === element.selectionEnd;
}
if ( ! element.isContentEditable ) {
return true;
}
const selection = window.getSelection();
const range = selection.rangeCount ? selection.getRangeAt( 0 ) : null;
if ( ! range ) {
return true;
}
const { startContainer, endContainer, startOffset, endOffset } = range;
if (
startContainer === element &&
endContainer === element &&
startOffset === 0 &&
endOffset === element.childNodes.length
) {
return true;
}
const lastChild = element.lastChild;
const lastChildContentLength = lastChild.nodeType === TEXT_NODE ?
lastChild.data.length :
lastChild.childNodes.length;
return (
startContainer === element.firstChild &&
endContainer === element.lastChild &&
startOffset === 0 &&
endOffset === lastChildContentLength
);
}
/**
* Given a DOM node, finds the closest scrollable container node.
*
* @param {Element} node Node from which to start.
*
* @return {?Element} Scrollable container node, if found.
*/
export function getScrollContainer( node ) {
if ( ! node ) {
return;
}
// Scrollable if scrollable height exceeds displayed...
if ( node.scrollHeight > node.clientHeight ) {
// ...except when overflow is defined to be hidden or visible
const { overflowY } = window.getComputedStyle( node );
if ( /(auto|scroll)/.test( overflowY ) ) {
return node;
}
}
// Continue traversing
return getScrollContainer( node.parentNode );
}
/**
* Returns the closest positioned element, or null under any of the conditions
* of the offsetParent specification. Unlike offsetParent, this function is not
* limited to HTMLElement and accepts any Node (e.g. Node.TEXT_NODE).
*
* @see https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetparent
*
* @param {Node} node Node from which to find offset parent.
*
* @return {?Node} Offset parent.
*/
export function getOffsetParent( node ) {
// Cannot retrieve computed style or offset parent only anything other than
// an element node, so find the closest element node.
let closestElement;
while ( ( closestElement = node.parentNode ) ) {
if ( closestElement.nodeType === ELEMENT_NODE ) {
break;
}
}
if ( ! closestElement ) {
return null;
}
// If the closest element is already positioned, return it, as offsetParent
// does not otherwise consider the node itself.
if ( getComputedStyle( closestElement ).position !== 'static' ) {
return closestElement;
}
return closestElement.offsetParent;
}
/**
* Given two DOM nodes, replaces the former with the latter in the DOM.
*
* @param {Element} processedNode Node to be removed.
* @param {Element} newNode Node to be inserted in its place.
* @return {void}
*/
export function replace( processedNode, newNode ) {
insertAfter( newNode, processedNode.parentNode );
remove( processedNode );
}
/**
* Given a DOM node, removes it from the DOM.
*
* @param {Element} node Node to be removed.
* @return {void}
*/
export function remove( node ) {
node.parentNode.removeChild( node );
}
/**
* Given two DOM nodes, inserts the former in the DOM as the next sibling of
* the latter.
*
* @param {Element} newNode Node to be inserted.
* @param {Element} referenceNode Node after which to perform the insertion.
* @return {void}
*/
export function insertAfter( newNode, referenceNode ) {
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
/**
* Unwrap the given node. This means any child nodes are moved to the parent.
*
* @param {Node} node The node to unwrap.
*
* @return {void}
*/
export function unwrap( node ) {
const parent = node.parentNode;
while ( node.firstChild ) {
parent.insertBefore( node.firstChild, node );
}
parent.removeChild( node );
}
/**
* Replaces the given node with a new node with the given tag name.
*
* @param {Element} node The node to replace
* @param {string} tagName The new tag name.
*
* @return {Element} The new node.
*/
export function replaceTag( node, tagName ) {
const newNode = node.ownerDocument.createElement( tagName );
while ( node.firstChild ) {
newNode.appendChild( node.firstChild );
}
node.parentNode.replaceChild( newNode, node );
return newNode;
}
/**
* Wraps the given node with a new node with the given tag name.
*
* @param {Element} newNode The node to insert.
* @param {Element} referenceNode The node to wrap.
*/
export function wrap( newNode, referenceNode ) {
referenceNode.parentNode.insertBefore( newNode, referenceNode );
newNode.appendChild( referenceNode );
}