-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathlink_hints.js
1518 lines (1383 loc) · 53.4 KB
/
link_hints.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
//
// This implements link hinting. Typing "F" will enter link-hinting mode, where all clickable items
// on the page have a hint marker displayed containing a sequence of letters. Typing those letters
// will select a link.
//
// In our 'default' mode, the characters we use to show link hints are a user-configurable option.
// By default they're the home row. The CSS which is used on the link hints is also a configurable
// option.
//
// In 'filter' mode, our link hints are numbers, and the user can narrow down the range of
// possibilities by typing the text of the link itself.
//
// A DOM element that sits on top of a link, showing the key the user should type to select the
// link.
class HintMarker {
hintDescriptor;
localHint;
linkText; // Used in FilterHints
hintString; // Used in AlphabetHints
markerRect; // Cached rectangle of the element, used for rotating hints.
// Element is null if the hint marker reflects a hint that's owned by another frame.
element;
// Cached book-keeping when computing a marker's score against a query.
linkWords;
score;
stableSortCount;
constructor() {
Object.seal(this);
}
isLocalMarker() {
return this.localHint != null;
}
}
// A clickable element in the current frame, plus metadata about how to show a hint marker for it.
class LocalHint {
element; // The clickable element.
image; // When element is an <area> (image map), `image` is its associated image.
rect; // The rectangle where the hint should shown, to avoid overlapping with other hints.
linkText; // Used in FilterHints.
showLinkText; // Used in FilterHints.
// The reason that an element has a link hint when the reason isn't obvious, e.g. the body of a
// frame so that the frame can be focused. This reason is shown to the user in the hint's caption.
reason;
// "secondClassCitizen" means the element isn't clickable, but does have a tab index. We show
// hints for these elements unless their hit box collides with another clickable element.
secondClassCitizen;
// An element that may be clickable based on our heuristics. It's a "false positive" if one of its
// child elements is detected as clickable.
possibleFalsePositive;
constructor(o) {
Object.seal(this);
if (o) Object.assign(this, o);
}
}
// Metadata about each LocalHint which is transferred to other frames in the current tab, so that
// every frame can be aware of every other frame's local hints.
class HintDescriptor {
frameId; // The frameId that the hint is local to.
localIndex; // An index into the owner frame's localHints.
linkText; // The link's text. This is non-null only for FilterHints.
constructor(o) {
Object.seal(this);
if (o) Object.assign(this, o);
}
}
// The "name" property below is a short-form name to appear in the link-hints mode's name. It's for
// debug only.
//
const isMac = KeyboardUtils.platform === "Mac";
const OPEN_IN_CURRENT_TAB = {
name: "curr-tab",
indicator: "Open link in current tab",
};
const OPEN_IN_NEW_BG_TAB = {
name: "bg-tab",
indicator: "Open link in new tab",
clickModifiers: { metaKey: isMac, ctrlKey: !isMac },
};
const OPEN_IN_NEW_FG_TAB = {
name: "fg-tab",
indicator: "Open link in new tab and switch to it",
clickModifiers: { shiftKey: true, metaKey: isMac, ctrlKey: !isMac },
};
const OPEN_WITH_QUEUE = {
name: "queue",
indicator: "Open multiple links in new tabs",
clickModifiers: { metaKey: isMac, ctrlKey: !isMac },
};
const COPY_LINK_URL = {
name: "link",
indicator: "Copy link URL to Clipboard",
linkActivator(link) {
if (link.href != null) {
let url = link.href;
if (url.slice(0, 7) === "mailto:") url = url.slice(7);
HUD.copyToClipboard(url);
if (28 < url.length) url = url.slice(0, 26) + "....";
HUD.show(`Yanked ${url}`, 2000);
} else {
HUD.show("No link to yank.", 2000);
}
},
};
const OPEN_INCOGNITO = {
name: "incognito",
indicator: "Open link in incognito window",
linkActivator(link) {
chrome.runtime.sendMessage({ handler: "openUrlInIncognito", url: link.href });
},
};
const DOWNLOAD_LINK_URL = {
name: "download",
indicator: "Download link URL",
clickModifiers: { altKey: true, ctrlKey: false, metaKey: false },
};
const COPY_LINK_TEXT = {
name: "copy-link-text",
indicator: "Copy link text",
linkActivator(link) {
let text = link.textContent;
if (text.length > 0) {
HUD.copyToClipboard(text);
if (28 < text.length) text = text.slice(0, 26) + "....";
HUD.show(`Yanked ${text}`, 2000);
} else {
HUD.show("No text to yank.", 2000);
}
},
};
const HOVER_LINK = {
name: "hover",
indicator: "Hover link",
linkActivator(link) {
new HoverMode(link);
},
};
const FOCUS_LINK = {
name: "focus",
indicator: "Focus link",
linkActivator(link) {
link.focus();
},
};
const availableModes = [
OPEN_IN_CURRENT_TAB,
OPEN_IN_NEW_BG_TAB,
OPEN_IN_NEW_FG_TAB,
OPEN_WITH_QUEUE,
COPY_LINK_URL,
OPEN_INCOGNITO,
DOWNLOAD_LINK_URL,
COPY_LINK_TEXT,
HOVER_LINK,
FOCUS_LINK,
];
const HintCoordinator = {
onExit: [],
localHints: null,
cacheAllKeydownEvents: null,
// A WeakRef to the last clicked element. We track this so that we can mouse of it if the user
// types ESC after clicking on it. See #3073.
lastClickedElementRef: null,
// Returns if the HintCoordinator will handle a given LinkHintsMessage.
// Some messages will not be handled in the case where the help dialog is shown, and is then
// hidden, but is still receiving link hints messages via broadcastLinkHintsMessage.
willHandleMessage(messageType) {
if (this.linkHintsMode) return true;
return ["prepareToActivateMode", "activateMode", "getHintDescriptors", "exit"].includes(
messageType,
);
},
sendMessage(messageType, request) {
if (request == null) request = {};
request = Object.assign(request, { messageType, handler: "broadcastLinkHintsMessage" });
chrome.runtime.sendMessage(request);
},
prepareToActivateMode(mode, onExit) {
// We need to communicate with the background page (and other frames) to initiate link-hints
// mode. To prevent other Vimium commands from being triggered before link-hints mode is
// launched, we install a temporary mode to block (and cache) keyboard events.
let cacheAllKeydownEvents;
this.cacheAllKeydownEvents = cacheAllKeydownEvents = new CacheAllKeydownEvents({
name: "link-hints/suppress-keyboard-events",
singleton: "link-hints-mode",
indicator: "Collecting hints...",
exitOnEscape: true,
});
// FIXME(smblott) Global link hints is currently insufficiently reliable. If the mode above is
// left in place, then Vimium blocks. As a temporary measure, we install a timer to remove it.
// TODO(philc): I believe link hints is sufficiently reliable after the manifest V3 port
// that this safeguard can now be removed.
Utils.setTimeout(1000, function () {
if (cacheAllKeydownEvents && cacheAllKeydownEvents.modeIsActive) {
cacheAllKeydownEvents.exit();
}
});
this.onExit = [onExit];
chrome.runtime.sendMessage({
handler: "prepareToActivateLinkHintsMode",
modeIndex: availableModes.indexOf(mode),
isVimiumHelpDialog: globalThis.isVimiumHelpDialog,
isVimiumOptionsPage: globalThis.isVimiumOptionsPage,
});
},
// Returns a list of HintDescriptors. Hint descriptors are global. They include all of the
// information necessary for each frame to determine whether and when a hint from *any* frame is
// selected.
getHintDescriptors({ modeIndex, isVimiumHelpDialog }, _sender) {
if (!DomUtils.isReady() || DomUtils.windowIsTooSmall()) return [];
const requireHref = [COPY_LINK_URL, OPEN_INCOGNITO].includes(availableModes[modeIndex]);
// If link hints is launched within the help dialog, then we only offer hints from that frame.
// This improves the usability of the help dialog on the options page (particularly for
// selecting command names).
if (isVimiumHelpDialog && !globalThis.isVimiumHelpDialog) {
this.localHints = [];
} else {
this.localHints = LocalHints.getLocalHints(requireHref);
}
this.localHintDescriptors = this.localHints.map(({ linkText }, localIndex) => (
new HintDescriptor({
frameId,
localIndex,
linkText,
})
));
return this.localHintDescriptors;
},
// We activate LinkHintsMode() in every frame and provide every frame with exactly the same hint
// descriptors. We also propagate the key state between frames. Therefore, the hint-selection
// process proceeds in lock step in every frame, and this.linkHintsMode is in the same state in
// every frame.
activateMode({ frameId, frameIdToHintDescriptors, modeIndex, originatingFrameId }) {
// We do not receive the frame's own hint descritors back from the background page. Instead, we
// merge them with the hint descriptors from other frames here. Note that
// this.localHintDescriptors can be null if "getHintDescriptors" failed in this frame when it
// was last called, or if this frame didn't exist at the time that hints were requested.
frameIdToHintDescriptors[frameId] = this.localHintDescriptors || [];
this.localHintDescriptors = null;
const hintDescriptors = Object.keys(frameIdToHintDescriptors)
.sort()
.flatMap((frame) => frameIdToHintDescriptors[frame]);
if (this.cacheAllKeydownEvents?.modeIsActive) {
this.cacheAllKeydownEvents.exit();
}
if (frameId !== originatingFrameId) {
this.onExit = [];
}
this.linkHintsMode = new LinkHintsMode(hintDescriptors, availableModes[modeIndex]);
// Replay keydown events which we missed (but for filtered hints only).
if (Settings.get("filterLinkHints" && this.cacheAllKeydownEvents)) {
this.cacheAllKeydownEvents.replayKeydownEvents();
}
this.cacheAllKeydownEvents = null;
},
// The following messages are exchanged between frames while link-hints mode is active.
updateKeyState(request) {
this.linkHintsMode.updateKeyState(request);
},
rotateHints() {
this.linkHintsMode.rotateHints();
},
setOpenLinkMode({ modeIndex }) {
this.linkHintsMode.setOpenLinkMode(availableModes[modeIndex], false);
},
activateActiveHintMarker() {
this.linkHintsMode.activateLink(this.linkHintsMode.markerMatcher.activeHintMarker);
},
getLocalHint(hint) {
return this.localHints[hint.localIndex];
},
exit({ isSuccess }) {
if (this.linkHintsMode != null) {
this.linkHintsMode.deactivateMode();
}
while (this.onExit.length > 0) {
this.onExit.pop()(isSuccess);
}
this.linkHintsMode = this.localHints = null;
},
mouseOutOfLastClickedElement() {
if (this.lastClickedElementRef == null) return;
const el = this.lastClickedElementRef.deref();
if (el) {
DomUtils.simulateMouseEvent("mouseout", el, null);
}
this.lastClickedElementRef = null;
},
};
const LinkHints = {
activateMode(count, { mode, registryEntry }) {
if (count == null) count = 1;
if (mode == null) mode = OPEN_IN_CURRENT_TAB;
switch (registryEntry?.options.action) {
case "copy-text":
mode = COPY_LINK_TEXT;
break;
case "hover":
mode = HOVER_LINK;
break;
case "focus":
mode = FOCUS_LINK;
break;
}
if ((count > 0) || (mode === OPEN_WITH_QUEUE)) {
HintCoordinator.prepareToActivateMode(mode, function (isSuccess) {
if (isSuccess) {
// Wait for the next tick to allow the previous mode to exit. It might yet generate a
// click event, which would cause our new mode to exit immediately.
Utils.nextTick(() => LinkHints.activateMode(count - 1, { mode }));
}
});
}
},
activateModeToOpenInNewTab(count) {
this.activateMode(count, { mode: OPEN_IN_NEW_BG_TAB });
},
activateModeToOpenInNewForegroundTab(count) {
this.activateMode(count, { mode: OPEN_IN_NEW_FG_TAB });
},
activateModeToCopyLinkUrl(count) {
this.activateMode(count, { mode: COPY_LINK_URL });
},
activateModeWithQueue() {
this.activateMode(1, { mode: OPEN_WITH_QUEUE });
},
activateModeToOpenIncognito(count) {
this.activateMode(count, { mode: OPEN_INCOGNITO });
},
activateModeToDownloadLink(count) {
this.activateMode(count, { mode: DOWNLOAD_LINK_URL });
},
};
class LinkHintsMode {
// @mode: One of the enums listed at the top of this file.
constructor(hintDescriptors, mode) {
if (mode == null) mode = OPEN_IN_CURRENT_TAB;
this.mode = mode;
// We need documentElement to be ready in order to append links.
if (!document.documentElement) return;
this.containerEl = null;
// Function that does the appropriate action on the selected link.
this.linkActivator = undefined;
// The link-hints "mode" (in the key-handler, indicator sense).
this.hintMode = null;
// A count of the number of Tab presses since the last non-Tab keyboard event.
this.tabCount = 0;
if (hintDescriptors.length === 0) {
HUD.show("No links to select.", 2000);
return;
}
// This count is used to rank equal-scoring hints when sorting, thereby making JavaScript's sort
// stable.
this.stableSortCount = 0;
this.hintMarkers = hintDescriptors.map((desc) => this.createMarkerFor(desc));
this.markerMatcher = Settings.get("filterLinkHints") ? new FilterHints() : new AlphabetHints();
this.markerMatcher.fillInMarkers(this.hintMarkers);
this.hintMode = new Mode();
this.hintMode.init({
name: `hint/${this.mode.name}`,
indicator: false,
singleton: "link-hints-mode",
suppressAllKeyboardEvents: true,
suppressTrailingKeyEvents: true,
exitOnEscape: true,
exitOnClick: true,
keydown: this.onKeyDownInMode.bind(this),
});
this.hintMode.onExit((event) => {
const hintsWereCancelled = (event?.type === "click") ||
((event?.type === "keydown") &&
(KeyboardUtils.isEscape(event) || KeyboardUtils.isBackspace(event)));
if (hintsWereCancelled) {
HintCoordinator.sendMessage("exit", { isSuccess: false });
}
});
this.renderHints();
this.setIndicator();
}
renderHints() {
if (this.containerEl == null) {
const div = DomUtils.createElement("div");
div.id = "vimiumHintMarkerContainer";
div.className = "vimiumReset";
this.containerEl = div;
document.documentElement.appendChild(div);
}
// Append these markers as top level children instead of as child nodes to the link itself,
// because some clickable elements cannot contain children, e.g. submit buttons.
const markerEls = this.hintMarkers.filter((m) => m.isLocalMarker()).map((m) => m.element);
for (const el of markerEls) {
this.containerEl.appendChild(el);
}
// TODO(philc): 2024-03-27 Remove this hasPopoverSupport check once Firefox has popover support.
// Also move this CSS into vimium.css.
const hasPopoverSupport = this.containerEl.showPopover != null;
if (hasPopoverSupport) {
this.containerEl.popover = "manual";
this.containerEl.showPopover();
Object.assign(this.containerEl.style, {
top: 0,
left: 0,
position: "absolute",
// This display: block is required to override Github Enterprise's CSS circa 2024-04-01. See
// #4446.
display: "block",
width: "100%",
height: "100%",
overflow: "visible",
});
}
this.setIndicator();
}
setOpenLinkMode(mode, shouldPropagateToOtherFrames) {
this.mode = mode;
if (shouldPropagateToOtherFrames == null) {
shouldPropagateToOtherFrames = true;
}
if (shouldPropagateToOtherFrames) {
HintCoordinator.sendMessage("setOpenLinkMode", {
modeIndex: availableModes.indexOf(this.mode),
});
} else {
this.setIndicator();
}
}
setIndicator() {
if (windowIsFocused()) {
const typedCharacters = this.markerMatcher.linkTextKeystrokeQueue
? this.markerMatcher.linkTextKeystrokeQueue.join("")
: "";
const indicator = this.mode.indicator + (typedCharacters ? `: \"${typedCharacters}\"` : "") +
".";
this.hintMode.setIndicator(indicator);
}
}
// Creates a link marker for the given link.
createMarkerFor(desc) {
const marker = new HintMarker();
const isLocalMarker = desc.frameId === frameId;
if (isLocalMarker) {
const localHint = HintCoordinator.getLocalHint(desc);
const el = DomUtils.createElement("div");
el.style.left = localHint.rect.left + "px";
el.style.top = localHint.rect.top + "px";
// Each hint marker is assigned a different z-index.
el.className = "vimiumReset internalVimiumHintMarker vimiumHintMarker";
Object.assign(marker, {
element: el,
localHint,
});
}
return Object.assign(marker, {
hintDescriptor: desc,
linkText: desc.linkText,
stableSortCount: ++this.stableSortCount,
});
}
// Handles all keyboard events.
onKeyDownInMode(event) {
if (event.repeat) return;
// NOTE(smblott) The modifier behaviour here applies only to alphabet hints.
if (
["Control", "Shift"].includes(event.key) && !Settings.get("filterLinkHints") &&
[OPEN_IN_CURRENT_TAB, OPEN_WITH_QUEUE, OPEN_IN_NEW_BG_TAB, OPEN_IN_NEW_FG_TAB].includes(
this.mode,
)
) {
// Toggle whether to open the link in a new or current tab.
const previousMode = this.mode;
const key = event.key;
switch (key) {
case "Shift":
this.setOpenLinkMode(
this.mode === OPEN_IN_CURRENT_TAB ? OPEN_IN_NEW_BG_TAB : OPEN_IN_CURRENT_TAB,
);
break;
case "Control":
this.setOpenLinkMode(
this.mode === OPEN_IN_NEW_FG_TAB ? OPEN_IN_NEW_BG_TAB : OPEN_IN_NEW_FG_TAB,
);
break;
}
this.hintMode.push({
keyup: (event) => {
if (event.key === key) {
handlerStack.remove();
this.setOpenLinkMode(previousMode);
}
return true; // Continue bubbling the event.
},
});
} else if (KeyboardUtils.isBackspace(event)) {
if (this.markerMatcher.popKeyChar()) {
this.tabCount = 0;
this.updateVisibleMarkers();
} else {
// Exit via @hintMode.exit(), so that the LinkHints.activate() "onExit" callback sees the
// key event and knows not to restart hints mode.
this.hintMode.exit(event);
}
} else if (event.key === "Enter") {
// Activate the active hint, if there is one. Only FilterHints uses an active hint.
if (this.markerMatcher.activeHintMarker) {
HintCoordinator.sendMessage("activateActiveHintMarker");
}
} else if (event.key === "Tab") {
if (event.shiftKey) {
this.tabCount--;
} else {
this.tabCount++;
}
this.updateVisibleMarkers();
} else if ((event.key === " ") && this.markerMatcher.shouldRotateHints(event)) {
HintCoordinator.sendMessage("rotateHints");
} else {
if (!event.repeat) {
let keyChar = Settings.get("filterLinkHints")
? KeyboardUtils.getKeyChar(event)
: KeyboardUtils.getKeyChar(event).toLowerCase();
if (keyChar) {
if (keyChar === "space") {
keyChar = " ";
}
if (keyChar.length === 1) {
this.tabCount = 0;
this.markerMatcher.pushKeyChar(keyChar);
this.updateVisibleMarkers();
} else {
return handlerStack.suppressPropagation;
}
}
}
}
return handlerStack.suppressEvent;
}
updateVisibleMarkers() {
const { hintKeystrokeQueue, linkTextKeystrokeQueue } = this.markerMatcher;
return HintCoordinator.sendMessage("updateKeyState", {
hintKeystrokeQueue,
linkTextKeystrokeQueue,
tabCount: this.tabCount,
});
}
updateKeyState({ hintKeystrokeQueue, linkTextKeystrokeQueue, tabCount }) {
Object.assign(this.markerMatcher, { hintKeystrokeQueue, linkTextKeystrokeQueue });
const { linksMatched, userMightOverType } = this.markerMatcher.getMatchingHints(
this.hintMarkers,
tabCount,
);
if (linksMatched.length === 0) {
this.deactivateMode();
} else if (linksMatched.length === 1) {
this.activateLink(linksMatched[0], userMightOverType);
} else {
for (const marker of this.hintMarkers) {
this.hideMarker(marker);
}
for (const matched of linksMatched) {
this.showMarker(matched, this.markerMatcher.hintKeystrokeQueue.length);
}
}
return this.setIndicator();
}
markerOverlapsStack(marker, stack) {
for (const otherMarker of stack) {
if (Rect.intersects(marker.markerRect, otherMarker.markerRect)) {
return true;
}
}
return false;
}
// Rotate the hints' z-index values so that hidden hints become visible.
rotateHints() {
// Get local, visible hint markers.
const localHintMarkers = this.hintMarkers.filter((m) =>
m.isLocalMarker() && (m.element.style.display !== "none")
);
// Fill in the markers' rects, if necessary.
for (const marker of localHintMarkers) {
if (marker.markerRect == null) {
marker.markerRect = marker.element.getClientRects()[0];
}
}
// Calculate the overlapping groups of hints. We call each group a "stack". This is O(n^2).
let stacks = [];
for (const marker of localHintMarkers) {
let stackForThisMarker = null;
const results = [];
for (const stack of stacks) {
const markerOverlapsThisStack = this.markerOverlapsStack(marker, stack);
if (markerOverlapsThisStack && (stackForThisMarker == null)) {
// We've found an existing stack for this marker.
stack.push(marker);
stackForThisMarker = stack;
results.push(stack);
} else if (markerOverlapsThisStack && (stackForThisMarker != null)) {
// This marker overlaps a second (or subsequent) stack; merge that stack into
// stackForThisMarker and discard it.
stackForThisMarker.push(...stack);
continue; // Discard this stack.
} else {
stack; // Keep this stack.
results.push(stack);
}
}
stacks = results;
if (stackForThisMarker == null) {
stacks.push([marker]);
}
}
const newMarkers = [];
for (let stack of stacks) {
if (stack.length > 1) {
// Push the last element to the beginning.
stack = stack.splice(-1, 1).concat(stack);
}
newMarkers.push(...stack);
}
this.hintMarkers = newMarkers;
this.renderHints();
}
// When only one hint remains, activate it in the appropriate way. The current frame may or may
// not contain the matched link, and may or may not have the focus. The resulting four cases are
// accounted for here by selectively pushing the appropriate HintCoordinator.onExit handlers.
activateLink(linkMatched, userMightOverType) {
let clickEl;
if (userMightOverType == null) {
userMightOverType = false;
}
this.removeHintMarkers();
if (linkMatched.isLocalMarker()) {
const localHint = linkMatched.localHint;
clickEl = localHint.element;
HintCoordinator.onExit.push((isSuccess) => {
if (isSuccess) {
if (localHint.reason === "Frame.") {
return Utils.nextTick(() => focusThisFrame({ highlight: true }));
} else if (localHint.reason === "Scroll.") {
// Tell the scroller that this is the activated element.
return handlerStack.bubbleEvent(Utils.isFirefox() ? "click" : "DOMActivate", {
target: clickEl,
});
} else if (localHint.reason === "Open.") {
return clickEl.open = !clickEl.open;
} else if (DomUtils.isSelectable(clickEl)) {
globalThis.focus();
return DomUtils.simulateSelect(clickEl);
} else {
const clickActivator = (modifiers) => (link) => DomUtils.simulateClick(link, modifiers);
const linkActivator = this.mode.linkActivator != null
? this.mode.linkActivator
: clickActivator(this.mode.clickModifiers);
// Note(gdh1995): Here we should allow special elements to get focus,
// <select>: latest Chrome refuses `mousedown` event, and we can only focus it to let
// user press space to activate the popup menu
// <object> & <embed>: for Flash games which have their own key event handlers since we
// have been able to blur them by pressing `Escape`
if (["input", "select", "object", "embed"].includes(clickEl.nodeName.toLowerCase())) {
clickEl.focus();
}
HintCoordinator.lastClickedElementRef = new WeakRef(clickEl);
return linkActivator(clickEl);
}
}
});
}
// If flash elements are created, then this function can be used later to remove them.
let removeFlashElements = function () {};
if (linkMatched.isLocalMarker()) {
const { top: viewportTop, left: viewportLeft } = DomUtils.getViewportTopLeft();
const flashElements = Array.from(clickEl.getClientRects()).map((rect) =>
DomUtils.addFlashRect(Rect.translate(rect, viewportLeft, viewportTop))
);
removeFlashElements = () => flashElements.map((flashEl) => DomUtils.removeElement(flashEl));
}
// If we're using a keyboard blocker, then the frame with the focus sends the "exit" message,
// otherwise the frame containing the matched link does.
if (userMightOverType) {
HintCoordinator.onExit.push(removeFlashElements);
if (windowIsFocused()) {
const callback = (isSuccess) => HintCoordinator.sendMessage("exit", { isSuccess });
return Settings.get("waitForEnterForFilteredHints")
? new WaitForEnter(callback)
: new TypingProtector(200, callback);
}
} else if (linkMatched.isLocalMarker()) {
Utils.setTimeout(400, removeFlashElements);
return HintCoordinator.sendMessage("exit", { isSuccess: true });
}
}
// Shows the marker, highlighting matchingCharCount characters.
showMarker(linkMarker, matchingCharCount) {
if (!linkMarker.isLocalMarker()) return;
linkMarker.element.style.display = "";
for (let j = 0, end = linkMarker.element.childNodes.length; j < end; j++) {
if (j < matchingCharCount) {
linkMarker.element.childNodes[j].classList.add("matchingCharacter");
} else {
linkMarker.element.childNodes[j].classList.remove("matchingCharacter");
}
}
}
hideMarker(marker) {
if (marker.isLocalMarker()) {
marker.element.style.display = "none";
}
}
deactivateMode() {
this.removeHintMarkers();
if (this.hintMode != null) this.hintMode.exit();
}
removeHintMarkers() {
if (this.containerEl) {
DomUtils.removeElement(this.containerEl);
}
this.containerEl = null;
}
}
// Use characters for hints, and do not filter links by their text.
class AlphabetHints {
constructor() {
this.linkHintCharacters = Settings.get("linkHintCharacters").toLowerCase();
this.hintKeystrokeQueue = [];
}
fillInMarkers(hintMarkers) {
const hintStrings = this.hintStrings(hintMarkers.length);
if (hintMarkers.length != hintStrings.length) {
// This can only happen if the user's linkHintCharacters setting is empty.
console.warn("Unable to generate link hint strings.");
} else {
for (let i = 0; i < hintMarkers.length; i++) {
const marker = hintMarkers[i];
marker.hintString = hintStrings[i];
if (marker.isLocalMarker()) {
marker.element.innerHTML = spanWrap(marker.hintString.toUpperCase());
}
}
}
}
//
// Returns a list of hint strings which will uniquely identify the given number of links. The hint
// strings may be of different lengths.
//
hintStrings(linkCount) {
if (this.linkHintCharacters.length == 0) return [];
let hints = [""];
let offset = 0;
while (((hints.length - offset) < linkCount) || (hints.length === 1)) {
const hint = hints[offset++];
for (const ch of this.linkHintCharacters) {
hints.push(ch + hint);
}
}
hints = hints.slice(offset, offset + linkCount);
// Shuffle the hints so that they're scattered; hints starting with the same character and short
// hints are spread evenly throughout the array.
return hints.sort().map((str) => str.reverse());
}
getMatchingHints(hintMarkers) {
const matchString = this.hintKeystrokeQueue.join("");
return {
linksMatched: hintMarkers.filter((m) => m.hintString.startsWith(matchString)),
};
}
pushKeyChar(keyChar) {
this.hintKeystrokeQueue.push(keyChar);
}
popKeyChar() {
return this.hintKeystrokeQueue.pop();
}
// For alphabet hints, <Space> always rotates the hints, regardless of modifiers.
shouldRotateHints() {
return true;
}
}
// Use characters for hints, and also filter links by their text.
class FilterHints {
constructor() {
this.linkHintNumbers = Settings.get("linkHintNumbers").toUpperCase();
this.hintKeystrokeQueue = [];
this.linkTextKeystrokeQueue = [];
this.activeHintMarker = null;
// The regexp for splitting typed text and link texts. We split on sequences of non-word
// characters and link-hint numbers.
this.splitRegexp = new RegExp(
`[\\W${Utils.escapeRegexSpecialCharacters(this.linkHintNumbers)}]+`,
);
}
generateHintString(linkHintNumber) {
const base = this.linkHintNumbers.length;
const hint = [];
while (linkHintNumber > 0) {
hint.push(this.linkHintNumbers[Math.floor(linkHintNumber % base)]);
linkHintNumber = Math.floor(linkHintNumber / base);
}
return hint.reverse().join("");
}
// Populates the marker's element with the correct caption.
renderMarker(marker) {
let linkText = marker.linkText;
if (linkText.length > 35) {
linkText = linkText.slice(0, 33) + "...";
}
const caption = marker.hintString + (marker.localHint.showLinkText ? ": " + linkText : "");
marker.element.innerHTML = spanWrap(caption);
}
fillInMarkers(hintMarkers) {
for (const marker of hintMarkers) {
if (marker.isLocalMarker()) {
this.renderMarker(marker);
}
}
// We use getMatchingHints() here (although we know that all of the hints will match) to get an
// order on the hints and highlight the first one.
return this.getMatchingHints(hintMarkers, 0);
}
getMatchingHints(hintMarkers, tabCount) {
// At this point, linkTextKeystrokeQueue and hintKeystrokeQueue have been updated to reflect the
// latest input. Use them to filter the link hints accordingly.
const matchString = this.hintKeystrokeQueue.join("");
let linksMatched = this.filterLinkHints(hintMarkers);
linksMatched = linksMatched.filter((linkMarker) =>
linkMarker.hintString.startsWith(matchString)
);
// Visually highlight the active hint (that is, the one that will be activated if the user types
// <Enter>).
tabCount = ((linksMatched.length * Math.abs(tabCount)) + tabCount) % linksMatched.length;
if (this.activeHintMarker?.element) {
this.activeHintMarker.element.classList.remove("vimiumActiveHintMarker");
}
this.activeHintMarker = linksMatched[tabCount];
if (this.activeHintMarker?.element) {
this.activeHintMarker.element.classList.add("vimiumActiveHintMarker");
}
return {
linksMatched,
userMightOverType: (this.hintKeystrokeQueue.length === 0) &&
(this.linkTextKeystrokeQueue.length > 0),
};
}
pushKeyChar(keyChar) {
if (this.linkHintNumbers.indexOf(keyChar) >= 0) {
this.hintKeystrokeQueue.push(keyChar);
} else if (
(keyChar.toLowerCase() !== keyChar) &&
(this.linkHintNumbers.toLowerCase() !== this.linkHintNumbers.toUpperCase())
) {
// The keyChar is upper case and the link hint "numbers" contain characters (e.g.
// [a-zA-Z]). We don't want some upper-case letters matching hints (above) and some matching
// text (below), so we ignore such keys.
return;
// We only accept <Space> and characters which are not used for splitting (e.g. "a", "b",
// etc., but not "-").
} else if ((keyChar === " ") || !this.splitRegexp.test(keyChar)) {
// Since we might renumber the hints, we should reset the current hintKeyStrokeQueue.
this.hintKeystrokeQueue = [];
this.linkTextKeystrokeQueue.push(keyChar.toLowerCase());
}
}
popKeyChar() {
return this.hintKeystrokeQueue.pop() || this.linkTextKeystrokeQueue.pop();
}
// Filter link hints by search string, renumbering the hints as necessary.
filterLinkHints(hintMarkers) {
const scoreFunction = this.scoreLinkHint(this.linkTextKeystrokeQueue.join(""));
const matchingHintMarkers = hintMarkers
.filter((linkMarker) => {
linkMarker.score = scoreFunction(linkMarker);
return (this.linkTextKeystrokeQueue.length === 0) || (linkMarker.score > 0);
}).sort(function (a, b) {
if (b.score === a.score) return b.stableSortCount - a.stableSortCount;
else return b.score - a.score;
});
if (
(matchingHintMarkers.length === 0) && (this.hintKeystrokeQueue.length === 0) &&
(this.linkTextKeystrokeQueue.length > 0)
) {
// We don't accept typed text which doesn't match any hints.
this.linkTextKeystrokeQueue.pop();
return this.filterLinkHints(hintMarkers);
} else {
let linkHintNumber = 1;
return matchingHintMarkers.map((m) => {
m.hintString = this.generateHintString(linkHintNumber++);
if (m.isLocalMarker()) this.renderMarker(m);
return m;
});
}
}
// Assign a score to a filter match (higher is better). We assign a higher score for matches at
// the start of a word, and a considerably higher score still for matches which are whole words.
scoreLinkHint(linkSearchString) {
const searchWords = linkSearchString.trim().toLowerCase().split(this.splitRegexp);
return (linkMarker) => {
if (!(searchWords.length > 0)) return 0;
// We only keep non-empty link words. Empty link words cannot be matched, and leading empty
// link words disrupt the scoring of matches at the start of the text.
if (!linkMarker.linkWords) {
linkMarker.linkWords = linkMarker.linkText.toLowerCase().split(this.splitRegexp).filter(
(term) => term,
);
}
const linkWords = linkMarker.linkWords;
const searchWordScores = searchWords.map((searchWord) => {
const linkWordScores = linkWords.map((linkWord, idx) => {
const position = linkWord.indexOf(searchWord);
if (position < 0) {
return 0; // No match.
} else if ((position === 0) && (searchWord.length === linkWord.length)) {
if (idx === 0) return 8;
else return 4; // Whole-word match.
} else if (position === 0) {
if (idx === 0) return 6;