summaryrefslogtreecommitdiffstats
path: root/browser/components/screenshots/ScreenshotsOverlayChild.sys.mjs
blob: db2c24f3dc9d8e1f7c7bd278f6a3c744a3a5fe5c (plain)
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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
/* 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/. */

/**
 * The Screenshots overlay is inserted into the document's
 * canvasFrame anonymous content container (see dom/webidl/Document.webidl).
 *
 * This container gets cleared automatically when the document navigates.
 *
 * Since the overlay markup is inserted in the canvasFrame using
 * insertAnonymousContent, this means that it can be modified using the API
 * described in AnonymousContent.webidl.
 *
 * Any mutation of this content must be via the AnonymousContent API.
 * This is similar in design to [devtools' highlighters](https://firefox-source-docs.mozilla.org/devtools/tools/highlighters.html#inserting-content-in-the-page),
 * though as Screenshots doesnt need to work on XUL documents, or allow multiple kinds of
 * highlight/overlay our case is a little simpler.
 *
 * To retrieve the AnonymousContent instance, use the `content` getter.
 */

/* 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

  A pointerdown goes from crosshairs to dragging.
  A pointerup goes from dragging to selected
  A click outside of the selection goes from selected to crosshairs
  A pointerdown on one of the draggers goes from selected to resizing

  */

import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

const lazy = {};

XPCOMUtils.defineLazyGetter(lazy, "overlayLocalization", () => {
  return new Localization(["browser/screenshotsOverlay.ftl"], true);
});

const STYLESHEET_URL =
  "chrome://browser/content/screenshots/overlay/overlay.css";

// 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:
let MAX_DETECT_HEIGHT = 700;
let MAX_DETECT_WIDTH = 1000;

const REGION_CHANGE_THRESHOLD = 5;
const SCROLL_BY_EDGE = 20;

const doNotAutoselectTags = {
  H1: true,
  H2: true,
  H3: true,
  H4: true,
  H5: true,
  H6: true,
};

class AnonymousContentOverlay {
  constructor(contentDocument, screenshotsChild) {
    this.listeners = new Map();
    this.elements = new Map();

    this.screenshotsChild = screenshotsChild;

    this.contentDocument = contentDocument;
    // aliased for easier diffs/maintenance of the event management code borrowed from devtools highlighters
    this.pageListenerTarget = contentDocument.ownerGlobal;

    this.overlayFragment = null;

    this.overlayId = "screenshots-overlay-container";
    this.previewId = "preview-container";
    this.selectionId = "selection-container";
    this.hoverBoxId = "hover-highlight";

    this._initialized = false;

    this.moverIds = [
      "mover-left",
      "mover-top",
      "mover-right",
      "mover-bottom",
      "mover-topLeft",
      "mover-topRight",
      "mover-bottomLeft",
      "mover-bottomRight",
    ];
  }
  get content() {
    if (!this._content || Cu.isDeadWrapper(this._content)) {
      return null;
    }
    return this._content;
  }
  async initialize() {
    if (this._initialized) {
      return;
    }

    let document = this.contentDocument;
    let window = document.ownerGlobal;

    // Inject stylesheet
    if (!this.overlayFragment) {
      try {
        window.windowUtils.loadSheetUsingURIString(
          STYLESHEET_URL,
          window.windowUtils.AGENT_SHEET
        );
      } catch {
        // The method fails if the url is already loaded.
      }
      // Inject markup for the overlay UI
      this.overlayFragment = this.buildOverlay();
    }

    this._content = document.insertAnonymousContent(
      this.overlayFragment.children[0]
    );

    this.addEventListeners();

    const hoverElementBox = new HoverElementBox(
      this.hoverBoxId,
      this.content,
      document
    );

    const previewLayer = new PreviewLayer(this.previewId, this.content);
    const selectionLayer = new SelectionLayer(
      this.selectionId,
      this.content,
      hoverElementBox
    );

    this.screenshotsContainer = new ScreenshotsContainerLayer(
      this.overlayId,
      this.content,
      previewLayer,
      selectionLayer
    );

    this.stateHandler = new StateHandler(
      this.screenshotsContainer,
      this.screenshotsChild
    );

    this.screenshotsContainer.updateSize(window);

    this.stateHandler.setState("crosshairs");

    this._initialized = true;
  }

  /**
   * The Anonymous Content doesn't shrink when the window is resized so we need
   * to find the largest element that isn't the Anonymous Content and we will
   * use that width and height.
   * Otherwise we will fallback to the documentElement scroll width and height
   * @param eventType If "resize", we called this from a resize event so we will
   *  try shifting the SelectionBox.
   *  If "scroll", we called this from a scroll event so we will redraw the buttons
   */
  updateScreenshotsSize(eventType) {
    this.stateHandler.updateScreenshotsContainerSize(
      this.contentDocument.ownerGlobal,
      eventType
    );
  }

  /**
   * Add required event listeners to the overlay
   */
  addEventListeners() {
    let cancelScreenshotsFunciton = () => {
      this.screenshotsChild.requestCancelScreenshot("overlay_cancel");
    };
    this.addEventListenerForElement(
      "screenshots-cancel-button",
      "click",
      cancelScreenshotsFunciton
    );
    this.addEventListenerForElement(
      "cancel",
      "click",
      cancelScreenshotsFunciton
    );
    this.addEventListenerForElement("copy", "click", (event, targetId) => {
      this.screenshotsChild.requestCopyScreenshot(
        this.screenshotsContainer.getSelectionLayerBoxDimensions()
      );
    });
    this.addEventListenerForElement("download", "click", (event, targetId) => {
      this.screenshotsChild.requestDownloadScreenshot(
        this.screenshotsContainer.getSelectionLayerBoxDimensions()
      );
    });

    // The pointerdown event is added to the selection buttons to prevent the
    // pointerdown event from occurring on the "screenshots-overlay-container"
    this.addEventListenerForElement(
      "cancel",
      "pointerdown",
      (event, targetId) => {
        event.stopPropagation();
      }
    );
    this.addEventListenerForElement(
      "copy",
      "pointerdown",
      (event, targetId) => {
        event.stopPropagation();
      }
    );
    this.addEventListenerForElement(
      "download",
      "pointerdown",
      (event, targetId) => {
        event.stopPropagation();
      }
    );

    this.addEventListenerForElement(
      this.overlayId,
      "pointerdown",
      (event, targetId) => {
        this.dragStart(event, targetId);
      }
    );
    this.addEventListenerForElement(
      this.overlayId,
      "pointerup",
      (event, targetId) => {
        this.dragEnd(event, targetId);
      }
    );
    this.addEventListenerForElement(
      this.overlayId,
      "pointermove",
      (event, targetId) => {
        this.drag(event, targetId);
      }
    );

    for (let id of this.moverIds.concat(["highlight"])) {
      this.addEventListenerForElement(id, "pointerdown", (event, targetId) => {
        this.dragStart(event, targetId);
      });
      this.addEventListenerForElement(id, "pointerup", (event, targetId) => {
        this.dragEnd(event, targetId);
      });
      this.addEventListenerForElement(id, "pointermove", (event, targetId) => {
        this.drag(event, targetId);
      });
    }
  }

