-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathfragment-generation-utils.js
2342 lines (2205 loc) · 92.7 KB
/
fragment-generation-utils.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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setTimeout = exports.isValidRangeForFragmentGeneration = exports.generateFragmentFromRange = exports.generateFragment = exports.forTesting = exports.GenerateFragmentStatus = void 0;
/**
* Copyright 2020 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
*
* https://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.
*/
// Block elements. elements of a text fragment cannot cross the boundaries of a
// block element. Source for the list:
// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements#Elements
const BLOCK_ELEMENTS = ['ADDRESS', 'ARTICLE', 'ASIDE', 'BLOCKQUOTE', 'BR', 'DETAILS', 'DIALOG', 'DD', 'DIV', 'DL', 'DT', 'FIELDSET', 'FIGCAPTION', 'FIGURE', 'FOOTER', 'FORM', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'HGROUP', 'HR', 'LI', 'MAIN', 'NAV', 'OL', 'P', 'PRE', 'SECTION', 'TABLE', 'UL', 'TR', 'TH', 'TD', 'COLGROUP', 'COL', 'CAPTION', 'THEAD', 'TBODY', 'TFOOT'];
// Characters that indicate a word boundary. Use the script
// tools/generate-boundary-regex.js if it's necessary to modify or regenerate
// this. Because it's a hefty regex, this should be used infrequently and only
// on single-character strings.
const BOUNDARY_CHARS = /[\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u;
// The same thing, but with a ^.
const NON_BOUNDARY_CHARS = /[^\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u;
/**
* Searches the document for a given text fragment.
*
* @param {TextFragment} textFragment - Text Fragment to highlight.
* @param {Document} documentToProcess - document where to extract and mark
* fragments in.
* @return {Ranges[]} - Zero or more ranges within the document corresponding
* to the fragment. If the fragment corresponds to more than one location
* in the document (i.e., is ambiguous) then the first two matches will be
* returned (regardless of how many more matches there may be in the
* document).
*/
const processTextFragmentDirective = (textFragment, documentToProcess = document) => {
const results = [];
const searchRange = documentToProcess.createRange();
searchRange.selectNodeContents(documentToProcess.body);
while (!searchRange.collapsed && results.length < 2) {
let potentialMatch;
if (textFragment.prefix) {
const prefixMatch = findTextInRange(textFragment.prefix, searchRange);
if (prefixMatch == null) {
break;
}
// Future iterations, if necessary, should start after the first
// character of the prefix match.
advanceRangeStartPastOffset(searchRange, prefixMatch.startContainer, prefixMatch.startOffset);
// The search space for textStart is everything after the prefix and
// before the end of the top-level search range, starting at the next
// non- whitespace position.
const matchRange = documentToProcess.createRange();
matchRange.setStart(prefixMatch.endContainer, prefixMatch.endOffset);
matchRange.setEnd(searchRange.endContainer, searchRange.endOffset);
advanceRangeStartToNonWhitespace(matchRange);
if (matchRange.collapsed) {
break;
}
potentialMatch = findTextInRange(textFragment.textStart, matchRange);
// If textStart wasn't found anywhere in the matchRange, then there's
// no possible match and we can stop early.
if (potentialMatch == null) {
break;
}
// If potentialMatch is immediately after the prefix (i.e., its start
// equals matchRange's start), this is a candidate and we should keep
// going with this iteration. Otherwise, we'll need to find the next
// instance (if any) of the prefix.
if (potentialMatch.compareBoundaryPoints(Range.START_TO_START, matchRange) !== 0) {
continue;
}
} else {
// With no prefix, just look directly for textStart.
potentialMatch = findTextInRange(textFragment.textStart, searchRange);
if (potentialMatch == null) {
break;
}
advanceRangeStartPastOffset(searchRange, potentialMatch.startContainer, potentialMatch.startOffset);
}
if (textFragment.textEnd) {
const textEndRange = documentToProcess.createRange();
textEndRange.setStart(potentialMatch.endContainer, potentialMatch.endOffset);
textEndRange.setEnd(searchRange.endContainer, searchRange.endOffset);
// Keep track of matches of the end term followed by suffix term
// (if needed).
// If no matches are found then there's no point in keeping looking
// for matches of the start term after the current start term
// occurrence.
let matchFound = false;
// Search through the rest of the document to find a textEnd match.
// This may take multiple iterations if a suffix needs to be found.
while (!textEndRange.collapsed && results.length < 2) {
const textEndMatch = findTextInRange(textFragment.textEnd, textEndRange);
if (textEndMatch == null) {
break;
}
advanceRangeStartPastOffset(textEndRange, textEndMatch.startContainer, textEndMatch.startOffset);
potentialMatch.setEnd(textEndMatch.endContainer, textEndMatch.endOffset);
if (textFragment.suffix) {
// If there's supposed to be a suffix, check if it appears after
// the textEnd we just found.
const suffixResult = checkSuffix(textFragment.suffix, potentialMatch, searchRange, documentToProcess);
if (suffixResult === CheckSuffixResult.NO_SUFFIX_MATCH) {
break;
} else if (suffixResult === CheckSuffixResult.SUFFIX_MATCH) {
matchFound = true;
results.push(potentialMatch.cloneRange());
continue;
} else if (suffixResult === CheckSuffixResult.MISPLACED_SUFFIX) {
continue;
}
} else {
// If we've found textEnd and there's no suffix, then it's a
// match!
matchFound = true;
results.push(potentialMatch.cloneRange());
}
}
// Stopping match search because suffix or textEnd are missing from
// the rest of the search space.
if (!matchFound) {
break;
}
} else if (textFragment.suffix) {
// If there's no textEnd but there is a suffix, search for the suffix
// after potentialMatch
const suffixResult = checkSuffix(textFragment.suffix, potentialMatch, searchRange, documentToProcess);
if (suffixResult === CheckSuffixResult.NO_SUFFIX_MATCH) {
break;
} else if (suffixResult === CheckSuffixResult.SUFFIX_MATCH) {
results.push(potentialMatch.cloneRange());
advanceRangeStartPastOffset(searchRange, searchRange.startContainer, searchRange.startOffset);
continue;
} else if (suffixResult === CheckSuffixResult.MISPLACED_SUFFIX) {
continue;
}
} else {
results.push(potentialMatch.cloneRange());
}
}
return results;
};
/**
* Enum indicating the result of the checkSuffix function.
*/
const CheckSuffixResult = {
NO_SUFFIX_MATCH: 0,
// Suffix wasn't found at all. Search should halt.
SUFFIX_MATCH: 1,
// The suffix matches the expectation.
MISPLACED_SUFFIX: 2 // The suffix was found, but not in the right place.
};
/**
* Checks to see if potentialMatch satisfies the suffix conditions of this
* Text Fragment.
* @param {String} suffix - the suffix text to find
* @param {Range} potentialMatch - the Range containing the match text.
* @param {Range} searchRange - the Range in which to search for |suffix|.
* Regardless of the start boundary of this Range, nothing appearing before
* |potentialMatch| will be considered.
* @param {Document} documentToProcess - document where to extract and mark
* fragments in.
* @return {CheckSuffixResult} - enum value indicating that potentialMatch
* should be accepted, that the search should continue, or that the search
* should halt.
*/
const checkSuffix = (suffix, potentialMatch, searchRange, documentToProcess) => {
const suffixRange = documentToProcess.createRange();
suffixRange.setStart(potentialMatch.endContainer, potentialMatch.endOffset);
suffixRange.setEnd(searchRange.endContainer, searchRange.endOffset);
advanceRangeStartToNonWhitespace(suffixRange);
const suffixMatch = findTextInRange(suffix, suffixRange);
// If suffix wasn't found anywhere in the suffixRange, then there's no
// possible match and we can stop early.
if (suffixMatch == null) {
return CheckSuffixResult.NO_SUFFIX_MATCH;
}
// If suffixMatch is immediately after potentialMatch (i.e., its start
// equals suffixRange's start), this is a match. If not, we have to
// start over from the beginning.
if (suffixMatch.compareBoundaryPoints(Range.START_TO_START, suffixRange) !== 0) {
return CheckSuffixResult.MISPLACED_SUFFIX;
}
return CheckSuffixResult.SUFFIX_MATCH;
};
/**
* Sets the start of |range| to be the first boundary point after |offset| in
* |node|--either at offset+1, or after the node.
* @param {Range} range - the range to mutate
* @param {Node} node - the node used to determine the new range start
* @param {Number} offset - the offset immediately before the desired new
* boundary point
*/
const advanceRangeStartPastOffset = (range, node, offset) => {
try {
range.setStart(node, offset + 1);
} catch (err) {
range.setStartAfter(node);
}
};
/**
* Modifies |range| to start at the next non-whitespace position.
* @param {Range} range - the range to mutate
*/
const advanceRangeStartToNonWhitespace = range => {
const walker = makeTextNodeWalker(range);
let node = walker.nextNode();
while (!range.collapsed && node != null) {
if (node !== range.startContainer) {
range.setStart(node, 0);
}
if (node.textContent.length > range.startOffset) {
const firstChar = node.textContent[range.startOffset];
if (!firstChar.match(/\s/)) {
return;
}
}
try {
range.setStart(node, range.startOffset + 1);
} catch (err) {
node = walker.nextNode();
if (node == null) {
range.collapse();
} else {
range.setStart(node, 0);
}
}
}
};
/**
* Creates a TreeWalker that traverses a range and emits visible text nodes in
* the range.
* @param {Range} range - Range to be traversed by the walker
* @return {TreeWalker}
*/
const makeTextNodeWalker = range => {
const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, node => {
return acceptTextNodeIfVisibleInRange(node, range);
});
return walker;
};
/**
* Helper function to calculate the visibility of a Node based on its CSS
* computed style. This function does not take into account the visibility of
* the node's ancestors so even if the node is visible according to its style
* it might not be visible on the page if one of its ancestors is not visible.
* @param {Node} node - the Node to evaluate
* @return {Boolean} - true if the node is visible. A node will be visible if
* its computed style meets all of the following criteria:
* - non zero height, width, height and opacity
* - visibility not hidden
* - display not none
*/
const isNodeVisible = node => {
// Find an HTMLElement (this node or an ancestor) so we can check
// visibility.
let elt = node;
while (elt != null && !(elt instanceof HTMLElement)) elt = elt.parentNode;
if (elt != null) {
const nodeStyle = window.getComputedStyle(elt);
// If the node is not rendered, just skip it.
if (nodeStyle.visibility === 'hidden' || nodeStyle.display === 'none' || parseInt(nodeStyle.height, 10) === 0 || parseInt(nodeStyle.width, 10) === 0 || parseInt(nodeStyle.opacity, 10) === 0) {
return false;
}
}
return true;
};
/**
* Filter function for use with TreeWalkers. Rejects nodes that aren't in the
* given range or aren't visible.
* @param {Node} node - the Node to evaluate
* @param {Range|Undefined} range - the range in which node must fall. Optional;
* if null, the range check is skipped.
* @return {NodeFilter} - FILTER_ACCEPT or FILTER_REJECT, to be passed along to
* a TreeWalker.
*/
const acceptNodeIfVisibleInRange = (node, range) => {
if (range != null && !range.intersectsNode(node)) return NodeFilter.FILTER_REJECT;
return isNodeVisible(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
};
/**
* Filter function for use with TreeWalkers. Accepts only visible text nodes
* that are in the given range. Other types of nodes visible in the given range
* are skipped so a TreeWalker using this filter function still visits text
* nodes in the node's subtree.
* @param {Node} node - the Node to evaluate
* @param {Range} range - the range in which node must fall. Optional;
* if null, the range check is skipped/
* @return {NodeFilter} - NodeFilter value to be passed along to a TreeWalker.
* Values returned:
* - FILTER_REJECT: Node not in range or not visible.
* - FILTER_SKIP: Non Text Node visible and in range
* - FILTER_ACCEPT: Text Node visible and in range
*/
const acceptTextNodeIfVisibleInRange = (node, range) => {
if (range != null && !range.intersectsNode(node)) return NodeFilter.FILTER_REJECT;
if (!isNodeVisible(node)) {
return NodeFilter.FILTER_REJECT;
}
return node.nodeType === Node.TEXT_NODE ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
};
/**
* Extracts all the text nodes within the given range.
* @param {Node} root - the root node in which to search
* @param {Range} range - a range restricting the scope of extraction
* @return {Array<String[]>} - a list of lists of text nodes, in document order.
* Lists represent block boundaries; i.e., two nodes appear in the same list
* iff there are no block element starts or ends in between them.
*/
const getAllTextNodes = (root, range) => {
const blocks = [];
let tmp = [];
const nodes = Array.from(getElementsIn(root, node => {
return acceptNodeIfVisibleInRange(node, range);
}));
for (const node of nodes) {
if (node.nodeType === Node.TEXT_NODE) {
tmp.push(node);
} else if (node instanceof HTMLElement && BLOCK_ELEMENTS.includes(node.tagName.toUpperCase()) && tmp.length > 0) {
// If this is a block element, the current set of text nodes in |tmp| is
// complete, and we need to move on to a new one.
blocks.push(tmp);
tmp = [];
}
}
if (tmp.length > 0) blocks.push(tmp);
return blocks;
};
/**
* Returns the textContent of all the textNodes and normalizes strings by
* replacing duplicated spaces with single space.
* @param {Node[]} nodes - TextNodes to get the textContent from.
* @param {Number} startOffset - Where to start in the first TextNode.
* @param {Number|undefined} endOffset Where to end in the last TextNode.
* @return {string} Entire text content of all the nodes, with spaces
* normalized.
*/
const getTextContent = (nodes, startOffset, endOffset) => {
let str = '';
if (nodes.length === 1) {
str = nodes[0].textContent.substring(startOffset, endOffset);
} else {
str = nodes[0].textContent.substring(startOffset) + nodes.slice(1, -1).reduce((s, n) => s + n.textContent, '') + nodes.slice(-1)[0].textContent.substring(0, endOffset);
}
return str.replace(/[\t\n\r ]+/g, ' ');
};
/**
* @callback ElementFilterFunction
* @param {HTMLElement} element - Node to accept, reject or skip.
* @return {number} Either NodeFilter.FILTER_ACCEPT, NodeFilter.FILTER_REJECT
* or NodeFilter.FILTER_SKIP.
*/
/**
* Returns all nodes inside root using the provided filter.
* @generator
* @param {Node} root - Node where to start the TreeWalker.
* @param {ElementFilterFunction} filter - Filter provided to the TreeWalker's
* acceptNode filter.
* @yield {HTMLElement} All elements that were accepted by filter.
*/
function* getElementsIn(root, filter) {
const treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
acceptNode: filter
});
const finishedSubtrees = new Set();
while (forwardTraverse(treeWalker, finishedSubtrees) !== null) {
yield treeWalker.currentNode;
}
}
/**
* Returns a range pointing to the first instance of |query| within |range|.
* @param {String} query - the string to find
* @param {Range} range - the range in which to search
* @return {Range|Undefined} - The first found instance of |query| within
* |range|.
*/
const findTextInRange = (query, range) => {
const textNodeLists = getAllTextNodes(range.commonAncestorContainer, range);
const segmenter = makeNewSegmenter();
for (const list of textNodeLists) {
const found = findRangeFromNodeList(query, range, list, segmenter);
if (found !== undefined) return found;
}
return undefined;
};
/**
* Finds a range pointing to the first instance of |query| within |range|,
* searching over the text contained in a list |nodeList| of relevant textNodes.
* @param {String} query - the string to find
* @param {Range} range - the range in which to search
* @param {Node[]} textNodes - the visible text nodes within |range|
* @param {Intl.Segmenter} [segmenter] - a segmenter to be used for finding word
* boundaries, if supported
* @return {Range} - the found range, or undefined if no such range could be
* found
*/
const findRangeFromNodeList = (query, range, textNodes, segmenter) => {
if (!query || !range || !(textNodes || []).length) return undefined;
const data = normalizeString(getTextContent(textNodes, 0, undefined));
const normalizedQuery = normalizeString(query);
let searchStart = textNodes[0] === range.startContainer ? range.startOffset : 0;
let start;
let end;
while (searchStart < data.length) {
const matchIndex = data.indexOf(normalizedQuery, searchStart);
if (matchIndex === -1) return undefined;
if (isWordBounded(data, matchIndex, normalizedQuery.length, segmenter)) {
start = getBoundaryPointAtIndex(matchIndex, textNodes, /* isEnd=*/false);
end = getBoundaryPointAtIndex(matchIndex + normalizedQuery.length, textNodes, /* isEnd=*/true);
}
if (start != null && end != null) {
const foundRange = new Range();
foundRange.setStart(start.node, start.offset);
foundRange.setEnd(end.node, end.offset);
// Verify that |foundRange| is a subrange of |range|
if (range.compareBoundaryPoints(Range.START_TO_START, foundRange) <= 0 && range.compareBoundaryPoints(Range.END_TO_END, foundRange) >= 0) {
return foundRange;
}
}
searchStart = matchIndex + 1;
}
return undefined;
};
/**
* Provides the data needed for calling setStart/setEnd on a Range.
* @typedef {Object} BoundaryPoint
* @property {Node} node
* @property {Number} offset
*/
/**
* Generates a boundary point pointing to the given text position.
* @param {Number} index - the text offset indicating the start/end of a
* substring of the concatenated, normalized text in |textNodes|
* @param {Node[]} textNodes - the text Nodes whose contents make up the search
* space
* @param {bool} isEnd - indicates whether the offset is the start or end of the
* substring
* @return {BoundaryPoint} - a boundary point suitable for setting as the start
* or end of a Range, or undefined if it couldn't be computed.
*/
const getBoundaryPointAtIndex = (index, textNodes, isEnd) => {
let counted = 0;
let normalizedData;
for (let i = 0; i < textNodes.length; i++) {
const node = textNodes[i];
if (!normalizedData) normalizedData = normalizeString(node.data);
let nodeEnd = counted + normalizedData.length;
if (isEnd) nodeEnd += 1;
if (nodeEnd > index) {
// |index| falls within this node, but we need to turn the offset in the
// normalized data into an offset in the real node data.
const normalizedOffset = index - counted;
let denormalizedOffset = Math.min(index - counted, node.data.length);
// Walk through the string until denormalizedOffset produces a substring
// that corresponds to the target from the normalized data.
const targetSubstring = isEnd ? normalizedData.substring(0, normalizedOffset) : normalizedData.substring(normalizedOffset);
let candidateSubstring = isEnd ? normalizeString(node.data.substring(0, denormalizedOffset)) : normalizeString(node.data.substring(denormalizedOffset));
// We will either lengthen or shrink the candidate string to approach the
// length of the target string. If we're looking for the start, adding 1
// makes the candidate shorter; if we're looking for the end, it makes the
// candidate longer.
const direction = (isEnd ? -1 : 1) * (targetSubstring.length > candidateSubstring.length ? -1 : 1);
while (denormalizedOffset >= 0 && denormalizedOffset <= node.data.length) {
if (candidateSubstring.length === targetSubstring.length) {
return {
node: node,
offset: denormalizedOffset
};
}
denormalizedOffset += direction;
candidateSubstring = isEnd ? normalizeString(node.data.substring(0, denormalizedOffset)) : normalizeString(node.data.substring(denormalizedOffset));
}
}
counted += normalizedData.length;
if (i + 1 < textNodes.length) {
// Edge case: if this node ends with a whitespace character and the next
// node starts with one, they'll be double-counted relative to the
// normalized version. Subtract 1 from |counted| to compensate.
const nextNormalizedData = normalizeString(textNodes[i + 1].data);
if (normalizedData.slice(-1) === ' ' && nextNormalizedData.slice(0, 1) === ' ') {
counted -= 1;
}
// Since we already normalized the next node's data, hold on to it for the
// next iteration.
normalizedData = nextNormalizedData;
}
}
return undefined;
};
/**
* Checks if a substring is word-bounded in the context of a longer string.
*
* If an Intl.Segmenter is provided for locale-specific segmenting, it will be
* used for this check. This is the most desirable option, but not supported in
* all browsers.
*
* If one is not provided, a heuristic will be applied,
* returning true iff:
* - startPos == 0 OR char before start is a boundary char, AND
* - length indicates end of string OR char after end is a boundary char
* Where boundary chars are whitespace/punctuation defined in the const above.
* This causes the known issue that some languages, notably Japanese, only match
* at the level of roughly a full clause or sentence, rather than a word.
*
* @param {String} text - the text to search
* @param {Number} startPos - the index of the start of the substring
* @param {Number} length - the length of the substring
* @param {Intl.Segmenter} [segmenter] - a segmenter to be used for finding word
* boundaries, if supported
* @return {bool} - true iff startPos and length point to a word-bounded
* substring of |text|.
*/
const isWordBounded = (text, startPos, length, segmenter) => {
if (startPos < 0 || startPos >= text.length || length <= 0 || startPos + length > text.length) {
return false;
}
if (segmenter) {
// If the Intl.Segmenter API is available on this client, use it for more
// reliable word boundary checking.
const segments = segmenter.segment(text);
const startSegment = segments.containing(startPos);
if (!startSegment) return false;
// If the start index is inside a word segment but not the first character
// in that segment, it's not word-bounded. If it's not a word segment, then
// it's punctuation, etc., so that counts for word bounding.
if (startSegment.isWordLike && startSegment.index != startPos) return false;
// |endPos| points to the first character outside the target substring.
const endPos = startPos + length;
const endSegment = segments.containing(endPos);
// If there's no end segment found, it's because we're at the end of the
// text, which is a valid boundary. (Because of the preconditions we
// checked above, we know we aren't out of range.)
// If there's an end segment found but it's non-word-like, that's also OK,
// since punctuation and whitespace are acceptable boundaries.
// Lastly, if there's an end segment and it is word-like, then |endPos|
// needs to point to the start of that new word, or |endSegment.index|.
if (endSegment && endSegment.isWordLike && endSegment.index != endPos) return false;
} else {
// We don't have Intl.Segmenter support, so fall back to checking whether or
// not the substring is flanked by boundary characters.
// If the first character is already a boundary, move it once.
if (text[startPos].match(BOUNDARY_CHARS)) {
++startPos;
--length;
if (!length) {
return false;
}
}
// If the last character is already a boundary, move it once.
if (text[startPos + length - 1].match(BOUNDARY_CHARS)) {
--length;
if (!length) {
return false;
}
}
if (startPos !== 0 && !text[startPos - 1].match(BOUNDARY_CHARS)) return false;
if (startPos + length !== text.length && !text[startPos + length].match(BOUNDARY_CHARS)) return false;
}
return true;
};
/**
* @param {String} str - a string to be normalized
* @return {String} - a normalized version of |str| with all consecutive
* whitespace chars converted to a single ' ' and all diacriticals removed
* (e.g., 'é' -> 'e').
*/
const normalizeString = str => {
// First, decompose any characters with diacriticals. Then, turn all
// consecutive whitespace characters into a standard " ", and strip out
// anything in the Unicode U+0300..U+036F (Combining Diacritical Marks) range.
// This may change the length of the string.
return (str || '').normalize('NFKD').replace(/\s+/g, ' ').replace(/[\u0300-\u036f]/g, '').toLowerCase();
};
/**
* @return {Intl.Segmenter|undefined} - a segmenter object suitable for finding
* word boundaries. Returns undefined on browsers/platforms that do not yet
* support the Intl.Segmenter API.
*/
const makeNewSegmenter = () => {
if (Intl.Segmenter) {
let lang = document.documentElement.lang;
if (!lang) {
lang = navigator.languages;
}
return new Intl.Segmenter(lang, {
granularity: 'word'
});
}
return undefined;
};
/**
* Performs traversal on a TreeWalker, visiting each subtree in document order.
* When visiting a subtree not already visited (its root not in finishedSubtrees
* ), first the root is emitted then the subtree is traversed, then the root is
* emitted again and then the next subtree in document order is visited.
*
* Subtree's roots are emitted twice to signal the beginning and ending of
* element nodes. This is useful for ensuring the ends of block boundaries are
* found.
* @param {TreeWalker} walker - the TreeWalker to be traversed
* @param {Set} finishedSubtrees - set of subtree roots already visited
* @return {Node} - next node in the traversal
*/
const forwardTraverse = (walker, finishedSubtrees) => {
// If current node's subtree is not already finished
// try to go first down the subtree.
if (!finishedSubtrees.has(walker.currentNode)) {
const firstChild = walker.firstChild();
if (firstChild !== null) {
return firstChild;
}
}
// If no subtree go to next sibling if any.
const nextSibling = walker.nextSibling();
if (nextSibling !== null) {
return nextSibling;
}
// If no sibling go back to parent and mark it as finished.
const parent = walker.parentNode();
if (parent !== null) {
finishedSubtrees.add(parent);
}
return parent;
};
/**
* Performs backwards traversal on a TreeWalker, visiting each subtree in
* backwards document order. When visiting a subtree not already visited (its
* root not in finishedSubtrees ), first the root is emitted then the subtree is
* backward traversed, then the root is emitted again and then the previous
* subtree in document order is visited.
*
* Subtree's roots are emitted twice to signal the beginning and ending of
* element nodes. This is useful for ensuring block boundaries are found.
* @param {TreeWalker} walker - the TreeWalker to be traversed
* @param {Set} finishedSubtrees - set of subtree roots already visited
* @return {Node} - next node in the backwards traversal
*/
const backwardTraverse = (walker, finishedSubtrees) => {
// If current node's subtree is not already finished
// try to go first down the subtree.
if (!finishedSubtrees.has(walker.currentNode)) {
const lastChild = walker.lastChild();
if (lastChild !== null) {
return lastChild;
}
}
// If no subtree go to previous sibling if any.
const previousSibling = walker.previousSibling();
if (previousSibling !== null) {
return previousSibling;
}
// If no sibling go back to parent and mark it as finished.
const parent = walker.parentNode();
if (parent !== null) {
finishedSubtrees.add(parent);
}
return parent;
};
/**
* Should only be used by other files in this directory.
*/
const internal = {
BLOCK_ELEMENTS: BLOCK_ELEMENTS,
BOUNDARY_CHARS: BOUNDARY_CHARS,
NON_BOUNDARY_CHARS: NON_BOUNDARY_CHARS,
acceptNodeIfVisibleInRange: acceptNodeIfVisibleInRange,
normalizeString: normalizeString,
makeNewSegmenter: makeNewSegmenter,
forwardTraverse: forwardTraverse,
backwardTraverse: backwardTraverse,
makeTextNodeWalker: makeTextNodeWalker,
isNodeVisible: isNodeVisible
};
// Allow importing module from closure-compiler projects that haven't migrated
// to ES6 modules.
if (typeof goog !== 'undefined') {
// clang-format off
goog.declareModuleId('googleChromeLabs.textFragmentPolyfill.textFragmentUtils');
// clang-format on
}
/**
* Copyright 2020 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
*
* https://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 MAX_EXACT_MATCH_LENGTH = 300;
const MIN_LENGTH_WITHOUT_CONTEXT = 20;
const ITERATIONS_BEFORE_ADDING_CONTEXT = 1;
const WORDS_TO_ADD_FIRST_ITERATION = 3;
const WORDS_TO_ADD_SUBSEQUENT_ITERATIONS = 1;
const TRUNCATE_RANGE_CHECK_CHARS = 10000;
const MAX_DEPTH = 500;
// Desired max run time, in ms. Can be overwritten.
let timeoutDurationMs = 500;
let t0; // Start timestamp for fragment generation
/**
* Allows overriding the max runtime to specify a different interval. Fragment
* generation will halt and throw an error after this amount of time.
* @param {Number} newTimeoutDurationMs - the desired timeout length, in ms.
*/
const setTimeout = newTimeoutDurationMs => {
timeoutDurationMs = newTimeoutDurationMs;
};
/**
* Enum indicating the success, or failure reason, of generateFragment.
*/
exports.setTimeout = setTimeout;
const GenerateFragmentStatus = exports.GenerateFragmentStatus = {
SUCCESS: 0,
// A fragment was generated.
INVALID_SELECTION: 1,
// The selection provided could not be used.
AMBIGUOUS: 2,
// No unique fragment could be identified for this selection.
TIMEOUT: 3,
// Computation could not complete in time.
EXECUTION_FAILED: 4 // An exception was raised during generation.
};
/**
* @typedef {Object} GenerateFragmentResult
* @property {GenerateFragmentStatus} status
* @property {TextFragment} [fragment]
*/
/**
* Attempts to generate a fragment, suitable for formatting and including in a
* URL, which will highlight the given selection upon opening.
* @param {Selection} selection - a Selection object, the result of
* window.getSelection
* @param {Date} [startTime] - the time when generation began, for timeout
* purposes. Defaults to current timestamp.
* @return {GenerateFragmentResult}
*/
const generateFragment = (selection, startTime = Date.now()) => {
return doGenerateFragment(selection, startTime);
};
/**
* Attampts to generate a fragment using a given range. @see {@link generateFragment}
*
* @param {Range} range
* @param {Date} [startTime] - the time when generation began, for timeout
* purposes. Defaults to current timestamp.
* @return {GenerateFragmentResult}
*/
exports.generateFragment = generateFragment;
const generateFragmentFromRange = (range, startTime = Date.now()) => {
try {
return doGenerateFragmentFromRange(range, startTime);
} catch (err) {
if (err.isTimeout) {
return {
status: GenerateFragmentStatus.TIMEOUT
};
} else {
return {
status: GenerateFragmentStatus.EXECUTION_FAILED
};
}
}
};
/**
* Checks whether fragment generation can be attempted for a given range. This
* checks a handful of simple conditions: the range must be nonempty, not inside
* an <input>, etc. A true return is not a guarantee that fragment generation
* will succeed; instead, this is a way to quickly rule out generation in cases
* where a failure is predictable.
* @param {Range} range
* @return {boolean} - true if fragment generation may proceed; false otherwise.
*/
exports.generateFragmentFromRange = generateFragmentFromRange;
const isValidRangeForFragmentGeneration = range => {
// Check that the range isn't just punctuation and whitespace. Only check the
// first |TRUNCATE_RANGE_CHECK_CHARS| to put an upper bound on runtime; ranges
// that start with (e.g.) thousands of periods should be rare.
// This also implicitly ensures the selection isn't in an input or textarea
// field, as document.selection contains an empty range in these cases.
if (!range.toString().substring(0, TRUNCATE_RANGE_CHECK_CHARS).match(internal.NON_BOUNDARY_CHARS)) {
return false;
}
// Check for iframe
try {
if (range.startContainer.ownerDocument.defaultView !== window.top) {
return false;
}
} catch {
// If accessing window.top throws an error, this is in a cross-origin
// iframe.
return false;
}
// Walk up the DOM to ensure that the range isn't inside an editable. Limit
// the search depth to |MAX_DEPTH| to constrain runtime.
let node = range.commonAncestorContainer;
let numIterations = 0;
while (node) {
if (node.nodeType == Node.ELEMENT_NODE) {
if (['TEXTAREA', 'INPUT'].includes(node.tagName.toUpperCase())) {
return false;
}
const editable = node.attributes.getNamedItem('contenteditable');
if (editable && editable.value !== 'false') {
return false;
}
// Cap the number of iterations at |MAX_PRECONDITION_DEPTH| to put an
// upper bound on runtime.
numIterations++;
if (numIterations >= MAX_DEPTH) {
return false;
}
}
node = node.parentNode;
}
return true;
};
/**
* @param {Selection} selection
* @param {Date} startTime
* @return {GenerateFragmentResult}
* @see {@link generateFragment} - this method wraps the error-throwing portions
* of that method.
* @throws {Error} - Will throw if computation takes longer than the accepted
* timeout length.
*/
exports.isValidRangeForFragmentGeneration = isValidRangeForFragmentGeneration;
const doGenerateFragment = (selection, startTime) => {
let range;
try {
range = selection.getRangeAt(0);
} catch {
return {
status: GenerateFragmentStatus.INVALID_SELECTION
};
}
return doGenerateFragmentFromRange(range, startTime);
};
/**
* @param {Range} range
* @param {Date} startTime
* @return {GenerateFragmentResult}
* @see {@link doGenerateFragment}
*/
const doGenerateFragmentFromRange = (range, startTime) => {
recordStartTime(startTime);
expandRangeStartToWordBound(range);
expandRangeEndToWordBound(range);
// Keep a copy of the range before we try to shrink it to make it start and
// end in text nodes. We need to use the range edges as starting points
// for context term building, so it makes sense to start from the original
// edges instead of the edges after shrinking. This way we don't have to
// traverse all the non-text nodes that are between the edges after shrinking
// and the original ones.
const rangeBeforeShrinking = range.cloneRange();
moveRangeEdgesToTextNodes(range);
if (range.collapsed) {
return {
status: GenerateFragmentStatus.INVALID_SELECTION
};
}
let factory;
if (canUseExactMatch(range)) {
const exactText = internal.normalizeString(range.toString());
const fragment = {
textStart: exactText
};
// If the exact text is long enough to be used on its own, try this and skip
// the longer process below.
if (exactText.length >= MIN_LENGTH_WITHOUT_CONTEXT && isUniquelyIdentifying(fragment)) {
return {
status: GenerateFragmentStatus.SUCCESS,
fragment: fragment
};
}
factory = new FragmentFactory().setExactTextMatch(exactText);
} else {
// We have to use textStart and textEnd to identify a range. First, break
// the range up based on block boundaries, as textStart/textEnd can't cross
// these.
const startSearchSpace = getSearchSpaceForStart(range);
const endSearchSpace = getSearchSpaceForEnd(range);
if (startSearchSpace && endSearchSpace) {
// If the search spaces are truthy, then there's a block boundary between
// them.
factory = new FragmentFactory().setStartAndEndSearchSpace(startSearchSpace, endSearchSpace);
} else {
// If the search space was empty/undefined, it's because no block boundary
// was found. That means textStart and textEnd *share* a search space, so
// our approach must ensure the substrings chosen as candidates don't
// overlap.
factory = new FragmentFactory().setSharedSearchSpace(range.toString().trim());
}
}
const prefixRange = document.createRange();
prefixRange.selectNodeContents(document.body);
const suffixRange = prefixRange.cloneRange();
prefixRange.setEnd(rangeBeforeShrinking.startContainer, rangeBeforeShrinking.startOffset);
suffixRange.setStart(rangeBeforeShrinking.endContainer, rangeBeforeShrinking.endOffset);
const prefixSearchSpace = getSearchSpaceForEnd(prefixRange);
const suffixSearchSpace = getSearchSpaceForStart(suffixRange);
if (prefixSearchSpace || suffixSearchSpace) {
factory.setPrefixAndSuffixSearchSpace(prefixSearchSpace, suffixSearchSpace);
}
factory.useSegmenter(internal.makeNewSegmenter());
let didEmbiggen = false;
do {
checkTimeout();
didEmbiggen = factory.embiggen();
const fragment = factory.tryToMakeUniqueFragment();
if (fragment != null) {
return {
status: GenerateFragmentStatus.SUCCESS,
fragment: fragment
};
}
} while (didEmbiggen);
return {
status: GenerateFragmentStatus.AMBIGUOUS
};
};
/**
* @throws {Error} - if the timeout duration has been exceeded, an error will
* be thrown so that execution can be halted.
*/
const checkTimeout = () => {