File: traverse_content.js

package info (click to toggle)
chromium-browser 41.0.2272.118-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 2,189,132 kB
  • sloc: cpp: 9,691,462; ansic: 3,341,451; python: 712,689; asm: 518,779; xml: 208,926; java: 169,820; sh: 119,353; perl: 68,907; makefile: 28,311; yacc: 13,305; objc: 11,385; tcl: 3,186; cs: 2,225; sql: 2,217; lex: 2,215; lisp: 1,349; pascal: 1,256; awk: 407; ruby: 155; sed: 53; php: 14; exp: 11
file content (482 lines) | stat: -rw-r--r-- 15,028 bytes parent folder | download | duplicates (2)
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
// 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 DOM traversal interface for moving a selection around a
 * webpage. Provides multiple granularities:
 * 1. Move by paragraph.
 * 2. Move by sentence.
 * 3. Move by line.
 * 4. Move by word.
 * 5. Move by character.
 */

goog.provide('cvox.TraverseContent');

goog.require('cvox.CursorSelection');
goog.require('cvox.DomUtil');
goog.require('cvox.SelectionUtil');
goog.require('cvox.TraverseUtil');

/**
 * Moves a selection around a document or within a provided DOM object.
 *
 * @constructor
 * @param {Node=} domObj a DOM node (optional).
 */
cvox.TraverseContent = function(domObj) {
  if (domObj != null) {
    this.currentDomObj = domObj;
  } else {
    this.currentDomObj = document.body;
  }
  var range = document.createRange();
  // TODO (dmazzoni): Switch this to avoid using range methods. Range methods
  // can cause exceptions (such as if the node is not attached to the DOM).
  try {
    range.selectNode(this.currentDomObj);
    this.startCursor_ = new cvox.Cursor(
        range.startContainer, range.startOffset,
        cvox.TraverseUtil.getNodeText(range.startContainer));
    this.endCursor_ = new cvox.Cursor(
        range.endContainer, range.endOffset,
        cvox.TraverseUtil.getNodeText(range.endContainer));
  } catch (e) {
    // Ignoring this error so that it will not break everything else.
    window.console.log('Error: Unselectable node:');
    window.console.log(domObj);
  }
};
goog.addSingletonGetter(cvox.TraverseContent);

/**
 * Whether the last navigated selection only contained whitespace.
 * @type {boolean}
 */
cvox.TraverseContent.prototype.lastSelectionWasWhitespace = false;

/**
 * Whether we should skip whitespace when traversing individual characters.
 * @type {boolean}
 */
cvox.TraverseContent.prototype.skipWhitespace = false;

/**
 * If moveNext and movePrev should skip past an invalid selection,
 * so the user never gets stuck. Ideally the navigation code should never
 * return a range that's not a valid selection, but this keeps the user from
 * getting stuck if that code fails.  This is set to false for unit testing.
 * @type {boolean}
 */
cvox.TraverseContent.prototype.skipInvalidSelections = true;

/**
 * If line and sentence navigation should break at <a> links.
 * @type {boolean}
 */
cvox.TraverseContent.prototype.breakAtLinks = true;

/**
 * The string constant for character granularity.
 * @type {string}
 * @const
 */
cvox.TraverseContent.kCharacter = 'character';

/**
 * The string constant for word granularity.
 * @type {string}
 * @const
 */
cvox.TraverseContent.kWord = 'word';

/**
 * The string constant for sentence granularity.
 * @type {string}
 * @const
 */
cvox.TraverseContent.kSentence = 'sentence';

/**
 * The string constant for line granularity.
 * @type {string}
 * @const
 */
cvox.TraverseContent.kLine = 'line';

/**
 * The string constant for paragraph granularity.
 * @type {string}
 * @const
 */
cvox.TraverseContent.kParagraph = 'paragraph';

/**
 * A constant array of all granularities.
 * @type {Array.<string>}
 * @const
 */
cvox.TraverseContent.kAllGrains =
    [cvox.TraverseContent.kParagraph,
     cvox.TraverseContent.kSentence,
     cvox.TraverseContent.kLine,
     cvox.TraverseContent.kWord,
     cvox.TraverseContent.kCharacter];

/**
 * Set the current position to match the current WebKit selection.
 */
cvox.TraverseContent.prototype.syncToSelection = function() {
  this.normalizeSelection();

  var selection = window.getSelection();
  if (!selection || !selection.anchorNode || !selection.focusNode) {
    return;
  }
  this.startCursor_ = new cvox.Cursor(
      selection.anchorNode, selection.anchorOffset,
      cvox.TraverseUtil.getNodeText(selection.anchorNode));
  this.endCursor_ = new cvox.Cursor(
      selection.focusNode, selection.focusOffset,
      cvox.TraverseUtil.getNodeText(selection.focusNode));
};

/**
 * Set the start and end cursors to the selection.
 * @param {cvox.CursorSelection} sel The selection.
 */
cvox.TraverseContent.prototype.syncToCursorSelection = function(sel) {
  this.startCursor_ = sel.start.clone();
  this.endCursor_ = sel.end.clone();
};