  /**
   * Removes all event listeners and removes the overlay from the Anonymous Content
   */
  tearDown() {
    if (this._content) {
      this._removeAllListeners();
      try {
        this.contentDocument.removeAnonymousContent(this._content);
      } catch (e) {
        // If the current window isn't the one the content was inserted into, this
        // will fail, but that's fine.
      }
    }
    this._initialized = false;
  }

  /**
   * Creates the document fragment that will be added to the Anonymous Content
   * @returns document fragment that can be injected into the Anonymous Content
   */
  buildOverlay() {
    let [cancel, instructions, download, copy] =
      lazy.overlayLocalization.formatMessagesSync([
        { id: "screenshots-overlay-cancel-button" },
        { id: "screenshots-overlay-instructions" },
        { id: "screenshots-overlay-download-button" },
        { id: "screenshots-overlay-copy-button" },
      ]);

    const htmlString = `
    <div id="screenshots-component">
      <div id="${this.overlayId}">
        <div id="${this.previewId}">
          <div class="fixed-container">
            <div class="face-container">
              <div class="eye left"><div id="left-eye" class="eyeball"></div></div>
              <div class="eye right"><div id="right-eye" class="eyeball"></div></div>
              <div class="face"></div>
            </div>
            <div class="preview-instructions">${instructions.value}</div>
            <button class="screenshots-button" id="screenshots-cancel-button">${cancel.value}</button>
          </div>
        </div>
        <div id="${this.hoverBoxId}"></div>
        <div id="${this.selectionId}" style="display:none;">
          <div id="bgTop" class="bghighlight" style="display:none;"></div>
          <div id="bgBottom" class="bghighlight" style="display:none;"></div>
          <div id="bgLeft" class="bghighlight" style="display:none;"></div>
          <div id="bgRight" class="bghighlight" style="display:none;"></div>
          <div id="highlight" class="highlight" style="display:none;">
            <div id="mover-topLeft" class="mover-target direction-topLeft">
              <div class="mover"></div>
            </div>
            <div id="mover-top" class="mover-target direction-top">
              <div class="mover"></div>
            </div>
            <div id="mover-topRight" class="mover-target direction-topRight">
              <div class="mover"></div>
            </div>
            <div id="mover-left" class="mover-target direction-left">
              <div class="mover"></div>
            </div>
            <div id="mover-right" class="mover-target direction-right">
              <div class="mover"></div>
            </div>
            <div id="mover-bottomLeft" class="mover-target direction-bottomLeft">
              <div class="mover"></div>
            </div>
            <div id="mover-bottom" class="mover-target direction-bottom">
              <div class="mover"></div>
            </div>
            <div id="mover-bottomRight" class="mover-target direction-bottomRight">
              <div class="mover"></div>
            </div>
          </div>
          <div id="buttons" style="display:none;">
            <button id="cancel" class="screenshots-button" title="${cancel.value}" aria-label="${cancel.value}"><img/></button>
            <button id="copy" class="screenshots-button" title="${copy.value}" aria-label="${copy.value}"><img/>${copy.value}</button>
            <button id="download" class="screenshots-button primary" title="${download.value}" aria-label="${download.value}"><img/>${download.value}</button>
          </div>
        </div>
      </div>
    </div>`;

    const parser = new this.contentDocument.ownerGlobal.DOMParser();
    const tmpDoc = parser.parseFromSafeString(htmlString, "text/html");
    const fragment = this.contentDocument.createDocumentFragment();

    fragment.appendChild(tmpDoc.body.children[0]);
    return fragment;
  }

  // The event tooling is borrowed directly from devtools' highlighters (CanvasFrameAnonymousContentHelper)
  /**
   * Add an event listener to one of the elements inserted in the canvasFrame
   * native anonymous container.
   * Like other methods in this helper, this requires the ID of the element to
   * be passed in.
   *
   * Note that if the content page navigates, the event listeners won't be
   * added again.
   *
   * Also note that unlike traditional DOM events, the events handled by
   * listeners added here will propagate through the document only through
   * bubbling phase, so the useCapture parameter isn't supported.
   * It is possible however to call e.stopPropagation() to stop the bubbling.
   *
   * IMPORTANT: the chrome-only canvasFrame insertion API takes great care of
   * not leaking references to inserted elements to chrome JS code. That's
   * because otherwise, chrome JS code could freely modify native anon elements
   * inside the canvasFrame and probably change things that are assumed not to
   * change by the C++ code managing this frame.
   * See https://wiki.mozilla.org/DevTools/Highlighter#The_AnonymousContent_API
   * Unfortunately, the inserted nodes are still available via
   * event.originalTarget, and that's what the event handler here uses to check
   * that the event actually occured on the right element, but that also means
   * consumers of this code would be able to access the inserted elements.
   * Therefore, the originalTarget property will be nullified before the event
   * is passed to your handler.
   *
   * IMPL DETAIL: A single event listener is added per event types only, at
   * browser level and if the event originalTarget is found to have the provided
   * ID, the callback is executed (and then IDs of parent nodes of the
   * originalTarget are checked too).
   *
   * @param {String} id
   * @param {String} type
   * @param {Function} handler
   */
  addEventListenerForElement(id, type, handler) {
    if (typeof id !== "string") {
      throw new Error(
        "Expected a string ID in addEventListenerForElement but got: " + id
      );
    }

    // If no one is listening for this type of event yet, add one listener.
    if (!this.listeners.has(type)) {
      const target = this.pageListenerTarget;
      target.addEventListener(type, this, true);
      // Each type entry in the map is a map of ids:handlers.
      this.listeners.set(type, new Map());
    }

    const listeners = this.listeners.get(type);
    listeners.set(id, handler);
  }

  /**
   * Remove an event listener from one of the elements inserted in the
   * canvasFrame native anonymous container.
   * @param {String} id
   * @param {String} type
   */
  removeEventListenerForElement(id, type) {
    const listeners = this.listeners.get(type);
    if (!listeners) {
      return;
    }
    listeners.delete(id);

    // If no one is listening for event type anymore, remove the listener.
    if (!listeners.size) {
      const target = this.pageListenerTarget;
      target.removeEventListener(type, this, true);
    }
  }

  handleEvent(event) {
    const listeners = this.listeners.get(event.type);
    if (!listeners) {
      return;
    }

    // Hide the originalTarget property to avoid exposing references to native
    // anonymous elements. See addEventListenerForElement's comment.
    let isPropagationStopped = false;
    const eventProxy = new Proxy(event, {
      get: (obj, name) => {
        if (name === "originalTarget") {
          return null;
        } else if (name === "stopPropagation") {
          return () => {
            isPropagationStopped = true;
          };
        }
        return obj[name];
      },
    });

    // Start at originalTarget, bubble through ancestors and call handlers when
    // needed.
    let node = event.originalTarget;
    while (node) {
      let nodeId = node.id;
      if (nodeId) {
        const handler = listeners.get(node.id);
        if (handler) {
          handler(eventProxy, nodeId);
          if (isPropagationStopped) {
            break;
          }
        }
        if (nodeId == this.overlayId) {
          break;
        }
      }
      node = node.parentNode;
    }
  }

