-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathcontent.ts
2991 lines (2620 loc) · 91.3 KB
/
content.ts
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
/// <reference path="../common/constants.d.ts" />
/*
10ten Japanese Reader
by Brian Birtles
https://github.com/birchill/10ten-ja-reader
---
Originally based on Rikaikun
by Erek Speed
http://code.google.com/p/rikaikun/
---
Originally based on Rikaichan 1.07
by Jonathan Zarate
http://www.polarcloud.com/
---
Originally based on RikaiXUL 0.4 by Todd Rudick
http://www.rikai.com/
http://rikaixul.mozdev.org/
---
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
---
Please do not change or remove any of the copyrights or links to web pages
when modifying any of the files. - Jon
*/
import type { MajorDataSeries } from '@birchill/jpdict-idb';
import * as s from 'superstruct';
import browser, { Runtime } from 'webextension-polyfill';
import { BackgroundMessageSchema } from '../background/background-message';
import {
AutoExpandableEntry,
ContentConfigParams,
} from '../common/content-config-params';
import { CopyKeys, CopyType } from '../common/copy-keys';
import { isEditableNode } from '../utils/dom-utils';
import {
addMarginToPoint,
getMarginAroundPoint,
MarginBox,
Point,
Rect,
union,
} from '../utils/geometry';
import { mod } from '../utils/mod';
import { stripFields } from '../utils/strip-fields';
import { WithRequired } from '../utils/type-helpers';
import { isSafari } from '../utils/ua-utils';
import { copyText } from './clipboard';
import { CopyEntry, getTextToCopy } from './copy-text';
import { injectGdocsStyles, removeGdocsStyles } from './gdocs-canvas';
import { getCopyEntryFromResult } from './get-copy-entry';
import { getTextAtPoint } from './get-text';
import {
findIframeElement,
getIframeOrigin,
getWindowDimensions,
IframeSearchParams,
IframeSourceParams,
} from './iframes';
import { SelectionMeta } from './meta';
import {
getPopupDimensions,
hidePopup,
isPopupVisible,
isPopupWindowHostElem,
type PopupOptions,
removePopup,
renderPopup,
renderPopupArrow,
setFontSize,
setPopupStyle,
} from './popup/popup';
import { CopyState, getCopyMode } from './popup/copy-state';
import {
getPopupPosition,
PopupPositionConstraints,
PopupPositionMode,
} from './popup-position';
import { clearPopupTimeout, DisplayMode, PopupState } from './popup-state';
import {
isPuckPointerEvent,
LookupPuck,
PuckPointerEvent,
removePuck,
} from './puck';
import { query, QueryResult } from './query';
import { removeSafeAreaProvider, SafeAreaProvider } from './safe-area-provider';
import { isForeignObjectElement, isSvgDoc, isSvgSvgElement } from './svg';
import {
getBestFitSize,
getPageTargetProps,
selectionSizesToScreenCoords,
TargetProps,
textBoxSizeLengths,
} from './target-props';
import { TextHighlighter } from './text-highlighter';
import { TextRange, textRangesEqual } from './text-range';
import { hasReasonableTimerResolution } from './timer-precision';
import { TouchClickTracker } from './touch-click-tracker';
import { getScrollOffset, toPageCoords, toScreenCoords } from './scroll-offset';
import { hasModifiers, normalizeKey, normalizeKeys } from './keyboard';
import { ContentConfig, ContentConfigChange } from './content-config';
const enum HoldToShowKeyType {
None = 0,
Text = 1 << 0,
Images = 1 << 1,
All = Text | Images,
}
export class ContentHandler {
// The content script is injected into every frame in a page but we delegate
// some responsibilities to the top-most window since that allows us to,
// for example, show the popup without it being clipped by its iframe
// boundary. Furthermore, we want to handle key events regardless of which
// iframe is currently in focus.
//
// As a result, we can divide the state and methods in this class into:
//
// 1. Things done by the window / iframe where the text lives,
// e.g. processing mouse events, extracting text, highlighting text, etc.
//
// 2. Things only the topmost window does,
// e.g. querying the dictionary, showing the popup, etc.
//
// There are a few exceptions like copyMode which is mirrored in both and
// popup visibility tracking which only iframes need to care about but
// roughly these categories hold.
//
// One day we might actually separating these out into separate classes but
// for now we just document which is which here.
//
// Common concerns
//
private config: ContentConfig;
private frameId: number | undefined;
//
// Text handling window concerns
//
private textHighlighter: TextHighlighter;
private currentTextRange: TextRange | undefined;
// The current point is used both by the text handling window to detect
// redundant mouse moves and by the topmost window to know where to position
// the popup.
private currentPagePoint: Point | undefined;
// We keep track of the last element that was the target of a mouse move so
// that we can popup the window later using its properties.
private lastMouseTarget: Element | null = null;
private lastMouseMoveScreenPoint = { x: -1, y: -1 };
// Safari-only redundant pointermove/mousemove event handling
//
// See notes in `onPointerMove` for why we need to do this.
private ignoreNextPointerMove = false;
// Track the state of the popup
//
// This is used by top-most windows and child iframes alike to detect if
// a mouse movement is "between" `currentPoint` and the popup so we can avoid
// hiding the popup in that case (provided the popup is configured to be
// interactive).
//
// Note, however, that the position of the popup (i.e. the `pos` member) is
// only ever stored on the top-most window and on the child iframe which
// contains the content that the popup is positioned relative to (if any).
//
// This is also used to determine how to handle keyboard keys since. For
// example, we should ignore keyboard events (and certainly _not_ call
// preventDefault on them) if the popup is not showing.
private popupState: PopupState | undefined;
// Mouse tracking
//
// We don't show the popup when the mouse is moving at speed because it's
// mostly distracting and introduces unnecessary work.
private static MOUSE_SPEED_SAMPLES = 2;
private static MOUSE_SPEED_THRESHOLD = 0.5;
private mouseSpeedRollingSum = 0;
private mouseSpeeds: Array<number> = [];
private previousMousePosition: Point | undefined;
private previousMouseMoveTime: number | undefined;
// We disable this feature by default and only turn it on once we've
// established that we have a sufficiently precise timer. If
// privacy.resistFingerprinting is enabled then the timer won't be precise
// enough for us to test the speed of the mouse.
private hidePopupWhenMovingAtSpeed = false;
// Keyboard support
private kanjiLookupMode = false;
private pinToggleState: 'idle' | 'keydown' | 'ignore' = 'idle';
// Used to try to detect when we are typing so we know when to ignore key
// events.
private typingMode = false;
// Detect touch taps so we can show the popup for them, but not for
// regular mouse clicks.
private touchClickTracker: TouchClickTracker = new TouchClickTracker();
//
// Top-most window concerns
//
// This should be enough for most (but not all) entries for now.
//
// See https://github.com/birchill/10ten-ja-reader/issues/319#issuecomment-655545971
// for a snapshot of the entry lengths by frequency.
//
// Once we have switched all databases to IndexedDB, we should investigate the
// performance impact of increasing this further.
private static MAX_LENGTH = 16;
private isEffectiveTopMostWindow = false;
private currentLookupParams:
| {
text: string;
wordLookup: boolean;
meta?: SelectionMeta;
source: IframeSourceParams | null;
}
| undefined;
private currentSearchResult: QueryResult | undefined;
private currentTargetProps: TargetProps | undefined;
private currentDict: MajorDataSeries = 'words';
// Copy support
//
// (copyMode is actually used by the text-handling window too to know which
// keyboard events to handle and how to interpret them.)
private copyState: CopyState = { kind: 'inactive' };
// Manual positioning support
private popupPositionMode: PopupPositionMode = PopupPositionMode.Auto;
// Content collapsing
private isPopupExpanded = false;
// Consulted in order to determine safe area
private safeAreaProvider: SafeAreaProvider = new SafeAreaProvider();
// Consulted in order to determine popup positioning
private puck: LookupPuck | null = null;
constructor(config: ContentConfigParams) {
this.config = new ContentConfig(config);
this.textHighlighter = new TextHighlighter();
this.onPointerMove = this.onPointerMove.bind(this);
this.onMouseDown = this.onMouseDown.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
this.onKeyUp = this.onKeyUp.bind(this);
this.onFocusIn = this.onFocusIn.bind(this);
this.onFullScreenChange = this.onFullScreenChange.bind(this);
this.onInterFrameMessage = this.onInterFrameMessage.bind(this);
this.onBackgroundMessage = this.onBackgroundMessage.bind(this);
this.onConfigChange = this.onConfigChange.bind(this);
this.config.addListener(this.onConfigChange);
window.addEventListener('pointermove', this.onPointerMove);
window.addEventListener('mousedown', this.onMouseDown);
window.addEventListener('keydown', this.onKeyDown, { capture: true });
window.addEventListener('keyup', this.onKeyUp, { capture: true });
window.addEventListener('focusin', this.onFocusIn);
window.addEventListener('fullscreenchange', this.onFullScreenChange);
window.addEventListener('message', this.onInterFrameMessage, {
capture: true,
});
browser.runtime.onMessage.addListener(this.onBackgroundMessage);
this.touchClickTracker.onTouchClick = (event: MouseEvent) => {
// Ignore clicks on interactive elements
if (
event.target instanceof HTMLAnchorElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
// If the puck is showing but inactive, use that as a signal that the user
// doesn't want to do lookups at the moment.
if (this.puck?.getEnabledState() === 'inactive') {
return;
}
// We need to ensure the 'buttons' field of the event is zero since
// normally we ignore mousemoves when the buttons are being pressed, but
// we've decided to allow this "click".
//
// This is, unfortunately, a little involved since:
//
// (a) the 'buttons' member of `event` is readonly,
// (b) the object spread operator only deals with enumerable _own_
// properties so we can't just spread the values from `event` into a
// new object, and
// (c) we use `getModifierState` etc. on `PointerEvent` elsewhere so we
// actually need to generate a `PointerEvent` object rather than just
// a property bag.
const pointerMoveEvent = new PointerEvent('pointermove', {
altKey: event.altKey,
bubbles: true,
button: 0,
buttons: 0,
clientX: event.clientX,
clientY: event.clientY,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
pointerType: 'mouse',
relatedTarget: event.relatedTarget,
screenX: event.screenX,
screenY: event.screenY,
shiftKey: event.shiftKey,
});
(pointerMoveEvent as TouchClickEvent).fromTouch = true;
(event.target || document.body).dispatchEvent(pointerMoveEvent);
};
if (!this.config.enableTapLookup) {
this.touchClickTracker.disable();
}
void hasReasonableTimerResolution().then((isReasonable) => {
if (isReasonable) {
this.hidePopupWhenMovingAtSpeed = true;
}
});
// If we are an iframe, check if the popup is currently showing
if (!this.isTopMostWindow()) {
void browser.runtime.sendMessage({ type: 'top:isPopupShowing' });
}
this.applyPuckConfig();
if (document.location.host === 'docs.google.com') {
injectGdocsStyles();
}
}
applyPuckConfig() {
if (!this.isTopMostWindow()) {
return;
}
if (this.config.showPuck === 'show') {
this.setUpPuck();
} else {
this.tearDownPuck();
}
}
setUpPuck() {
if (!this.puck) {
this.puck = new LookupPuck({
initialPosition: this.config.puckState,
safeAreaProvider: this.safeAreaProvider,
onLookupDisabled: () => {
this.clearResult();
},
onPuckStateChanged: (state) => {
void browser.runtime.sendMessage({
type: 'puckStateChanged',
value: state,
});
},
});
}
this.puck.render({
icon: this.config.toolbarIcon,
theme: this.config.popupStyle,
});
this.puck.setEnabledState(
this.config.puckState?.active === false ? 'inactive' : 'active'
);
}
tearDownPuck() {
this.puck?.unmount();
this.puck = null;
removePuck();
}
setConfig(config: Readonly<ContentConfigParams>) {
this.config.set(config);
}
get canHover() {
return this.config.canHover;
}
onConfigChange(changes: readonly ContentConfigChange[]) {
for (const { key, value } of changes) {
switch (key) {
case 'accentDisplay':
case 'posDisplay':
case 'readingOnly':
case 'showKanjiComponents':
case 'showPriority':
case 'tabDisplay':
if (this.isTopMostWindow()) {
this.updatePopup();
}
break;
case 'enableTapLookup':
value
? this.touchClickTracker.enable()
: this.touchClickTracker.disable();
break;
case 'fontSize':
setFontSize(value);
break;
case 'showRomaji':
// Enabling romaji currently means we need to re-run the lookup
if (
this.isTopMostWindow() &&
this.currentLookupParams &&
this.currentTargetProps
) {
const lookupParams: Parameters<typeof this.lookupText>[0] = {
dictMode: 'default',
...this.currentLookupParams,
targetProps: this.currentTargetProps,
};
if (this.isTopMostWindow()) {
void this.lookupText(lookupParams);
}
}
break;
case 'popupInteractive':
if (this.isTopMostWindow()) {
// We can't use updatePopup here since it will try to re-use the
// existing popup display mode but we specifically want to change it
// in this case.
this.showPopup({
allowOverlap: this.popupState?.pos?.allowOverlap,
displayMode: value ? 'hover' : 'static',
});
}
break;
case 'popupStyle':
setPopupStyle(value);
this.puck?.setTheme(value);
break;
case 'puckState':
if (value) {
this.puck?.setState(value);
}
break;
case 'showPuck':
this.applyPuckConfig();
break;
case 'toolbarIcon':
this.puck?.setIcon(value);
break;
case 'canHover':
void browser.runtime.sendMessage({ type: 'canHoverChanged', value });
break;
}
}
}
detach() {
this.config.removeListener(this.onConfigChange);
window.removeEventListener('pointermove', this.onPointerMove);
window.removeEventListener('mousedown', this.onMouseDown);
window.removeEventListener('keydown', this.onKeyDown, { capture: true });
window.removeEventListener('keyup', this.onKeyUp, { capture: true });
window.removeEventListener('focusin', this.onFocusIn);
window.removeEventListener('fullscreenchange', this.onFullScreenChange);
window.removeEventListener('message', this.onInterFrameMessage, {
capture: true,
});
browser.runtime.onMessage.removeListener(this.onBackgroundMessage);
this.clearResult();
this.tearDownPuck();
this.textHighlighter.detach();
this.copyState = { kind: 'inactive' };
this.isPopupExpanded = false;
this.safeAreaProvider.destroy();
this.touchClickTracker.destroy();
removePopup();
removeGdocsStyles();
}
setEffectiveTopMostWindow() {
const wasTopMost = this.isTopMostWindow();
this.isEffectiveTopMostWindow = true;
// If we are now the top most we might now be the puck host
if (!wasTopMost) {
this.applyPuckConfig();
}
}
isTopMostWindow() {
// If a descendant of an iframe is being displayed full-screen, that iframe
// can temporarily act as the topmost window.
if (document.fullscreenElement) {
if (document.fullscreenElement.tagName === 'IFRAME') {
return false;
}
if (document.fullscreenElement.ownerDocument === document) {
return true;
}
}
return (
this.isEffectiveTopMostWindow || window.self === this.getTopMostWindow()
);
}
getTopMostWindow() {
return this.isEffectiveTopMostWindow
? window.self
: window.top || window.self;
}
getFrameId(): number | undefined {
if (typeof this.frameId === 'number') {
return this.frameId;
}
if (typeof browser.runtime.getFrameId === 'function') {
const frameId = browser.runtime.getFrameId(window);
if (frameId !== -1) {
return frameId;
}
}
return undefined;
}
setFrameId(frameId: number) {
this.frameId = frameId;
}
onPointerMove(event: PointerEvent) {
this.typingMode = false;
// Safari has an odd bug where it dispatches extra pointermove/mousemove
// events when you press any modifier key (e.g. Shift).
//
// It goes something like this:
//
// * Press Shift down
// -> mousemove with shiftKey = true
// -> keydown with shiftKey = true
//
// * Release Shift key
// -> mousemove with shiftKey = false
// -> keyup with shiftKey = false
//
// We really need to ignore these events since they will intefere with
// detecting taps of the "pin popup" key as well as when using Shift to only
// show kanji.
//
// For now the best way we know of doing that is to just check if the
// position has changed.
//
// 2022-09-12: This is tracked as WebKit bug
// https://bugs.webkit.org/show_bug.cgi?id=16271
// which was apparently fixed in July 2021 but in September 2022 I can still
// reproduce it, at least with the control key.
//
// 2023-08-03: It looks like this was finally fixed in May 2023 in
// https://github.com/WebKit/WebKit/pull/14221
// It will be some time before that's available in release Safari everywhere
// we care about.
if (isSafari()) {
if (
(event.shiftKey ||
event.altKey ||
event.metaKey ||
event.ctrlKey ||
this.ignoreNextPointerMove) &&
this.lastMouseMoveScreenPoint.x === event.clientX &&
this.lastMouseMoveScreenPoint.y === event.clientY
) {
// We need to ignore the mousemove event corresponding to the keyup
// event too.
this.ignoreNextPointerMove = !this.ignoreNextPointerMove;
return;
}
this.ignoreNextPointerMove = false;
}
this.lastMouseMoveScreenPoint = { x: event.clientX, y: event.clientY };
// If we start moving the mouse, we should stop trying to recognize a tap on
// the "pin" key as such since it's no longer a tap (and very often these
// keys overlap with the hold-to-show keys which are held while moving the
// mouse).
//
// Note that it's not enough just to check if `pinToggleState` is in the
// 'keydown' state because it seems like sometimes browsers (at least
// Firefox) batch up input events so that all the mousemove events arrive
// before the keyboard events.
//
// In order to handle that case, we need to check if the relevant key for
// pinning are being held (and hence we are likely to get a keydown event
// soon).
if (
this.pinToggleState === 'keydown' ||
(this.pinToggleState === 'idle' && this.hasPinKeysPressed(event))
) {
this.pinToggleState = 'ignore';
}
// Ignore mouse events while buttons are being pressed.
if (event.buttons) {
return;
}
// If we are ignoring taps, ignore events that are not from the mouse
//
// You might think, "Why don't we just listen for mousemove events in the
// first place?" but iOS Safari will dispatch mousemove events for touch
// events too (e.g. if you start to select text) and we need to ignore them
// so we need to know what kind of "mousemove" event we got.
//
// If we are NOT ignoring taps then we probably should allow other pointer
// types since it's probably useful to look up things with a pen?
if (!this.config.enableTapLookup && event.pointerType !== 'mouse') {
return;
}
// We don't know how to deal with anything that's not an element
if (!(event.target instanceof Element)) {
return;
}
// Ignore mouse moves if we are pinned
if (
!isTouchClickEvent(event) &&
this.popupState?.display.mode === 'pinned'
) {
this.lastMouseTarget = event.target;
return;
}
// Ignore mouse events on the popup window
if (isPopupWindowHostElem(event.target)) {
return;
}
// Check if we have released the hold-to-show keys such that a ghosted popup
// should be committed.
//
// Normally we'd handle this case in onKeyUp, but it's possible, even common
// to have the focus in a different window/frame while mousing over content.
//
// Our window/frame will still get mousemove events with the corresponding
// modifier key attributes set so we can _show_ the popup, but we _won't_
// get the `keyup` event(s) when the modifier(s) are released so instead
// we need to try and detect when that happens on the next mousemove event.
if (
!isTouchClickEvent(event) &&
this.popupState?.display.mode === 'ghost' &&
this.popupState.display.trigger === 'keys' &&
!(this.getActiveHoldToShowKeys(event) & this.popupState.display.keyType)
) {
this.commitPopup();
return;
}
// Check if any required "hold to show keys" are held.
//
// We do this before checking throttling since that can be expensive and
// when this is configured, typically the user will have the extension
// more-or-less permanently enabled so we don't want to add unnecessary
// latency to regular mouse events.
//
// Note that the "hold to show keys" setting is only relevant for mouse
// events, not puck events.
const contentsToMatch =
this.getActiveHoldToShowKeys(event) |
(isPuckPointerEvent(event) || isTouchClickEvent(event)
? HoldToShowKeyType.All
: 0);
const matchText = !!(contentsToMatch & HoldToShowKeyType.Text);
const matchImages = !!(contentsToMatch & HoldToShowKeyType.Images);
// If nothing is going to match, close the popup. If we're in hover mode,
// however, we need to proceed with the regular processing to see if we are
// hovering over the arrow area or not.
//
// (For pinned mode and touch mode, contentsToMatch is guaranteed to be
// non-zero. For static mode we certainly want to close the popup, and we
// never seem to hit this case in ghost mode but presumably if we did we'd
// want to close the popup.)
if (!contentsToMatch && this.popupState?.display.mode !== 'hover') {
if (this.popupState) {
this.clearResult({ currentElement: event.target });
}
// We still want to set the current position and element information so
// that if the user presses the hold-to-show keys later we can show the
// popup immediately.
this.currentPagePoint = toPageCoords({
x: event.clientX,
y: event.clientY,
});
this.lastMouseTarget = event.target;
return;
}
// If the mouse have moved in a triangular shape between the original popup
// point and the popup, don't hide it, but instead allow the user to
// interact with the popup.
if (this.isEnRouteToPopup(event)) {
return;
}
// If the mouse is moving too quickly, don't show the popup
if (this.shouldThrottlePopup(event)) {
this.clearResult({ currentElement: event.target });
return;
}
let dictMode: 'default' | 'kanji' = 'default';
if (event.shiftKey && this.config.keys.kanjiLookup.includes('Shift')) {
this.kanjiLookupMode = event.shiftKey;
dictMode = 'kanji';
}
// Record the last mouse target in case we need to trigger the popup
// again.
this.lastMouseTarget = event.target;
void this.tryToUpdatePopup({
fromPuck: isPuckPointerEvent(event),
fromTouch: isTouchClickEvent(event),
matchText,
matchImages,
screenPoint: { x: event.clientX, y: event.clientY },
eventElement: event.target,
dictMode,
});
}
isEnRouteToPopup(event: PointerEvent) {
if (isPuckPointerEvent(event) || isTouchClickEvent(event)) {
return false;
}
if (
this.popupState?.display.mode !== 'hover' ||
!this.popupState.pos?.lookupPoint
) {
return false;
}
const {
x: popupX,
y: popupY,
width: popupWidth,
height: popupHeight,
direction,
lookupPoint: {
x: lookupX,
y: lookupY,
marginX: lookupMarginX,
marginY: lookupMarginY,
},
} = this.popupState.pos;
// If the popup is not related to the mouse position we don't want to allow
// mousing over it as it might require making most of the screen
// un-scannable.
if (direction === 'disjoint') {
return false;
}
// Check block axis range
const lookupBlockPos = direction === 'vertical' ? lookupY : lookupX;
// Get the closest edge of the popup edge
const popupBlockPos = direction === 'vertical' ? popupY : popupX;
const popupBlockSize = direction === 'vertical' ? popupHeight : popupWidth;
const popupEdge =
popupBlockPos >= lookupBlockPos
? popupBlockPos
: popupBlockPos + popupBlockSize;
// Work out the distance between the lookup point and the edge of the popup
const popupDist = popupEdge - lookupBlockPos;
// Work out the mouse distance from the lookup point
//
// NOTE: We _don't_ want to use event.pageY/pageX since that will return the
// wrong result when we are in full-screen mode. Instead we should manually
// add the scroll offset in.
const { scrollX, scrollY } = getScrollOffset();
const mouseBlockPos =
direction === 'vertical'
? event.clientY + scrollY
: event.clientX + scrollX;
// Work out the portion of the distance we are in the gap between the lookup
// point and the edge of the popup.
const blockOffset =
popupDist < 0
? lookupBlockPos - mouseBlockPos
: mouseBlockPos - lookupBlockPos;
const blockRange = Math.abs(popupDist);
const blockMargin =
direction === 'vertical' ? lookupMarginY : lookupMarginX;
// Check if we are in the gap (or the margin)
if (blockOffset < -blockMargin || blockOffset > blockRange) {
return false;
}
// Check the inline range
//
// We do this by basically drawing a triangle from the lookup point spanning
// outwards towards the edge of the popup using the defined angle.
//
// e.g.
//
// +
// / \
// / x \
// /<-D-->\
// / \
// +----------------------------------------------+
// | <----B----> |
// | ^ |
// | C |
// A
//
// + = Lookup point (lookup inline position)
// x = Mouse position
// A = Inline popup start
// B = Max inline range (i.e. the inline range at the edge)
// C = Max inline range start
// D = Proportional inline range
const lookupInlinePos = direction === 'vertical' ? lookupX : lookupY;
const mouseInlinePos =
direction === 'vertical'
? event.clientX + scrollX
: event.clientY + scrollY;
const ENVELOPE_SPREAD_DEGREES = 120;
const inlineHalfRange =
Math.tan(((ENVELOPE_SPREAD_DEGREES / 2) * Math.PI) / 180) * blockOffset;
const inlineMargin =
direction === 'vertical' ? lookupMarginX : lookupMarginY;
const inlineRangeStart =
lookupInlinePos - Math.max(inlineHalfRange, inlineMargin);
const inlineRangeEnd =
lookupInlinePos + Math.max(inlineHalfRange, inlineMargin);
if (mouseInlinePos < inlineRangeStart || mouseInlinePos > inlineRangeEnd) {
return false;
}
return true;
}
shouldThrottlePopup(event: PointerEvent) {
if (!this.hidePopupWhenMovingAtSpeed) {
return false;
}
let averageSpeed = 0;
if (this.previousMousePosition && this.previousMouseMoveTime) {
// If the events are backed up their times might be equal. Likewise, if
// the events are more than a couple of animation frames apart either the
// mouse stopped, or the system is backed up and the OS can't even
// dispatch the events.
//
// In either case we should:
//
// - Update the previous mouse position and time so that when we get the
// *next* event we can accurately measure the speed.
//
// - Not throttle the popup since for some content we might always be
// backed up (YouTube with browser console open seems particularly bad)
// and its safer to just allow the popup in this case rather than risk
// permanently hiding it.
//
if (
event.timeStamp === this.previousMouseMoveTime ||
event.timeStamp - this.previousMouseMoveTime > 32
) {
this.previousMousePosition = { x: event.pageX, y: event.pageY };
this.previousMouseMoveTime = event.timeStamp;
return false;
}
const distance = Math.sqrt(
Math.pow(event.pageX - this.previousMousePosition.x, 2) +
Math.pow(event.pageY - this.previousMousePosition.y, 2)
);
const speed = distance / (event.timeStamp - this.previousMouseMoveTime);
this.mouseSpeeds.push(speed);
this.mouseSpeedRollingSum += speed;
if (this.mouseSpeeds.length > ContentHandler.MOUSE_SPEED_SAMPLES) {
this.mouseSpeedRollingSum -= this.mouseSpeeds.shift()!;
}
averageSpeed = this.mouseSpeedRollingSum / this.mouseSpeeds.length;
}
this.previousMousePosition = { x: event.pageX, y: event.pageY };
this.previousMouseMoveTime = event.timeStamp;
return averageSpeed >= ContentHandler.MOUSE_SPEED_THRESHOLD;
}
onMouseDown(event: MouseEvent) {
// Ignore mouse events on the popup window
if (isPopupWindowHostElem(event.target)) {
return;
}
// Clear the highlight since it interferes with selection.
this.clearResult({ currentElement: event.target as Element });
}
onKeyDown(event: KeyboardEvent) {
const textBoxInFocus =
document.activeElement && isEditableNode(document.activeElement);
// If the user pressed the hold-to-show key combination, show the popup
// if possible.
//
// It's important we only do this when the popup is not visible, however,
// since these keys may overlap with the keys we've defined for pinning the
// popup--which only apply when the popup is visible.
const matchedHoldToShowKeys = this.isHoldToShowKeyStroke(event);
if (matchedHoldToShowKeys && !this.isVisible()) {
event.preventDefault();
// We don't do this when the there is a text box in focus because we
// we risk interfering with the text selection when, for example, the
// hold-to-show key is Ctrl and the user presses Ctrl+V etc.
if (!textBoxInFocus && this.currentPagePoint && this.lastMouseTarget) {
void this.tryToUpdatePopup({
fromPuck: false,
fromTouch: false,
matchText: !!(matchedHoldToShowKeys & HoldToShowKeyType.Text),
matchImages: !!(matchedHoldToShowKeys & HoldToShowKeyType.Images),
screenPoint: toScreenCoords(this.currentPagePoint),
eventElement: this.lastMouseTarget,