/**
 * Get the cursor selection.
 * @return {cvox.CursorSelection} The selection.
 */
cvox.TraverseContent.prototype.getCurrentCursorSelection = function() {
  return new cvox.CursorSelection(this.startCursor_, this.endCursor_);
};

/**
 * Set the WebKit selection based on the current position.
 */
cvox.TraverseContent.prototype.updateSelection = function() {
  cvox.TraverseUtil.setSelection(this.startCursor_, this.endCursor_);
  cvox.SelectionUtil.scrollToSelection(window.getSelection());
};

/**
 * Get the current position as a range.
 * @return {Range} The current range.
 */
cvox.TraverseContent.prototype.getCurrentRange = function() {
  var range = document.createRange();
  try {
    range.setStart(this.startCursor_.node, this.startCursor_.index);
    range.setEnd(this.endCursor_.node, this.endCursor_.index);
  } catch (e) {
    console.log('Invalid range ');
  }
  return range;
};

/**
 * Get the current text content as a string.
 * @return {string} The current spanned content.
 */
cvox.TraverseContent.prototype.getCurrentText = function() {
  return cvox.SelectionUtil.getRangeText(this.getCurrentRange());
};

/**
 * Collapse to the end of the range.
 */
cvox.TraverseContent.prototype.collapseToEnd = function() {
  this.startCursor_ = this.endCursor_.clone();
};

/**
 * Collapse to the start of the range.
 */
cvox.TraverseContent.prototype.collapseToStart = function() {
  this.endCursor_ = this.startCursor_.clone();
};

/**
 * Moves selection forward.
 *
 * @param {string} grain specifies "sentence", "word", "character",
 *     or "paragraph" granularity.
 * @return {?string} Either:
 *                1) The new selected text.
 *                2) null if the end of the domObj has been reached.
 */
cvox.TraverseContent.prototype.moveNext = function(grain) {
  var breakTags = this.getBreakTags();

  // As a special case, if the current selection is empty or all
  // whitespace, ensure that the next returned selection will NOT be
  // only whitespace - otherwise you can get trapped.
  var skipWhitespace = this.skipWhitespace;

  var range = this.getCurrentRange();
  if (!cvox.SelectionUtil.isRangeValid(range)) {
    skipWhitespace = true;
  }

  var elementsEntered = [];
  var elementsLeft = [];
  var str;
  do {
    if (grain === cvox.TraverseContent.kSentence) {
      str = cvox.TraverseUtil.getNextSentence(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,
          breakTags);
    } else if (grain === cvox.TraverseContent.kWord) {
      str = cvox.TraverseUtil.getNextWord(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft);
    } else if (grain === cvox.TraverseContent.kCharacter) {
      str = cvox.TraverseUtil.getNextChar(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,
          skipWhitespace);
    } else if (grain === cvox.TraverseContent.kParagraph) {
      str = cvox.TraverseUtil.getNextParagraph(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft);
    } else if (grain === cvox.TraverseContent.kLine) {
      str = cvox.TraverseUtil.getNextLine(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,
          breakTags);
    } else {
      // User has provided an invalid string.
      // Fall through to default: extend by sentence
      window.console.log('Invalid selection granularity: "' + grain + '"');
      grain = cvox.TraverseContent.kSentence;
      str = cvox.TraverseUtil.getNextSentence(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,
          breakTags);
    }

    if (str == null) {
      // We reached the end of the document.
      return null;
    }

    range = this.getCurrentRange();
    var isInvalid = !range.getBoundingClientRect();
  } while (this.skipInvalidSelections && isInvalid);

  if (!cvox.SelectionUtil.isRangeValid(range)) {
    // It's OK if the selection navigation lands on whitespace once (in
    // character granularity), but if it hits whitespace more than once, then
    // skip forward until there is real content.
    if (!this.lastSelectionWasWhitespace &&
        grain == cvox.TraverseContent.kCharacter) {
      this.lastSelectionWasWhitespace = true;
    } else {
      while (!cvox.SelectionUtil.isRangeValid(this.getCurrentRange())) {
        if (this.moveNext(grain) == null) {
          break;
        }
      }
    }
  } else {
    this.lastSelectionWasWhitespace = false;
  }

  return this.getCurrentText();
};


/**
 * Moves selection backward.
 *
 * @param {string} grain specifies "sentence", "word", "character",
 *     or "paragraph" granularity.
 * @return {?string} Either:
 *                1) The new selected text.
 *                2) null if the beginning of the domObj has been reached.
 */