  _removeAllListeners() {
    if (this.pageListenerTarget) {
      const target = this.pageListenerTarget;
      for (const [type] of this.listeners) {
        target.removeEventListener(type, this, true);
      }
    }
    this.listeners.clear();
  }

  /**
   * Pass the pointer down event to the state handler
   * @param event The pointer down event
   * @param targetId The target element id
   */
  dragStart(event, targetId) {
    this.stateHandler.dragStart(event, targetId);
  }

  /**
   * Pass the pointer move event to the state handler
   * @param event The pointer move event
   * @param targetId The target element id
   */
  drag(event, targetId) {
    this.stateHandler.drag(event, targetId);
  }

  /**
   * Pass the pointer up event to the state handler
   * @param event The pointer up event
   * @param targetId The target element id
   */
  dragEnd(event, targetId) {
    this.stateHandler.dragEnd(event);
  }
}

export var ScreenshotsOverlayChild = {
  AnonymousContentOverlay,
};

/**
 * The StateHandler class handles the state of the overlay
 */
class StateHandler {
  #state;
  #lastBox;
  #moverId;
  #lastX;
  #lastY;
  #screenshotsContainer;
  #screenshotsChild;
  #previousDimensions;

  constructor(screenshotsContainer, screenshotsChild) {
    this.#state = "crosshairs";
    this.#lastBox = {};

    this.#screenshotsContainer = screenshotsContainer;
    this.#screenshotsChild = screenshotsChild;
  }

