summaryrefslogtreecommitdiffstats
path: root/devtools/client/inspector/shared/highlighters-overlay.js
blob: 6082b8b8426b8bc8db1e22073cad9813f463a1e8 (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
/* 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/. */

"use strict";

const {
  safeAsyncMethod,
} = require("resource://devtools/shared/async-utils.js");
const EventEmitter = require("resource://devtools/shared/event-emitter.js");
const WalkerEventListener = require("resource://devtools/client/inspector/shared/walker-event-listener.js");
const {
  VIEW_NODE_VALUE_TYPE,
  VIEW_NODE_SHAPE_POINT_TYPE,
} = require("resource://devtools/client/inspector/shared/node-types.js");

loader.lazyRequireGetter(
  this,
  "parseURL",
  "resource://devtools/client/shared/source-utils.js",
  true
);
loader.lazyRequireGetter(
  this,
  "asyncStorage",
  "resource://devtools/shared/async-storage.js"
);
loader.lazyRequireGetter(
  this,
  "gridsReducer",
  "resource://devtools/client/inspector/grids/reducers/grids.js"
);
loader.lazyRequireGetter(
  this,
  "highlighterSettingsReducer",
  "resource://devtools/client/inspector/grids/reducers/highlighter-settings.js"
);
loader.lazyRequireGetter(
  this,
  "flexboxReducer",
  "resource://devtools/client/inspector/flexbox/reducers/flexbox.js"
);
loader.lazyRequireGetter(
  this,
  "deepEqual",
  "resource://devtools/shared/DevToolsUtils.js",
  true
);
loader.lazyGetter(this, "HighlightersBundle", () => {
  return new Localization(["devtools/shared/highlighters.ftl"], true);
});

const DEFAULT_HIGHLIGHTER_COLOR = "#9400FF";
const SUBGRID_PARENT_ALPHA = 0.5;

const TYPES = {
  BOXMODEL: "BoxModelHighlighter",
  FLEXBOX: "FlexboxHighlighter",
  GEOMETRY: "GeometryEditorHighlighter",
  GRID: "CssGridHighlighter",
  SHAPES: "ShapesHighlighter",
  SELECTOR: "SelectorHighlighter",
  TRANSFORM: "CssTransformHighlighter",
};

/**
 * While refactoring to an abstracted way to show and hide highlighters,
 * we did not update all tests and code paths which listen for exact events.
 *
 * When we show or hide highlighters we reference this mapping to
 * emit events that consumers may be listening to.
 *
 * This list should go away as we incrementally rewrite tests to use
 * abstract event names with data payloads indicating the highlighter.
 *
 * DO NOT OPTIMIZE THIS MAPPING AS CONCATENATED SUBSTRINGS!
 * It makes it difficult to do project-wide searches for exact matches.
 */
const HIGHLIGHTER_EVENTS = {
  [TYPES.GRID]: {
    shown: "grid-highlighter-shown",
    hidden: "grid-highlighter-hidden",
  },
  [TYPES.GEOMETRY]: {
    shown: "geometry-editor-highlighter-shown",
    hidden: "geometry-editor-highlighter-hidden",
  },
  [TYPES.SHAPES]: {
    shown: "shapes-highlighter-shown",
    hidden: "shapes-highlighter-hidden",
  },
  [TYPES.TRANSFORM]: {
    shown: "css-transform-highlighter-shown",
    hidden: "css-transform-highlighter-hidden",
  },
};

// Tool IDs mapped by highlighter type. Used to log telemetry for opening & closing tools.
const TELEMETRY_TOOL_IDS = {
  [TYPES.FLEXBOX]: "FLEXBOX_HIGHLIGHTER",
  [TYPES.GRID]: "GRID_HIGHLIGHTER",
};

// Scalars mapped by highlighter type. Used to log telemetry about highlighter triggers.
const TELEMETRY_SCALARS = {
  [TYPES.FLEXBOX]: {
    layout: "devtools.layout.flexboxhighlighter.opened",
    markup: "devtools.markup.flexboxhighlighter.opened",
    rule: "devtools.rules.flexboxhighlighter.opened",
  },

  [TYPES.GRID]: {
    grid: "devtools.grid.gridinspector.opened",
    markup: "devtools.markup.gridinspector.opened",
    rule: "devtools.rules.gridinspector.opened",
  },
};

/**
 * HighlightersOverlay manages the visibility of highlighters in the Inspector.
 */
class HighlightersOverlay {
  /**
   * @param  {Inspector} inspector
   *         Inspector toolbox panel.
   */
  constructor(inspector) {
    this.inspector = inspector;
    this.store = this.inspector.store;

    this.telemetry = this.inspector.telemetry;
    this.maxGridHighlighters = Services.prefs.getIntPref(
      "devtools.gridinspector.maxHighlighters"
    );

    // Map of active highlighter types to objects with the highlighted nodeFront and the
    // highlighter instance. Ex: "BoxModelHighlighter" => { nodeFront, highlighter }
    // It will fully replace this.highlighters when all highlighter consumers are updated
    // to use it as the single source of truth for which highlighters are visible.
    this._activeHighlighters = new Map();
    // Map of highlighter types to symbols. Showing highlighters is an async operation,
    // until it doesn't complete, this map will be populated with the requested type and
    // a unique symbol identifying that request. Once completed, the entry is removed.
    this._pendingHighlighters = new Map();
    // Map of highlighter types to objects with metadata used to restore active
    // highlighters after a page reload.
    this._restorableHighlighters = new Map();
    // Collection of instantiated highlighter actors like FlexboxHighlighter,
    // ShapesHighlighter and GeometryEditorHighlighter.
    this.highlighters = {};
    // Map of grid container node to an object with the grid highlighter instance
    // and, if the node is a subgrid, the parent grid node and parent grid highlighter.
    // Ex: {NodeFront} => {
    //  highlighter: {CustomHighlighterFront},
    //  parentGridNode: {NodeFront|null},
    //  parentGridHighlighter: {CustomHighlighterFront|null}
    // }
    this.gridHighlighters = new Map();
    // Collection of instantiated in-context editors, like ShapesInContextEditor, which
    // behave like highlighters but with added editing capabilities that need to map value
    // changes to properties in the Rule view.
    this.editors = {};

    // Highlighter state.
    this.state = {
      // Map of grid container NodeFront to the their stored grid options
      // Used to restore grid highlighters on reload (should be migrated to
      // _restorableHighlighters in Bug 1572652).
      grids: new Map(),
      // Shape Path Editor highlighter options.
      // Used as a cache for the latest configuration when showing the highlighter.
      // It is reused and augmented when hovering coordinates in the Rules view which
      // mark the corresponding points in the highlighter overlay.
      shapes: {},
    };

    // NodeFront of element that is highlighted by the geometry editor.
    this.geometryEditorHighlighterShown = null;
    // Name of the highlighter shown on mouse hover.
    this.hoveredHighlighterShown = null;
    // NodeFront of the shape that is highlighted
    this.shapesHighlighterShown = null;

    this.onClick = this.onClick.bind(this);
    this.onDisplayChange = this.onDisplayChange.bind(this);
    this.onMarkupMutation = this.onMarkupMutation.bind(this);
    this._onResourceAvailable = this._onResourceAvailable.bind(this);

    this.onMouseMove = this.onMouseMove.bind(this);
    this.onMouseOut = this.onMouseOut.bind(this);
    this.hideAllHighlighters = this.hideAllHighlighters.bind(this);
    this.hideFlexboxHighlighter = this.hideFlexboxHighlighter.bind(this);
    this.hideGridHighlighter = this.hideGridHighlighter.bind(this);
    this.hideShapesHighlighter = this.hideShapesHighlighter.bind(this);
    this.showFlexboxHighlighter = this.showFlexboxHighlighter.bind(this);
    this.showGridHighlighter = this.showGridHighlighter.bind(this);
    this.showShapesHighlighter = this.showShapesHighlighter.bind(this);
    this._handleRejection = this._handleRejection.bind(this);
    this.onShapesHighlighterShown = this.onShapesHighlighterShown.bind(this);
    this.onShapesHighlighterHidden = this.onShapesHighlighterHidden.bind(this);

    // Catch unexpected errors from async functions if the manager has been destroyed.
    this.hideHighlighterType = safeAsyncMethod(
      this.hideHighlighterType.bind(this),
      () => this.destroyed
    );
    this.showHighlighterTypeForNode = safeAsyncMethod(
      this.showHighlighterTypeForNode.bind(this),
      () => this.destroyed
    );
    this.showGridHighlighter = safeAsyncMethod(
      this.showGridHighlighter.bind(this),
      () => this.destroyed
    );
    this.restoreState = safeAsyncMethod(
      this.restoreState.bind(this),
      () => this.destroyed
    );

    // Add inspector events, not specific to a given view.
    this.inspector.on("markupmutation", this.onMarkupMutation);

    this.resourceCommand = this.inspector.toolbox.resourceCommand;
    this.resourceCommand.watchResources(
      [this.resourceCommand.TYPES.ROOT_NODE],
      { onAvailable: this._onResourceAvailable }
    );

    this.walkerEventListener = new WalkerEventListener(this.inspector, {
      "display-change": this.onDisplayChange,
    });

    if (this.toolbox.win.matchMedia("(prefers-reduced-motion)").matches) {
      this._showSimpleHighlightersMessage();
    }

    EventEmitter.decorate(this);
  }

  get inspectorFront() {
    return this.inspector.inspectorFront;
  }

  get target() {
    return this.inspector.currentTarget;
  }

  get toolbox() {
    return this.inspector.toolbox;
  }

  // FIXME: Shim for HighlightersOverlay.parentGridHighlighters
  // Remove after updating tests to stop accessing this map directly. Bug 1683153
  get parentGridHighlighters() {
    return Array.from(this.gridHighlighters.values()).reduce((map, value) => {
      const { parentGridNode, parentGridHighlighter } = value;
      if (parentGridNode) {
        map.set(parentGridNode, parentGridHighlighter);
      }

      return map;
    }, new Map());
  }

  /**
   * Optionally run some operations right after showing a highlighter of a given type,
   * but before notifying consumers by emitting the "highlighter-shown" event.
   *
   * This is a chance to run some non-essential operations like: logging telemetry data,
   * storing metadata about the highlighter to enable restoring it after refresh, etc.
   *
   * @param  {String} type
   *          Highlighter type shown.
   * @param  {NodeFront} nodeFront
   *          Node front of the element that was highlighted.
   * @param  {Options} options
   *          Optional object with options passed to the highlighter.
   */
  _afterShowHighlighterTypeForNode(type, nodeFront, options) {
    switch (type) {
      // Log telemetry for showing the flexbox and grid highlighters.
      case TYPES.FLEXBOX:
      case TYPES.GRID:
        const toolID = TELEMETRY_TOOL_IDS[type];
        if (toolID) {
          this.telemetry.toolOpened(toolID, this);
        }

        const scalar = TELEMETRY_SCALARS[type]?.[options?.trigger];
        if (scalar) {
          this.telemetry.scalarAdd(scalar, 1);
        }

        break;
    }

    // Set metadata necessary to restore the active highlighter upon page refresh.
    if (type === TYPES.FLEXBOX) {
      const { url } = this.target;
      const selectors = [...this.inspector.selectionCssSelectors];

      this._restorableHighlighters.set(type, {
        options,
        selectors,
        type,
        url,
      });
    }
  }

  /**
   * Optionally run some operations before showing a highlighter of a given type.
   *
   * Depending its type, before showing a new instance of a highlighter, we may do extra
   * operations, like hiding another visible highlighter, or preventing the show
   * operation, for example due to a duplicate call with the same arguments.
   *
   * Returns a promise that resovles with a boolean indicating whether to skip showing
   * the highlighter with these arguments.
   *
   * @param  {String} type
   *          Highlighter type to show.
   * @param  {NodeFront} nodeFront
   *          Node front of the element to be highlighted.
   * @param  {Options} options
   *          Optional object with options to pass to the highlighter.
   * @return {Promise}
   */
  async _beforeShowHighlighterTypeForNode(type, nodeFront, options) {
    // Get the data associated with the visible highlighter of this type, if any.
    const {
      highlighter: activeHighlighter,
      nodeFront: activeNodeFront,
      options: activeOptions,
      timer: activeTimer,
    } = this.getDataForActiveHighlighter(type);

    // There isn't an active highlighter of this type. Early return, proceed with showing.
    if (!activeHighlighter) {
      return false;
    }

    // Whether conditions are met to skip showing the highlighter (ex: duplicate calls).
    let skipShow = false;

    // Clear any autohide timer associated with this highlighter type.
    // This clears any existing timer for duplicate calls to show() if:
    // - called with different options.duration
    // - called once with options.duration, then without (see deepEqual() above)
    clearTimeout(activeTimer);

    switch (type) {
      // Hide the visible selector highlighter if called for the same node,
      // but with a different selector.
      case TYPES.SELECTOR:
        if (
          nodeFront === activeNodeFront &&
          options?.selector !== activeOptions?.selector
        ) {
          await this.hideHighlighterType(TYPES.SELECTOR);
        }
        break;

      // For others, hide the existing highlighter before showing it for a different node.
      // Else, if the node is the same and options are the same, skip a duplicate call.
      // Duplicate calls to show the highlighter for the same node are allowed
      // if the options are different (for example, when scheduling autohide).
      default:
        if (nodeFront !== activeNodeFront) {
          await this.hideHighlighterType(type);
        } else if (deepEqual(options, activeOptions)) {
          skipShow = true;
        }
    }

    return skipShow;
  }

  /**
   * Optionally run some operations before hiding a highlighter of a given type.
   * Runs only if a highlighter of that type exists.
   *
   * @param {String} type
   *         highlighter type
   * @return {Promise}
   */
  _beforeHideHighlighterType(type) {
    switch (type) {
      // Log telemetry for hiding the flexbox and grid highlighters.
      case TYPES.FLEXBOX:
      case TYPES.GRID:
        const toolID = TELEMETRY_TOOL_IDS[type];
        const conditions = {
          [TYPES.FLEXBOX]: () => {
            // always stop the timer when the flexbox highlighter is about to be hidden.
            return true;
          },
          [TYPES.GRID]: () => {
            // stop the timer only once the last grid highlighter is about to be hidden.
            return this.gridHighlighters.size === 1;
          },
        };

        if (toolID && conditions[type].call(this)) {
          this.telemetry.toolClosed(toolID, this);
        }

        break;
    }
  }

  /**
   * Get the maximum number of possible active highlighter instances of a given type.
   *
   * @param  {String} type
   *         Highlighter type
   * @return {Number}
   *         Default 1
   */
  _getMaxActiveHighlighters(type) {
    let max;

    switch (type) {
      // Grid highligthters are special (there is a parent-child relationship between
      // subgrid and parent grid) so we suppport multiple visible instances.
      // Grid highlighters are performance-intensive and this limit is somewhat arbitrary
      // to guard against performance degradation.
      case TYPES.GRID:
        max = this.maxGridHighlighters;
        break;
      // By default, for all other highlighter types, only one instance may visible.
      // Before showing a new highlighter, any other instance will be hidden.
      default:
        max = 1;
    }

    return max;
  }

  /**
   * Get a highlighter instance of the given type for the given node front.
   *
   * @param  {String} type
   *         Highlighter type.
   * @param  {NodeFront} nodeFront
   *         Node front of the element to be highlighted with the requested highlighter.
   * @return {Promise}
   *         Promise which resolves with a highlighter instance
   */
  async _getHighlighterTypeForNode(type, nodeFront) {
    const { inspectorFront } = nodeFront;
    const max = this._getMaxActiveHighlighters(type);
    let highlighter;

    // If only one highlighter instance may be visible, get a highlighter front
    // and cache it to return it on future requests.
    // Otherwise, return a new highlighter front every time and clean-up manually.
    if (max === 1) {
      highlighter = await inspectorFront.getOrCreateHighlighterByType(type);
    } else {
      highlighter = await inspectorFront.getHighlighterByType(type);
    }

    return highlighter;
  }

  /**
   * Get the currently active highlighter of a given type.
   *
   * @param  {String} type
   *         Highlighter type.
   * @return {Highlighter|null}
   *         Highlighter instance
   *         or null if no highlighter of that type is active.
   */
  getActiveHighlighter(type) {
    if (!this._activeHighlighters.has(type)) {
      return null;
    }

    const { highlighter } = this._activeHighlighters.get(type);
    return highlighter;
  }

  /**
   * Get an object with data associated with the active highlighter of a given type.
   * This data object contains:
   *   - nodeFront: NodeFront of the highlighted node
   *   - highlighter: Highlighter instance
   *   - options: Configuration options passed to the highlighter
   *   - timer: (Optional) index of timer set with setTimout() to autohide the highlighter
   * Returns an empty object if a highlighter of the given type is not active.
   *
   * @param  {String} type
   *         Highlighter type.
   * @return {Object}
   */
  getDataForActiveHighlighter(type) {
    if (!this._activeHighlighters.has(type)) {
      return {};
    }

    return this._activeHighlighters.get(type);
  }

  /**
   * Get the configuration options of the active highlighter of a given type.
   *
   * @param  {String} type
   *         Highlighter type.
   * @return {Object}
   */
  getOptionsForActiveHighlighter(type) {
    const { options } = this.getDataForActiveHighlighter(type);
    return options;
  }

  /**
   * Get the node front highlighted by a given highlighter type.
   *
   * @param  {String} type
   *         Highlighter type.
   * @return {NodeFront|null}
   *         Node front of the element currently being highlighted
   *         or null if no highlighter of that type is active.
   */
  getNodeForActiveHighlighter(type) {
    if (!this._activeHighlighters.has(type)) {
      return null;
    }

    const { nodeFront } = this._activeHighlighters.get(type);
    return nodeFront;
  }

  /**
   * Highlight a given node front with a given type of highlighter.
   *
   * Highlighters are shown for one node at a time. Before showing the same highlighter
   * type on another node, it will first be hidden from the previously highlighted node.
   * In pages with frames running in different processes, this ensures highlighters from
   * other frames do not stay visible.
   *
   * @param  {String} type
   *          Highlighter type to show.
   * @param  {NodeFront} nodeFront
   *          Node front of the element to be highlighted.
   * @param  {Options} options
   *         Optional object with options to pass to the highlighter.
   * @return {Promise}
   */
  async showHighlighterTypeForNode(type, nodeFront, options) {
    const promise = this._beforeShowHighlighterTypeForNode(
      type,
      nodeFront,
      options
    );

    // Set a pending highlighter in order to detect if, while we were awaiting, there was
    // a more recent request to highlight a node with the same type, or a request to hide
    // the highlighter. Then we will abort this one in favor of the newer one.
    // This needs to be done before the 'await' in order to be synchronous, but after
    // calling _beforeShowHighlighterTypeForNode, since it can call hideHighlighterType.
    const id = Symbol();
    this._pendingHighlighters.set(type, id);
    const skipShow = await promise;

    if (this._pendingHighlighters.get(type) !== id) {
      return;
    } else if (skipShow || nodeFront.isDestroyed()) {
      this._pendingHighlighters.delete(type);
      return;
    }

    const highlighter = await this._getHighlighterTypeForNode(type, nodeFront);

    if (this._pendingHighlighters.get(type) !== id) {
      return;
    }
    this._pendingHighlighters.delete(type);

    // Set a timer to automatically hide the highlighter if a duration is provided.
    const timer = this.scheduleAutoHideHighlighterType(type, options?.duration);
    // TODO: support case for multiple highlighter instances (ex: multiple grids)
    this._activeHighlighters.set(type, {
      nodeFront,
      highlighter,
      options,
      timer,
    });
    await highlighter.show(nodeFront, options);
    this._afterShowHighlighterTypeForNode(type, nodeFront, options);

    // Emit any type-specific highlighter shown event for tests
    // which have not yet been updated to listen for the generic event
    if (HIGHLIGHTER_EVENTS[type]?.shown) {
      this.emit(HIGHLIGHTER_EVENTS[type].shown, nodeFront, options);
    }
    this.emit("highlighter-shown", { type, highlighter, nodeFront, options });
  }

  /**
   * Set a timer to automatically hide all highlighters of a given type after a delay.
   *
   * @param  {String} type
   *         Highlighter type to hide.
   * @param  {Number|undefined} duration
   *         Delay in milliseconds after which to hide the highlighter.
   *         If a duration is not provided, return early without scheduling a task.
   * @return {Number|undefined}
   *         Index of the scheduled task returned by setTimeout().
   */
  scheduleAutoHideHighlighterType(type, duration) {
    if (!duration) {
      return undefined;
    }

    const timer = setTimeout(async () => {
      await this.hideHighlighterType(type);
      clearTimeout(timer);
    }, duration);

    return timer;
  }

  /**
   * Hide all instances of a given highlighter type.
   *
   * @param  {String} type
   *         Highlighter type to hide.
   * @return {Promise}
   */
  async hideHighlighterType(type) {
    if (this._pendingHighlighters.has(type)) {
      // Abort pending highlighters for the given type.
      this._pendingHighlighters.delete(type);
    }
    if (!this._activeHighlighters.has(type)) {
      return;
    }

    const data = this.getDataForActiveHighlighter(type);
    const { highlighter, nodeFront, timer } = data;
    // Clear any autohide timer associated with this highlighter type.
    clearTimeout(timer);
    // Remove any metadata used to restore this highlighter type on page refresh.
    this._restorableHighlighters.delete(type);
    this._activeHighlighters.delete(type);
    this._beforeHideHighlighterType(type);
    await highlighter.hide();

    // Emit any type-specific highlighter hidden event for tests
    // which have not yet been updated to listen for the generic event
    if (HIGHLIGHTER_EVENTS[type]?.hidden) {
      this.emit(HIGHLIGHTER_EVENTS[type].hidden, nodeFront);
    }
    this.emit("highlighter-hidden", { type, ...data });
  }

  /**
   * Returns true if the grid highlighter can be toggled on/off for the given node, and
   * false otherwise. A grid container can be toggled on if the max grid highlighters
   * is only 1 or less than the maximum grid highlighters that can be displayed or if
   * the grid highlighter already highlights the given node.
   *
   * @param  {NodeFront} node
   *         Grid container NodeFront.
   * @return {Boolean}
   */
  canGridHighlighterToggle(node) {
    return (
      this.maxGridHighlighters === 1 ||
      this.gridHighlighters.size < this.maxGridHighlighters ||
      this.gridHighlighters.has(node)
    );
  }

  /**
   * Returns true when the maximum number of grid highlighter instances is reached.
   * FIXME: Bug 1572652 should address this constraint.
   *
   * @return {Boolean}
   */
  isGridHighlighterLimitReached() {
    return this.gridHighlighters.size === this.maxGridHighlighters;
  }

  /**
   * Returns whether `node` is somewhere inside the DOM of the rule view.
   *
   * @param {DOMNode} node
   * @return {Boolean}
   */
  isRuleView(node) {
    return !!node.closest("#ruleview-panel");
  }

  /**
   * Add the highlighters overlay to the view. This will start tracking mouse events
   * and display highlighters when needed.
   *
   * @param  {CssRuleView|CssComputedView|LayoutView} view
   *         Either the rule-view or computed-view panel to add the highlighters overlay.
   */
  addToView(view) {
    const el = view.element;
    el.addEventListener("click", this.onClick, true);
    el.addEventListener("mousemove", this.onMouseMove);
    el.addEventListener("mouseout", this.onMouseOut);
    el.ownerDocument.defaultView.addEventListener("mouseout", this.onMouseOut);
  }

  /**
   * Remove the overlay from the given view. This will stop tracking mouse movement and
   * showing highlighters.
   *
   * @param  {CssRuleView|CssComputedView|LayoutView} view
   *         Either the rule-view or computed-view panel to remove the highlighters
   *         overlay.
   */
  removeFromView(view) {
    const el = view.element;
    el.removeEventListener("click", this.onClick, true);
    el.removeEventListener("mousemove", this.onMouseMove);
    el.removeEventListener("mouseout", this.onMouseOut);
  }

  /**
   * Toggle the shapes highlighter for the given node.
   *
   * @param  {NodeFront} node
   *         The NodeFront of the element with a shape to highlight.
   * @param  {Object} options
   *         Object used for passing options to the shapes highlighter.
   * @param {TextProperty} textProperty
   *        TextProperty where to write changes.
   */
  async toggleShapesHighlighter(node, options, textProperty) {
    const shapesEditor = await this.getInContextEditor(node, "shapesEditor");
    if (!shapesEditor) {
      return;
    }
    shapesEditor.toggle(node, options, textProperty);
  }

  /**
   * Show the shapes highlighter for the given node.
   * This method delegates to the in-context shapes editor.
   *
   * @param  {NodeFront} node
   *         The NodeFront of the element with a shape to highlight.
   * @param  {Object} options
   *         Object used for passing options to the shapes highlighter.
   */
  async showShapesHighlighter(node, options) {
    const shapesEditor = await this.getInContextEditor(node, "shapesEditor");
    if (!shapesEditor) {
      return;
    }
    shapesEditor.show(node, options);
  }

  /**
   * Called after the shape highlighter was shown.
   *
   * @param  {Object} data
   *         Data associated with the event.
   *         Contains:
   *         - {NodeFront} node: The NodeFront of the element that is highlighted.
   *         - {Object} options: Options that were passed to ShapesHighlighter.show()
   */
  onShapesHighlighterShown(data) {
    const { node, options } = data;
    this.shapesHighlighterShown = node;
    this.state.shapes.options = options;
    this.emit("shapes-highlighter-shown", node, options);
  }

  /**
   * Hide the shapes highlighter if visible.
   * This method delegates the to the in-context shapes editor which wraps
   * the shapes highlighter with additional functionality.
   *
   * @param  {NodeFront} node.
   */
  async hideShapesHighlighter(node) {
    const shapesEditor = await this.getInContextEditor(node, "shapesEditor");
    if (!shapesEditor) {
      return;
    }
    shapesEditor.hide();
  }

  /**
   * Called after the shapes highlighter was hidden.
   *
   * @param  {Object} data
   *         Data associated with the event.
   *         Contains:
   *         - {NodeFront} node: The NodeFront of the element that was highlighted.
   */
  onShapesHighlighterHidden(data) {
    this.emit(
      "shapes-highlighter-hidden",
      this.shapesHighlighterShown,
      this.state.shapes.options
    );
    this.shapesHighlighterShown = null;
    this.state.shapes = {};
  }

  /**
   * Show the shapes highlighter for the given element, with the given point highlighted.
   *
   * @param {NodeFront} node
   *        The NodeFront of the element to highlight.
   * @param {String} point
   *        The point to highlight in the shapes highlighter.
   */
  async hoverPointShapesHighlighter(node, point) {
    if (node == this.shapesHighlighterShown) {
      const options = Object.assign({}, this.state.shapes.options);
      options.hoverPoint = point;
      await this.showShapesHighlighter(node, options);
    }
  }

  /**
   * Returns the flexbox highlighter color for the given node.
   */
  async getFlexboxHighlighterColor() {
    // Load the Redux slice for flexbox if not yet available.
    const state = this.store.getState();
    if (!state.flexbox) {
      this.store.injectReducer("flexbox", flexboxReducer);
    }

    // Attempt to get the flexbox highlighter color from the Redux store.
    const { flexbox } = this.store.getState();
    const color = flexbox.color;

    if (color) {
      return color;
    }

    // If the flexbox inspector has not been initialized, attempt to get the flexbox
    // highlighter from the async storage.
    const customHostColors =
      (await asyncStorage.getItem("flexboxInspectorHostColors")) || {};

    // Get the hostname, if there is no hostname, fall back on protocol
    // ex: `data:` uri, and `about:` pages
    let hostname;
    try {
      hostname =
        parseURL(this.target.url).hostname ||
        parseURL(this.target.url).protocol;
    } catch (e) {
      this._handleRejection(e);
    }

    return hostname && customHostColors[hostname]
      ? customHostColors[hostname]
      : DEFAULT_HIGHLIGHTER_COLOR;
  }

  /**
   * Toggle the flexbox highlighter for the given flexbox container element.
   *
   * @param  {NodeFront} node
   *         The NodeFront of the flexbox container element to highlight.
   * @param. {String} trigger
   *         String name matching "layout", "markup" or "rule" to indicate where the
   *         flexbox highlighter was toggled on from. "layout" represents the layout view.
   *         "markup" represents the markup view. "rule" represents the rule view.
   */
  async toggleFlexboxHighlighter(node, trigger) {
    const highlightedNode = this.getNodeForActiveHighlighter(TYPES.FLEXBOX);
    if (node == highlightedNode) {
      await this.hideFlexboxHighlighter(node);
      return;
    }

    await this.showFlexboxHighlighter(node, {}, trigger);
  }

  /**
   * Show the flexbox highlighter for the given flexbox container element.
   *
   * @param  {NodeFront} node
   *         The NodeFront of the flexbox container element to highlight.
   * @param  {Object} options
   *         Object used for passing options to the flexbox highlighter.
   * @param. {String} trigger
   *         String name matching "layout", "markup" or "rule" to indicate where the
   *         flexbox highlighter was toggled on from. "layout" represents the layout view.
   *         "markup" represents the markup view. "rule" represents the rule view.
   *         Will be passed as an option even though the highlighter doesn't use it
   *         in order to log telemetry in _afterShowHighlighterTypeForNode()
   */
  async showFlexboxHighlighter(node, options, trigger) {
    const color = await this.getFlexboxHighlighterColor(node);
    await this.showHighlighterTypeForNode(TYPES.FLEXBOX, node, {
      ...options,
      trigger,
      color,
    });
  }

  /**
   * Hide the flexbox highlighter if any instance is visible.
   */
  async hideFlexboxHighlighter() {
    await this.hideHighlighterType(TYPES.FLEXBOX);
  }

  /**
   * Create a grid highlighter settings object for the provided nodeFront.
   *
   * @param  {NodeFront} nodeFront
   *         The NodeFront for which we need highlighter settings.
   */
  getGridHighlighterSettings(nodeFront) {
    // Load the Redux slices for grids and grid highlighter settings if not yet available.
    const state = this.store.getState();
    if (!state.grids) {
      this.store.injectReducer("grids", gridsReducer);
    }

    if (!state.highlighterSettings) {
      this.store.injectReducer(
        "highlighterSettings",
        highlighterSettingsReducer
      );
    }

    // Get grids and grid highlighter settings from the latest Redux state
    // in case they were just added above.
    const { grids, highlighterSettings } = this.store.getState();
    const grid = grids.find(g => g.nodeFront === nodeFront);
    const color = grid ? grid.color : DEFAULT_HIGHLIGHTER_COLOR;
    const zIndex = grid ? grid.zIndex : 0;
    return Object.assign({}, highlighterSettings, { color, zIndex });
  }

  /**
   * Return a list of all node fronts that are highlighted with a Grid highlighter.
   *
   * @return {Array}
   */
  getHighlightedGridNodes() {
    return [...Array.from(this.gridHighlighters.keys())];
  }

  /**
   * Toggle the grid highlighter for the given grid container element.
   *
   * @param  {NodeFront} node
   *         The NodeFront of the grid container element to highlight.
   * @param. {String} trigger
   *         String name matching "grid", "markup" or "rule" to indicate where the
   *         grid highlighter was toggled on from. "grid" represents the grid view.
   *         "markup" represents the markup view. "rule" represents the rule view.
   */
  async toggleGridHighlighter(node, trigger) {
    if (this.gridHighlighters.has(node)) {
      await this.hideGridHighlighter(node);
      return;
    }

    await this.showGridHighlighter(node, {}, trigger);
  }

  /**
   * Show the grid highlighter for the given grid container element.
   * Allow as many active highlighter instances as permitted by the
   * maxGridHighlighters limit (default 3).
   *
   * Logic of showing grid highlighters:
   * - GRID:
   *  - Show a highlighter for a grid container when explicitly requested
   *    (ex. click badge in Markup view) and count it against the limit.
   *  - When the limit of active highlighters is reached, do no show any more
   *    until other instances are hidden. If configured to show only one instance,
   *    hide the existing highlighter before showing a new one.
   *
   * - SUBGRID:
   *  - When a highlighter for a subgrid is shown, also show a highlighter for its parent
   *    grid, but with faded-out colors (serves as a visual reference for the subgrid)
   *  - The "active" state of the highlighter for the parent grid is not reflected
   *    in the UI (checkboxes in the Layout panel, badges in the Markup view, etc.)
   *  - The highlighter for the parent grid DOES NOT count against the highlighter limit
   *  - If the highlighter for the parent grid is explicitly requested to be shown
   *    (ex: click badge in Markup view), show it in full color and reflect its "active"
   *    state in the UI (checkboxes in the Layout panel, badges in the Markup view)
   *  - When a highlighter for a subgrid is hidden, also hide the highlighter for its
   *    parent grid; if the parent grid was explicitly requested separately, keep the
   *    highlighter for the parent grid visible, but show it in full color.
   *
   * @param  {NodeFront} node
   *         The NodeFront of the grid container element to highlight.
   * @param  {Object} options
   *         Object used for passing options to the grid highlighter.
   * @param  {String} trigger
   *         String name matching "grid", "markup" or "rule" to indicate where the
   *         grid highlighter was toggled on from. "grid" represents the grid view.
   *         "markup" represents the markup view. "rule" represents the rule view.
   */
  async showGridHighlighter(node, options, trigger) {
    if (!this.gridHighlighters.has(node)) {
      // If only one grid highlighter can be shown at a time, hide the other instance.
      // Otherwise, if the max highlighter limit is reached, do not show another one.
      if (this.maxGridHighlighters === 1) {
        await this.hideGridHighlighter(
          this.gridHighlighters.keys().next().value
        );
      } else if (this.gridHighlighters.size === this.maxGridHighlighters) {
        return;
      }
    }

    // If the given node is already highlighted as the parent grid for a subgrid,
    // hide the parent grid highlighter because it will be explicitly shown below.
    const isHighlightedAsParentGrid = Array.from(this.gridHighlighters.values())
      .map(value => value.parentGridNode)
      .includes(node);
    if (isHighlightedAsParentGrid) {
      await this.hideParentGridHighlighter(node);
    }

    // Show a translucent highlight of the parent grid container if the given node is
    // a subgrid and the parent grid container is not already explicitly highlighted.
    let parentGridNode = null;
    let parentGridHighlighter = null;
    if (node.displayType === "subgrid") {
      parentGridNode = await node.walkerFront.getParentGridNode(node);
      parentGridHighlighter = await this.showParentGridHighlighter(
        parentGridNode
      );
    }

    // When changing highlighter colors, we call highlighter.show() again with new options
    // Reuse the active highlighter instance if present; avoid creating new highlighters
    let highlighter;
    if (this.gridHighlighters.has(node)) {
      highlighter = this.gridHighlighters.get(node).highlighter;
    }

    if (!highlighter) {
      highlighter = await this._getHighlighterTypeForNode(TYPES.GRID, node);
    }

    this.gridHighlighters.set(node, {
      highlighter,
      parentGridNode,
      parentGridHighlighter,
    });

    options = { ...options, ...this.getGridHighlighterSettings(node) };
    await highlighter.show(node, options);

    this._afterShowHighlighterTypeForNode(TYPES.GRID, node, {
      ...options,
      trigger,
    });

    try {
      // Save grid highlighter state.
      const { url } = this.target;

      const selectors =
        await this.inspector.commands.inspectorCommand.getNodeFrontSelectorsFromTopDocument(
          node
        );

      this.state.grids.set(node, { selectors, options, url });

      // Emit the NodeFront of the grid container element that the grid highlighter was
      // shown for, and its options for testing the highlighter setting options.
      this.emit("grid-highlighter-shown", node, options);

      // XXX: Shim to use generic highlighter events until addressing Bug 1572652
      // Ensures badges in the Markup view reflect the state of the grid highlighter.
      this.emit("highlighter-shown", {
        type: TYPES.GRID,
        nodeFront: node,
        highlighter,
        options,
      });
    } catch (e) {
      this._handleRejection(e);
    }
  }

  /**
   * Show the grid highlighter for the given subgrid's parent grid container element.
   * The parent grid highlighter is shown with faded-out colors, as opposed
   * to the full-color grid highlighter shown when calling showGridHighlighter().
   * If the grid container is already explicitly highlighted (i.e. standalone grid),
   * skip showing the another grid highlighter for it.
   *
   * @param   {NodeFront} node
   *          The NodeFront of the parent grid container element to highlight.
   * @returns {Promise}
   *          Resolves with either the highlighter instance or null if it was skipped.
   */
  async showParentGridHighlighter(node) {
    const isHighlighted = Array.from(this.gridHighlighters.keys()).includes(
      node
    );

    if (!node || isHighlighted) {
      return null;
    }

    // Get the parent grid highlighter for the parent grid container if one already exists
    let highlighter = this.getParentGridHighlighter(node);
    if (!highlighter) {
      highlighter = await this._getHighlighterTypeForNode(TYPES.GRID, node);
    }
    const options = {
      ...this.getGridHighlighterSettings(node),
      // Configure the highlighter with faded-out colors.
      globalAlpha: SUBGRID_PARENT_ALPHA,
    };
    await highlighter.show(node, options);

    this.emitForTests("highlighter-shown", {
      type: TYPES.GRID,
      nodeFront: node,
      highlighter,
      options,
    });

    return highlighter;
  }

  /**
   * Get the parent grid highlighter associated with the given node
   * if the node is a parent grid container for a highlighted subgrid.
   *
   * @param  {NodeFront} node
   *         NodeFront of the parent grid container for a subgrid.
   * @return {CustomHighlighterFront|null}
   */
  getParentGridHighlighter(node) {
    // Find the highlighter map value for the subgrid whose parent grid is the given node.
    const value = Array.from(this.gridHighlighters.values()).find(
      ({ parentGridNode }) => {
        return parentGridNode === node;
      }
    );

    if (!value) {
      return null;
    }

    const { parentGridHighlighter } = value;
    return parentGridHighlighter;
  }

  /**
   * Restore the parent grid highlighter for a subgrid.
   *
   * A grid node can be highlighted both explicitly (ex: by clicking a badge in the
   * Markup view) and implicitly, as a parent grid for a subgrid.
   *
   * An explicit grid highlighter overwrites a subgrid's parent grid highlighter.
   * After an explicit grid highlighter for a node is hidden, but that node is also the
   * parent grid container for a subgrid which is still highlighted, restore the implicit
   * parent grid highlighter.
   *
   * @param  {NodeFront} node
   *         NodeFront for a grid node which may also be a subgrid's parent grid
   *         container.
   * @return {Promise}
   */
  async restoreParentGridHighlighter(node) {
    // Find the highlighter map entry for the subgrid whose parent grid is the given node.
    const entry = Array.from(this.gridHighlighters.entries()).find(
      ([key, value]) => {
        return value?.parentGridNode === node;
      }
    );

    if (!Array.isArray(entry)) {
      return;
    }

    const [highlightedSubgridNode, data] = entry;
    if (!data.parentGridHighlighter) {
      const parentGridHighlighter = await this.showParentGridHighlighter(node);
      this.gridHighlighters.set(highlightedSubgridNode, {
        ...data,
        parentGridHighlighter,
      });
    }
  }

  /**
   * Hide the grid highlighter for the given grid container element.
   *
   * @param  {NodeFront} node
   *         The NodeFront of the grid container element to unhighlight.
   */
  async hideGridHighlighter(node) {
    const { highlighter, parentGridNode } =
      this.gridHighlighters.get(node) || {};

    if (!highlighter) {
      return;
    }

    // Hide the subgrid's parent grid highlighter, if any.
    if (parentGridNode) {
      await this.hideParentGridHighlighter(parentGridNode);
    }

    this._beforeHideHighlighterType(TYPES.GRID);
    // Don't just hide the highlighter, destroy the front instance to release memory.
    // If another highlighter is shown later, a new front will be created.
    highlighter.destroy();
    this.gridHighlighters.delete(node);
    this.state.grids.delete(node);

    // It's possible we just destroyed the grid highlighter for a node which also serves
    // as a subgrid's parent grid. If so, restore the parent grid highlighter.
    await this.restoreParentGridHighlighter(node);

    // Emit the NodeFront of the grid container element that the grid highlighter was
    // hidden for.
    this.emit("grid-highlighter-hidden", node);

    // XXX: Shim to use generic highlighter events until addressing Bug 1572652
    // Ensures badges in the Markup view reflect the state of the grid highlighter.
    this.emit("highlighter-hidden", {
      type: TYPES.GRID,
      nodeFront: node,
    });
  }

  /**
   * Hide the parent grid highlighter for the given parent grid container element.
   * If there are multiple subgrids with the same parent grid, do not hide the parent
   * grid highlighter.
   *
   * @param  {NodeFront} node
   *         The NodeFront of the parent grid container element to unhiglight.
   */
  async hideParentGridHighlighter(node) {
    let count = 0;
    let parentGridHighlighter;
    let subgridNode;
    for (const [key, value] of this.gridHighlighters.entries()) {
      if (value.parentGridNode === node) {
        parentGridHighlighter = value.parentGridHighlighter;
        subgridNode = key;
        count++;
      }
    }

    if (!parentGridHighlighter || count > 1) {
      return;
    }

    // Destroy the highlighter front instance to release memory.
    parentGridHighlighter.destroy();

    // Update the grid highlighter entry to indicate the parent grid highlighter is gone.
    this.gridHighlighters.set(subgridNode, {
      ...this.gridHighlighters.get(subgridNode),
      parentGridHighlighter: null,
    });
  }

  /**
   * Toggle the geometry editor highlighter for the given element.
   *
   * @param {NodeFront} node
   *        The NodeFront of the element to highlight.
   */
  async toggleGeometryHighlighter(node) {
    if (node == this.geometryEditorHighlighterShown) {
      await this.hideGeometryEditor();
      return;
    }

    await this.showGeometryEditor(node);
  }

  /**
   * Show the geometry editor highlightor for the given element.
   *
   * @param {NodeFront} node
   *        THe NodeFront of the element to highlight.
   */
  async showGeometryEditor(node) {
    const highlighter = await this._getHighlighterTypeForNode(
      "GeometryEditorHighlighter",
      node
    );
    if (!highlighter) {
      return;
    }

    const isShown = await highlighter.show(node);
    if (!isShown) {
      return;
    }

    this.emit("geometry-editor-highlighter-shown");
    this.geometryEditorHighlighterShown = node;
  }

  /**
   * Hide the geometry editor highlighter.
   */
  async hideGeometryEditor() {
    if (!this.geometryEditorHighlighterShown) {
      return;
    }

    const highlighter =
      this.geometryEditorHighlighterShown.inspectorFront.getKnownHighlighter(
        "GeometryEditorHighlighter"
      );

    if (!highlighter) {
      return;
    }

    await highlighter.hide();

    this.emit("geometry-editor-highlighter-hidden");
    this.geometryEditorHighlighterShown = null;
  }

  /**
   * Restores the saved flexbox highlighter state.
   */
  async restoreFlexboxState() {
    const state = this._restorableHighlighters.get(TYPES.FLEXBOX);
    if (!state) {
      return;
    }

    this._restorableHighlighters.delete(TYPES.FLEXBOX);
    await this.restoreState(TYPES.FLEXBOX, state, this.showFlexboxHighlighter);
  }

  /**
   * Restores the saved grid highlighter state.
   */
  async restoreGridState() {
    // The NodeFronts that are used as the keys in the grid state Map are no longer in the
    // tree after a reload. To clean up the grid state, we create a copy of the values of
    // the grid state before restoring and clear it.
    const values = [...this.state.grids.values()];
    this.state.grids.clear();

    try {
      for (const gridState of values) {
        await this.restoreState(
          TYPES.GRID,
          gridState,
          this.showGridHighlighter
        );
      }
    } catch (e) {
      this._handleRejection(e);
    }
  }

  /**
   * Helper function called by restoreFlexboxState, restoreGridState.
   * Restores the saved highlighter state for the given highlighter
   * and their state.
   *
   * @param  {String} type
   *         Highlighter type to be restored.
   * @param  {Object} state
   *         Object containing the metadata used to restore the highlighter.
   *         {Array} state.selectors
   *         Array of CSS selector which identifies the node to be highlighted.
   *         If the node is in the top-level document, the array contains just one item.
   *         Otherwise, if the node is nested within a stack of iframes, each iframe is
   *         identified by its unique selector; the last item in the array identifies
   *         the target node within its host iframe document.
   *         {Object} state.options
   *         Configuration options to use when showing the highlighter.
   *         {String} state.url
   *         URL of the top-level target when the metadata was stored. Used to identify
   *         if there was a page refresh or a navigation away to a different page.
   * @param  {Function} showFunction
   *         The function that shows the highlighter
   * @return {Promise} that resolves when the highlighter was restored and shown.
   */
  async restoreState(type, state, showFunction) {
    const { selectors = [], options, url } = state;

    if (!selectors.length || url !== this.target.url) {
      // Bail out if no selector was saved, or if we are on a different page.
      this.emit(`highlighter-discarded`, { type });
      return;
    }

    const nodeFront =
      await this.inspector.commands.inspectorCommand.findNodeFrontFromSelectors(
        selectors
      );

    if (nodeFront) {
      await showFunction(nodeFront, options);
      this.emit(`highlighter-restored`, { type });
    } else {
      this.emit(`highlighter-discarded`, { type });
    }
  }

  /**
   * Get an instance of an in-context editor for the given type.
   *
   * In-context editors behave like highlighters but with added editing capabilities which
   * need to write value changes back to something, like to properties in the Rule view.
   * They typically exist in the context of the page, like the ShapesInContextEditor.
   *
   * @param  {NodeFront} node.
   * @param  {String} type
   *         Type of in-context editor. Currently supported: "shapesEditor"
   * @return {Object|null}
   *         Reference to instance for given type of in-context editor or null.
   */
  async getInContextEditor(node, type) {
    if (this.editors[type]) {
      return this.editors[type];
    }

    let editor;

    switch (type) {
      case "shapesEditor":
        const highlighter = await this._getHighlighterTypeForNode(
          "ShapesHighlighter",
          node
        );
        if (!highlighter) {
          return null;
        }
        const ShapesInContextEditor = require("resource://devtools/client/shared/widgets/ShapesInContextEditor.js");

        editor = new ShapesInContextEditor(
          highlighter,
          this.inspector,
          this.state
        );
        editor.on("show", this.onShapesHighlighterShown);
        editor.on("hide", this.onShapesHighlighterHidden);
        break;
      default:
        throw new Error(`Unsupported in-context editor '${name}'`);
    }

    this.editors[type] = editor;

    return editor;
  }

  /**
   * Get a highlighter front given a type. It will only be initialized once.
   *
   * @param  {String} type
   *         The highlighter type. One of this.highlighters.
   * @return {Promise} that resolves to the highlighter
   */
  async _getHighlighter(type) {
    if (this.highlighters[type]) {
      return this.highlighters[type];
    }

    let highlighter;

    try {
      highlighter = await this.inspectorFront.getHighlighterByType(type);
    } catch (e) {
      this._handleRejection(e);
    }

    if (!highlighter) {
      return null;
    }

    this.highlighters[type] = highlighter;
    return highlighter;
  }

  /**
   * Ignore unexpected errors from async function calls
   * if HighlightersOverlay has been destroyed.
   *
   * @param {Error} error
   */
  _handleRejection(error) {
    if (!this.destroyed) {
      console.error(error);
    }
  }

  /**
   * Toggle the class "active" on the given shape point in the rule view if the current
   * inspector selection is highlighted by the shapes highlighter.
   *
   * @param {NodeFront} node
   *        The NodeFront of the shape point to toggle
   * @param {Boolean} active
   *        Whether the shape point should be active
   */
  _toggleShapePointActive(node, active) {
    if (this.inspector.selection.nodeFront != this.shapesHighlighterShown) {
      return;
    }

    node.classList.toggle("active", active);
  }

  /**
   * Hide the currently shown hovered highlighter.
   */
  _hideHoveredHighlighter() {
    if (
      !this.hoveredHighlighterShown ||
      !this.highlighters[this.hoveredHighlighterShown]
    ) {
      return;
    }

    // For some reason, the call to highlighter.hide doesn't always return a
    // promise. This causes some tests to fail when trying to install a
    // rejection handler on the result of the call. To avoid this, check
    // whether the result is truthy before installing the handler.
    const onHidden = this.highlighters[this.hoveredHighlighterShown].hide();
    if (onHidden) {
      onHidden.catch(console.error);
    }

    this.hoveredHighlighterShown = null;
    this.emit("css-transform-highlighter-hidden");
  }

  /**
   * Given a node front and a function that hides the given node's highlighter, hides
   * the highlighter if the node front is no longer in the DOM tree. This is called
   * from the "markupmutation" event handler.
   *
   * @param  {NodeFront} node
   *         The NodeFront of a highlighted DOM node.
   * @param  {Function} hideHighlighter
   *         The function that will hide the highlighter of the highlighted node.
   */
  async _hideHighlighterIfDeadNode(node, hideHighlighter) {
    if (!node) {
      return;
    }

    try {
      const isInTree =
        node.walkerFront && (await node.walkerFront.isInDOMTree(node));
      if (!isInTree) {
        await hideHighlighter(node);
      }
    } catch (e) {
      this._handleRejection(e);
    }
  }

  /**
   * Is the current hovered node a css transform property value in the
   * computed-view.
   *
   * @param  {Object} nodeInfo
   * @return {Boolean}
   */
  _isComputedViewTransform(nodeInfo) {
    if (nodeInfo.view != "computed") {
      return false;
    }
    return (
      nodeInfo.type === VIEW_NODE_VALUE_TYPE &&
      nodeInfo.value.property === "transform"
    );
  }

  /**
   * Does the current clicked node have the shapes highlighter toggle in the
   * rule-view.
   *
   * @param  {DOMNode} node
   * @return {Boolean}
   */
  _isRuleViewShapeSwatch(node) {
    return (
      this.isRuleView(node) && node.classList.contains("ruleview-shapeswatch")
    );
  }

  /**
   * Is the current hovered node a css transform property value in the rule-view.
   *
   * @param  {Object} nodeInfo
   * @return {Boolean}
   */
  _isRuleViewTransform(nodeInfo) {
    if (nodeInfo.view != "rule") {
      return false;
    }
    const isTransform =
      nodeInfo.type === VIEW_NODE_VALUE_TYPE &&
      nodeInfo.value.property === "transform";
    const isEnabled =
      nodeInfo.value.enabled &&
      !nodeInfo.value.overridden &&
      !nodeInfo.value.pseudoElement;
    return isTransform && isEnabled;
  }

  /**
   * Is the current hovered node a highlightable shape point in the rule-view.
   *
   * @param  {Object} nodeInfo
   * @return {Boolean}
   */
  isRuleViewShapePoint(nodeInfo) {
    if (nodeInfo.view != "rule") {
      return false;
    }
    const isShape =
      nodeInfo.type === VIEW_NODE_SHAPE_POINT_TYPE &&
      (nodeInfo.value.property === "clip-path" ||
        nodeInfo.value.property === "shape-outside");
    const isEnabled =
      nodeInfo.value.enabled &&
      !nodeInfo.value.overridden &&
      !nodeInfo.value.pseudoElement;
    return (
      isShape &&
      isEnabled &&
      nodeInfo.value.toggleActive &&
      !this.state.shapes.options.transformMode
    );
  }

  onClick(event) {
    if (this._isRuleViewShapeSwatch(event.target)) {
      event.stopPropagation();

      const view = this.inspector.getPanel("ruleview").view;
      const nodeInfo = view.getNodeInfo(event.target);

      this.toggleShapesHighlighter(
        this.inspector.selection.nodeFront,
        {
          mode: event.target.dataset.mode,
          transformMode: event.metaKey || event.ctrlKey,
        },
        nodeInfo.value.textProperty
      );
    }
  }

  /**
   * Handler for "display-change" events from walker fronts. Hides the flexbox or
   * grid highlighter if their respective node is no longer a flex container or
   * grid container.
   *
   * @param  {Array} nodes
   *         An array of nodeFronts
   */
  async onDisplayChange(nodes) {
    const highlightedGridNodes = this.getHighlightedGridNodes();

    for (const node of nodes) {
      const display = node.displayType;

      // Hide the flexbox highlighter if the node is no longer a flexbox container.
      if (
        display !== "flex" &&
        display !== "inline-flex" &&
        node == this.getNodeForActiveHighlighter(TYPES.FLEXBOX)
      ) {
        await this.hideFlexboxHighlighter(node);
        return;
      }

      // Hide the grid highlighter if the node is no longer a grid container.
      if (
        display !== "grid" &&
        display !== "inline-grid" &&
        display !== "subgrid" &&
        highlightedGridNodes.includes(node)
      ) {
        await this.hideGridHighlighter(node);
        return;
      }
    }
  }

  onMouseMove(event) {
    // Bail out if the target is the same as for the last mousemove.
    if (event.target === this._lastHovered) {
      return;
    }

    // Only one highlighter can be displayed at a time, hide the currently shown.
    this._hideHoveredHighlighter();

    this._lastHovered = event.target;

    const view = this.isRuleView(this._lastHovered)
      ? this.inspector.getPanel("ruleview").view
      : this.inspector.getPanel("computedview").computedView;
    const nodeInfo = view.getNodeInfo(event.target);
    if (!nodeInfo) {
      return;
    }

    if (this.isRuleViewShapePoint(nodeInfo)) {
      const { point } = nodeInfo.value;
      this.hoverPointShapesHighlighter(
        this.inspector.selection.nodeFront,
        point
      );
      return;
    }

    // Choose the type of highlighter required for the hovered node.
    let type;
    if (
      this._isRuleViewTransform(nodeInfo) ||
      this._isComputedViewTransform(nodeInfo)
    ) {
      type = "CssTransformHighlighter";
    }

    if (type) {
      this.hoveredHighlighterShown = type;
      const node = this.inspector.selection.nodeFront;
      this._getHighlighter(type)
        .then(highlighter => highlighter.show(node))
        .then(shown => {
          if (shown) {
            this.emit("css-transform-highlighter-shown");
          }
        });
    }
  }

  onMouseOut(event) {
    // Only hide the highlighter if the mouse leaves the currently hovered node.
    if (
      !this._lastHovered ||
      (event && this._lastHovered.contains(event.relatedTarget))
    ) {
      return;
    }

    // Otherwise, hide the highlighter.
    const view = this.isRuleView(this._lastHovered)
      ? this.inspector.getPanel("ruleview").view
      : this.inspector.getPanel("computedview").computedView;
    const nodeInfo = view.getNodeInfo(this._lastHovered);
    if (nodeInfo && this.isRuleViewShapePoint(nodeInfo)) {
      this.hoverPointShapesHighlighter(
        this.inspector.selection.nodeFront,
        null
      );
    }
    this._lastHovered = null;
    this._hideHoveredHighlighter();
  }

  /**
   * Handler function called when a new root-node has been added in the
   * inspector. Nodes may have been added / removed and highlighters should
   * be updated.
   */
  async _onResourceAvailable(resources) {
    for (const resource of resources) {
      if (
        resource.resourceType !== this.resourceCommand.TYPES.ROOT_NODE ||
        // It might happen that the ROOT_NODE resource (which is a Front) is already
        // destroyed, and in such case we want to ignore it.
        resource.isDestroyed()
      ) {
        // Only handle root-node resources.
        // Note that we could replace this with DOCUMENT_EVENT resources, since
        // the actual root-node resource is not used here.
        continue;
      }

      if (resource.targetFront.isTopLevel && resource.isTopLevelDocument) {
        // The topmost root node will lead to the destruction and recreation of
        // the MarkupView, and highlighters will be refreshed afterwards. This is
        // handled by the inspector.
        continue;
      }

      await this._hideOrphanedHighlighters();
    }
  }

  /**
   * Handler function for "markupmutation" events. Hides the flexbox/grid/shapes
   * highlighter if the flexbox/grid/shapes container is no longer in the DOM tree.
   */
  async onMarkupMutation(mutations) {
    const hasInterestingMutation = mutations.some(
      mut => mut.type === "childList"
    );
    if (!hasInterestingMutation) {
      // Bail out if the mutations did not remove nodes, or if no grid highlighter is
      // displayed.
      return;
    }

    await this._hideOrphanedHighlighters();
  }

  /**
   * Hide every active highlighter whose nodeFront is no longer present in the DOM.
   * Returns a promise that resolves when all orphaned highlighters are hidden.
   *
   * @return {Promise}
   */
  async _hideOrphanedHighlighters() {
    await this._hideHighlighterIfDeadNode(
      this.shapesHighlighterShown,
      this.hideShapesHighlighter
    );

    // Hide all active highlighters whose nodeFront is no longer attached.
    const promises = [];
    for (const [type, data] of this._activeHighlighters) {
      promises.push(
        this._hideHighlighterIfDeadNode(data.nodeFront, () => {
          return this.hideHighlighterType(type);
        })
      );
    }

    const highlightedGridNodes = this.getHighlightedGridNodes();
    for (const node of highlightedGridNodes) {
      promises.push(
        this._hideHighlighterIfDeadNode(node, this.hideGridHighlighter)
      );
    }

    return Promise.all(promises);
  }

  /**
   * Hides any visible highlighter and clear internal state. This should be called to
   * have a clean slate, for example when the page navigates or when a given frame is
   * selected in the iframe picker.
   */
  async hideAllHighlighters() {
    this.destroyEditors();

    // Hide any visible highlighters and clear any timers set to autohide highlighters.
    for (const { highlighter, timer } of this._activeHighlighters.values()) {
      await highlighter.hide();
      clearTimeout(timer);
    }

    this._activeHighlighters.clear();
    this._pendingHighlighters.clear();
    this.gridHighlighters.clear();

    this.geometryEditorHighlighterShown = null;
    this.hoveredHighlighterShown = null;
    this.shapesHighlighterShown = null;
  }

  /**
   * Display a message about the simple highlighters which can be enabled for
   * users relying on prefers-reduced-motion. This message will be a toolbox
   * notification, which will contain a button to open the settings panel and
   * will no longer be displayed if the user decides to explicitly close the
   * message.
   */
  _showSimpleHighlightersMessage() {
    const pref = "devtools.inspector.simple-highlighters.message-dismissed";
    const messageDismissed = Services.prefs.getBoolPref(pref, false);
    if (messageDismissed) {
      return;
    }
    const notificationBox = this.inspector.toolbox.getNotificationBox();
    const message = HighlightersBundle.formatValueSync(
      "simple-highlighters-message"
    );

    notificationBox.appendNotification(
      message,
      "simple-highlighters-message",
      null,
      notificationBox.PRIORITY_INFO_MEDIUM,
      [
        {
          label: HighlightersBundle.formatValueSync(
            "simple-highlighters-settings-button"
          ),
          callback: async () => {
            const { panelDoc } = await this.toolbox.selectTool("options");
            const option = panelDoc.querySelector(
              "[data-pref='devtools.inspector.simple-highlighters-reduced-motion']"
            ).parentNode;
            option.scrollIntoView({ block: "center" });
            option.classList.add("options-panel-highlight");

            // Emit a test-only event to know when the settings panel is opened.
            this.toolbox.emitForTests("test-highlighters-settings-opened");
          },
        },
      ],
      evt => {
        if (evt === "removed") {
          // Flip the preference when the message is dismissed.
          Services.prefs.setBoolPref(pref, true);
        }
      }
    );
  }

  /**
   * Destroy and clean-up all instances of in-context editors.
   */
  destroyEditors() {
    for (const type in this.editors) {
      this.editors[type].off("show");
      this.editors[type].off("hide");
      this.editors[type].destroy();
    }

    this.editors = {};
  }

  /**
   * Destroy and clean-up all instances of highlighters.
   */
  destroyHighlighters() {
    // Destroy all highlighters and clear any timers set to autohide highlighters.
    const values = [
      ...this._activeHighlighters.values(),
      ...this.gridHighlighters.values(),
    ];
    for (const { highlighter, parentGridHighlighter, timer } of values) {
      if (highlighter) {
        highlighter.destroy();
      }

      if (parentGridHighlighter) {
        parentGridHighlighter.destroy();
      }

      if (timer) {
        clearTimeout(timer);
      }
    }

    this._activeHighlighters.clear();
    this._pendingHighlighters.clear();
    this.gridHighlighters.clear();

    for (const type in this.highlighters) {
      if (this.highlighters[type]) {
        this.highlighters[type].finalize();
        this.highlighters[type] = null;
      }
    }
  }

  /**
   * Destroy this overlay instance, removing it from the view and destroying
   * all initialized highlighters.
   */
  destroy() {
    this.inspector.off("markupmutation", this.onMarkupMutation);
    this.resourceCommand.unwatchResources(
      [this.resourceCommand.TYPES.ROOT_NODE],
      { onAvailable: this._onResourceAvailable }
    );

    this.walkerEventListener.destroy();
    this.walkerEventListener = null;

    this.destroyEditors();
    this.destroyHighlighters();

    this._lastHovered = null;

    this.inspector = null;
    this.state = null;
    this.store = null;
    this.telemetry = null;

    this.geometryEditorHighlighterShown = null;
    this.hoveredHighlighterShown = null;
    this.shapesHighlighterShown = null;

    this.destroyed = true;
  }
}

HighlightersOverlay.TYPES = HighlightersOverlay.prototype.TYPES = TYPES;

module.exports = HighlightersOverlay;