cvox.TraverseContent.prototype.movePrev = function(grain) {
  var breakTags = this.getBreakTags();

  // As a special case, if the current selection is empty or all
  // whitespace, ensure that the next returned selection will NOT be
  // only whitespace - otherwise you can get trapped.
  var skipWhitespace = this.skipWhitespace;

  var range = this.getCurrentRange();
  if (!cvox.SelectionUtil.isRangeValid(range)) {
    skipWhitespace = true;
  }

  var elementsEntered = [];
  var elementsLeft = [];
  var str;
  do {
    if (grain === cvox.TraverseContent.kSentence) {
      str = cvox.TraverseUtil.getPreviousSentence(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,
          breakTags);
    } else if (grain === cvox.TraverseContent.kWord) {
      str = cvox.TraverseUtil.getPreviousWord(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft);
    } else if (grain === cvox.TraverseContent.kCharacter) {
      str = cvox.TraverseUtil.getPreviousChar(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,
          skipWhitespace);
    } else if (grain === cvox.TraverseContent.kParagraph) {
      str = cvox.TraverseUtil.getPreviousParagraph(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft);
    } else if (grain === cvox.TraverseContent.kLine) {
      str = cvox.TraverseUtil.getPreviousLine(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,
          breakTags);
    } else {
      // User has provided an invalid string.
      // Fall through to default: extend by sentence
      window.console.log('Invalid selection granularity: "' + grain + '"');
      grain = cvox.TraverseContent.kSentence;
      str = cvox.TraverseUtil.getPreviousSentence(
          this.startCursor_, this.endCursor_, elementsEntered, elementsLeft,
          breakTags);
    }

    if (str == null) {
      // We reached the end of the document.
      return null;
    }

    range = this.getCurrentRange();
    var isInvalid = !range.getBoundingClientRect();
  } while (this.skipInvalidSelections && isInvalid);

  if (!cvox.SelectionUtil.isRangeValid(range)) {
    // It's OK if the selection navigation lands on whitespace once (in
    // character granularity), but if it hits whitespace more than once, then
    // skip forward until there is real content.
    if (!this.lastSelectionWasWhitespace &&
        grain == cvox.TraverseContent.kCharacter) {
      this.lastSelectionWasWhitespace = true;
    } else {
      while (!cvox.SelectionUtil.isRangeValid(this.getCurrentRange())) {
        if (this.movePrev(grain) == null) {
          break;
        }
      }
    }
  } else {
    this.lastSelectionWasWhitespace = false;
  }

  return this.getCurrentText();
};

/**
 * Get the tag names that should break a sentence or line. Currently
 * just an anchor 'A' should break a sentence or line if the breakAtLinks
 * flag is true, but in the future we might have other rules for breaking.
 *
 * @return {Object} An associative array mapping a tag name to true if
 *     it should break a sentence or line.
 */
cvox.TraverseContent.prototype.getBreakTags = function() {
  return {
    'A': this.breakAtLinks,
    'BR': true,
    'HR': true
  };
};

/**
 * Selects the next element of the document or within the provided DOM object.
 * Scrolls the window as appropriate.
 *
 * @param {string} grain specifies "sentence", "word", "character",
 *     or "paragraph" granularity.
 * @param {Node=} domObj a DOM node (optional).
 * @return {?string} Either:
 *                1) The new selected text.
 *                2) null if the end of the domObj has been reached.
 */
cvox.TraverseContent.prototype.nextElement = function(grain, domObj) {
  if (domObj != null) {
    this.currentDomObj = domObj;
  }

  var result = this.moveNext(grain);
  if (result != null &&
      (!cvox.DomUtil.isDescendantOfNode(
          this.startCursor_.node, this.currentDomObj) ||
       !cvox.DomUtil.isDescendantOfNode(
           this.endCursor_.node, this.currentDomObj))) {
    return null;
  }

  return result;
};


/**
 * Selects the previous element of the document or within the provided DOM
 * object. Scrolls the window as appropriate.
 *
 * @param {string} grain specifies "sentence", "word", "character",
 *     or "paragraph" granularity.
 * @param {Node=} domObj a DOM node (optional).
 * @return {?string} Either:
 *                1) The new selected text.
 *                2) null if the beginning of the domObj has been reached.
 */
cvox.TraverseContent.prototype.prevElement = function(grain, domObj) {
  if (domObj != null) {
    this.currentDomObj = domObj;
  }

  var result = this.movePrev(grain);
  if (result != null &&
      (!cvox.DomUtil.isDescendantOfNode(
          this.startCursor_.node, this.currentDomObj) ||
       !cvox.DomUtil.isDescendantOfNode(
           this.endCursor_.node, this.currentDomObj))) {
    return null;
  }

  return result;
};

/**
 * Make sure that exactly one item is selected. If there's no selection,
 * set the selection to the start of the document.
 */
cvox.TraverseContent.prototype.normalizeSelection = function() {
  var selection = window.getSelection();
  if (selection.rangeCount < 1) {
    // Before the user has clicked a freshly-loaded page

    var range = document.createRange();
    range.setStart(this.currentDomObj, 0);
    range.setEnd(this.currentDomObj, 0);

    selection.removeAllRanges();
    selection.addRange(range);

  } else if (selection.rangeCount > 1) {
    //  Multiple ranges exist - remove all ranges but the last one
    for (var i = 0; i < (selection.rangeCount - 1); i++) {
      selection.removeRange(selection.getRangeAt(i));
    }
  }
};

/**
 * Resets the selection.
 *
 * @param {Node=} domObj a DOM node.  Optional.
 *
 */
cvox.TraverseContent.prototype.reset = function(domObj) {
  window.getSelection().removeAllRanges();
};