  setState(newState) {
    if (this.#state === "selected" && newState === "crosshairs") {
      this.#screenshotsChild.recordTelemetryEvent(
        "started",
        "overlay_retry",
        {}
      );
    }
    this.#state = newState;
    this.start();
  }

  getState() {
    return this.#state;
  }

  getHoverElementBoxRect() {
    return this.#screenshotsContainer.hoverElementBoxRect;
  }

  /**
   * At the start of the some states we need to perform some actions
   */
  start() {
    switch (this.#state) {
      case "crosshairs": {
        this.crosshairsStart();
        break;
      }
      case "draggingReady": {
        this.draggingReadyStart();
        break;
      }
      case "dragging": {
        this.draggingStart();
        break;
      }
      case "selected": {
        this.selectedStart();
        break;
      }
      case "resizing": {
        this.resizingStart();
        break;
      }
    }
  }

  /**
   * Returns the x and y coordinates of the event
   * @param event The mouse or touch event
   * @returns object containing the x and y coordinates of the mouse
   */
  getCoordinates(event) {
    const { clientX, clientY, pageX, pageY } = event;

    MAX_DETECT_HEIGHT = Math.max(event.target.clientHeight + 100, 700);
    MAX_DETECT_WIDTH = Math.max(event.target.clientWidth + 100, 1000);

    return { clientX, clientY, pageX, pageY };
  }

  /**
   * Handles the mousedown/touchstart event depending on the state
   * @param event The mousedown or touchstart event
   * @param targetId The id of the event target
   */
  dragStart(event, targetId) {
    const { pageX, pageY } = this.getCoordinates(event);

    switch (this.#state) {
      case "crosshairs": {
        this.crosshairsDragStart(pageX, pageY);
        break;
      }
      case "selected": {
        this.selectedDragStart(pageX, pageY, targetId);
        break;
      }
    }
  }

  /**
   * Handles the move event depending on the state
   * @param event The mousemove or touchmove event
   * @param targetId The id of the event target
   */
  drag(event, targetId) {
    const { pageX, pageY, clientX, clientY } = this.getCoordinates(event);

    switch (this.#state) {
      case "crosshairs": {
        this.crosshairsMove(clientX, clientY, targetId);
        break;
      }
      case "draggingReady": {
        this.draggingReadyDrag(pageX, pageY);
        break;
      }
      case "dragging": {
        this.draggingDrag(pageX, pageY);
        break;
      }
      case "resizing": {
        this.resizingDrag(pageX, pageY);
        break;
      }
    }
  }

  /**
   * Handles the move event depending on the state
   * @param event The mouseup event
   * @param targetId The id of the event target
   */
  dragEnd(event, targetId) {
    const { pageX, pageY, clientX, clientY } = this.getCoordinates(event);

    switch (this.#state) {
      case "draggingReady": {
        this.draggingReadyDragEnd(pageX - clientX, pageY - clientY);
        break;
      }
      case "dragging": {
        this.draggingDragEnd(pageX, pageY, targetId);
        break;
      }
      case "resizing": {
        this.resizingDragEnd(pageX, pageY, targetId);
        break;
      }
    }
  }

  /**
   * Hide the box and highlighter and show the overlay at the start of crosshairs state
   */
  crosshairsStart() {
    this.#screenshotsContainer.hideSelectionLayer();
    this.#screenshotsContainer.showPreviewLayer();
    this.#screenshotsChild.showPanel();
    this.#previousDimensions = null;
  }

  /**
   *
   */
  draggingReadyStart() {
    this.#screenshotsChild.hidePanel();
  }

  /**
   * Hide the overlay and draw the box at the start of dragging state
   */
  draggingStart() {
    this.#screenshotsContainer.hidePreviewLayer();
    this.#screenshotsContainer.hideButtonsLayer();
    this.#screenshotsContainer.drawSelectionBox();
  }

  /**
   * Show the buttons at the start of the selected state
   */
  selectedStart() {
    this.#screenshotsContainer.drawButtonsLayer();
  }

  /**
   * Hide the buttons and store width and height of box at the start of the resizing state
   */
  resizingStart() {
    this.#screenshotsContainer.hideButtonsLayer();
    let { width, height } =
      this.#screenshotsContainer.getSelectionLayerBoxDimensions();
    this.#lastBox = {
      width,
      height,
    };
  }

  /**
   * Set the initial box coordinates and set the state to "draggingReady"
   * @param pageX x coordinate
   * @param pageY y coordinate
   */
  crosshairsDragStart(pageX, pageY) {
    this.#screenshotsContainer.setSelectionBoxDimensions({
      left: pageX,
      top: pageY,
      right: pageX,
      bottom: pageY,
    });

    this.setState("draggingReady");
  }

  /**
   * If the background is clicked we set the state to crosshairs
   * otherwise set the state to resizing
   * @param pageX x coordinate
   * @param pageY y coordinate
   * @param targetId The id of the event target
   */
  selectedDragStart(pageX, pageY, targetId) {
    if (targetId === this.#screenshotsContainer.id) {
      this.setState("crosshairs");
      return;
    }
    this.#moverId = targetId;
    this.#lastX = pageX;
    this.#lastY = pageY;

    this.setState("resizing");
  }

  /**
   * Handles the pointer move for the crosshairs state
   * @param clientX x pointer position in the visible window
   * @param clientY y pointer position in the visible window
   * @param targetId The id of the target element
   */
  crosshairsMove(clientX, clientY, targetId) {
    this.#screenshotsContainer.drawPreviewEyes(clientX, clientY);

    this.#screenshotsContainer.handleElementHover(clientX, clientY, targetId);
  }

  /**
   * Set the bottom and right coordinates of the box and draw the box
   * @param pageX x coordinate
   * @param pageY y coordinate
   */
  draggingDrag(pageX, pageY) {
    this.scrollIfByEdge(pageX, pageY);
    this.#screenshotsContainer.setSelectionBoxDimensions({
      right: pageX,
      bottom: pageY,
    });

    this.#screenshotsContainer.drawSelectionBox();
  }

  /**
   * If the mouse has moved at least 40 pixels then set the state to "dragging"
   * @param pageX x coordinate
   * @param pageY y coordinate
   */
  draggingReadyDrag(pageX, pageY) {
    this.#screenshotsContainer.setSelectionBoxDimensions({
      right: pageX,
      bottom: pageY,
    });

    if (this.#screenshotsContainer.selectionBoxDistance() > 40) {
      this.setState("dragging");
    }
  }

  /**
   * Depending on what mover was selected we will resize the box accordingly
   * @param pageX x coordinate
   * @param pageY y coordinate
   */
  resizingDrag(pageX, pageY) {
    this.scrollIfByEdge(pageX, pageY);
    switch (this.#moverId) {
      case "mover-topLeft": {
        this.#screenshotsContainer.setSelectionBoxDimensions({
          left: pageX,
          top: pageY,
        });
        break;
      }
      case "mover-top": {
        this.#screenshotsContainer.setSelectionBoxDimensions({ top: pageY });
        break;
      }
      case "mover-topRight": {
        this.#screenshotsContainer.setSelectionBoxDimensions({
          top: pageY,
          right: pageX,
        });
        break;
      }
      case "mover-right": {
        this.#screenshotsContainer.setSelectionBoxDimensions({
          right: pageX,
        });
        break;
      }
      case "mover-bottomRight": {
        this.#screenshotsContainer.setSelectionBoxDimensions({
          right: pageX,
          bottom: pageY,
        });
        break;
      }
      case "mover-bottom": {
        this.#screenshotsContainer.setSelectionBoxDimensions({
          bottom: pageY,
        });
        break;
      }
      case "mover-bottomLeft": {
        this.#screenshotsContainer.setSelectionBoxDimensions({
          left: pageX,
          bottom: pageY,
        });
        break;
      }
      case "mover-left": {
        this.#screenshotsContainer.setSelectionBoxDimensions({ left: pageX });
        break;
      }
      case "highlight": {
        let lastBox = this.#lastBox;
        let diffX = this.#lastX - pageX;
        let diffY = this.#lastY - pageY;

        let newLeft;
        let newRight;
        let newTop;
        let newBottom;

        // Unpack SelectionBox dimensions to use here
        let {
          boxLeft,
          boxTop,
          boxRight,
          boxBottom,
          boxWidth,
          boxHeight,
          scrollWidth,
          scrollHeight,
        } = this.#screenshotsContainer.getSelectionLayerDimensions();

        // wait until all 4 if elses have completed before setting box dimensions
        if (boxWidth <= lastBox.width && boxLeft === 0) {
          newLeft = boxRight - lastBox.width;
        } else {
          newLeft = boxLeft;
        }

        if (boxWidth <= lastBox.width && boxRight === scrollWidth) {
          newRight = boxLeft + lastBox.width;
        } else {
          newRight = boxRight;
        }

        if (boxHeight <= lastBox.height && boxTop === 0) {
          newTop = boxBottom - lastBox.height;
        } else {
          newTop = boxTop;
        }

        if (boxHeight <= lastBox.height && boxBottom === scrollHeight) {
          newBottom = boxTop + lastBox.height;
        } else {
          newBottom = boxBottom;
        }

        this.#screenshotsContainer.setSelectionBoxDimensions({
          left: newLeft - diffX,
          top: newTop - diffY,
          right: newRight - diffX,
          bottom: newBottom - diffY,
        });

        this.#lastX = pageX;
        this.#lastY = pageY;
        break;
      }
    }
    this.#screenshotsContainer.drawSelectionBox();
  }

  /**
   * Draw the selection box from the hover element box if it exists
   * Else set the state to "crosshairs"
   */
  draggingReadyDragEnd(scrollX, scrollY) {
    if (this.#screenshotsContainer.hoverElementBoxRect) {
      this.#screenshotsContainer.hidePreviewLayer();
      this.#screenshotsContainer.updateSelectionBoxFromRect(scrollX, scrollY);
      this.#screenshotsContainer.drawSelectionBox();
      this.setState("selected");
      this.#screenshotsChild.recordTelemetryEvent("selected", "element", {});
    } else {
      this.setState("crosshairs");
    }
  }

  /**
   * Draw the box one last time and set the state to "selected"
   * @param pageX x coordinate
   * @param pageY y coordinate
   */
  draggingDragEnd(pageX, pageY) {
    this.#screenshotsContainer.setSelectionBoxDimensions({
      right: pageX,
      bottom: pageY,
    });
    this.#screenshotsContainer.sortSelectionLayerBoxCoords();
    this.setState("selected");

    let { width, height } =
      this.#screenshotsContainer.getSelectionLayerBoxDimensions();

    if (
      !this.#previousDimensions ||
      (Math.abs(this.#previousDimensions.width - width) >
        REGION_CHANGE_THRESHOLD &&
        Math.abs(this.#previousDimensions.height - height) >
          REGION_CHANGE_THRESHOLD)
    ) {
      this.#screenshotsChild.recordTelemetryEvent(
        "selected",
        "region_selection",
        {}
      );
    }
    this.#previousDimensions = { width, height };
  }

  /**
   * Draw the box one last time and set the state to "selected"
   * @param pageX x coordinate
   * @param pageY y coordinate
   */
  resizingDragEnd(pageX, pageY, targetId) {
    this.resizingDrag(pageX, pageY, targetId);
    this.#screenshotsContainer.sortSelectionLayerBoxCoords();
    this.setState("selected");
  }

  /**
   * The page was resized or scrolled. We need to update the
   * ScreenshotsContainer size so we don't draw outside the window bounds
   * If the current state is "selected" and this was called from a resize event
   * then we need to maybe shift the SelectionBox
   * @param win The window object of the page
   * @param eventType If this was called from a resize event
   */
  updateScreenshotsContainerSize(win, eventType) {
    if (this.#state === "crosshairs" && eventType === "resize") {
      this.#screenshotsContainer.hideHoverElementBox();
    }

    this.#screenshotsContainer.updateSize(win);

    if (this.#state === "selected" && eventType === "resize") {
      this.#screenshotsContainer.shiftSelectionLayerBox();
    } else if (
      this.#state !== "resizing" &&
      this.#state !== "dragging" &&
      eventType === "scroll"
    ) {
      this.#screenshotsContainer.drawButtonsLayer();
      if (this.#state === "crosshairs") {
        this.#screenshotsContainer.handleElementScroll();
      }
    }
  }

  scrollIfByEdge(pageX, pageY) {
    let dimensions = this.#screenshotsContainer.getSelectionLayerDimensions();

    if (pageY - dimensions.scrollY <= SCROLL_BY_EDGE) {
      // Scroll up
      this.#screenshotsChild.scrollWindow(0, -SCROLL_BY_EDGE);
    } else if (
      dimensions.scrollY + dimensions.clientHeight - pageY <=
      SCROLL_BY_EDGE
    ) {
      // Scroll down
      this.#screenshotsChild.scrollWindow(0, SCROLL_BY_EDGE);
    }

    if (pageX - dimensions.scrollX <= SCROLL_BY_EDGE) {
      // Scroll left
      this.#screenshotsChild.scrollWindow(-SCROLL_BY_EDGE, 0);
    } else if (
      dimensions.scrollX + dimensions.clientWidth - pageX <=
      SCROLL_BY_EDGE
    ) {
      // Scroll right
      this.#screenshotsChild.scrollWindow(SCROLL_BY_EDGE, 0);
    }
  }
}

