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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/* globals log, catcher, util, ui, slides, global */
/* globals shooter, callBackground, selectorLoader, assertIsTrusted, selection */
"use strict";
this.uicontrol = (function () {
const exports = {};
/** ********************************************************
* selection
*/
/* States:
"crosshairs":
Nothing has happened, and the crosshairs will follow the movement of the mouse
"draggingReady":
The user has pressed the mouse button, but hasn't moved enough to create a selection
"dragging":
The user has pressed down a mouse button, and is dragging out an area far enough to show a selection
"selected":
The user has selected an area
"resizing":
The user is resizing the selection
"cancelled":
Everything has been cancelled
"previewing":
The user is previewing the full-screen/visible image
A mousedown goes from crosshairs to dragging.
A mouseup goes from dragging to selected
A click outside of the selection goes from selected to crosshairs
A click on one of the draggers goes from selected to resizing
State variables:
state (string, one of the above)
mousedownPos (object with x/y during draggingReady, shows where the selection started)
selectedPos (object with x/y/h/w during selected or dragging, gives the entire selection)
resizeDirection (string: top, topLeft, etc, during resizing)
resizeStartPos (x/y position where resizing started)
mouseupNoAutoselect (true if a mouseup in draggingReady should not trigger autoselect)
*/
const { watchFunction, watchPromise } = catcher;
const MAX_PAGE_HEIGHT = 10000;
const MAX_PAGE_WIDTH = 10000;
// An autoselection smaller than these will be ignored entirely:
const MIN_DETECT_ABSOLUTE_HEIGHT = 10;
const MIN_DETECT_ABSOLUTE_WIDTH = 30;
// An autoselection smaller than these will not be preferred:
const MIN_DETECT_HEIGHT = 30;
const MIN_DETECT_WIDTH = 100;
// An autoselection bigger than either of these will be ignored:
const MAX_DETECT_HEIGHT = Math.max(window.innerHeight + 100, 700);
const MAX_DETECT_WIDTH = Math.max(window.innerWidth + 100, 1000);
// This is how close (in pixels) you can get to the edge of the window and then
// it will scroll:
const SCROLL_BY_EDGE = 20;
// This is how wide the inboard scrollbars are, generally 0 except on Mac
const SCROLLBAR_WIDTH = window.navigator.platform.match(/Mac/i) ? 17 : 0;
const { Selection } = selection;
const { sendEvent } = shooter;
const log = global.log;
function round10(n) {
return Math.floor(n / 10) * 10;
}
function eventOptionsForBox(box) {
return {
cd1: round10(Math.abs(box.bottom - box.top)),
cd2: round10(Math.abs(box.right - box.left)),
};
}
function eventOptionsForResize(boxStart, boxEnd) {
return {
cd1: round10(
boxEnd.bottom - boxEnd.top - (boxStart.bottom - boxStart.top)
),
cd2: round10(
boxEnd.right - boxEnd.left - (boxStart.right - boxStart.left)
),
};
}
function eventOptionsForMove(posStart, posEnd) {
return {
cd1: round10(posEnd.y - posStart.y),
cd2: round10(posEnd.x - posStart.x),
};
}
function downloadShot() {
const previewDataUrl = captureType === "fullPageTruncated" ? null : dataUrl;
// Downloaded shots don't have dimension limits
removeDimensionLimitsOnFullPageShot();
shooter.downloadShot(selectedPos, previewDataUrl, captureType);
}
function copyShot() {
const previewDataUrl = captureType === "fullPageTruncated" ? null : dataUrl;
// Copied shots don't have dimension limits
removeDimensionLimitsOnFullPageShot();
shooter.copyShot(selectedPos, previewDataUrl, captureType);
}
/** *********************************************
* State and stateHandlers infrastructure
*/
// This enumerates all the anchors on the selection, and what part of the
// selection they move:
const movements = {
topLeft: ["x1", "y1"],
top: [null, "y1"],
topRight: ["x2", "y1"],
left: ["x1", null],
right: ["x2", null],
bottomLeft: ["x1", "y2"],
bottom: [null, "y2"],
bottomRight: ["x2", "y2"],
move: ["*", "*"],
};
const doNotAutoselectTags = {
H1: true,
H2: true,
H3: true,
H4: true,
H5: true,
H6: true,
};
let captureType;
function removeDimensionLimitsOnFullPageShot() {
if (captureType === "fullPageTruncated") {
captureType = "fullPage";
selectedPos = new Selection(
0,
0,
getDocumentWidth(),
getDocumentHeight()
);
}
}
const standardDisplayCallbacks = {
cancel: () => {
sendEvent("cancel-shot", "overlay-cancel-button");
exports.deactivate();
},
download: () => {
sendEvent("download-shot", "overlay-download-button");
downloadShot();
},
copy: () => {
sendEvent("copy-shot", "overlay-copy-button");
copyShot();
},
};
const standardOverlayCallbacks = {
cancel: () => {
sendEvent("cancel-shot", "cancel-preview-button");
exports.deactivate();
},
onClickCancel: e => {
sendEvent("cancel-shot", "cancel-selection-button");
e.preventDefault();
e.stopPropagation();
exports.deactivate();
},
onClickVisible: () => {
callBackground("captureTelemetry", "visible");
sendEvent("capture-visible", "selection-button");
selectedPos = new Selection(
window.scrollX,
window.scrollY,
window.scrollX + document.documentElement.clientWidth,
window.scrollY + window.innerHeight
);
captureType = "visible";
setState("previewing");
},
onClickFullPage: () => {
callBackground("captureTelemetry", "full_page");
sendEvent("capture-full-page", "selection-button");
captureType = "fullPage";
const width = getDocumentWidth();
if (width > MAX_PAGE_WIDTH) {
captureType = "fullPageTruncated";
}
const height = getDocumentHeight();
if (height > MAX_PAGE_HEIGHT) {
captureType = "fullPageTruncated";
}
selectedPos = new Selection(0, 0, width, height);
setState("previewing");
},
onDownloadPreview: () => {
sendEvent(
`download-${captureType
.replace(/([a-z])([A-Z])/g, "$1-$2")
.toLowerCase()}`,
"download-preview-button"
);
downloadShot();
},
onCopyPreview: () => {
sendEvent(
`copy-${captureType.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()}`,
"copy-preview-button"
);
copyShot();
},
};
/** Holds all the objects that handle events for each state: */
const stateHandlers = {};
function getState() {
return getState.state;
}
getState.state = "cancel";
function setState(s) {
if (!stateHandlers[s]) {
throw new Error("Unknown state: " + s);
}
const cur = getState.state;
const handler = stateHandlers[cur];
if (handler.end) {
handler.end();
}
getState.state = s;
if (stateHandlers[s].start) {
stateHandlers[s].start();
}
}
/** Various values that the states use: */
let mousedownPos;
let selectedPos;
let resizeDirection;
let resizeStartPos;
let resizeStartSelected;
let resizeHasMoved;
let mouseupNoAutoselect = false;
let autoDetectRect;
/** Represents a single x/y point, typically for a mouse click that doesn't have a drag: */
class Pos {
constructor(x, y) {
this.x = x;
this.y = y;
}
elementFromPoint() {
return ui.iframe.getElementFromPoint(
this.x - window.pageXOffset,
this.y - window.pageYOffset
);
}
distanceTo(x, y) {
return Math.sqrt(Math.pow(this.x - x, 2) + Math.pow(this.y - y, 2));
}
}
/** *********************************************
* all stateHandlers
*/
let dataUrl;
stateHandlers.previewing = {
start() {
shooter.preview(selectedPos, captureType);
},
};
stateHandlers.crosshairs = {
cachedEl: null,
start() {
selectedPos = mousedownPos = null;
this.cachedEl = null;
watchPromise(
ui.iframe
.display(installHandlersOnDocument, standardOverlayCallbacks)
.then(() => {
ui.iframe.usePreSelection();
ui.Box.remove();
})
);
},
mousemove(event) {
ui.PixelDimensions.display(
event.pageX,
event.pageY,
event.pageX,
event.pageY
);
if (
event.target.classList &&
!event.target.classList.contains("preview-overlay")
) {
// User is hovering over a toolbar button or control
autoDetectRect = null;
if (this.cachedEl) {
this.cachedEl = null;
}
ui.HoverBox.hide();
return;
}
let el;
if (
event.target.classList &&
event.target.classList.contains("preview-overlay")
) {
// The hover is on the overlay, so we need to figure out the real element
el = ui.iframe.getElementFromPoint(
event.pageX + window.scrollX - window.pageXOffset,
event.pageY + window.scrollY - window.pageYOffset
);
const xpos = Math.floor(
(10 * (event.pageX - window.innerWidth / 2)) / window.innerWidth
);
const ypos = Math.floor(
(10 * (event.pageY - window.innerHeight / 2)) / window.innerHeight
);
for (let i = 0; i < 2; i++) {
const move = `translate(${xpos}px, ${ypos}px)`;
event.target.getElementsByClassName("eyeball")[i].style.transform =
move;
}
} else {
// The hover is on the element we care about, so we use that
el = event.target;
}
if (this.cachedEl && this.cachedEl === el) {
// Still hovering over the same element
return;
}
this.cachedEl = el;
this.setAutodetectBasedOnElement(el);
},
setAutodetectBasedOnElement(el) {
let lastRect;
let lastNode;
let rect;
let attemptExtend = false;
let node = el;
while (node) {
rect = Selection.getBoundingClientRect(node);
if (!rect) {
rect = lastRect;
break;
}
if (rect.width < MIN_DETECT_WIDTH || rect.height < MIN_DETECT_HEIGHT) {
// Avoid infinite loop for elements with zero or nearly zero height,
// like non-clearfixed float parents with or without borders.
break;
}
if (rect.width > MAX_DETECT_WIDTH || rect.height > MAX_DETECT_HEIGHT) {
// Then the last rectangle is better
rect = lastRect;
attemptExtend = true;
break;
}
if (
rect.width >= MIN_DETECT_WIDTH &&
rect.height >= MIN_DETECT_HEIGHT
) {
if (!doNotAutoselectTags[node.tagName]) {
break;
}
}
lastRect = rect;
lastNode = node;
node = node.parentNode;
}
if (rect && node) {
const evenBetter = this.evenBetterElement(node, rect);
if (evenBetter) {
node = lastNode = evenBetter;
rect = Selection.getBoundingClientRect(evenBetter);
attemptExtend = false;
}
}
if (rect && attemptExtend) {
let extendNode = lastNode.nextSibling;
while (extendNode) {
if (extendNode.nodeType === document.ELEMENT_NODE) {
break;
}
extendNode = extendNode.nextSibling;
if (!extendNode) {
const parent = lastNode.parentNode;
for (let i = 0; i < parent.childNodes.length; i++) {
if (parent.childNodes[i] === lastNode) {
extendNode = parent.childNodes[i + 1];
}
}
}
}
if (extendNode) {
const extendSelection = Selection.getBoundingClientRect(extendNode);
const extendRect = rect.union(extendSelection);
if (
extendRect.width <= MAX_DETECT_WIDTH &&
extendRect.height <= MAX_DETECT_HEIGHT
) {
rect = extendRect;
}
}
}
if (
rect &&
(rect.width < MIN_DETECT_ABSOLUTE_WIDTH ||
rect.height < MIN_DETECT_ABSOLUTE_HEIGHT)
) {
rect = null;
}
if (!rect) {
ui.HoverBox.hide();
} else {
ui.HoverBox.display(rect);
}
autoDetectRect = rect;
},
/** When we find an element, maybe there's one that's just a little bit better... */
evenBetterElement(node, origRect) {
let el = node.parentNode;
const ELEMENT_NODE = document.ELEMENT_NODE;
while (el && el.nodeType === ELEMENT_NODE) {
if (!el.getAttribute) {
return null;
}
const role = el.getAttribute("role");
if (
role === "article" ||
(el.className &&
typeof el.className === "string" &&
el.className.search("tweet ") !== -1)
) {
const rect = Selection.getBoundingClientRect(el);
if (!rect) {
return null;
}
if (
rect.width <= MAX_DETECT_WIDTH &&
rect.height <= MAX_DETECT_HEIGHT
) {
return el;
}
return null;
}
el = el.parentNode;
}
return null;
},
mousedown(event) {
// FIXME: this is happening but we don't know why, we'll track it now
// but avoid popping up messages:
if (typeof ui === "undefined") {
const exc = new Error("Undefined ui in mousedown");
exc.unloadTime = unloadTime;
exc.nowTime = Date.now();
exc.noPopup = true;
exc.noReport = true;
throw exc;
}
if (ui.isHeader(event.target)) {
return undefined;
}
// If the pageX is greater than this, then probably it's an attempt to get
// to the scrollbar, or an actual scroll, and not an attempt to start the
// selection:
const maxX = window.innerWidth - SCROLLBAR_WIDTH;
if (event.pageX >= maxX) {
event.stopPropagation();
event.preventDefault();
return false;
}
mousedownPos = new Pos(
event.pageX + window.scrollX,
event.pageY + window.scrollY
);
setState("draggingReady");
event.stopPropagation();
event.preventDefault();
return false;
},
end() {
ui.HoverBox.remove();
ui.PixelDimensions.remove();
},
};
stateHandlers.draggingReady = {
minMove: 40, // px
minAutoImageWidth: 40,
minAutoImageHeight: 40,
maxAutoElementWidth: 800,
maxAutoElementHeight: 600,
start() {
ui.iframe.usePreSelection();
ui.Box.remove();
},
mousemove(event) {
if (mousedownPos.distanceTo(event.pageX, event.pageY) > this.minMove) {
selectedPos = new Selection(
mousedownPos.x,
mousedownPos.y,
event.pageX + window.scrollX,
event.pageY + window.scrollY
);
mousedownPos = null;
setState("dragging");
}
},
mouseup(event) {
// If we don't get into "dragging" then we attempt an autoselect
if (mouseupNoAutoselect) {
sendEvent("cancel-selection", "selection-background-mousedown");
setState("crosshairs");
return false;
}
if (autoDetectRect) {
selectedPos = autoDetectRect;
selectedPos.x1 += window.scrollX;
selectedPos.y1 += window.scrollY;
selectedPos.x2 += window.scrollX;
selectedPos.y2 += window.scrollY;
autoDetectRect = null;
mousedownPos = null;
ui.iframe.useSelection();
ui.Box.display(selectedPos, standardDisplayCallbacks);
sendEvent(
"make-selection",
"selection-click",
eventOptionsForBox(selectedPos)
);
setState("selected");
sendEvent("autoselect");
callBackground("captureTelemetry", "element");
} else {
sendEvent("no-selection", "no-element-found");
setState("crosshairs");
}
return undefined;
},
click(event) {
this.mouseup(event);
},
findGoodEl() {
let el = mousedownPos.elementFromPoint();
if (!el) {
return null;
}
const isGoodEl = element => {
if (element.nodeType !== document.ELEMENT_NODE) {
return false;
}
if (element.tagName === "IMG") {
const rect = element.getBoundingClientRect();
return (
rect.width >= this.minAutoImageWidth &&
rect.height >= this.minAutoImageHeight
);
}
const display = window.getComputedStyle(element).display;
if (["block", "inline-block", "table"].includes(display)) {
return true;
// FIXME: not sure if this is useful:
// let rect = el.getBoundingClientRect();
// return rect.width <= this.maxAutoElementWidth && rect.height <= this.maxAutoElementHeight;
}
return false;
};
while (el) {
if (isGoodEl(el)) {
return el;
}
el = el.parentNode;
}
return null;
},
end() {
mouseupNoAutoselect = false;
},
};
stateHandlers.dragging = {
start() {
ui.iframe.useSelection();
ui.Box.display(selectedPos);
},
mousemove(event) {
selectedPos.x2 = util.truncateX(event.pageX);
selectedPos.y2 = util.truncateY(event.pageY);
scrollIfByEdge(event.pageX, event.pageY);
ui.Box.display(selectedPos);
ui.PixelDimensions.display(
event.pageX,
event.pageY,
selectedPos.width,
selectedPos.height
);
},
mouseup(event) {
selectedPos.x2 = util.truncateX(event.pageX);
selectedPos.y2 = util.truncateY(event.pageY);
ui.Box.display(selectedPos, standardDisplayCallbacks);
sendEvent(
"make-selection",
"selection-drag",
eventOptionsForBox({
top: selectedPos.y1,
bottom: selectedPos.y2,
left: selectedPos.x1,
right: selectedPos.x2,
})
);
setState("selected");
callBackground("captureTelemetry", "custom");
},
end() {
ui.PixelDimensions.remove();
},
};
stateHandlers.selected = {
start() {
ui.iframe.useSelection();
},
mousedown(event) {
const target = event.target;
if (target.tagName === "HTML") {
// This happens when you click on the scrollbar
return undefined;
}
const direction = ui.Box.draggerDirection(target);
if (direction) {
sendEvent("start-resize-selection", "handle");
stateHandlers.resizing.startResize(event, direction);
} else if (ui.Box.isSelection(target)) {
sendEvent("start-move-selection", "selection");
stateHandlers.resizing.startResize(event, "move");
} else if (!ui.Box.isControl(target)) {
mousedownPos = new Pos(event.pageX, event.pageY);
setState("crosshairs");
}
event.preventDefault();
return false;
},
};
stateHandlers.resizing = {
start() {
ui.iframe.useSelection();
selectedPos.sortCoords();
},
startResize(event, direction) {
selectedPos.sortCoords();
resizeDirection = direction;
resizeStartPos = new Pos(event.pageX, event.pageY);
resizeStartSelected = selectedPos.clone();
resizeHasMoved = false;
setState("resizing");
},
mousemove(event) {
this._resize(event);
if (resizeDirection !== "move") {
ui.PixelDimensions.display(
event.pageX,
event.pageY,
selectedPos.width,
selectedPos.height
);
}
return false;
},
mouseup(event) {
this._resize(event);
sendEvent("selection-resized");
ui.Box.display(selectedPos, standardDisplayCallbacks);
if (resizeHasMoved) {
if (resizeDirection === "move") {
const startPos = new Pos(
resizeStartSelected.left,
resizeStartSelected.top
);
const endPos = new Pos(selectedPos.left, selectedPos.top);
sendEvent(
"move-selection",
"mouseup",
eventOptionsForMove(startPos, endPos)
);
} else {
sendEvent(
"resize-selection",
"mouseup",
eventOptionsForResize(resizeStartSelected, selectedPos)
);
}
} else if (resizeDirection === "move") {
sendEvent("keep-resize-selection", "mouseup");
} else {
sendEvent("keep-move-selection", "mouseup");
}
setState("selected");
callBackground("captureTelemetry", "custom");
},
_resize(event) {
const diffX = event.pageX - resizeStartPos.x;
const diffY = event.pageY - resizeStartPos.y;
const movement = movements[resizeDirection];
if (movement[0]) {
let moveX = movement[0];
moveX = moveX === "*" ? ["x1", "x2"] : [moveX];
for (const moveDir of moveX) {
selectedPos[moveDir] = util.truncateX(
resizeStartSelected[moveDir] + diffX
);
}
}
if (movement[1]) {
let moveY = movement[1];
moveY = moveY === "*" ? ["y1", "y2"] : [moveY];
for (const moveDir of moveY) {
selectedPos[moveDir] = util.truncateY(
resizeStartSelected[moveDir] + diffY
);
}
}
if (diffX || diffY) {
resizeHasMoved = true;
}
scrollIfByEdge(event.pageX, event.pageY);
ui.Box.display(selectedPos);
},
end() {
resizeDirection = resizeStartPos = resizeStartSelected = null;
selectedPos.sortCoords();
ui.PixelDimensions.remove();
},
};
stateHandlers.cancel = {
start() {
ui.iframe.hide();
ui.Box.remove();
},
};
function getDocumentWidth() {
return Math.max(
document.body && document.body.clientWidth,
document.documentElement.clientWidth,
document.body && document.body.scrollWidth,
document.documentElement.scrollWidth
);
}
function getDocumentHeight() {
return Math.max(
document.body && document.body.clientHeight,
document.documentElement.clientHeight,
document.body && document.body.scrollHeight,
document.documentElement.scrollHeight
);
}
function scrollIfByEdge(pageX, pageY) {
const top = window.scrollY;
const bottom = top + window.innerHeight;
const left = window.scrollX;
const right = left + window.innerWidth;
if (pageY + SCROLL_BY_EDGE >= bottom && bottom < getDocumentHeight()) {
window.scrollBy(0, SCROLL_BY_EDGE);
} else if (pageY - SCROLL_BY_EDGE <= top) {
window.scrollBy(0, -SCROLL_BY_EDGE);
}
if (pageX + SCROLL_BY_EDGE >= right && right < getDocumentWidth()) {
window.scrollBy(SCROLL_BY_EDGE, 0);
} else if (pageX - SCROLL_BY_EDGE <= left) {
window.scrollBy(-SCROLL_BY_EDGE, 0);
}
}
/** *********************************************
* Selection communication
*/
exports.activate = function () {
if (!document.body) {
callBackground("abortStartShot");
const tagName = String(document.documentElement.tagName || "").replace(
/[^a-z0-9]/gi,
""
);
sendEvent("abort-start-shot", `document-is-${tagName}`);
selectorLoader.unloadModules();
return;
}
if (isFrameset()) {
callBackground("abortStartShot");
sendEvent("abort-start-shot", "frame-page");
selectorLoader.unloadModules();
return;
}
addHandlers();
setState("crosshairs");
};
function isFrameset() {
return document.body.tagName === "FRAMESET";
}
exports.deactivate = function () {
try {
sendEvent("internal", "deactivate");
setState("cancel");
selectorLoader.unloadModules();
} catch (e) {
log.error("Error in deactivate", e);
// Sometimes this fires so late that the document isn't available
// We don't care about the exception, so we swallow it here
}
};
let unloadTime = 0;
exports.unload = function () {
// Note that ui.unload() will be called on its own
unloadTime = Date.now();
removeHandlers();
};
/** *********************************************
* Event handlers
*/
const primedDocumentHandlers = new Map();
let registeredDocumentHandlers = [];
function addHandlers() {
["mouseup", "mousedown", "mousemove", "click"].forEach(eventName => {
const fn = watchFunction(
assertIsTrusted(function (event) {
if (typeof event.button === "number" && event.button !== 0) {
// Not a left click
return undefined;
}
if (
event.ctrlKey ||
event.shiftKey ||
event.altKey ||
event.metaKey
) {
// Modified click of key
return undefined;
}
const state = getState();
const handler = stateHandlers[state];
if (handler[event.type]) {
return handler[event.type](event);
}
return undefined;
})
);
primedDocumentHandlers.set(eventName, fn);
});
primedDocumentHandlers.set(
"keyup",
watchFunction(assertIsTrusted(keyupHandler))
);
primedDocumentHandlers.set(
"keydown",
watchFunction(assertIsTrusted(keydownHandler))
);
window.document.addEventListener(
"visibilitychange",
visibilityChangeHandler
);
window.addEventListener("beforeunload", beforeunloadHandler);
}
let mousedownSetOnDocument = false;
function installHandlersOnDocument(docObj) {
for (const [eventName, handler] of primedDocumentHandlers) {
const watchHandler = watchFunction(handler);
const useCapture = eventName !== "keyup";
docObj.addEventListener(eventName, watchHandler, useCapture);
registeredDocumentHandlers.push({
name: eventName,
doc: docObj,
handler: watchHandler,
useCapture,
});
}
if (!mousedownSetOnDocument) {
const mousedownHandler = primedDocumentHandlers.get("mousedown");
document.addEventListener("mousedown", mousedownHandler, true);
registeredDocumentHandlers.push({
name: "mousedown",
doc: document,
handler: mousedownHandler,
useCapture: true,
});
mousedownSetOnDocument = true;
}
}
function beforeunloadHandler() {
sendEvent("cancel-shot", "tab-load");
exports.deactivate();
}
function keydownHandler(event) {
// In MacOS, the keyup event for 'c' is not fired when performing cmd+c.
if (
event.code === "KeyC" &&
(event.ctrlKey || event.metaKey) &&
["previewing", "selected"].includes(getState.state)
) {
catcher.watchPromise(
callBackground("getPlatformOs").then(os => {
if (
(event.ctrlKey && os !== "mac") ||
(event.metaKey && os === "mac")
) {
sendEvent("copy-shot", "keyboard-copy");
copyShot();
}
})
);
}
}
function keyupHandler(event) {
if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {
// unused modifier keys
return;
}
if ((event.key || event.code) === "Escape") {
sendEvent("cancel-shot", "keyboard-escape");
exports.deactivate();
}
// Enter to trigger Download by default. But if the user tabbed to
// select another button, then we do not want this.
if (
(event.key || event.code) === "Enter" &&
getState.state === "selected" &&
ui.iframe.document().activeElement.tagName === "BODY"
) {
sendEvent("download-shot", "keyboard-enter");
downloadShot();
}
}
function visibilityChangeHandler(event) {
// The document is the event target
if (event.target.hidden) {
sendEvent("internal", "document-hidden");
}
}
function removeHandlers() {
window.removeEventListener("beforeunload", beforeunloadHandler);
window.document.removeEventListener(
"visibilitychange",
visibilityChangeHandler
);
for (const {
name,
doc,
handler,
useCapture,
} of registeredDocumentHandlers) {
doc.removeEventListener(name, handler, !!useCapture);
}
registeredDocumentHandlers = [];
}
catcher.watchFunction(exports.activate)();
return exports;
})();
null;
|