-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
selection_util.js
607 lines (546 loc) · 18.2 KB
/
selection_util.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
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A collection of JavaScript utilities used to improve selection
* at different granularities.
*/
goog.provide('cvox.SelectionUtil');
goog.require('cvox.DomUtil');
goog.require('cvox.XpathUtil');
/**
* Utilities for improving selection.
* @constructor
*/
cvox.SelectionUtil = function() {};
/**
* Cleans up a paragraph selection acquired by extending forward.
* In this context, a paragraph selection is 'clean' when the focus
* node (the end of the selection) is not on a text node.
* @param {Selection} sel The paragraph-length selection.
* @return {boolean} True if the selection has been cleaned.
* False if the selection cannot be cleaned without invalid extension.
*/
cvox.SelectionUtil.cleanUpParagraphForward = function(sel) {
var expand = true;
// nodeType:3 == TEXT_NODE
while (sel.focusNode.nodeType == 3) {
// Ending with a text node, which is incorrect. Keep extending forward.
var fnode = sel.focusNode;
var foffset = sel.focusOffset;
sel.modify('extend', 'forward', 'sentence');
if ((fnode == sel.focusNode) && (foffset == sel.focusOffset)) {
// Nothing more to be done, cannot extend forward further.
return false;
}
}
return true;
};
/**
* Cleans up a paragraph selection acquired by extending backward.
* In this context, a paragraph selection is 'clean' when the focus
* node (the end of the selection) is not on a text node.
* @param {Selection} sel The paragraph-length selection.
* @return {boolean} True if the selection has been cleaned.
* False if the selection cannot be cleaned without invalid extension.
*/
cvox.SelectionUtil.cleanUpParagraphBack = function(sel) {
var expand = true;
var fnode;
var foffset;
// nodeType:3 == TEXT_NODE
while (sel.focusNode.nodeType == 3) {
// Ending with a text node, which is incorrect. Keep extending backward.
fnode = sel.focusNode;
foffset = sel.focusOffset;
sel.modify('extend', 'backward', 'sentence');
if ((fnode == sel.focusNode) && (foffset == sel.focusOffset)) {
// Nothing more to be done, cannot extend backward further.
return true;
}
}
return true;
};
/**
* Cleans up a sentence selection by extending forward.
* In this context, a sentence selection is 'clean' when the focus
* node (the end of the selection) is either:
* - not on a text node
* - on a text node that ends with a period or a space
* @param {Selection} sel The sentence-length selection.
* @return {boolean} True if the selection has been cleaned.
* False if the selection cannot be cleaned without invalid extension.
*/
cvox.SelectionUtil.cleanUpSentence = function(sel) {
var expand = true;
var lastSelection;
var lastSelectionOffset;
while (expand) {
// nodeType:3 == TEXT_NODE
if (sel.focusNode.nodeType == 3) {
// The focus node is of type text, check end for period
var fnode = sel.focusNode;
var foffset = sel.focusOffset;
if (sel.rangeCount > 0 && sel.getRangeAt(0).endOffset > 0) {
if (fnode.substringData(sel.getRangeAt(0).endOffset - 1, 1) == '.') {
// Text node ends with period.
return true;
} else if (
fnode.substringData(sel.getRangeAt(0).endOffset - 1, 1) == ' ') {
// Text node ends with space.
return true;
} else {
// Text node does not end with period or space. Extend forward.
sel.modify('extend', 'forward', 'sentence');
if ((fnode == sel.focusNode) && (foffset == sel.focusOffset)) {
// Nothing more to be done, cannot extend forward any further.
return false;
}
}
} else {
return true;
}
} else {
// Focus node is not text node, no further cleaning required.
return true;
}
}
return true;
};
/**
* Finds the starting position (height from top and left width) of a
* selection in a document.
* @param {Selection} sel The selection.
* @return {Array} The coordinates [top, left] of the selection.
*/
cvox.SelectionUtil.findSelPosition = function(sel) {
if (sel.rangeCount == 0) {
return [0, 0];
}
var clientRect = sel.getRangeAt(0).getBoundingClientRect();
if (!clientRect) {
return [0, 0];
}
var top = window.pageYOffset + clientRect.top;
var left = window.pageXOffset + clientRect.left;
return [top, left];
};
/**
* Calculates the horizontal and vertical position of a node
* @param {Node} targetNode The node.
* @return {Array} The coordinates [top, left] of the node.
*/
cvox.SelectionUtil.findTopLeftPosition = function(targetNode) {
var left = 0;
var top = 0;
var obj = targetNode;
if (obj.offsetParent) {
left = obj.offsetLeft;
top = obj.offsetTop;
obj = obj.offsetParent;
while (obj !== null) {
left += obj.offsetLeft;
top += obj.offsetTop;
obj = obj.offsetParent;
}
}
return [top, left];
};
/**
* Checks the contents of a selection for meaningful content.
* @param {Selection} sel The selection.
* @return {boolean} True if the selection is valid. False if the selection
* contains only whitespace or is an empty string.
*/
cvox.SelectionUtil.isSelectionValid = function(sel) {
var regExpWhiteSpace = new RegExp(/^\s+$/);
return (!((regExpWhiteSpace.test(sel.toString())) || (sel.toString() == '')));
};
/**
* Checks the contents of a range for meaningful content.
* @param {Range} range The range.
* @return {boolean} True if the range is valid. False if the range
* contains only whitespace or is an empty string.
*/
cvox.SelectionUtil.isRangeValid = function(range) {
var text = range.cloneContents().textContent;
var regExpWhiteSpace = new RegExp(/^\s+$/);
return (!((regExpWhiteSpace.test(text)) || (text == '')));
};
/**
* Returns absolute top and left positions of an element.
*
* @param {!Node} node The element for which to compute the position.
* @return {Array<number>} Index 0 is the left; index 1 is the top.
* @private
*/
cvox.SelectionUtil.findPos_ = function(node) {
var curLeft = 0;
var curTop = 0;
if (node.offsetParent) {
do {
curLeft += node.offsetLeft;
curTop += node.offsetTop;
} while (node = node.offsetParent);
}
return [curLeft, curTop];
};
/**
* Scrolls node in its parent node such the given node is visible.
* @param {Node} focusNode The node.
*/
cvox.SelectionUtil.scrollElementsToView = function(focusNode) {
// First, walk up the DOM until we find a node with a bounding rectangle.
while (focusNode && !focusNode.getBoundingClientRect) {
focusNode = focusNode.parentElement;
}
if (!focusNode) {
return;
}
// Walk up the DOM, ensuring each element is visible inside its parent.
var node = focusNode;
var parentNode = node.parentElement;
while (node != document.body && parentNode) {
node.scrollTop = node.offsetTop;
node.scrollLeft = node.offsetLeft;
node = parentNode;
parentNode = node.parentElement;
}
// Center the active element on the page once we know it's visible.
var pos = cvox.SelectionUtil.findPos_(focusNode);
window.scrollTo(
pos[0] - window.innerWidth / 2, pos[1] - window.innerHeight / 2);
};
/**
* Scrolls the selection into view if it is out of view in the current window.
* Inspired by workaround for already-on-screen elements @
* http://
* www.performantdesign.com/2009/08/26/scrollintoview-but-only-if-out-of-view/
* @param {Selection} sel The selection to be scrolled into view.
*/
cvox.SelectionUtil.scrollToSelection = function(sel) {
if (sel.rangeCount == 0) {
return;
}
// First, scroll all parent elements into view. Later, move the body
// which works slightly differently.
cvox.SelectionUtil.scrollElementsToView(sel.focusNode);
var pos = cvox.SelectionUtil.findSelPosition(sel);
var top = pos[0];
var left = pos[1];
var scrolledVertically = window.pageYOffset ||
document.documentElement.scrollTop || document.body.scrollTop;
var pageHeight = window.innerHeight ||
document.documentElement.clientHeight || document.body.clientHeight;
var pageWidth = window.innerWidth || document.documentElement.innerWidth ||
document.body.clientWidth;
if (left < pageWidth) {
left = 0;
}
// window.scroll puts specified pixel in upper left of window
if ((scrolledVertically + pageHeight) < top) {
// Align with bottom of page
var diff = top - pageHeight;
window.scroll(left, diff + 100);
} else if (top < scrolledVertically) {
// Align with top of page
window.scroll(left, top - 100);
}
};
/**
* This is from https://developer.mozilla.org/en/Whitespace_in_the_DOM
* Determine whether a node's text content is entirely whitespace.
*
* Throughout, whitespace is defined as one of the characters
* "\t" TAB \u0009
* "\n" LF \u000A
* "\r" CR \u000D
* " " SPC \u0020
*
* This does not use Javascript's "\s" because that includes non-breaking
* spaces (and also some other characters).
*
* @param {Node} node A node implementing the |CharacterData| interface (i.e.,
* a |Text|, |Comment|, or |CDATASection| node.
* @return {boolean} True if all of the text content of |node| is whitespace,
* otherwise false.
*/
cvox.SelectionUtil.isAllWs = function(node) {
// Use ECMA-262 Edition 3 String and RegExp features
return !(/[^\t\n\r ]/.test(node.data));
};
/**
* This is from https://developer.mozilla.org/en/Whitespace_in_the_DOM
* Determine if a node should be ignored by the iterator functions.
*
* @param {Node} node An object implementing the DOM1 |Node| interface.
* @return {boolean} True if the node is:
* 1) A |Text| node that is all whitespace
* 2) A |Comment| node
* and otherwise false.
*/
cvox.SelectionUtil.isIgnorable = function(node) {
return (node.nodeType == 8) || // A comment node
((node.nodeType == 3) &&
cvox.SelectionUtil.isAllWs(node)); // a text node, all ws
};
/**
* This is from https://developer.mozilla.org/en/Whitespace_in_the_DOM
* Version of |previousSibling| that skips nodes that are entirely
* whitespace or comments. (Normally |previousSibling| is a property
* of all DOM nodes that gives the sibling node, the node that is
* a child of the same parent, that occurs immediately before the
* reference node.)
*
* @param {Node} sib The reference node.
* @return {Node} Either:
* 1) The closest previous sibling to |sib| that is not
* ignorable according to |isIgnorable|, or
* 2) null if no such node exists.
*/
cvox.SelectionUtil.nodeBefore = function(sib) {
while ((sib = sib.previousSibling)) {
if (!cvox.SelectionUtil.isIgnorable(sib)) {
return sib;
}
}
return null;
};
/**
* This is from https://developer.mozilla.org/en/Whitespace_in_the_DOM
* Version of |nextSibling| that skips nodes that are entirely
* whitespace or comments.
*
* @param {Node} sib The reference node.
* @return {Node} Either:
* 1) The closest next sibling to |sib| that is not
* ignorable according to |isIgnorable|, or
* 2) null if no such node exists.
*/
cvox.SelectionUtil.nodeAfter = function(sib) {
while ((sib = sib.nextSibling)) {
if (!cvox.SelectionUtil.isIgnorable(sib)) {
return sib;
}
}
return null;
};
/**
* This is from https://developer.mozilla.org/en/Whitespace_in_the_DOM
* Version of |lastChild| that skips nodes that are entirely
* whitespace or comments. (Normally |lastChild| is a property
* of all DOM nodes that gives the last of the nodes contained
* directly in the reference node.)
*
* @param {Node} par The reference node.
* @return {Node} Either:
* 1) The last child of |sib| that is not
* ignorable according to |isIgnorable|, or
* 2) null if no such node exists.
*/
cvox.SelectionUtil.lastChildNode = function(par) {
var res = par.lastChild;
while (res) {
if (!cvox.SelectionUtil.isIgnorable(res)) {
return res;
}
res = res.previousSibling;
}
return null;
};
/**
* This is from https://developer.mozilla.org/en/Whitespace_in_the_DOM
* Version of |firstChild| that skips nodes that are entirely
* whitespace and comments.
*
* @param {Node} par The reference node.
* @return {Node} Either:
* 1) The first child of |sib| that is not
* ignorable according to |isIgnorable|, or
* 2) null if no such node exists.
*/
cvox.SelectionUtil.firstChildNode = function(par) {
var res = par.firstChild;
while (res) {
if (!cvox.SelectionUtil.isIgnorable(res)) {
return res;
}
res = res.nextSibling;
}
return null;
};
/**
* This is from https://developer.mozilla.org/en/Whitespace_in_the_DOM
* Version of |data| that doesn't include whitespace at the beginning
* and end and normalizes all whitespace to a single space. (Normally
* |data| is a property of text nodes that gives the text of the node.)
*
* @param {Node} txt The text node whose data should be returned.
* @return {string} A string giving the contents of the text node with
* whitespace collapsed.
*/
cvox.SelectionUtil.dataOf = function(txt) {
var data = txt.data;
// Use ECMA-262 Edition 3 String and RegExp features
data = data.replace(/[\t\n\r ]+/g, ' ');
if (data.charAt(0) == ' ') {
data = data.substring(1, data.length);
}
if (data.charAt(data.length - 1) == ' ') {
data = data.substring(0, data.length - 1);
}
return data;
};
/**
* Returns true if the selection has content from at least one node
* that has the specified tagName.
*
* @param {Selection} sel The selection.
* @param {string} tagName Tagname that the selection should be checked for.
* @return {boolean} True if the selection has content from at least one node
* with the specified tagName.
*/
cvox.SelectionUtil.hasContentWithTag = function(sel, tagName) {
if (!sel || !sel.anchorNode || !sel.focusNode) {
return false;
}
if (sel.anchorNode.tagName && (sel.anchorNode.tagName == tagName)) {
return true;
}
if (sel.focusNode.tagName && (sel.focusNode.tagName == tagName)) {
return true;
}
if (sel.anchorNode.parentNode.tagName &&
(sel.anchorNode.parentNode.tagName == tagName)) {
return true;
}
if (sel.focusNode.parentNode.tagName &&
(sel.focusNode.parentNode.tagName == tagName)) {
return true;
}
var docFrag = sel.getRangeAt(0).cloneContents();
var span = document.createElement('span');
span.appendChild(docFrag);
return (span.getElementsByTagName(tagName).length > 0);
};
/**
* Selects text within a text node.
*
* Note that the input node MUST be of type TEXT; otherwise, the offset
* count would not mean # of characters - this is because of the way Range
* works in JavaScript.
*
* @param {Node} textNode The text node to select text within.
* @param {number} start The start of the selection.
* @param {number} end The end of the selection.
*/
cvox.SelectionUtil.selectText = function(textNode, start, end) {
var newRange = document.createRange();
newRange.setStart(textNode, start);
newRange.setEnd(textNode, end);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(newRange);
};
/**
* Selects all the text in a given node.
*
* @param {Node} node The target node.
*/
cvox.SelectionUtil.selectAllTextInNode = function(node) {
var newRange = document.createRange();
newRange.setStart(node, 0);
newRange.setEndAfter(node);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(newRange);
};
/**
* Collapses the selection to the start. If nothing is selected,
* selects the beginning of the given node.
*
* @param {Node} node The target node.
*/
cvox.SelectionUtil.collapseToStart = function(node) {
var sel = window.getSelection();
var cursorNode = sel.anchorNode;
var cursorOffset = sel.anchorOffset;
if (cursorNode == null) {
cursorNode = node;
cursorOffset = 0;
}
var newRange = document.createRange();
newRange.setStart(cursorNode, cursorOffset);
newRange.setEnd(cursorNode, cursorOffset);
sel.removeAllRanges();
sel.addRange(newRange);
};
/**
* Collapses the selection to the end. If nothing is selected,
* selects the end of the given node.
*
* @param {Node} node The target node.
*/
cvox.SelectionUtil.collapseToEnd = function(node) {
var sel = window.getSelection();
var cursorNode = sel.focusNode;
var cursorOffset = sel.focusOffset;
if (cursorNode == null) {
cursorNode = node;
cursorOffset = 0;
}
var newRange = document.createRange();
newRange.setStart(cursorNode, cursorOffset);
newRange.setEnd(cursorNode, cursorOffset);
sel.removeAllRanges();
sel.addRange(newRange);
};
/**
* Retrieves all the text within a selection.
*
* Note that this can be different than simply using the string from
* window.getSelection() as this will account for IMG nodes, etc.
*
* @return {string} The string of text contained in the current selection.
*/
cvox.SelectionUtil.getText = function() {
var sel = window.getSelection();
if (cvox.SelectionUtil.hasContentWithTag(sel, 'IMG')) {
var text = '';
var docFrag = sel.getRangeAt(0).cloneContents();
var span = document.createElement('span');
span.appendChild(docFrag);
var leafNodes = cvox.XpathUtil.getLeafNodes(span);
for (var i = 0, node; node = leafNodes[i]; i++) {
text = text + ' ' + cvox.DomUtil.getName(node);
}
return text;
} else {
return cvox.SelectionUtil.getSelectionText_();
}
};
/**
* Returns the selection as text instead of a selection object. Note that this
* function must be used in place of getting text directly from the DOM
* if you want i18n tests to pass.
*
* @return {string} The text.
* @private
*/
cvox.SelectionUtil.getSelectionText_ = function() {
return '' + window.getSelection();
};
/**
* Returns a range as text instead of a selection object. Note that this
* function must be used in place of getting text directly from the DOM
* if you want i18n tests to pass.
*
* @param {Range} range A range.
* @return {string} The text.
*/
cvox.SelectionUtil.getRangeText = function(range) {
if (range)
return range.cloneContents().textContent.replace(/\s+/g, ' ');
else
return '';
};