class AnonLayer {
  id;
  content;

  constructor(id, content) {
    this.id = id;
    this.content = content;
  }

  /**
   * Show element with id this.id
   */
  show() {
    this.content.removeAttributeForElement(this.id, "style");
  }

  /**
   * Hide element with id this.id
   */
  hide() {
    this.content.setAttributeForElement(this.id, "style", "display:none;");
  }
}

class HoverElementBox extends AnonLayer {
  #document;
  #rect;
  #lastX;
  #lastY;

  constructor(id, content, document) {
    super(id, content);

    this.#document = document;
  }

  get rect() {
    return this.#rect;
  }

  /**
   * Draws the hover box over an element from the given rect
   * @param rect The rect to draw the hover element box
   */
  drawHoverBox(rect) {
    if (!rect) {
      this.hide();
    } else {
      let maxHeight = this.selectionLayer.scrollHeight;
      let maxWidth = this.selectionLayer.scrollWidth;
      let top = this.#document.documentElement.scrollTop + rect.top;
      top = top > 0 ? top : 0;
      let left = this.#document.documentElement.scrollLeft + rect.left;
      left = left > 0 ? left : 0;
      let height =
        rect.top + rect.height > maxHeight ? maxHeight - rect.top : rect.height;
      let width =
        rect.left + rect.width > maxWidth ? maxWidth - rect.left : rect.width;

      this.content.setAttributeForElement(
        this.id,
        "style",
        `top:${top}px;left:${left}px;height:${height}px;width:${width}px;`
      );
    }
  }

  /**
   * Handles when the user moves the mouse over an element
   * @param clientX The x coordinate in the visible window
   * @param clientY The y coordinate in the visible window
   * @param targetId The target element id
   */
  handleElementHover(clientX, clientY, targetId) {
    if (targetId === "screenshots-overlay-container") {
      let ele = this.getElementFromPoint(clientX, clientY);

      if (this.cachedEle && this.cachedEle === ele) {
        // Still hovering over the same element
        return;
      }
      this.cachedEle = ele;

      this.getBestRectForElement(ele);

      this.#lastX = clientX;
      this.#lastY = clientY;
    }
  }

  /**
   * Handles moving the rect when the user has scrolled but not moved the mouse
   * It uses the last x and y coordinates to find the new element at the mouse position
   */
  handleElementScroll() {
    if (this.#lastX && this.#lastY) {
      this.cachedEle = null;
      this.handleElementHover(
        this.#lastX,
        this.#lastY,
        "screenshots-overlay-container"
      );
    }
  }

  /**
   * Finds an element for the given coordinates within the viewport
   * @param x The x coordinate in the visible window
   * @param y The y coordinate in the visible window
   * @returns An element location at the given coordinates
   */
  getElementFromPoint(x, y) {
    this.setPointerEventsNone();
    let ele;
    try {
      ele = this.#document.elementFromPoint(x, y);
    } finally {
      this.resetPointerEvents();
    }

    return ele;
  }

  /**
   * Gets the rect for an element if getBoundingClientRect exists
   * @param ele The element to get the rect from
   * @returns The bounding client rect of the element or null
   */
  getBoundingClientRect(ele) {
    if (!ele.getBoundingClientRect) {
      return null;
    }

    return ele.getBoundingClientRect();
  }

  /**
   * This function takes an element and finds a suitable rect to draw the hover box on
   * @param ele The element to find a suitale rect of
   */
  getBestRectForElement(ele) {
    let lastRect;
    let lastNode;
    let rect;
    let attemptExtend = false;
    let node = ele;
    while (node) {
      rect = this.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);
      if (evenBetter) {
        node = lastNode = evenBetter;
        rect = this.getBoundingClientRect(evenBetter);
        attemptExtend = false;
      }
    }
    if (rect && attemptExtend) {
      let extendNode = lastNode.nextSibling;
      while (extendNode) {
        if (extendNode.nodeType === this.#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 extendRect = this.getBoundingClientRect(extendNode);
        let x = Math.min(rect.x, extendRect.x);
        let y = Math.min(rect.y, extendRect.y);
        let width = Math.max(rect.right, extendRect.right) - x;
        let height = Math.max(rect.bottom, extendRect.bottom) - y;
        const combinedRect = new DOMRect(x, y, width, height);
        if (
          combinedRect.width <= MAX_DETECT_WIDTH &&
          combinedRect.height <= MAX_DETECT_HEIGHT
        ) {
          rect = combinedRect;
        }
      }
    }

    if (
      rect &&
      (rect.width < MIN_DETECT_ABSOLUTE_WIDTH ||
        rect.height < MIN_DETECT_ABSOLUTE_HEIGHT)
    ) {
      rect = null;
    }

    if (!rect) {
      this.hide();
    } else {
      this.drawHoverBox(rect);
    }

    this.#rect = rect;
  }

