-
Notifications
You must be signed in to change notification settings - Fork 28
/
fragment-generation-utils.js
1760 lines (1592 loc) · 61.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
/**
* 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.
*/
import * as fragments from './text-fragment-utils.js';
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.
*/
export const setTimeout = (newTimeoutDurationMs) => {
timeoutDurationMs = newTimeoutDurationMs;
};
/**
* Enum indicating the success, or failure reason, of generateFragment.
*/
export const 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}
*/
export 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}
*/
export 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.
*/
export 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(fragments.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.
*/
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 = fragments.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(fragments.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 = () => {
// disable check when no timeout duration specified
if (timeoutDurationMs === null) {
return;
}
const delta = Date.now() - t0;
if (delta > timeoutDurationMs) {
const timeoutError =
new Error(`Fragment generation timed out after ${delta} ms.`);
timeoutError.isTimeout = true;
throw timeoutError;
}
};
/**
* Call at the start of fragment generation to set the baseline for timeout
* checking.
* @param {Date} newStartTime - the timestamp when fragment generation began
*/
const recordStartTime = (newStartTime) => {
t0 = newStartTime;
};
/**
* Finds the search space for parameters when using range or suffix match.
* This is the text from the start of the range to the first block boundary,
* trimmed to remove any leading/trailing whitespace characters.
* @param {Range} range - the range which will be highlighted.
* @return {String|Undefined} - the text which may be used for constructing a
* textStart parameter identifying this range. Will return undefined if no
* block boundaries are found inside this range, or if all the candidate
* ranges were empty (or included only whitespace characters).
*/
const getSearchSpaceForStart = (range) => {
let node = getFirstNodeForBlockSearch(range);
const walker = makeWalkerForNode(node, range.endContainer);
if (!walker) {
return undefined;
}
const finishedSubtrees = new Set();
// If the range starts after the last child of an element node
// don't visit its subtree because it's not included in the range.
if (range.startContainer.nodeType === Node.ELEMENT_NODE &&
range.startOffset === range.startContainer.childNodes.length) {
finishedSubtrees.add(range.startContainer);
}
const origin = node;
const textAccumulator = new BlockTextAccumulator(range, true);
// tempRange monitors whether we've exhausted our search space yet.
const tempRange = range.cloneRange();
while (!tempRange.collapsed && node != null) {
checkTimeout();
// Depending on whether |node| is an ancestor of the start of our
// search, we use either its leading or trailing edge as our start.
if (node.contains(origin)) {
tempRange.setStartAfter(node);
} else {
tempRange.setStartBefore(node);
}
// Add node to accumulator to keep track of text inside the current block
// boundaries
textAccumulator.appendNode(node);
// If the accumulator found a non empty block boundary we've got our search
// space.
if (textAccumulator.textInBlock !== null) {
return textAccumulator.textInBlock;
}
node = fragments.internal.forwardTraverse(walker, finishedSubtrees);
}
return undefined;
};
/**
* Finds the search space for parameters when using range or prefix match.
* This is the text from the last block boundary to the end of the range,
* trimmed to remove any leading/trailing whitespace characters.
* @param {Range} range - the range which will be highlighted.
* @return {String|Undefined} - the text which may be used for constructing a
* textEnd parameter identifying this range. Will return undefined if no
* block boundaries are found inside this range, or if all the candidate
* ranges were empty (or included only whitespace characters).
*/
const getSearchSpaceForEnd = (range) => {
let node = getLastNodeForBlockSearch(range);
const walker = makeWalkerForNode(node, range.startContainer);
if (!walker) {
return undefined;
}
const finishedSubtrees = new Set();
// If the range ends before the first child of an element node
// don't visit its subtree because it's not included in the range.
if (range.endContainer.nodeType === Node.ELEMENT_NODE &&
range.endOffset === 0) {
finishedSubtrees.add(range.endContainer);
}
const origin = node;
const textAccumulator = new BlockTextAccumulator(range, false);
// tempRange monitors whether we've exhausted our search space yet.
const tempRange = range.cloneRange();
while (!tempRange.collapsed && node != null) {
checkTimeout();
// Depending on whether |node| is an ancestor of the start of our
// search, we use either its leading or trailing edge as our end.
if (node.contains(origin)) {
tempRange.setEnd(node, 0);
} else {
tempRange.setEndAfter(node);
}
// Add node to accumulator to keep track of text inside the current block
// boundaries.
textAccumulator.appendNode(node);
// If the accumulator found a non empty block boundary we've got our search
// space.
if (textAccumulator.textInBlock !== null) {
return textAccumulator.textInBlock;
}
node = fragments.internal.backwardTraverse(walker, finishedSubtrees);
}
return undefined;
};
/**
* Helper class for constructing range-based fragments for selections that cross
* block boundaries.
*/
const FragmentFactory = class {
/**
* Initializes the basic state of the factory. Users should then call exactly
* one of setStartAndEndSearchSpace, setSharedSearchSpace, or
* setExactTextMatch, and optionally setPrefixAndSuffixSearchSpace.
*/
constructor() {
this.Mode = {
ALL_PARTS: 1,
SHARED_START_AND_END: 2,
CONTEXT_ONLY: 3,
};
this.startOffset = null;
this.endOffset = null;
this.prefixOffset = null;
this.suffixOffset = null;
this.prefixSearchSpace = '';
this.backwardsPrefixSearchSpace = '';
this.suffixSearchSpace = '';
this.numIterations = 0;
}
/**
* Generates a fragment based on the current state, then tests it for
* uniqueness.
* @return {TextFragment|Undefined} - a text fragment if the current state is
* uniquely identifying, or undefined if the current state is ambiguous.
*/
tryToMakeUniqueFragment() {
let fragment;
if (this.mode === this.Mode.CONTEXT_ONLY) {
fragment = {textStart: this.exactTextMatch};
} else {
fragment = {
textStart:
this.getStartSearchSpace().substring(0, this.startOffset).trim(),
textEnd: this.getEndSearchSpace().substring(this.endOffset).trim(),
};
}
if (this.prefixOffset != null) {
const prefix =
this.getPrefixSearchSpace().substring(this.prefixOffset).trim();
if (prefix) {
fragment.prefix = prefix;
}
}
if (this.suffixOffset != null) {
const suffix =
this.getSuffixSearchSpace().substring(0, this.suffixOffset).trim();
if (suffix) {
fragment.suffix = suffix;
}
}
return isUniquelyIdentifying(fragment) ? fragment : undefined;
}
/**
* Shifts the current state such that the candidates for textStart and textEnd
* represent more of the possible search spaces.
* @return {boolean} - true if the desired expansion occurred; false if the
* entire search space has been consumed and no further attempts can be
* made.
*/
embiggen() {
let canExpandRange = true;
if (this.mode === this.Mode.SHARED_START_AND_END) {
if (this.startOffset >= this.endOffset) {
// If the search space is shared between textStart and textEnd, then
// stop expanding when textStart overlaps textEnd.
canExpandRange = false;
}
} else if (this.mode === this.Mode.ALL_PARTS) {
// Stop expanding if both start and end have already consumed their full
// search spaces.
if (this.startOffset === this.getStartSearchSpace().length &&
this.backwardsEndOffset() === this.getEndSearchSpace().length) {
canExpandRange = false;
}
} else if (this.mode === this.Mode.CONTEXT_ONLY) {
canExpandRange = false;
}
if (canExpandRange) {
const desiredIterations = this.getNumberOfRangeWordsToAdd();
if (this.startOffset < this.getStartSearchSpace().length) {
let i = 0;
if (this.getStartSegments() != null) {
while (i < desiredIterations &&
this.startOffset < this.getStartSearchSpace().length) {
this.startOffset = this.getNextOffsetForwards(
this.getStartSegments(), this.startOffset,
this.getStartSearchSpace());
i++;
}
} else {
// We don't have a segmenter, so find the next boundary character
// instead. Shift to the next boundary char, and repeat until we've
// added a word char.
let oldStartOffset = this.startOffset;
do {
checkTimeout();
const newStartOffset =
this.getStartSearchSpace()
.substring(this.startOffset + 1)
.search(fragments.internal.BOUNDARY_CHARS);
if (newStartOffset === -1) {
this.startOffset = this.getStartSearchSpace().length;
} else {
this.startOffset = this.startOffset + 1 + newStartOffset;
}
// Only count as an iteration if a word character was added.
if (this.getStartSearchSpace()
.substring(oldStartOffset, this.startOffset)
.search(fragments.internal.NON_BOUNDARY_CHARS) !== -1) {
oldStartOffset = this.startOffset;
i++;
}
} while (this.startOffset < this.getStartSearchSpace().length &&
i < desiredIterations);
}
// Ensure we don't have overlapping start and end offsets.
if (this.mode === this.Mode.SHARED_START_AND_END) {
this.startOffset = Math.min(this.startOffset, this.endOffset);
}
}
if (this.backwardsEndOffset() < this.getEndSearchSpace().length) {
let i = 0;
if (this.getEndSegments() != null) {
while (i < desiredIterations && this.endOffset > 0) {
this.endOffset = this.getNextOffsetBackwards(
this.getEndSegments(), this.endOffset);
i++;
}
} else {
// No segmenter, so shift to the next boundary char, and repeat until
// we've added a word char.
let oldBackwardsEndOffset = this.backwardsEndOffset();
do {
checkTimeout();
const newBackwardsOffset =
this.getBackwardsEndSearchSpace()
.substring(this.backwardsEndOffset() + 1)
.search(fragments.internal.BOUNDARY_CHARS);
if (newBackwardsOffset === -1) {
this.setBackwardsEndOffset(this.getEndSearchSpace().length);
} else {
this.setBackwardsEndOffset(
this.backwardsEndOffset() + 1 + newBackwardsOffset);
}
// Only count as an iteration if a word character was added.
if (this.getBackwardsEndSearchSpace()
.substring(oldBackwardsEndOffset, this.backwardsEndOffset())
.search(fragments.internal.NON_BOUNDARY_CHARS) !== -1) {
oldBackwardsEndOffset = this.backwardsEndOffset();
i++;
}
} while (this.backwardsEndOffset() <
this.getEndSearchSpace().length &&
i < desiredIterations);
}
// Ensure we don't have overlapping start and end offsets.
if (this.mode === this.Mode.SHARED_START_AND_END) {
this.endOffset = Math.max(this.startOffset, this.endOffset);
}
}
}
let canExpandContext = false;
if (!canExpandRange ||
this.startOffset + this.backwardsEndOffset() <
MIN_LENGTH_WITHOUT_CONTEXT ||
this.numIterations >= ITERATIONS_BEFORE_ADDING_CONTEXT) {
// Check if there's any unused search space left.
if ((this.backwardsPrefixOffset() != null &&
this.backwardsPrefixOffset() !==
this.getPrefixSearchSpace().length) ||
(this.suffixOffset != null &&
this.suffixOffset !== this.getSuffixSearchSpace().length)) {
canExpandContext = true;
}
}
if (canExpandContext) {
const desiredIterations = this.getNumberOfContextWordsToAdd();
if (this.backwardsPrefixOffset() < this.getPrefixSearchSpace().length) {
let i = 0;
if (this.getPrefixSegments() != null) {
while (i < desiredIterations && this.prefixOffset > 0) {
this.prefixOffset = this.getNextOffsetBackwards(
this.getPrefixSegments(), this.prefixOffset);
i++;
}
} else {
// Shift to the next boundary char, and repeat until we've added a
// word char.
let oldBackwardsPrefixOffset = this.backwardsPrefixOffset();
do {
checkTimeout();
const newBackwardsPrefixOffset =
this.getBackwardsPrefixSearchSpace()
.substring(this.backwardsPrefixOffset() + 1)
.search(fragments.internal.BOUNDARY_CHARS);
if (newBackwardsPrefixOffset === -1) {
this.setBackwardsPrefixOffset(
this.getBackwardsPrefixSearchSpace().length);
} else {
this.setBackwardsPrefixOffset(
this.backwardsPrefixOffset() + 1 + newBackwardsPrefixOffset);
}
// Only count as an iteration if a word character was added.
if (this.getBackwardsPrefixSearchSpace()
.substring(
oldBackwardsPrefixOffset, this.backwardsPrefixOffset())
.search(fragments.internal.NON_BOUNDARY_CHARS) !== -1) {
oldBackwardsPrefixOffset = this.backwardsPrefixOffset();
i++;
}
} while (this.backwardsPrefixOffset() <
this.getPrefixSearchSpace().length &&
i < desiredIterations);
}
}
if (this.suffixOffset < this.getSuffixSearchSpace().length) {
let i = 0;
if (this.getSuffixSegments() != null) {
while (i < desiredIterations &&
this.suffixOffset < this.getSuffixSearchSpace().length) {
this.suffixOffset = this.getNextOffsetForwards(
this.getSuffixSegments(), this.suffixOffset,
this.getSuffixSearchSpace());
i++;
}
} else {
let oldSuffixOffset = this.suffixOffset;
do {
checkTimeout();
const newSuffixOffset =
this.getSuffixSearchSpace()
.substring(this.suffixOffset + 1)
.search(fragments.internal.BOUNDARY_CHARS);
if (newSuffixOffset === -1) {
this.suffixOffset = this.getSuffixSearchSpace().length;
} else {
this.suffixOffset = this.suffixOffset + 1 + newSuffixOffset;
}
// Only count as an iteration if a word character was added.
if (this.getSuffixSearchSpace()
.substring(oldSuffixOffset, this.suffixOffset)
.search(fragments.internal.NON_BOUNDARY_CHARS) !== -1) {
oldSuffixOffset = this.suffixOffset;
i++;
}
} while (this.suffixOffset < this.getSuffixSearchSpace().length &&
i < desiredIterations);
}
}
}
this.numIterations++;
// TODO: check if this exceeds the total length limit
return canExpandRange || canExpandContext;
}
/**
* Sets up the factory for a range-based match with a highlight that crosses
* block boundaries.
*
* Exactly one of this, setSharedSearchSpace, or setExactTextMatch should be
* called so the factory can identify the fragment.
*
* @param {String} startSearchSpace - the maximum possible string which can be
* used to identify the start of the fragment
* @param {String} endSearchSpace - the maximum possible string which can be
* used to identify the end of the fragment
* @return {FragmentFactory} - returns |this| to allow call chaining and
* assignment
*/
setStartAndEndSearchSpace(startSearchSpace, endSearchSpace) {
this.startSearchSpace = startSearchSpace;
this.endSearchSpace = endSearchSpace;
this.backwardsEndSearchSpace = reverseString(endSearchSpace);
this.startOffset = 0;
this.endOffset = endSearchSpace.length;
this.mode = this.Mode.ALL_PARTS;
return this;
}
/**
* Sets up the factory for a range-based match with a highlight that doesn't
* cross block boundaries.
*
* Exactly one of this, setStartAndEndSearchSpace, or setExactTextMatch should
* be called so the factory can identify the fragment.
*
* @param {String} sharedSearchSpace - the full text of the highlight
* @return {FragmentFactory} - returns |this| to allow call chaining and
* assignment
*/
setSharedSearchSpace(sharedSearchSpace) {
this.sharedSearchSpace = sharedSearchSpace;
this.backwardsSharedSearchSpace = reverseString(sharedSearchSpace);
this.startOffset = 0;
this.endOffset = sharedSearchSpace.length;
this.mode = this.Mode.SHARED_START_AND_END;
return this;
}
/**
* Sets up the factory for an exact text match.
*
* Exactly one of this, setStartAndEndSearchSpace, or setSharedSearchSpace
* should be called so the factory can identify the fragment.
*
* @param {String} exactTextMatch - the full text of the highlight
* @return {FragmentFactory} - returns |this| to allow call chaining and
* assignment
*/
setExactTextMatch(exactTextMatch) {
this.exactTextMatch = exactTextMatch;
this.mode = this.Mode.CONTEXT_ONLY;
return this;
}
/**
* Sets up the factory for context-based matches.
*
* @param {String} prefixSearchSpace - the string to be used as the search
* space for prefix
* @param {String} suffixSearchSpace - the string to be used as the search
* space for suffix
* @return {FragmentFactory} - returns |this| to allow call chaining and
* assignment
*/
setPrefixAndSuffixSearchSpace(prefixSearchSpace, suffixSearchSpace) {
if (prefixSearchSpace) {
this.prefixSearchSpace = prefixSearchSpace;
this.backwardsPrefixSearchSpace = reverseString(prefixSearchSpace);
this.prefixOffset = prefixSearchSpace.length;
}
if (suffixSearchSpace) {
this.suffixSearchSpace = suffixSearchSpace;
this.suffixOffset = 0;
}
return this;
}
/**
* Sets up the factory to use an instance of Intl.Segmenter when identifying
* the start/end of words. |segmenter| is not actually retained; instead it is
* used to create segment objects which are cached.
*
* This must be called AFTER any calls to setStartAndEndSearchSpace,
* setSharedSearchSpace, and/or setPrefixAndSuffixSearchSpace, as these search
* spaces will be segmented immediately.
*
* @param {Intl.Segmenter | Undefined} segmenter
* @return {FragmentFactory} - returns |this| to allow call chaining and
* assignment
*/
useSegmenter(segmenter) {
if (segmenter == null) {
return this;
}
if (this.mode === this.Mode.ALL_PARTS) {
this.startSegments = segmenter.segment(this.startSearchSpace);
this.endSegments = segmenter.segment(this.endSearchSpace);
} else if (this.mode === this.Mode.SHARED_START_AND_END) {
this.sharedSegments = segmenter.segment(this.sharedSearchSpace);
}
if (this.prefixSearchSpace) {
this.prefixSegments = segmenter.segment(this.prefixSearchSpace);
}
if (this.suffixSearchSpace) {
this.suffixSegments = segmenter.segment(this.suffixSearchSpace);
}
return this;
}
/**
* @return {number} - how many words should be added to the prefix and suffix
* when embiggening. This changes depending on the current state of the
* prefix/suffix, so it should be invoked once per embiggen, before either
* is modified.
*/
getNumberOfContextWordsToAdd() {
return (this.backwardsPrefixOffset() === 0 && this.suffixOffset === 0) ?
WORDS_TO_ADD_FIRST_ITERATION :
WORDS_TO_ADD_SUBSEQUENT_ITERATIONS;
}
/**
* @return {number} - how many words should be added to textStart and textEnd
* when embiggening. This changes depending on the current state of
* textStart/textEnd, so it should be invoked once per embiggen, before
* either is modified.
*/
getNumberOfRangeWordsToAdd() {
return (this.startOffset === 0 && this.backwardsEndOffset() === 0) ?
WORDS_TO_ADD_FIRST_ITERATION :
WORDS_TO_ADD_SUBSEQUENT_ITERATIONS;
}
/**
* Helper method for embiggening using Intl.Segmenter. Finds the next offset
* to be tried in the forwards direction (i.e., a prefix of the search space).
* @param {Segments} segments - the output of segmenting the desired search
* space using Intl.Segmenter
* @param {number} offset - the current offset
* @param {string} searchSpace - the search space that was segmented
* @return {number} - the next offset which should be tried.
*/
getNextOffsetForwards(segments, offset, searchSpace) {
// Find the nearest wordlike segment and move to the end of it.
let currentSegment = segments.containing(offset);
while (currentSegment != null) {
checkTimeout();
const currentSegmentEnd =
currentSegment.index + currentSegment.segment.length;
if (currentSegment.isWordLike) {
return currentSegmentEnd;
}
currentSegment = segments.containing(currentSegmentEnd);
}
// If we didn't find a wordlike segment by the end of the string, set the
// offset to the full search space.
return searchSpace.length;
}
/**
* Helper method for embiggening using Intl.Segmenter. Finds the next offset
* to be tried in the backwards direction (i.e., a suffix of the search
* space).
* @param {Segments} segments - the output of segmenting the desired search
* space using Intl.Segmenter
* @param {number} offset - the current offset
* @return {number} - the next offset which should be tried.
*/
getNextOffsetBackwards(segments, offset) {
// Find the nearest wordlike segment and move to the start of it.
let currentSegment = segments.containing(offset);
// Handle two edge cases:
// 1. |offset| is at the end of the search space, so |currentSegment|
// is undefined
// 2. We're already at the start of a segment, so moving to the start of
// |currentSegment| would be a no-op.
// In both cases, the solution is to grab the segment immediately
// prior to this offset.
if (!currentSegment || offset == currentSegment.index) {
// If offset is 0, this will return null, which is handled below.
currentSegment = segments.containing(offset - 1);
}
while (currentSegment != null) {
checkTimeout();
if (currentSegment.isWordLike) {
return currentSegment.index;
}
currentSegment = segments.containing(currentSegment.index - 1);
}
// If we didn't find a wordlike segment by the start of the string,
// set the offset to the full search space.
return 0;
}
/**
* @return {String} - the string to be used as the search space for textStart
*/
getStartSearchSpace() {
return this.mode === this.Mode.SHARED_START_AND_END ?
this.sharedSearchSpace :
this.startSearchSpace;
}
/**
* @return {Segments | Undefined} - the result of segmenting the start search
* space using Intl.Segmenter, or undefined if a segmenter was not
* provided.
*/
getStartSegments() {
return this.mode === this.Mode.SHARED_START_AND_END ? this.sharedSegments :
this.startSegments;
}
/**
* @return {String} - the string to be used as the search space for textEnd
*/
getEndSearchSpace() {
return this.mode === this.Mode.SHARED_START_AND_END ?
this.sharedSearchSpace :
this.endSearchSpace;
}
/**
* @return {Segments | Undefined} - the result of segmenting the end search
* space using Intl.Segmenter, or undefined if a segmenter was not
* provided.
*/
getEndSegments() {
return this.mode === this.Mode.SHARED_START_AND_END ? this.sharedSegments :
this.endSegments;
}
/**
* @return {String} - the string to be used as the search space for textEnd,
* backwards.
*/
getBackwardsEndSearchSpace() {
return this.mode === this.Mode.SHARED_START_AND_END ?
this.backwardsSharedSearchSpace :
this.backwardsEndSearchSpace;
}
/**
* @return {String} - the string to be used as the search space for prefix
*/
getPrefixSearchSpace() {
return this.prefixSearchSpace;
}
/**
* @return {Segments | Undefined} - the result of segmenting the prefix
* search space using Intl.Segmenter, or undefined if a segmenter was not
* provided.
*/
getPrefixSegments() {
return this.prefixSegments;
}
/**
* @return {String} - the string to be used as the search space for prefix,
* backwards.
*/
getBackwardsPrefixSearchSpace() {
return this.backwardsPrefixSearchSpace;
}
/**
* @return {String} - the string to be used as the search space for suffix
*/
getSuffixSearchSpace() {
return this.suffixSearchSpace;
}
/**
* @return {Segments | Undefined} - the result of segmenting the suffix
* search space using Intl.Segmenter, or undefined if a segmenter was not
* provided.
*/
getSuffixSegments() {
return this.suffixSegments;
}
/**
* Helper method for doing arithmetic in the backwards search space.
* @return {Number} - the current end offset, as a start offset in the
* backwards search space
*/
backwardsEndOffset() {
return this.getEndSearchSpace().length - this.endOffset;
}
/**
* Helper method for doing arithmetic in the backwards search space.
* @param {Number} backwardsEndOffset - the desired new value of the start
* offset in the backwards search space
*/
setBackwardsEndOffset(backwardsEndOffset) {
this.endOffset = this.getEndSearchSpace().length - backwardsEndOffset;
}
/**
* Helper method for doing arithmetic in the backwards search space.
* @return {Number} - the current prefix offset, as a start offset in the
* backwards search space
*/
backwardsPrefixOffset() {
if (this.prefixOffset == null) return null;
return this.getPrefixSearchSpace().length - this.prefixOffset;
}