  /**
   * This finds a better element by looking for elements with role article
   * @param node The currently hovered node
   * @returns A better node or null
   */
  evenBetterElement(node) {
    let el = node.parentNode;
    const ELEMENT_NODE = this.#document.ELEMENT_NODE;
    while (el && el.nodeType === ELEMENT_NODE) {
      if (!el.getAttribute) {
        return null;
      }
      if (el.getAttribute("role") === "article") {
        const rect = this.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;
  }

  /**
   * The pointer events need to be removed temporarily so we can find the
   * correct element from document.elementFromPoint()
   * If the pointer events are on for the screenshots elements, then we will always
   * get the screenshots elements as the elements from a given point
   */
  setPointerEventsNone() {
    this.content.setAttributeForElement(
      "screenshots-component",
      "style",
      "pointer-events:none;"
    );

    let temp = this.content.getAttributeForElement(
      "screenshots-overlay-container",
      "style"
    );
    this.content.setAttributeForElement(
      "screenshots-overlay-container",
      "style",
      temp + "pointer-events:none;"
    );
  }

  /**
   * Return the pointer events to the original state because we found the element
   */
  resetPointerEvents() {
    this.content.setAttributeForElement("screenshots-component", "style", "");

    let temp = this.content.getAttributeForElement(
      "screenshots-overlay-container",
      "style"
    );
    this.content.setAttributeForElement(
      "screenshots-overlay-container",
      "style",
      temp.replace("pointer-events:none;", "")
    );
  }
}

class SelectionLayer extends AnonLayer {
  #selectionBox;
  #hoverElementBox;
  #buttons;
  #hidden;
  /**
   * the documentDimensions follows the below structure
   * {
   *    scrollWidth: the total document width
   *    scrollHeight: the total document height
   *    scrollX: the x scrolled offset
   *    scrollY: the y scrolled offset
   *    clientWidth: the viewport width
   *    clientHeight: the viewport height
   * }
   */
  #documentDimensions;

  constructor(id, content, hoverElementBox) {
    super(id, content);
    this.#selectionBox = new SelectionBox(content, this);
    this.#buttons = new ButtonsLayer("buttons", content, this);
    this.#hoverElementBox = hoverElementBox;
    this.#hoverElementBox.selectionLayer = this;

    this.#hidden = true;
    this.#documentDimensions = {};
  }

  /**
   * Hide the buttons layer
   */
  hideButtons() {
    this.#buttons.hide();
  }

  /**
   * Call
   */
  drawButtonsLayer() {
    this.#buttons.show();
  }

  /**
   * Hide the selection-container element
   */
  hide() {
    super.hide();
    this.#hidden = true;
  }

  /**
   * Draw the SelectionBox
   */
  drawSelectionBox() {
    if (this.#hidden) {
      this.show();
      this.#hidden = false;
    }
    this.#selectionBox.show();
  }

  /**
   * Sort the SelectionBox coordinates
   */
  sortSelectionBoxCoords() {
    this.#selectionBox.sortCoords();
  }

  /**
   * Sets the SelectionBox dimensions
   * @param {Object} dims The new box dimensions
   *  {
   *    left: new left dimension value or undefined
   *    top: new top dimension value or undefined
   *    right: new right dimension value or undefined
   *    bottom: new bottom dimension value or undefined
   *   }
   */
  setSelectionBoxDimensions(dims) {
    if (dims.left) {
      this.#selectionBox.left = dims.left;
    }
    if (dims.top) {
      this.#selectionBox.top = dims.top;
    }
    if (dims.right) {
      this.#selectionBox.right = dims.right;
    }
    if (dims.bottom) {
      this.#selectionBox.bottom = dims.bottom;
    }
  }

  /**
   * Gets the selections box dimensions
   * @returns {Object}
   *  {
   *    x1: the left dimension value
   *    y1: the top dimension value
   *    width: the width of the selected region
   *    height: the height of the selected region
   *  }
   */
  getSelectionBoxDimensions() {
    return this.#selectionBox.getDimensions();
  }

  /**
   * Returns the box dimensions and the page dimensions
   * @returns {Object}
   *  {
   *    boxLeft: the left position of the box
   *    boxTop: the top position of the box
   *    boxRight: the right position of the box
   *    boxBottom: the bottom position of the box
   *    scrollWidth: the total document width
   *    scrollHeight: the total document height
   *    scrollX: the x scrolled offset
   *    scrollY: the y scrolled offset
   *    clientWidth: the viewport width
   *    clientHeight: the viewport height
   *  }
   */
  getDimensions() {
    return {
      boxLeft: this.#selectionBox.left,
      boxTop: this.#selectionBox.top,
      boxRight: this.#selectionBox.right,
      boxBottom: this.#selectionBox.bottom,
      boxWidth: this.#selectionBox.width,
      boxHeight: this.#selectionBox.height,
      ...this.#documentDimensions,
    };
  }

  /**
   * Gets the diagonal distance of the SelectionBox
   * @returns The diagonal distance of the SelectionBox
   */
  getSelectionBoxDistance() {
    return this.#selectionBox.distance;
  }

  /**
   * Shift the SelectionBox so that it is always within the document
   */
  shiftSelectionBox() {
    this.#selectionBox.shiftBox();
  }

  /**
   * Update the box coordinates from the hover element rect
   */
  updateSelectionBoxFromRect(scrollX, scrollY) {
    this.#selectionBox.updateBoxFromRect(
      this.#hoverElementBox.rect,
      scrollX,
      scrollY
    );
  }

  /**
   * Handles when the user moves the mouse over an element
   * @param clientX The x coordinate in the visible window
   * @param clientY The y coordinate in the visible window
   * @param targetId The target element id
   */
  handleElementHover(clientX, clientY, targetId) {
    this.#hoverElementBox.handleElementHover(clientX, clientY, targetId);
  }

  /**
   * Handles moving the rect when the user has scrolled but not moved the mouse
   * It uses the last x and y coordinates to find the new element at the mouse position
   */
  handleElementScroll() {
    this.#hoverElementBox.handleElementScroll();
  }

  hideHoverElementSelection() {
    this.#hoverElementBox.hide();
  }

  get hoverElementBoxRect() {
    return this.#hoverElementBox.rect;
  }

  get scrollWidth() {
    return this.#documentDimensions.scrollWidth;
  }
  set scrollWidth(val) {
    this.#documentDimensions.scrollWidth = val;
  }

  get scrollHeight() {
    return this.#documentDimensions.scrollHeight;
  }
  set scrollHeight(val) {
    this.#documentDimensions.scrollHeight = val;
  }

  get scrollX() {
    return this.#documentDimensions.scrollX;
  }
  set scrollX(val) {
    this.#documentDimensions.scrollX = val;
  }

  get scrollY() {
    return this.#documentDimensions.scrollY;
  }
  set scrollY(val) {
    this.#documentDimensions.scrollY = val;
  }

  get clientWidth() {
    return this.#documentDimensions.clientWidth;
  }
  set clientWidth(val) {
    this.#documentDimensions.clientWidth = val;
  }

  get clientHeight() {
    return this.#documentDimensions.clientHeight;
  }
  set clientHeight(val) {
    this.#documentDimensions.clientHeight = val;
  }
}

/**
 * The SelectionBox class handles drawing the highlight and background
 */
class SelectionBox extends AnonLayer {
  #x1;
  #x2;
  #y1;
  #y2;
  #xOffset;
  #yOffset;
  #selectionLayer;

  constructor(content, selectionLayer) {
    super("", content);

    this.#selectionLayer = selectionLayer;

    this.#x1 = 0;
    this.#x2 = 0;
    this.#y1 = 0;
    this.#y2 = 0;
    this.#xOffset = 0;
    this.#yOffset = 0;
  }

  /**
   * Draw the selected region for screenshotting
   */
  show() {
    this.content.setAttributeForElement(
      "highlight",
      "style",
      `top:${this.top}px;left:${this.left}px;height:${this.height}px;width:${this.width}px;`
    );

    this.content.setAttributeForElement(
      "bgTop",
      "style",
      `top:0px;height:${this.top}px;left:0px;width:100%;`
    );

    this.content.setAttributeForElement(
      "bgBottom",
      "style",
      `top:${this.bottom}px;height:calc(100% - ${this.bottom}px);left:0px;width:100%;`
    );

    this.content.setAttributeForElement(
      "bgLeft",
      "style",
      `top:${this.top}px;height:${this.height}px;left:0px;width:${this.left}px;`
    );

    this.content.setAttributeForElement(
      "bgRight",
      "style",
      `top:${this.top}px;height:${this.height}px;left:${this.right}px;width:calc(100% - ${this.right}px);`
    );
  }

  /**
   * Update the box coordinates from the rect
   * @param rect The hover element box
   * @param scrollX The x offset the page is scrolled
   * @param scrollY The y offset the page is scrolled
   */
  updateBoxFromRect(rect, scrollX, scrollY) {
    this.top = rect.top + scrollY;
    this.left = rect.left + scrollX;
    this.right = rect.right + scrollX;
    this.bottom = rect.bottom + scrollY;
  }

  /**
   * Hide the selected region
   */
  hide() {
    this.content.setAttributeForElement("highlight", "style", "display:none;");
    this.content.setAttributeForElement("bgTop", "style", "display:none;");
    this.content.setAttributeForElement("bgBottom", "style", "display:none;");
    this.content.setAttributeForElement("bgLeft", "style", "display:none;");
    this.content.setAttributeForElement("bgRight", "style", "display:none;");
  }

  /**
   * The box should never appear outside the document so the SelectionBox will
   * be shifted if the bounds of the box are outside the documents width or height
   */
  shiftBox() {
    let didShift = false;
    let xDiff = this.right - this.#selectionLayer.scrollWidth;
    if (xDiff > 0) {
      this.right -= xDiff;
      this.left -= xDiff;

      didShift = true;
    }

    let yDiff = this.bottom - this.#selectionLayer.scrollHeight;
    if (yDiff > 0) {
      let curHeight = this.height;

      this.bottom -= yDiff;
      this.top = this.bottom - curHeight;

      didShift = true;
    }

    if (didShift) {
      this.show();
      this.#selectionLayer.drawButtonsLayer();
    }
  }

  /**
   * Sort the coordinates so x1 < x2 and y1 < y2
   */
  sortCoords() {
    if (this.#x1 > this.#x2) {
      [this.#x1, this.#x2] = [this.#x2, this.#x1];
    }
    if (this.#y1 > this.#y2) {
      [this.#y1, this.#y2] = [this.#y2, this.#y1];
    }
  }

  /**
   * Gets the dimensions of the currently selected region
   * @returns {Object}
   *  {
   *    x1: the left dimension value
   *    y1: the top dimension value
   *    width: the width of the selected region
   *    height: the height of the selected region
   *  }
   */
  getDimensions() {
    return {
      x1: this.left,
      y1: this.top,
      width: this.width,
      height: this.height,
    };
  }

  get distance() {
    return Math.sqrt(Math.pow(this.width, 2) + Math.pow(this.height, 2));
  }

  get xOffset() {
    return this.#xOffset;
  }
  set xOffset(val) {
    this.#xOffset = val;
  }

  get yOffset() {
    return this.#yOffset;
  }
  set yOffset(val) {
    this.#yOffset = val;
  }

  get top() {
    return Math.min(this.#y1, this.#y2);
  }
  set top(val) {
    this.#y1 = val > 0 ? val : 0;
  }

  get left() {
    return Math.min(this.#x1, this.#x2);
  }
  set left(val) {
    this.#x1 = val > 0 ? val : 0;
  }

  get right() {
    return Math.max(this.#x1, this.#x2);
  }
  set right(val) {
    this.#x2 =
      val > this.#selectionLayer.scrollWidth
        ? this.#selectionLayer.scrollWidth
        : val;
  }

  get bottom() {
    return Math.max(this.#y1, this.#y2);
  }
  set bottom(val) {
    this.#y2 =
      val > this.#selectionLayer.scrollHeight
        ? this.#selectionLayer.scrollHeight
        : val;
  }

  get width() {
    return Math.abs(this.#x2 - this.#x1);
  }
  get height() {
    return Math.abs(this.#y2 - this.#y1);
  }
}

class ButtonsLayer extends AnonLayer {
  #selectionLayer;

  constructor(id, content, selectionLayer) {
    super(id, content);

    this.#selectionLayer = selectionLayer;
  }

  /**
   * Draw the buttons. Check if the box is too near the bottom or left of the
   * viewport and adjust the buttons accordingly
   */
  show() {
    let {
      boxLeft,
      boxTop,
      boxRight,
      boxBottom,
      scrollX,
      scrollY,
      clientWidth,
      clientHeight,
    } = this.#selectionLayer.getDimensions();

    if (
      boxTop > scrollY + clientHeight ||
      boxBottom < scrollY ||
      boxLeft > scrollX + clientWidth ||
      boxRight < scrollX
    ) {
      // The box is offscreen so need to draw the buttons
      return;
    }

    let top = boxBottom;
    let leftOrRight = `right:calc(100% - ${boxRight}px);`;

    if (scrollY + clientHeight - boxBottom < 70) {
      if (boxBottom < scrollY + clientHeight) {
        top = boxBottom - 60;
      } else if (scrollY + clientHeight - boxTop < 70) {
        top = boxTop - 60;
      } else {
        top = scrollY + clientHeight - 60;
      }
    }
    if (boxRight < 300) {
      leftOrRight = `left:${boxLeft}px;`;
    }

    this.content.setAttributeForElement(
      "buttons",
      "style",
      `top:${top}px;${leftOrRight}`
    );
  }
}

class PreviewLayer extends AnonLayer {
  constructor(id, content) {
    super(id, content);
  }

  /**
   * Draw the eyeballs facing the mouse
   * @param clientX x pointer position
   * @param clientY y pointer position
   * @param width width of the viewport
   * @param height height of the viewport
   */
  drawEyes(clientX, clientY, width, height) {
    const xpos = Math.floor((10 * (clientX - width / 2)) / width);
    const ypos = Math.floor((10 * (clientY - height / 2)) / height);
    const move = `transform:translate(${xpos}px, ${ypos}px);`;
    this.content.setAttributeForElement("left-eye", "style", move);
    this.content.setAttributeForElement("right-eye", "style", move);
  }
}

class ScreenshotsContainerLayer extends AnonLayer {
  #width;
  #height;
  #previewLayer;
  #selectionLayer;

  constructor(id, content, previewLayer, selectionLayer) {
    super(id, content);

    this.#previewLayer = previewLayer;
    this.#selectionLayer = selectionLayer;
  }

  /**
   * Hide the SelectionLayer
   */
  hideSelectionLayer() {
    this.#selectionLayer.hide();
  }

  /**
   * Show the PreviewLayer
   */
  showPreviewLayer() {
    this.#previewLayer.show();
  }

  /**
   * Hide the PreviewLayer
   */
  hidePreviewLayer() {
    this.#previewLayer.hide();
    this.#selectionLayer.hideHoverElementSelection();
  }

  /**
   * Show the ButtonsLayer
   */
  drawButtonsLayer() {
    this.#selectionLayer.drawButtonsLayer();
  }

  /**
   * Hide the ButtonsLayer
   */
  hideButtonsLayer() {
    this.#selectionLayer.hideButtons();
  }

  /**
   * Show the SelectionBox
   */
  drawSelectionBox() {
    this.#selectionLayer.drawSelectionBox();
  }

  hideHoverElementBox() {
    this.#selectionLayer.hideHoverElementSelection();
  }

  /**
   * Update the box coordinates from the hover element rect
   */
  updateSelectionBoxFromRect(scrollX, scrollY) {
    this.#selectionLayer.updateSelectionBoxFromRect(scrollX, scrollY);
  }

  /**
   * Handles when the user moves the mouse over an element
   * @param clientX The x coordinate in the visible window
   * @param clientY The y coordinate in the visible window
   * @param targetId The target element id
   */
  handleElementHover(clientX, clientY, targetId) {
    this.#selectionLayer.handleElementHover(clientX, clientY, targetId);
  }

  /**
   * Handles moving the rect when the user has scrolled but not moved the mouse
   * It uses the last x and y coordinates to find the new element at the mouse position
   */
  handleElementScroll() {
    this.#selectionLayer.handleElementScroll();
  }

  /**
   * Draw the eyes in the PreviewLayer
   * @param clientX The x mouse position
   * @param clientY The y mouse position
   */
  drawPreviewEyes(clientX, clientY) {
    this.#previewLayer.drawEyes(
      clientX,
      clientY,
      this.#selectionLayer.clientWidth,
      this.#selectionLayer.clientHeight
    );
  }

  /**
   * Get the diagonal distance of the SelectionBox
   * @returns The diagonal distance of the currently selected region
   */
  selectionBoxDistance() {
    return this.#selectionLayer.getSelectionBoxDistance();
  }

  /**
   * Sort the coordinates of the SelectionBox
   */
  sortSelectionLayerBoxCoords() {
    this.#selectionLayer.sortSelectionBoxCoords();
  }

  /**
   * Get the SelectionLayer dimensions
   * @returns {Object}
   *  {
   *    x1: the left dimension value
   *    y1: the top dimension value
   *    width: the width of the selected region
   *    height: the height of the selected region
   *  }
   */
  getSelectionLayerBoxDimensions() {
    return this.#selectionLayer.getSelectionBoxDimensions();
  }

  /**
   * Gets the SelectionBox and page dimensions
   * @returns {Object}
   *  {
   *    boxLeft: the left position of the box
   *    boxTop: the top position of the box
   *    boxRight: the right position of the box
   *    boxBottom: the bottom position of the box
   *    scrollWidth: the total document width
   *    scrollHeight: the total document height
   *    scrollX: the x scrolled offset
   *    scrollY: the y scrolled offset
   *    clientWidth: the viewport width
   *    clientHeight: the viewport height
   *  }
   */
  getSelectionLayerDimensions() {
    return this.#selectionLayer.getDimensions();
  }

  /**
   * Shift the SelectionBox
   */
  shiftSelectionLayerBox() {
    this.#selectionLayer.shiftSelectionBox();
  }

  /**
   * Set the respective dimensions of the SelectionBox
   * @param {Object} boxDimensionObject The new box dimensions
   *  {
   *    left: new left dimension value or undefined
   *    top: new top dimension value or undefined
   *    right: new right dimension value or undefined
   *    bottom: new bottom dimension value or undefined
   *   }
   */
  setSelectionBoxDimensions(boxDimensionObject) {
    this.#selectionLayer.setSelectionBoxDimensions(boxDimensionObject);
  }

  /**
   * Returns the window's dimensions for the `window` given.
   *
   * @return {Object} An object containing window dimensions
   *   {
   *     clientWidth: The width of the viewport
   *     clientHeight: The height of the viewport
   *     width: The width of the enitre page
   *     height: The height of the entire page
   *     scrollX: The X scroll offset of the viewport
   *     scrollY: The Y scroll offest of the viewport
   *   }
   */
  getDimensionsFromWindow(window) {
    let {
      innerHeight,
      innerWidth,
      scrollMaxY,
      scrollMaxX,
      scrollMinY,
      scrollMinX,
      scrollY,
      scrollX,
    } = window;

    let width = innerWidth + scrollMaxX - scrollMinX;
    let height = innerHeight + scrollMaxY - scrollMinY;
    let clientHeight = innerHeight;
    let clientWidth = innerWidth;

    const scrollbarHeight = {};
    const scrollbarWidth = {};
    window.windowUtils.getScrollbarSize(false, scrollbarWidth, scrollbarHeight);
    width -= scrollbarWidth.value;
    height -= scrollbarHeight.value;
    clientWidth -= scrollbarWidth.value;
    clientHeight -= scrollbarHeight.value;

    return { clientWidth, clientHeight, width, height, scrollX, scrollY };
  }

  /**
   * The screenshots-overlay-container doesn't shrink with the window when the
   * window is resized so we have to manually find the width and height of the
   * window by looping throught the documentElement's children
   * If the children mysteriously have a height or width of 0 then we will
   * fallback to the scrollWidth and scrollHeight which can cause the container
   * to be larger than the window dimensions
   * @param win The window object
   */
  updateSize(win) {
    let { clientWidth, clientHeight, width, height, scrollX, scrollY } =
      this.getDimensionsFromWindow(win);

    let shouldDraw = true;

    if (
      clientHeight < this.#selectionLayer.clientHeight ||
      clientWidth < this.#selectionLayer.clientWidth
    ) {
      let widthDiff = this.#selectionLayer.clientWidth - clientWidth;
      let heightDiff = this.#selectionLayer.clientHeight - clientHeight;

      this.#width -= widthDiff;
      this.#height -= heightDiff;

      this.drawScreenshotsContainer();
      // We just updated the screenshots container so we check if the window
      // dimensions are still accurate
      let { width: updatedWidth, height: updatedHeight } =
        this.getDimensionsFromWindow(win);

      // If the width and height are the same then we don't need to draw the overlay again
      if (updatedWidth === width && updatedHeight === height) {
        shouldDraw = false;
      }

      width = updatedWidth;
      height = updatedHeight;
    }

    this.#selectionLayer.clientWidth = clientWidth;
    this.#selectionLayer.clientHeight = clientHeight;
    this.#selectionLayer.scrollX = scrollX;
    this.#selectionLayer.scrollY = scrollY;

    this.#selectionLayer.scrollWidth = width;
    this.#selectionLayer.scrollHeight = height;

    this.#width = width;
    this.#height = height;

    if (shouldDraw) {
      this.drawScreenshotsContainer();
    }
  }

  /**
   * Return the dimensions of the screenshots container
   * @returns {Object}
   *  width: the container width
   *  height: the container height
   */
  getDimension() {
    return { width: this.#width, height: this.#height };
  }

  /**
   * Draw the screenshots container
   */
  drawScreenshotsContainer() {
    this.content.setAttributeForElement(
      this.id,
      "style",
      `top:0;left:0;width:${this.#width}px;height:${this.#height}px;`
    );
  }

  get hoverElementBoxRect() {
    return this.#selectionLayer.hoverElementBoxRect;
  }
}