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
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
|
/* 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/. */
import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
ContextualIdentityService:
"resource://gre/modules/ContextualIdentityService.sys.mjs",
L10nCache: "resource:///modules/UrlbarUtils.sys.mjs",
ObjectUtils: "resource://gre/modules/ObjectUtils.sys.mjs",
UrlbarProviderOpenTabs: "resource:///modules/UrlbarProviderOpenTabs.sys.mjs",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.sys.mjs",
UrlbarProviderQuickSuggest:
"resource:///modules/UrlbarProviderQuickSuggest.sys.mjs",
UrlbarProviderRecentSearches:
"resource:///modules/UrlbarProviderRecentSearches.sys.mjs",
UrlbarProviderTopSites: "resource:///modules/UrlbarProviderTopSites.sys.mjs",
UrlbarProviderWeather: "resource:///modules/UrlbarProviderWeather.sys.mjs",
UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.sys.mjs",
UrlbarResult: "resource:///modules/UrlbarResult.sys.mjs",
UrlbarSearchOneOffs: "resource:///modules/UrlbarSearchOneOffs.sys.mjs",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.sys.mjs",
UrlbarUtils: "resource:///modules/UrlbarUtils.sys.mjs",
});
XPCOMUtils.defineLazyServiceGetter(
lazy,
"styleSheetService",
"@mozilla.org/content/style-sheet-service;1",
"nsIStyleSheetService"
);
// Query selector for selectable elements in results.
const SELECTABLE_ELEMENT_SELECTOR = "[role=button], [selectable]";
const KEYBOARD_SELECTABLE_ELEMENT_SELECTOR =
"[role=button]:not([keyboard-inaccessible]), [selectable]";
const ZERO_PREFIX_HISTOGRAM_DWELL_TIME = "FX_URLBAR_ZERO_PREFIX_DWELL_TIME_MS";
const ZERO_PREFIX_SCALAR_ABANDONMENT = "urlbar.zeroprefix.abandonment";
const ZERO_PREFIX_SCALAR_ENGAGEMENT = "urlbar.zeroprefix.engagement";
const ZERO_PREFIX_SCALAR_EXPOSURE = "urlbar.zeroprefix.exposure";
const RESULT_MENU_COMMANDS = {
DISMISS: "dismiss",
HELP: "help",
MANAGE: "manage",
};
const getBoundsWithoutFlushing = element =>
element.ownerGlobal.windowUtils.getBoundsWithoutFlushing(element);
// Used to get a unique id to use for row elements, it wraps at 9999, that
// should be plenty for our needs.
let gUniqueIdSerial = 1;
function getUniqueId(prefix) {
return prefix + (gUniqueIdSerial++ % 9999);
}
/**
* Receives and displays address bar autocomplete results.
*/
export class UrlbarView {
// Stale rows are removed on a timer with this timeout.
static removeStaleRowsTimeout = 400;
/**
* @param {UrlbarInput} input
* The UrlbarInput instance belonging to this UrlbarView instance.
*/
constructor(input) {
this.input = input;
this.panel = input.panel;
this.controller = input.controller;
this.document = this.panel.ownerDocument;
this.window = this.document.defaultView;
this.#rows = this.panel.querySelector(".urlbarView-results");
this.resultMenu = this.panel.querySelector(".urlbarView-result-menu");
this.#resultMenuCommands = new WeakMap();
this.#rows.addEventListener("mousedown", this);
// For the horizontal fade-out effect, set the overflow attribute on result
// rows when they overflow.
this.#rows.addEventListener("overflow", this);
this.#rows.addEventListener("underflow", this);
this.resultMenu.addEventListener("command", this);
this.resultMenu.addEventListener("popupshowing", this);
// `noresults` is used to style the one-offs without their usual top border
// when no results are present.
this.panel.setAttribute("noresults", "true");
this.controller.setView(this);
this.controller.addQueryListener(this);
// This is used by autoOpen to avoid flickering results when reopening
// previously abandoned searches.
this.queryContextCache = new QueryContextCache(5);
// We cache l10n strings to avoid Fluent's async lookup.
this.#l10nCache = new lazy.L10nCache(this.document.l10n);
for (let viewTemplate of UrlbarView.dynamicViewTemplatesByName.values()) {
if (viewTemplate.stylesheet) {
addDynamicStylesheet(this.window, viewTemplate.stylesheet);
}
}
}
get oneOffSearchButtons() {
if (!this.#oneOffSearchButtons) {
this.#oneOffSearchButtons = new lazy.UrlbarSearchOneOffs(this);
this.#oneOffSearchButtons.addEventListener(
"SelectedOneOffButtonChanged",
this
);
}
return this.#oneOffSearchButtons;
}
/**
* Whether the panel is open.
*
* @returns {boolean}
*/
get isOpen() {
return this.input.hasAttribute("open");
}
get allowEmptySelection() {
let { heuristicResult } = this.#queryContext || {};
return !heuristicResult || !this.#shouldShowHeuristic(heuristicResult);
}
get selectedRowIndex() {
if (!this.isOpen) {
return -1;
}
let selectedRow = this.#getSelectedRow();
if (!selectedRow) {
return -1;
}
return selectedRow.result.rowIndex;
}
set selectedRowIndex(val) {
if (!this.isOpen) {
throw new Error(
"UrlbarView: Cannot select an item if the view isn't open."
);
}
if (val < 0) {
this.#selectElement(null);
return;
}
let items = Array.from(this.#rows.children).filter(r =>
this.#isElementVisible(r)
);
if (val >= items.length) {
throw new Error(`UrlbarView: Index ${val} is out of bounds.`);
}
// Select the first selectable element inside the row. If it doesn't
// contain a selectable element, clear the selection.
let row = items[val];
let element = this.#getNextSelectableElement(row);
if (this.#getRowFromElement(element) != row) {
element = null;
}
this.#selectElement(element);
}
get selectedElementIndex() {
if (!this.isOpen || !this.#selectedElement) {
return -1;
}
return this.#selectedElement.elementIndex;
}
/**
* @returns {UrlbarResult}
* The currently selected result.
*/
get selectedResult() {
if (!this.isOpen) {
return null;
}
return this.#getSelectedRow()?.result;
}
/**
* @returns {Element}
* The currently selected element.
*/
get selectedElement() {
if (!this.isOpen) {
return null;
}
return this.#selectedElement;
}
/**
* @returns {boolean}
* Whether the SPACE key should activate the selected element (if any)
* instead of adding to the input value.
*/
shouldSpaceActivateSelectedElement() {
// We want SPACE to activate buttons only.
if (this.selectedElement?.getAttribute("role") != "button") {
return false;
}
// Make sure the input field is empty, otherwise the user might want to add
// a space to the current search string. As it stands, selecting a button
// should always clear the input field, so this is just an extra safeguard.
if (this.input.value) {
return false;
}
return true;
}
/**
* Clears selection, regardless of view status.
*/
clearSelection() {
this.#selectElement(null, { updateInput: false });
}
/**
* @returns {number}
* The number of visible results in the view. Note that this may be larger
* than the number of results in the current query context since the view
* may be showing stale results.
*/
get visibleRowCount() {
let sum = 0;
for (let row of this.#rows.children) {
sum += Number(this.#isElementVisible(row));
}
return sum;
}
/**
* Returns the result of the row containing the given element, or the result
* of the element if it itself is a row.
*
* @param {Element} element
* An element in the view.
* @returns {UrlbarResult}
* The result of the element's row.
*/
getResultFromElement(element) {
return element?.classList.contains("urlbarView-result-menuitem")
? this.#resultMenuResult
: this.#getRowFromElement(element)?.result;
}
/**
* @param {number} index
* The index from which to fetch the result.
* @returns {UrlbarResult}
* The result at `index`. Null if the view is closed or if there are no
* results.
*/
getResultAtIndex(index) {
if (
!this.isOpen ||
!this.#rows.children.length ||
index >= this.#rows.children.length
) {
return null;
}
return this.#rows.children[index].result;
}
/**
* @param {UrlbarResult} result A result.
* @returns {boolean} True if the given result is selected.
*/
resultIsSelected(result) {
if (this.selectedRowIndex < 0) {
return false;
}
return result.rowIndex == this.selectedRowIndex;
}
/**
* Moves the view selection forward or backward.
*
* @param {number} amount
* The number of steps to move.
* @param {object} options Options object
* @param {boolean} [options.reverse]
* Set to true to select the previous item. By default the next item
* will be selected.
* @param {boolean} [options.userPressedTab]
* Set to true if the user pressed Tab to select a result. Default false.
*/
selectBy(amount, { reverse = false, userPressedTab = false } = {}) {
if (!this.isOpen) {
throw new Error(
"UrlbarView: Cannot select an item if the view isn't open."
);
}
// Freeze results as the user is interacting with them, unless we are
// deferring events while waiting for critical results.
if (!this.input.eventBufferer.isDeferringEvents) {
this.controller.cancelQuery();
}
if (!userPressedTab) {
let { selectedRowIndex } = this;
let end = this.visibleRowCount - 1;
if (selectedRowIndex == -1) {
this.selectedRowIndex = reverse ? end : 0;
return;
}
let endReached = selectedRowIndex == (reverse ? 0 : end);
if (endReached) {
if (this.allowEmptySelection) {
this.#selectElement(null);
} else {
this.selectedRowIndex = reverse ? end : 0;
}
return;
}
this.selectedRowIndex = Math.max(
0,
Math.min(end, selectedRowIndex + amount * (reverse ? -1 : 1))
);
return;
}
// Tab key handling below.
// Do not set aria-activedescendant if the user is moving to a
// tab-to-search result with the Tab key. If
// accessibility.tabToSearch.announceResults is set, the tab-to-search
// result was announced to the user as they typed. We don't set
// aria-activedescendant so the user doesn't think they have to press
// Enter to enter search mode. See bug 1647929.
const isSkippableTabToSearchAnnounce = selectedElt => {
let result = this.getResultFromElement(selectedElt);
let skipAnnouncement =
result?.providerName == "TabToSearch" &&
!this.#announceTabToSearchOnSelection &&
lazy.UrlbarPrefs.get("accessibility.tabToSearch.announceResults");
if (skipAnnouncement) {
// Once we skip setting aria-activedescendant once, we should not skip
// it again if the user returns to that result.
this.#announceTabToSearchOnSelection = true;
}
return skipAnnouncement;
};
let selectedElement = this.#selectedElement;
// We cache the first and last rows since they will not change while
// selectBy is running.
let firstSelectableElement = this.#getFirstSelectableElement();
// #getLastSelectableElement will not return an element that is over
// maxResults and thus may be hidden and not selectable.
let lastSelectableElement = this.#getLastSelectableElement();
if (!selectedElement) {
selectedElement = reverse
? lastSelectableElement
: firstSelectableElement;
this.#selectElement(selectedElement, {
setAccessibleFocus: !isSkippableTabToSearchAnnounce(selectedElement),
});
return;
}
let endReached = reverse
? selectedElement == firstSelectableElement
: selectedElement == lastSelectableElement;
if (endReached) {
if (this.allowEmptySelection) {
selectedElement = null;
} else {
selectedElement = reverse
? lastSelectableElement
: firstSelectableElement;
}
this.#selectElement(selectedElement, {
setAccessibleFocus: !isSkippableTabToSearchAnnounce(selectedElement),
});
return;
}
while (amount-- > 0) {
let next = reverse
? this.#getPreviousSelectableElement(selectedElement)
: this.#getNextSelectableElement(selectedElement);
if (!next) {
break;
}
selectedElement = next;
}
this.#selectElement(selectedElement, {
setAccessibleFocus: !isSkippableTabToSearchAnnounce(selectedElement),
});
}
async acknowledgeFeedback(result) {
let row = this.#rows.children[result.rowIndex];
if (!row) {
return;
}
let l10n = { id: "firefox-suggest-feedback-acknowledgment" };
await this.#l10nCache.ensure(l10n);
if (row.result != result) {
return;
}
let { value } = this.#l10nCache.get(l10n);
row.setAttribute("feedback-acknowledgment", value);
this.window.A11yUtils.announce({
raw: value,
source: row._content.closest("[role=option]"),
});
}
/**
* Replaces the given result's row with a dismissal-acknowledgment tip.
*
* @param {UrlbarResult} result
* The result that was dismissed.
* @param {object} titleL10n
* The localization object shown as dismissed feedback.
*/
#acknowledgeDismissal(result, titleL10n) {
let row = this.#rows.children[result.rowIndex];
if (!row || row.result != result) {
return;
}
// The row is no longer selectable. It's necessary to clear the selection
// before replacing the row because replacement will likely create a new
// `urlbarView-row-inner`, which will interfere with the ability of
// `#selectElement()` to clear the old selection after replacement, below.
let isSelected = this.#getSelectedRow() == row;
if (isSelected) {
this.#selectElement(null, { updateInput: false });
}
this.#setRowSelectable(row, false);
// Replace the row with a dismissal acknowledgment tip.
let tip = Object.assign(
new lazy.UrlbarResult(
lazy.UrlbarUtils.RESULT_TYPE.TIP,
lazy.UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
type: "dismissalAcknowledgment",
titleL10n,
buttons: [{ l10n: { id: "urlbar-search-tips-confirm-short" } }],
icon: "chrome://branding/content/icon32.png",
}
),
{ rowLabel: this.#rowLabel(row) }
);
this.#updateRow(row, tip);
this.#updateIndices();
// If the row was selected, move the selection to the tip button.
if (isSelected) {
this.#selectElement(this.#getNextSelectableElement(row), {
updateInput: false,
});
}
}
removeAccessibleFocus() {
this.#setAccessibleFocus(null);
}
clear() {
this.#rows.textContent = "";
this.panel.setAttribute("noresults", "true");
this.clearSelection();
this.visibleResults = [];
}
/**
* Closes the view, cancelling the query if necessary.
*
* @param {object} options Options object
* @param {boolean} [options.elementPicked]
* True if the view is being closed because a result was picked.
* @param {boolean} [options.showFocusBorder]
* True if the Urlbar focus border should be shown after the view is closed.
*/
close({ elementPicked = false, showFocusBorder = true } = {}) {
this.controller.cancelQuery();
// We do not show the focus border when an element is picked because we'd
// flash it just before the input is blurred. The focus border is removed
// in UrlbarInput._on_blur.
if (!elementPicked && showFocusBorder) {
this.input.removeAttribute("suppress-focus-border");
}
if (!this.isOpen) {
return;
}
this.#inputWidthOnLastClose = getBoundsWithoutFlushing(
this.input.textbox
).width;
// We exit search mode preview on close since the result previewing it is
// implicitly unselected.
if (this.input.searchMode?.isPreview) {
this.input.searchMode = null;
}
this.resultMenu.hidePopup();
this.removeAccessibleFocus();
this.input.inputField.setAttribute("aria-expanded", "false");
this.#openPanelInstance = null;
this.#previousTabToSearchEngine = null;
this.input.removeAttribute("open");
this.input.endLayoutExtend();
// Search Tips can open the view without the Urlbar being focused. If the
// tip is ignored (e.g. the page content is clicked or the window loses
// focus) we should discard the telemetry event created when the view was
// opened.
if (!this.input.focused && !elementPicked) {
this.controller.engagementEvent.discard();
this.controller.engagementEvent.record(null, {});
}
this.window.removeEventListener("resize", this);
this.window.removeEventListener("blur", this);
this.controller.notify(this.controller.NOTIFICATIONS.VIEW_CLOSE);
// Revoke icon blob URLs that were created while the view was open.
if (this.#blobUrlsByResultUrl) {
for (let blobUrl of this.#blobUrlsByResultUrl.values()) {
URL.revokeObjectURL(blobUrl);
}
this.#blobUrlsByResultUrl.clear();
}
if (this.#isShowingZeroPrefix) {
if (elementPicked) {
Services.telemetry.scalarAdd(ZERO_PREFIX_SCALAR_ENGAGEMENT, 1);
} else {
Services.telemetry.scalarAdd(ZERO_PREFIX_SCALAR_ABANDONMENT, 1);
}
this.#setIsShowingZeroPrefix(false);
}
}
/**
* This can be used to open the view automatically as a consequence of
* specific user actions. For Top Sites searches (without a search string)
* the view is opened only for mouse or keyboard interactions.
* If the user abandoned a search (there is a search string) the view is
* reopened, and we try to use cached results to reduce flickering, then a new
* query is started to refresh results.
*
* @param {object} options Options object
* @param {Event} options.event The event associated with the call to autoOpen.
* @param {boolean} [options.suppressFocusBorder] If true, we hide the focus border
* when the panel is opened. This is true by default to avoid flashing
* the border when the unfocused address bar is clicked.
* @returns {boolean} Whether the view was opened.
*/
autoOpen({ event, suppressFocusBorder = true }) {
if (this.#pickSearchTipIfPresent(event)) {
return false;
}
if (!event) {
return false;
}
let queryOptions = { event };
if (
!this.input.value ||
(this.input.getAttribute("pageproxystate") == "valid" &&
!this.window.gBrowser.selectedBrowser.searchTerms)
) {
if (!this.isOpen && ["mousedown", "command"].includes(event.type)) {
// Try to reuse the cached top-sites context. If it's not cached, then
// there will be a gap of time between when the input is focused and
// when the view opens that can be perceived as flicker.
if (!this.input.searchMode && this.queryContextCache.topSitesContext) {
this.onQueryResults(this.queryContextCache.topSitesContext);
}
this.input.startQuery(queryOptions);
if (suppressFocusBorder) {
this.input.toggleAttribute("suppress-focus-border", true);
}
return true;
}
return false;
}
// Reopen abandoned searches only if the input is focused.
if (!this.input.focused) {
return false;
}
// Tab switch is the only case where we requery if the view is open, because
// switching tabs doesn't necessarily close the view.
if (this.isOpen && event.type != "tabswitch") {
return false;
}
// We can reuse the current rows as they are if the input value and width
// haven't changed since the view was closed. The width check is related to
// row overflow: If we reuse the current rows, overflow and underflow events
// won't fire even if the view's width has changed and there are rows that
// do actually overflow or underflow. That means previously overflowed rows
// may unnecessarily show the overflow gradient, for example.
if (
this.#rows.firstElementChild &&
this.#queryContext.searchString == this.input.value &&
this.#inputWidthOnLastClose ==
getBoundsWithoutFlushing(this.input.textbox).width
) {
// We can reuse the current rows.
queryOptions.allowAutofill = this.#queryContext.allowAutofill;
} else {
// To reduce flickering, try to reuse a cached UrlbarQueryContext. The
// overflow problem is addressed in this case because `onQueryResults()`
// starts the regular view-update process, during which the overflow state
// is reset on all rows.
let cachedQueryContext = this.queryContextCache.get(this.input.value);
if (cachedQueryContext) {
this.onQueryResults(cachedQueryContext);
}
}
this.controller.engagementEvent.discard();
queryOptions.searchString = this.input.value;
queryOptions.autofillIgnoresSelection = true;
queryOptions.event.interactionType = "returned";
// A search tip can be cached in results if it was shown but ignored
// by the user. Don't open the panel if a search tip is present or it
// will cause a flicker since it'll be quickly overwritten (Bug 1812261).
if (
this.#queryContext?.results?.length &&
this.#queryContext.results[0].type != lazy.UrlbarUtils.RESULT_TYPE.TIP
) {
this.#openPanel();
}
// If we had cached results, this will just refresh them, avoiding results
// flicker, otherwise there may be some noise.
this.input.startQuery(queryOptions);
if (suppressFocusBorder) {
this.input.toggleAttribute("suppress-focus-border", true);
}
return true;
}
// UrlbarController listener methods.
onQueryStarted(queryContext) {
this.#queryWasCancelled = false;
this.#queryUpdatedResults = false;
this.#openPanelInstance = null;
if (!queryContext.searchString) {
this.#previousTabToSearchEngine = null;
}
this.#startRemoveStaleRowsTimer();
// Cache l10n strings so they're available when we update the view as
// results arrive. This is a no-op for strings that are already cached.
// `#cacheL10nStrings` is async but we don't await it because doing so would
// require view updates to be async. Instead we just opportunistically cache
// and if there's a cache miss we fall back to `l10n.setAttributes`.
this.#cacheL10nStrings();
}
onQueryCancelled() {
this.#queryWasCancelled = true;
this.#cancelRemoveStaleRowsTimer();
}
onQueryFinished(queryContext) {
this.#cancelRemoveStaleRowsTimer();
if (this.#queryWasCancelled) {
return;
}
// At this point the query finished successfully. If it returned some
// results, remove stale rows. Otherwise remove all rows.
if (this.#queryUpdatedResults) {
this.#removeStaleRows();
} else {
this.clear();
}
// Now that the view has finished updating for this query, call
// `#setIsShowingZeroPrefix()`.
this.#setIsShowingZeroPrefix(!queryContext.searchString);
// If the query returned results, we're done.
if (this.#queryUpdatedResults) {
return;
}
// If search mode isn't active, close the view.
if (!this.input.searchMode) {
this.close();
return;
}
// Search mode is active. If the one-offs should be shown, make sure they
// are enabled and show the view.
let openPanelInstance = (this.#openPanelInstance = {});
this.oneOffSearchButtons.willHide().then(willHide => {
if (!willHide && openPanelInstance == this.#openPanelInstance) {
this.oneOffSearchButtons.enable(true);
this.#openPanel();
}
});
}
onQueryResults(queryContext) {
this.queryContextCache.put(queryContext);
this.#queryContext = queryContext;
if (!this.isOpen) {
this.clear();
}
this.#queryUpdatedResults = true;
this.#updateResults();
let firstResult = queryContext.results[0];
if (queryContext.lastResultCount == 0) {
// Clear the selection when we get a new set of results.
this.#selectElement(null, {
updateInput: false,
});
// Show the one-off search buttons unless any of the following are true:
// * The first result is a search tip
// * The search string is empty
// * The search string starts with an `@` or a search restriction
// character
this.oneOffSearchButtons.enable(
firstResult.providerName != "UrlbarProviderSearchTips" &&
queryContext.trimmedSearchString[0] != "@" &&
(queryContext.trimmedSearchString[0] !=
lazy.UrlbarTokenizer.RESTRICT.SEARCH ||
queryContext.trimmedSearchString.length != 1)
);
}
if (!this.#selectedElement && !this.oneOffSearchButtons.selectedButton) {
if (firstResult.heuristic) {
// Select the heuristic result. The heuristic may not be the first
// result added, which is why we do this check here when each result is
// added and not above.
if (this.#shouldShowHeuristic(firstResult)) {
this.#selectElement(this.#getFirstSelectableElement(), {
updateInput: false,
setAccessibleFocus:
this.controller._userSelectionBehavior == "arrow",
});
} else {
this.input.setResultForCurrentValue(firstResult);
}
} else if (
firstResult.payload.providesSearchMode &&
queryContext.trimmedSearchString != "@"
) {
// Filtered keyword offer results can be in the first position but not
// be heuristic results. We do this so the user can press Tab to select
// them, resembling tab-to-search. In that case, the input value is
// still associated with the first result.
this.input.setResultForCurrentValue(firstResult);
}
}
// Announce tab-to-search results to screen readers as the user types.
// Check to make sure we don't announce the same engine multiple times in
// a row.
let secondResult = queryContext.results[1];
if (
secondResult?.providerName == "TabToSearch" &&
lazy.UrlbarPrefs.get("accessibility.tabToSearch.announceResults") &&
this.#previousTabToSearchEngine != secondResult.payload.engine
) {
let engine = secondResult.payload.engine;
this.window.A11yUtils.announce({
id: secondResult.payload.isGeneralPurposeEngine
? "urlbar-result-action-before-tabtosearch-web"
: "urlbar-result-action-before-tabtosearch-other",
args: { engine },
});
this.#previousTabToSearchEngine = engine;
// Do not set aria-activedescendant when the user tabs to the result
// because we already announced it.
this.#announceTabToSearchOnSelection = false;
}
// If we update the selected element, a new unique ID is generated for it.
// We need to ensure that aria-activedescendant reflects this new ID.
if (this.#selectedElement && !this.oneOffSearchButtons.selectedButton) {
let aadID = this.input.inputField.getAttribute("aria-activedescendant");
if (aadID && !this.document.getElementById(aadID)) {
this.#setAccessibleFocus(this.#selectedElement);
}
}
this.#openPanel();
if (firstResult.heuristic) {
// The heuristic result may be a search alias result, so apply formatting
// if necessary. Conversely, the heuristic result of the previous query
// may have been an alias, so remove formatting if necessary.
this.input.formatValue();
}
if (queryContext.deferUserSelectionProviders.size) {
// DeferUserSelectionProviders block user selection until the result is
// shown, so it's the view's duty to remove them.
// Doing it sooner, like when the results are added by the provider,
// would not suffice because there's still a delay before those results
// reach the view.
queryContext.results.forEach(r => {
queryContext.deferUserSelectionProviders.delete(r.providerName);
});
}
}
/**
* Handles removing a result from the view when it is removed from the query,
* and attempts to select the new result on the same row.
*
* This assumes that the result rows are in index order.
*
* @param {number} index The index of the result that has been removed.
*/
onQueryResultRemoved(index) {
let rowToRemove = this.#rows.children[index];
let { result } = rowToRemove;
if (result.acknowledgeDismissalL10n) {
// Replace the result's row with a dismissal acknowledgment tip.
this.#acknowledgeDismissal(result, result.acknowledgeDismissalL10n);
return;
}
let updateSelection = rowToRemove == this.#getSelectedRow();
rowToRemove.remove();
this.#updateIndices();
if (!updateSelection) {
return;
}
// Select the row at the same index, if possible.
let newSelectionIndex = index;
if (index >= this.#queryContext.results.length) {
newSelectionIndex = this.#queryContext.results.length - 1;
}
if (newSelectionIndex >= 0) {
this.selectedRowIndex = newSelectionIndex;
}
}
openResultMenu(result, anchor) {
this.#resultMenuResult = result;
if (AppConstants.platform == "macosx") {
// `openPopup(anchor)` doesn't use a native context menu, which is very
// noticeable on Mac. Use `openPopup()` with x and y coords instead. See
// bug 1831760 and bug 1710459.
let rect = getBoundsWithoutFlushing(anchor);
rect = this.window.windowUtils.toScreenRectInCSSUnits(
rect.x,
rect.y,
rect.width,
rect.height
);
this.resultMenu.openPopup(null, {
x: rect.x,
y: rect.y + rect.height,
});
} else {
this.resultMenu.openPopup(anchor, "bottomright topright");
}
anchor.toggleAttribute("open", true);
let listener = event => {
if (event.target == this.resultMenu) {
anchor.removeAttribute("open");
this.resultMenu.removeEventListener("popuphidden", listener);
}
};
this.resultMenu.addEventListener("popuphidden", listener);
}
/**
* Clears the result menu commands cache, removing the cached commands for all
* results. This is useful when the commands for one or more results change
* while the results remain in the view.
*/
invalidateResultMenuCommands() {
this.#resultMenuCommands = new WeakMap();
}
/**
* Passes DOM events for the view to the on_<event type> methods.
*
* @param {Event} event
* DOM event from the <view>.
*/
handleEvent(event) {
let methodName = "on_" + event.type;
if (methodName in this) {
this[methodName](event);
} else {
throw new Error("Unrecognized UrlbarView event: " + event.type);
}
}
static dynamicViewTemplatesByName = new Map();
/**
* Registers the view template for a dynamic result type. A view template is
* a plain object that describes the DOM subtree for a dynamic result type.
* When a dynamic result is shown in the urlbar view, its type's view template
* is used to construct the part of the view that represents the result.
*
* The specified view template will be available to the urlbars in all current
* and future browser windows until it is unregistered. A given dynamic
* result type has at most one view template. If this method is called for a
* dynamic result type more than once, the view template in the last call
* overrides those in previous calls.
*
* @param {string} name
* The view template will be registered for the dynamic result type with
* this name.
* @param {object} viewTemplate
* This object describes the DOM subtree for the given dynamic result type.
* It should be a tree-like nested structure with each object in the nesting
* representing a DOM element to be created. This tree-like structure is
* achieved using the `children` property described below. Each object in
* the structure may include the following properties:
*
* {string} name
* The name of the object. It is required for all objects in the
* structure except the root object and serves two important functions:
* (1) The element created for the object will automatically have a class
* named `urlbarView-dynamic-${dynamicType}-${name}`, where
* `dynamicType` is the name of the dynamic result type. The element
* will also automatically have an attribute "name" whose value is
* this name. The class and attribute allow the element to be styled
* in CSS.
* (2) The name is used when updating the view. See
* UrlbarProvider.getViewUpdate().
* Names must be unique within a view template, but they don't need to be
* globally unique. i.e., two different view templates can use the same
* names, and other DOM elements can use the same names in their IDs and
* classes. The name also suffixes the dynamic element's ID: an element
* with name `data` will get the ID `urlbarView-row-{unique number}-data`.
* If there is no name provided for the root element, the root element
* will not get an ID.
* {string} tag
* The tag name of the object. It is required for all objects in the
* structure except the root object and declares the kind of element that
* will be created for the object: span, div, img, etc.
* {object} [attributes]
* An optional mapping from attribute names to values. For each
* name-value pair, an attribute is added to the element created for the
* object. The `id` attribute is reserved and cannot be set by the
* provider. Element IDs are passed back to the provider in getViewUpdate
* if they are needed.
* {array} [children]
* An optional list of children. Each item in the array must be an object
* as described here. For each item, a child element as described by the
* item is created and added to the element created for the parent object.
* {array} [classList]
* An optional list of classes. Each class will be added to the element
* created for the object by calling element.classList.add().
* {boolean} [overflowable]
* If true, the element's overflow status will be tracked in order to
* fade it out when needed.
* {string} [stylesheet]
* An optional stylesheet URL. This property is valid only on the root
* object in the structure. The stylesheet will be loaded in all browser
* windows so that the dynamic result type view may be styled.
*/
static addDynamicViewTemplate(name, viewTemplate) {
this.dynamicViewTemplatesByName.set(name, viewTemplate);
if (viewTemplate.stylesheet) {
for (let window of lazy.BrowserWindowTracker.orderedWindows) {
addDynamicStylesheet(window, viewTemplate.stylesheet);
}
}
}
/**
* Unregisters the view template for a dynamic result type.
*
* @param {string} name
* The view template will be unregistered for the dynamic result type with
* this name.
*/
static removeDynamicViewTemplate(name) {
let viewTemplate = this.dynamicViewTemplatesByName.get(name);
if (!viewTemplate) {
return;
}
this.dynamicViewTemplatesByName.delete(name);
if (viewTemplate.stylesheet) {
for (let window of lazy.BrowserWindowTracker.orderedWindows) {
removeDynamicStylesheet(window, viewTemplate.stylesheet);
}
}
}
// Private properties and methods below.
#announceTabToSearchOnSelection;
#blobUrlsByResultUrl = null;
#inputWidthOnLastClose = 0;
#l10nCache;
#mousedownSelectedElement;
#openPanelInstance;
#oneOffSearchButtons;
#previousTabToSearchEngine;
#queryContext;
#queryUpdatedResults;
#queryWasCancelled;
#removeStaleRowsTimer;
#resultMenuResult;
#resultMenuCommands;
#rows;
#rawSelectedElement;
#zeroPrefixStopwatchInstance = null;
/**
* #rawSelectedElement may be disconnected from the DOM (e.g. it was remove()d)
* but we want a connected #selectedElement usually. We don't use a WeakRef
* because it would depend too much on GC timing.
*
* @returns {DOMElement} the selected element.
*/
get #selectedElement() {
return this.#rawSelectedElement?.isConnected
? this.#rawSelectedElement
: null;
}
#createElement(name) {
return this.document.createElementNS("http://www.w3.org/1999/xhtml", name);
}
#openPanel() {
if (this.isOpen) {
return;
}
this.controller.userSelectionBehavior = "none";
this.panel.removeAttribute("action-override");
this.#enableOrDisableRowWrap();
this.input.inputField.setAttribute("aria-expanded", "true");
this.input.toggleAttribute("suppress-focus-border", true);
this.input.toggleAttribute("open", true);
this.input.startLayoutExtend();
this.window.addEventListener("resize", this);
this.window.addEventListener("blur", this);
this.controller.notify(this.controller.NOTIFICATIONS.VIEW_OPEN);
}
#shouldShowHeuristic(result) {
if (!result?.heuristic) {
throw new Error("A heuristic result must be given");
}
return (
!lazy.UrlbarPrefs.get("experimental.hideHeuristic") ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP
);
}
/**
* Whether a result is a search suggestion.
*
* @param {UrlbarResult} result The result to examine.
* @returns {boolean} Whether the result is a search suggestion.
*/
#resultIsSearchSuggestion(result) {
return Boolean(
result &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.payload.suggestion
);
}
/**
* Checks whether the given row index can be update to the result we want
* to apply. This is used in #updateResults to avoid flickering of results, by
* reusing existing rows.
*
* @param {number} rowIndex Index of the row to examine.
* @param {UrlbarResult} result The result we'd like to apply.
* @param {boolean} seenSearchSuggestion Whether the view update has
* encountered an existing row with a search suggestion result.
* @returns {boolean} Whether the row can be updated to this result.
*/
#rowCanUpdateToResult(rowIndex, result, seenSearchSuggestion) {
// The heuristic result must always be current, thus it's always compatible.
// Note that the `updateResults` code, when updating the selection, relies
// on the fact the heuristic is the first selectable row.
if (result.heuristic) {
return true;
}
let row = this.#rows.children[rowIndex];
// Don't replace a suggestedIndex result with a non-suggestedIndex result
// or vice versa.
if (result.hasSuggestedIndex != row.result.hasSuggestedIndex) {
return false;
}
// Don't replace a suggestedIndex result with another suggestedIndex
// result if the suggestedIndex values are different.
if (
result.hasSuggestedIndex &&
result.suggestedIndex != row.result.suggestedIndex
) {
return false;
}
// To avoid flickering results while typing, don't try to reuse results from
// different providers.
// For example user types "moz", provider A returns results much earlier
// than provider B, but results from provider B stabilize in the view at the
// end of the search. Typing the next letter "i" results from the faster
// provider A would temporarily replace old results from provider B, just
// to be replaced as soon as provider B returns its results.
if (result.providerName != row.result.providerName) {
return false;
}
let resultIsSearchSuggestion = this.#resultIsSearchSuggestion(result);
// If the row is same type, just update it.
if (
resultIsSearchSuggestion == this.#resultIsSearchSuggestion(row.result)
) {
return true;
}
// If the row has a different type, update it if we are in a compatible
// index range.
// In practice we don't want to overwrite a search suggestion with a non
// search suggestion, but we allow the opposite.
return resultIsSearchSuggestion && seenSearchSuggestion;
}
#updateResults() {
// TODO: For now this just compares search suggestions to the rest, in the
// future we should make it support any type of result. Or, even better,
// results should be grouped, thus we can directly update groups.
// Discard tentative exposures. This is analogous to marking the
// hypothetical hidden rows of hidden-exposure results as stale.
this.controller.engagementEvent.discardTentativeExposures();
// Walk rows and find an insertion index for results. To avoid flicker, we
// skip rows until we find one compatible with the result we want to apply.
// If we couldn't find a compatible range, we'll just update.
let results = this.#queryContext.results;
if (results[0]?.heuristic && !this.#shouldShowHeuristic(results[0])) {
// Exclude the heuristic.
results = results.slice(1);
}
let rowIndex = 0;
let resultIndex = 0;
let visibleSpanCount = 0;
let seenMisplacedResult = false;
let seenSearchSuggestion = false;
// We can have more rows than the visible ones.
for (
;
rowIndex < this.#rows.children.length && resultIndex < results.length;
++rowIndex
) {
let row = this.#rows.children[rowIndex];
if (this.#isElementVisible(row)) {
visibleSpanCount += lazy.UrlbarUtils.getSpanForResult(row.result);
}
// Continue updating rows as long as we haven't encountered a new
// suggestedIndex result that couldn't replace a current result.
if (!seenMisplacedResult) {
let result = results[resultIndex];
seenSearchSuggestion =
seenSearchSuggestion ||
(!row.result.heuristic && this.#resultIsSearchSuggestion(row.result));
if (
this.#rowCanUpdateToResult(rowIndex, result, seenSearchSuggestion)
) {
// We can replace the row's current result with the new one.
if (result.exposureResultHidden) {
this.controller.engagementEvent.addExposure(result);
} else {
this.#updateRow(row, result);
}
resultIndex++;
continue;
}
if (
(result.hasSuggestedIndex || row.result.hasSuggestedIndex) &&
!result.exposureResultHidden
) {
seenMisplacedResult = true;
}
}
row.setAttribute("stale", "true");
}
// Mark all the remaining rows as stale and update the visible span count.
// We include stale rows in the count because we should never show more than
// maxResults spans at one time. Later we'll remove stale rows and unhide
// excess non-stale rows.
for (; rowIndex < this.#rows.children.length; ++rowIndex) {
let row = this.#rows.children[rowIndex];
row.setAttribute("stale", "true");
if (this.#isElementVisible(row)) {
visibleSpanCount += lazy.UrlbarUtils.getSpanForResult(row.result);
}
}
// Add remaining results, if we have fewer rows than results.
for (; resultIndex < results.length; ++resultIndex) {
let result = results[resultIndex];
if (
!seenMisplacedResult &&
result.hasSuggestedIndex &&
!result.exposureResultHidden
) {
if (result.isSuggestedIndexRelativeToGroup) {
// We can't know at this point what the right index of a group-
// relative suggestedIndex result will be. To avoid all all possible
// flicker, don't make it (and all rows after it) visible until stale
// rows are removed.
seenMisplacedResult = true;
} else {
// We need to check whether the new suggestedIndex result will end up
// at its right index if we append it here. The "right" index is the
// final index the result will occupy once the update is done and all
// stale rows have been removed. We could use a more flexible
// definition, but we use this strict one in order to avoid all
// perceived flicker and movement of suggestedIndex results. Once
// stale rows are removed, the final number of rows in the view will
// be the new result count, so we base our arithmetic here on it.
let finalIndex =
result.suggestedIndex >= 0
? Math.min(results.length - 1, result.suggestedIndex)
: Math.max(0, results.length + result.suggestedIndex);
if (this.#rows.children.length != finalIndex) {
seenMisplacedResult = true;
}
}
}
let newSpanCount =
visibleSpanCount +
lazy.UrlbarUtils.getSpanForResult(result, {
includeExposureResultHidden: true,
});
let canBeVisible =
newSpanCount <= this.#queryContext.maxResults && !seenMisplacedResult;
if (result.exposureResultHidden) {
if (canBeVisible) {
this.controller.engagementEvent.addExposure(result);
} else {
// Add a tentative exposure: The hypothetical row for this
// hidden-exposure result can't be visible now, but as long as it were
// not marked stale in a later update, it would be shown when stale
// rows are removed.
this.controller.engagementEvent.addTentativeExposure(result);
}
continue;
}
let row = this.#createRow();
this.#updateRow(row, result);
if (canBeVisible) {
visibleSpanCount = newSpanCount;
} else {
// The new row must be hidden at first because the view is already
// showing maxResults spans, or we encountered a new suggestedIndex
// result that couldn't be placed in the right spot. We'll show it when
// stale rows are removed.
this.#setRowVisibility(row, false);
}
this.#rows.appendChild(row);
}
this.#updateIndices();
}
#createRow() {
let item = this.#createElement("div");
item.className = "urlbarView-row";
item._elements = new Map();
item._buttons = new Map();
// A note about row selection. Any element in a row that can be selected
// will have the `selectable` attribute set on it. For typical rows, the
// selectable element is not the `.urlbarView-row` itself but rather the
// `.urlbarView-row-inner` inside it. That's because the `.urlbarView-row`
// also contains the row's buttons, which should not be selected when the
// main part of the row -- `.urlbarView-row-inner` -- is selected.
//
// Since it's the row itself and not the row-inner that is a child of the
// `role=listbox` element (the rows container, `this.#rows`), screen readers
// will not automatically recognize the row-inner as a listbox option. To
// compensate, we set `role=option` on the row-inner and `role=presentation`
// on the row itself so that screen readers ignore it.
item.setAttribute("role", "presentation");
// These are used to cleanup result specific entities when row contents are
// cleared to reuse the row for a different result.
item._sharedAttributes = new Set(
[...item.attributes].map(v => v.name).concat(["stale", "id"])
);
item._sharedClassList = new Set(item.classList);
return item;
}
#createRowContent(item) {
// The url is the only element that can wrap, thus all the other elements
// are child of noWrap.
let noWrap = this.#createElement("span");
noWrap.className = "urlbarView-no-wrap";
item._content.appendChild(noWrap);
let favicon = this.#createElement("img");
favicon.className = "urlbarView-favicon";
noWrap.appendChild(favicon);
item._elements.set("favicon", favicon);
let typeIcon = this.#createElement("span");
typeIcon.className = "urlbarView-type-icon";
noWrap.appendChild(typeIcon);
let tailPrefix = this.#createElement("span");
tailPrefix.className = "urlbarView-tail-prefix";
noWrap.appendChild(tailPrefix);
item._elements.set("tailPrefix", tailPrefix);
// tailPrefix holds text only for alignment purposes so it should never be
// read to screen readers.
tailPrefix.toggleAttribute("aria-hidden", true);
let tailPrefixStr = this.#createElement("span");
tailPrefixStr.className = "urlbarView-tail-prefix-string";
tailPrefix.appendChild(tailPrefixStr);
item._elements.set("tailPrefixStr", tailPrefixStr);
let tailPrefixChar = this.#createElement("span");
tailPrefixChar.className = "urlbarView-tail-prefix-char";
tailPrefix.appendChild(tailPrefixChar);
item._elements.set("tailPrefixChar", tailPrefixChar);
let title = this.#createElement("span");
title.classList.add("urlbarView-title", "urlbarView-overflowable");
noWrap.appendChild(title);
item._elements.set("title", title);
let tagsContainer = this.#createElement("span");
tagsContainer.classList.add("urlbarView-tags", "urlbarView-overflowable");
noWrap.appendChild(tagsContainer);
item._elements.set("tagsContainer", tagsContainer);
let titleSeparator = this.#createElement("span");
titleSeparator.className = "urlbarView-title-separator";
noWrap.appendChild(titleSeparator);
item._elements.set("titleSeparator", titleSeparator);
let action = this.#createElement("span");
action.className = "urlbarView-action";
noWrap.appendChild(action);
item._elements.set("action", action);
let url = this.#createElement("span");
url.className = "urlbarView-url";
item._content.appendChild(url);
item._elements.set("url", url);
}
/**
* @param {Element} node
* The element to set attributes on.
* @param {object} attributes
* Attribute names to values mapping. For each name-value pair, an
* attribute is set on the element, except for `null` as a value which
* signals an attribute should be removed, and `undefined` in which case
* the attribute won't be set nor removed. The `id` attribute is reserved
* and cannot be set here.
*/
#setDynamicAttributes(node, attributes) {
if (!attributes) {
return;
}
for (let [name, value] of Object.entries(attributes)) {
if (name == "id") {
// IDs are managed externally to ensure they are unique.
console.error(
`Not setting id="${value}", as dynamic attributes may not include IDs.`
);
continue;
}
if (value === undefined) {
continue;
}
if (value === null) {
node.removeAttribute(name);
} else if (typeof value == "boolean") {
node.toggleAttribute(name, value);
} else {
node.setAttribute(name, value);
}
}
}
#createRowContentForDynamicType(item, result) {
let { dynamicType } = result.payload;
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
let viewTemplate =
provider.getViewTemplate?.(result) ||
UrlbarView.dynamicViewTemplatesByName.get(dynamicType);
if (!viewTemplate) {
console.error(`No viewTemplate found for ${result.providerName}`);
return;
}
let classes = this.#buildViewForDynamicType(
dynamicType,
item._content,
item._elements,
viewTemplate
);
item.toggleAttribute("has-url", classes.has("urlbarView-url"));
item.toggleAttribute("has-action", classes.has("urlbarView-action"));
this.#setRowSelectable(item, item._content.hasAttribute("selectable"));
}
/**
* Recursively builds a row's DOM for a dynamic result type.
*
* @param {string} type
* The name of the dynamic type.
* @param {Element} parentNode
* The element being recursed into. Pass `row._content`
* (i.e., the row's `.urlbarView-row-inner`) to start with.
* @param {Map} elementsByName
* The `row._elements` map.
* @param {object} template
* The template object being recursed into. Pass the top-level template
* object to start with.
* @param {Set} classes
* The CSS class names of all elements in the row's subtree are recursively
* collected in this set. Don't pass anything to start with so that the
* default argument, a new Set, is used.
* @returns {Set}
* The `classes` set, which on return will contain the CSS class names of
* all elements in the row's subtree.
*/
#buildViewForDynamicType(
type,
parentNode,
elementsByName,
template,
classes = new Set()
) {
// Set attributes on parentNode.
this.#setDynamicAttributes(parentNode, template.attributes);
// Add classes to parentNode's classList.
if (template.classList) {
parentNode.classList.add(...template.classList);
for (let c of template.classList) {
classes.add(c);
}
}
if (template.overflowable) {
parentNode.classList.add("urlbarView-overflowable");
}
if (template.name) {
parentNode.setAttribute("name", template.name);
elementsByName.set(template.name, parentNode);
}
// Recurse into children.
for (let childTemplate of template.children || []) {
let child = this.#createElement(childTemplate.tag);
child.classList.add(`urlbarView-dynamic-${type}-${childTemplate.name}`);
parentNode.appendChild(child);
this.#buildViewForDynamicType(
type,
child,
elementsByName,
childTemplate,
classes
);
}
return classes;
}
#createRowContentForRichSuggestion(item) {
item._content.toggleAttribute("selectable", true);
let favicon = this.#createElement("img");
favicon.className = "urlbarView-favicon";
item._content.appendChild(favicon);
item._elements.set("favicon", favicon);
let body = this.#createElement("span");
body.className = "urlbarView-row-body";
item._content.appendChild(body);
let top = this.#createElement("div");
top.className = "urlbarView-row-body-top";
body.appendChild(top);
let noWrap = this.#createElement("div");
noWrap.className = "urlbarView-row-body-top-no-wrap";
top.appendChild(noWrap);
item._elements.set("noWrap", noWrap);
let title = this.#createElement("span");
title.classList.add("urlbarView-title", "urlbarView-overflowable");
noWrap.appendChild(title);
item._elements.set("title", title);
let titleSeparator = this.#createElement("span");
titleSeparator.className = "urlbarView-title-separator";
noWrap.appendChild(titleSeparator);
item._elements.set("titleSeparator", titleSeparator);
let action = this.#createElement("span");
action.className = "urlbarView-action";
noWrap.appendChild(action);
item._elements.set("action", action);
let url = this.#createElement("span");
url.className = "urlbarView-url";
top.appendChild(url);
item._elements.set("url", url);
let description = this.#createElement("div");
description.classList.add("urlbarView-row-body-description");
body.appendChild(description);
item._elements.set("description", description);
let bottom = this.#createElement("div");
bottom.className = "urlbarView-row-body-bottom";
body.appendChild(bottom);
item._elements.set("bottom", bottom);
}
#addRowButtons(item, result) {
for (let i = 0; i < result.payload.buttons?.length; i++) {
this.#addRowButton(item, {
name: i.toString(),
...result.payload.buttons[i],
});
}
// TODO: `buttonText` is intended only for WebExtensions. We should remove
// it and the WebExtensions urlbar API since we're no longer using it.
if (result.payload.buttonText) {
this.#addRowButton(item, {
name: "tip",
url: result.payload.buttonUrl,
});
item._buttons.get("tip").textContent = result.payload.buttonText;
}
if (this.#getResultMenuCommands(result)) {
this.#addRowButton(item, {
name: "menu",
l10n: {
id: result.showFeedbackMenu
? "urlbar-result-menu-button-feedback"
: "urlbar-result-menu-button",
},
attributes: lazy.UrlbarPrefs.get("resultMenu.keyboardAccessible")
? null
: {
"keyboard-inaccessible": true,
},
});
}
}
#addRowButton(item, { name, command, l10n, url, attributes }) {
let button = this.#createElement("span");
this.#setDynamicAttributes(button, attributes);
button.id = `${item.id}-button-${name}`;
button.classList.add("urlbarView-button", "urlbarView-button-" + name);
button.setAttribute("role", "button");
button.dataset.name = name;
if (l10n) {
this.#setElementL10n(button, l10n);
}
if (command) {
button.dataset.command = command;
}
if (url) {
button.dataset.url = url;
}
item._buttons.set(name, button);
item.appendChild(button);
}
#createSecondaryAction(action, global = false) {
let actionContainer = this.#createElement("div");
actionContainer.classList.add("urlbarView-actions-container");
let button = this.#createElement("span");
button.classList.add("urlbarView-action-btn");
if (global) {
button.classList.add("urlbarView-global-action-btn");
}
button.setAttribute("role", "button");
if (action.icon) {
let icon = this.#createElement("img");
icon.src = action.icon;
button.appendChild(icon);
}
for (let key in action.dataset ?? {}) {
button.dataset[key] = action.dataset[key];
}
button.dataset.action = action.key;
button.dataset.providerName = action.providerName;
let label = this.#createElement("span");
if (action.l10nId) {
this.#setElementL10n(label, { id: action.l10nId, args: action.l10nArgs });
} else {
this.document.l10n.setAttributes(label, action.label, action.l10nArgs);
}
button.appendChild(label);
actionContainer.appendChild(button);
return actionContainer;
}
// eslint-disable-next-line complexity
#updateRow(item, result) {
let oldResult = item.result;
let oldResultType = item.result?.type;
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
item.result = result;
item.removeAttribute("stale");
item.id = getUniqueId("urlbarView-row-");
let needsNewContent =
oldResultType === undefined ||
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) !=
(result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) ||
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC &&
oldResult.payload.dynamicType != result.payload.dynamicType) ||
// Dynamic results that implement getViewTemplate will
// always need updating.
provider?.getViewTemplate ||
oldResult.isRichSuggestion != result.isRichSuggestion ||
!!this.#getResultMenuCommands(result) != item._buttons.has("menu") ||
!!oldResult.showFeedbackMenu != !!result.showFeedbackMenu ||
!lazy.ObjectUtils.deepEqual(
oldResult.payload.buttons,
result.payload.buttons
) ||
// Reusing a non-heuristic as a heuristic is risky as it may have DOM
// nodes/attributes/classes that are normally not present in a heuristic
// result. This may happen for example when switching from a zero-prefix
// search not having a heuristic to a search string one.
result.heuristic != oldResult.heuristic ||
// Container switch-tab results have a more complex DOM content that is
// only updated correctly by another switch-tab result.
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH &&
lazy.UrlbarProviderOpenTabs.isContainerUserContextId(
oldResult.payload.userContextId
) &&
result.type != oldResultType) ||
result.testForceNewContent;
if (needsNewContent) {
while (item.lastChild) {
item.lastChild.remove();
}
item._elements.clear();
item._buttons.clear();
item._content = this.#createElement("span");
item._content.className = "urlbarView-row-inner";
item.appendChild(item._content);
// Clear previously set attributes and classes that may refer to a
// different result type.
for (const attribute of item.attributes) {
if (!item._sharedAttributes.has(attribute.name)) {
item.removeAttribute(attribute.name);
}
}
for (const className of item.classList) {
if (!item._sharedClassList.has(className)) {
item.classList.remove(className);
}
}
if (item.result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) {
this.#createRowContentForDynamicType(item, result);
} else if (result.isRichSuggestion) {
this.#createRowContentForRichSuggestion(item, result);
} else {
this.#createRowContent(item, result);
}
this.#addRowButtons(item, result);
}
item._content.id = item.id + "-inner";
let isFirstChild = item === this.#rows.children[0];
let secAction =
result.heuristic || isFirstChild
? lazy.UrlbarProvidersManager.getGlobalAction()
: result.payload.action;
let container = item.querySelector(".urlbarView-actions-container");
if (secAction && !container) {
item.appendChild(this.#createSecondaryAction(secAction, isFirstChild));
} else if (
secAction &&
secAction.key != container.firstChild.dataset.action
) {
item.replaceChild(
this.#createSecondaryAction(secAction, isFirstChild),
container
);
} else if (!secAction && container) {
item.removeChild(container);
}
item.removeAttribute("feedback-acknowledgment");
if (
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
!result.payload.providesSearchMode &&
!result.payload.inPrivateWindow
) {
item.setAttribute("type", "search");
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB) {
item.setAttribute("type", "remotetab");
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH) {
item.setAttribute("type", "switchtab");
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP) {
item.setAttribute("type", "tip");
item.setAttribute("tip-type", result.payload.type);
// Due to role=button, the button and help icon can sometimes become
// focused. We want to prevent that because the input should always be
// focused instead. (This happens when input.search("", { focus: false })
// is called, a tip is the first result but not heuristic, and the user
// tabs the into the button from the navbar buttons. The input is skipped
// and the focus goes straight to the tip button.)
item.addEventListener("focus", () => this.input.focus(), true);
if (
result.providerName == "UrlbarProviderSearchTips" ||
result.payload.type == "dismissalAcknowledgment"
) {
// For a11y, we treat search tips as alerts. We use A11yUtils.announce
// instead of role="alert" because role="alert" will only fire an alert
// event when the alert (or something inside it) is the root of an
// insertion. In this case, the entire tip result gets inserted into the
// a11y tree as a single insertion, so no alert event would be fired.
this.window.A11yUtils.announce(result.payload.titleL10n);
}
} else if (result.source == lazy.UrlbarUtils.RESULT_SOURCE.BOOKMARKS) {
item.setAttribute("type", "bookmark");
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) {
item.setAttribute("type", "dynamic");
this.#updateRowForDynamicType(item, result);
return;
} else if (result.providerName == "TabToSearch") {
item.setAttribute("type", "tabtosearch");
} else {
item.setAttribute(
"type",
lazy.UrlbarUtils.searchEngagementTelemetryType(result)
);
}
let favicon = item._elements.get("favicon");
favicon.src = this.#iconForResult(result);
let title = item._elements.get("title");
this.#setResultTitle(result, title);
if (result.payload.tail && result.payload.tailOffsetIndex > 0) {
this.#fillTailSuggestionPrefix(item, result);
title.setAttribute("aria-label", result.payload.suggestion);
item.toggleAttribute("tail-suggestion", true);
} else {
item.removeAttribute("tail-suggestion");
title.removeAttribute("aria-label");
}
this.#updateOverflowTooltip(title, result.title);
let tagsContainer = item._elements.get("tagsContainer");
if (tagsContainer) {
tagsContainer.textContent = "";
if (result.payload.tags && result.payload.tags.length) {
tagsContainer.append(
...result.payload.tags.map((tag, i) => {
const element = this.#createElement("span");
element.className = "urlbarView-tag";
this.#addTextContentWithHighlights(
element,
tag,
result.payloadHighlights.tags[i]
);
return element;
})
);
}
}
let action = item._elements.get("action");
let actionSetter = null;
let isVisitAction = false;
let setURL = false;
let isRowSelectable = true;
switch (result.type) {
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
// Hide chichlet when showing secondaryActions.
if (lazy.UrlbarPrefs.get("secondaryActions.featureGate")) {
break;
}
actionSetter = () => {
this.#setSwitchTabActionChiclet(result, action);
};
setURL = true;
break;
case lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
actionSetter = () => {
this.#removeElementL10n(action);
action.textContent = result.payload.device;
};
setURL = true;
break;
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH:
if (result.payload.inPrivateWindow) {
if (result.payload.isPrivateEngine) {
actionSetter = () => {
this.#setElementL10n(action, {
id: "urlbar-result-action-search-in-private-w-engine",
args: { engine: result.payload.engine },
});
};
} else {
actionSetter = () => {
this.#setElementL10n(action, {
id: "urlbar-result-action-search-in-private",
});
};
}
} else if (result.providerName == "TabToSearch") {
actionSetter = () => {
this.#setElementL10n(action, {
id: result.payload.isGeneralPurposeEngine
? "urlbar-result-action-tabtosearch-web"
: "urlbar-result-action-tabtosearch-other-engine",
args: { engine: result.payload.engine },
});
};
} else if (!result.payload.providesSearchMode) {
actionSetter = () => {
this.#setElementL10n(action, {
id: "urlbar-result-action-search-w-engine",
args: { engine: result.payload.engine },
});
};
}
break;
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
isVisitAction = result.payload.input.trim() == result.payload.keyword;
break;
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
actionSetter = () => {
this.#removeElementL10n(action);
action.textContent = result.payload.content;
};
break;
case lazy.UrlbarUtils.RESULT_TYPE.TIP:
isRowSelectable = false;
break;
case lazy.UrlbarUtils.RESULT_TYPE.URL:
if (result.providerName == "UrlbarProviderClipboard") {
result.payload.displayUrl = "";
actionSetter = () => {
this.#setElementL10n(action, {
id: "urlbar-result-action-visit-from-clipboard",
});
};
title.toggleAttribute("is-url", true);
let label = { id: "urlbar-result-action-visit-from-clipboard" };
this.#l10nCache.ensure(label).then(() => {
let { value } = this.#l10nCache.get(label);
// We don't have to unset these attributes because, excluding heuristic results,
// we never reuse results from different providers. Thus clipboard results can
// only be reused by other clipboard results.
title.setAttribute("aria-label", `${value}, ${title.innerText}`);
action.setAttribute("aria-hidden", "true");
});
break;
}
// fall-through
default:
if (result.heuristic && !result.payload.title) {
isVisitAction = true;
} else if (
result.providerName != lazy.UrlbarProviderQuickSuggest.name ||
result.payload.shouldShowUrl
) {
setURL = true;
}
break;
}
this.#setRowSelectable(item, isRowSelectable);
action.toggleAttribute("slide-in", result.providerName == "TabToSearch");
item.toggleAttribute("pinned", !!result.payload.isPinned);
let sponsored =
result.payload.isSponsored &&
result.type != lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH &&
result.providerName != lazy.UrlbarProviderQuickSuggest.name;
item.toggleAttribute("sponsored", !!sponsored);
if (sponsored) {
actionSetter = () => {
this.#setElementL10n(action, {
id: "urlbar-result-action-sponsored",
});
};
}
item.toggleAttribute("rich-suggestion", !!result.isRichSuggestion);
if (result.isRichSuggestion) {
this.#updateRowForRichSuggestion(item, result);
}
item.toggleAttribute("has-url", setURL);
let url = item._elements.get("url");
if (setURL) {
let displayedUrl = result.payload.displayUrl;
let urlHighlights = result.payloadHighlights.displayUrl || [];
if (lazy.UrlbarUtils.isTextDirectionRTL(displayedUrl, this.window)) {
// Stripping the url prefix may change the initial text directionality,
// causing parts of it to jump to the end. To prevent that we insert a
// LRM character in place of the prefix.
displayedUrl = "\u200e" + displayedUrl;
urlHighlights = this.#offsetHighlights(urlHighlights, 1);
}
this.#addTextContentWithHighlights(url, displayedUrl, urlHighlights);
this.#updateOverflowTooltip(url, result.payload.displayUrl);
} else {
url.textContent = "";
this.#updateOverflowTooltip(url, "");
}
title.toggleAttribute("is-url", isVisitAction);
if (isVisitAction) {
actionSetter = () => {
this.#setElementL10n(action, {
id: "urlbar-result-action-visit",
});
};
}
item.toggleAttribute("has-action", actionSetter);
if (actionSetter) {
actionSetter();
item._originalActionSetter = actionSetter;
} else {
item._originalActionSetter = () => {
this.#removeElementL10n(action);
action.textContent = "";
};
item._originalActionSetter();
}
if (!title.hasAttribute("is-url")) {
title.setAttribute("dir", "auto");
} else {
title.removeAttribute("dir");
}
}
#setRowSelectable(item, isRowSelectable) {
item.toggleAttribute("row-selectable", isRowSelectable);
item._content.toggleAttribute("selectable", isRowSelectable);
if (isRowSelectable) {
item._content.setAttribute("role", "option");
} else {
item._content.removeAttribute("role");
}
}
#iconForResult(result, iconUrlOverride = null) {
if (
result.source == lazy.UrlbarUtils.RESULT_SOURCE.HISTORY &&
(result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.KEYWORD)
) {
return lazy.UrlbarUtils.ICON.HISTORY;
}
if (iconUrlOverride) {
return iconUrlOverride;
}
if (result.payload.icon) {
return result.payload.icon;
}
if (result.payload.iconBlob) {
// Blob icons are currently limited to Suggest results, which will define
// a `payload.originalUrl` if the result URL contains timestamp templates
// that are replaced at query time.
let resultUrl = result.payload.originalUrl || result.payload.url;
if (resultUrl) {
let blobUrl = this.#blobUrlsByResultUrl?.get(resultUrl);
if (!blobUrl) {
blobUrl = URL.createObjectURL(result.payload.iconBlob);
// Since most users will not trigger results with blob icons, we
// create this map lazily.
this.#blobUrlsByResultUrl ||= new Map();
this.#blobUrlsByResultUrl.set(resultUrl, blobUrl);
}
return blobUrl;
}
}
if (
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.payload.trending
) {
return lazy.UrlbarUtils.ICON.TRENDING;
}
if (
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.KEYWORD
) {
return lazy.UrlbarUtils.ICON.SEARCH_GLASS;
}
return lazy.UrlbarUtils.ICON.DEFAULT;
}
async #updateRowForDynamicType(item, result) {
item.setAttribute("dynamicType", result.payload.dynamicType);
let idsByName = new Map();
for (let [name, node] of item._elements) {
node.id = `${item.id}-${name}`;
idsByName.set(name, node.id);
}
// First, apply highlighting. We do this before updating via getViewUpdate
// so the dynamic provider can override the highlighting by setting the
// textContent of the highlighted node, if it wishes.
for (let [payloadName, highlights] of Object.entries(
result.payloadHighlights
)) {
if (!highlights.length) {
continue;
}
// Highlighting only works if the dynamic element name is the same as the
// highlighted payload property name.
let nodeToHighlight = item.querySelector(`#${item.id}-${payloadName}`);
this.#addTextContentWithHighlights(
nodeToHighlight,
result.payload[payloadName],
highlights
);
}
// Get the view update from the result's provider.
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
let viewUpdate = await provider.getViewUpdate(result, idsByName);
if (item.result != result) {
return;
}
// Update each node in the view by name.
for (let [nodeName, update] of Object.entries(viewUpdate)) {
let node = item.querySelector(`#${item.id}-${nodeName}`);
this.#setDynamicAttributes(node, update.attributes);
if (update.style) {
for (let [styleName, value] of Object.entries(update.style)) {
node.style[styleName] = value;
}
}
if (update.l10n) {
if (update.l10n.cacheable) {
await this.#l10nCache.ensureAll([update.l10n]);
if (item.result != result) {
return;
}
}
this.#setElementL10n(node, update.l10n);
} else if (update.textContent) {
node.textContent = update.textContent;
}
}
}
#updateRowForRichSuggestion(item, result) {
this.#setRowSelectable(item, true);
let favicon = item._elements.get("favicon");
if (result.richSuggestionIconSize) {
item.setAttribute("icon-size", result.richSuggestionIconSize);
favicon.setAttribute("icon-size", result.richSuggestionIconSize);
} else {
item.removeAttribute("icon-size");
favicon.removeAttribute("icon-size");
}
let description = item._elements.get("description");
if (result.payload.descriptionL10n) {
this.#setElementL10n(description, result.payload.descriptionL10n);
} else {
this.#removeElementL10n(description);
if (result.payload.description) {
description.textContent = result.payload.description;
}
}
let bottom = item._elements.get("bottom");
if (result.payload.bottomTextL10n) {
this.#setElementL10n(bottom, result.payload.bottomTextL10n);
} else {
this.#removeElementL10n(bottom);
}
}
/**
* Performs a final pass over all rows in the view after a view update, stale
* rows are removed, and other changes to the number of rows. Sets `rowIndex`
* on each result, updates row labels, and performs other tasks that must be
* deferred until all rows have been updated.
*/
#updateIndices() {
this.visibleResults = [];
// `currentLabel` is the last-seen row label as we iterate through the rows.
// When we encounter a label that's different from `currentLabel`, we add it
// to the row and set it to `currentLabel`; we remove the labels for all
// other rows, and therefore no label will appear adjacent to itself. (A
// label may appear more than once, but there will be at least one different
// label in between.) Each row's label is determined by `#rowLabel()`.
let currentLabel;
for (let i = 0; i < this.#rows.children.length; i++) {
let item = this.#rows.children[i];
item.result.rowIndex = i;
let visible = this.#isElementVisible(item);
if (visible) {
if (item.result.exposureResultType) {
this.controller.engagementEvent.addExposure(item.result);
}
this.visibleResults.push(item.result);
}
let newLabel = this.#updateRowLabel(item, visible, currentLabel);
if (newLabel) {
currentLabel = newLabel;
}
}
let selectableElement = this.#getFirstSelectableElement();
let uiIndex = 0;
while (selectableElement) {
selectableElement.elementIndex = uiIndex++;
selectableElement = this.#getNextSelectableElement(selectableElement);
}
if (this.visibleResults.length) {
this.panel.removeAttribute("noresults");
} else {
this.panel.setAttribute("noresults", "true");
}
}
/**
* Sets or removes the group label from a row. Designed to be called
* iteratively over each row.
*
* @param {Element} item
* A row in the view.
* @param {boolean} isVisible
* Whether the row is visible. This can be computed by the method itself,
* but it's a parameter as an optimization since the caller is expected to
* know it.
* @param {object} currentLabel
* The current group label during row iteration.
* @returns {object}
* If the given row should not have a label, returns null. Otherwise returns
* an l10n object for the label's l10n string: `{ id, args }`
*/
#updateRowLabel(item, isVisible, currentLabel) {
let label;
if (isVisible) {
label = this.#rowLabel(item, currentLabel);
if (label && lazy.ObjectUtils.deepEqual(label, currentLabel)) {
label = null;
}
}
// When the row-inner is selected, screen readers won't naturally read the
// label because it's a pseudo-element of the row, not the row-inner. To
// compensate, for rows that have labels we add an element to the row-inner
// with `aria-label` and no text content. Rows that don't have labels won't
// have this element.
let groupAriaLabel = item._elements.get("groupAriaLabel");
if (!label) {
this.#removeElementL10n(item, { attribute: "label" });
if (groupAriaLabel) {
groupAriaLabel.remove();
item._elements.delete("groupAriaLabel");
}
return null;
}
this.#setElementL10n(item, {
attribute: "label",
id: label.id,
args: label.args,
});
if (!groupAriaLabel) {
groupAriaLabel = this.#createElement("span");
groupAriaLabel.className = "urlbarView-group-aria-label";
item._content.insertBefore(groupAriaLabel, item._content.firstChild);
item._elements.set("groupAriaLabel", groupAriaLabel);
}
// `aria-label` must be a string, not an l10n ID, so first fetch the
// localized value and then set it as the attribute. There's no relevant
// aria attribute that uses l10n IDs.
this.#l10nCache.ensure(label).then(() => {
let message = this.#l10nCache.get(label);
groupAriaLabel.setAttribute("aria-label", message?.attributes.label);
});
return label;
}
/**
* Returns the group label to use for a row. Designed to be called iteratively
* over each row.
*
* @param {Element} row
* A row in the view.
* @param {object} currentLabel
* The current group label during row iteration.
* @returns {object}
* If the current row should not have a label, returns null. Otherwise
* returns an l10n object for the label's l10n string: `{ id, args }`
*/
#rowLabel(row, currentLabel) {
if (!lazy.UrlbarPrefs.get("groupLabels.enabled")) {
return null;
}
if (row.result.rowLabel) {
return row.result.rowLabel;
}
let engineName =
row.result.payload.engine || Services.search.defaultEngine.name;
if (row.result.payload.trending) {
return {
id: "urlbar-group-trending",
args: { engine: engineName },
};
}
if (row.result.providerName == lazy.UrlbarProviderRecentSearches.name) {
return { id: "urlbar-group-recent-searches" };
}
if (
row.result.isBestMatch &&
row.result.providerName == lazy.UrlbarProviderQuickSuggest.name
) {
switch (row.result.payload.telemetryType) {
case "amo":
return { id: "urlbar-group-addon" };
case "mdn":
return { id: "urlbar-group-mdn" };
case "pocket":
return { id: "urlbar-group-pocket" };
case "yelp":
return { id: "urlbar-group-local" };
}
}
if (
row.result.isBestMatch ||
row.result.providerName == lazy.UrlbarProviderWeather.name
) {
return { id: "urlbar-group-best-match" };
}
// Show "Shortcuts" if there's another result before that group.
if (
row.result.providerName == lazy.UrlbarProviderTopSites.name &&
this.#queryContext.results[0].providerName !=
lazy.UrlbarProviderTopSites.name
) {
return { id: "urlbar-group-shortcuts" };
}
if (!this.#queryContext?.searchString || row.result.heuristic) {
return null;
}
if (row.result.providerName == lazy.UrlbarProviderQuickSuggest.name) {
return { id: "urlbar-group-firefox-suggest" };
}
switch (row.result.type) {
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.URL:
return { id: "urlbar-group-firefox-suggest" };
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH:
// Show "{ $engine } suggestions" if it's not the first label.
if (currentLabel && row.result.payload.suggestion) {
return {
id: "urlbar-group-search-suggestions",
args: { engine: engineName },
};
}
break;
case lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC:
if (row.result.providerName == "quickactions") {
return { id: "urlbar-group-quickactions" };
}
break;
}
return null;
}
#setRowVisibility(row, visible) {
row.style.display = visible ? "" : "none";
if (
!visible &&
row.result.type != lazy.UrlbarUtils.RESULT_TYPE.TIP &&
row.result.type != lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC
) {
// Reset the overflow state of elements that can overflow in case their
// content changes while they're hidden. When making the row visible
// again, we'll get new overflow events if needed.
this.#setElementOverflowing(row._elements.get("title"), false);
this.#setElementOverflowing(row._elements.get("url"), false);
let tagsContainer = row._elements.get("tagsContainer");
if (tagsContainer) {
this.#setElementOverflowing(tagsContainer, false);
}
}
}
/**
* Returns true if the given element and its row are both visible.
*
* @param {Element} element
* An element in the view.
* @returns {boolean}
* True if the given element and its row are both visible.
*/
#isElementVisible(element) {
if (!element || element.style.display == "none") {
return false;
}
let row = this.#getRowFromElement(element);
return row && row.style.display != "none";
}
#removeStaleRows() {
let row = this.#rows.lastElementChild;
while (row) {
let next = row.previousElementSibling;
if (row.hasAttribute("stale")) {
row.remove();
} else {
this.#setRowVisibility(row, true);
}
row = next;
}
this.#updateIndices();
// Accept tentative exposures. This is analogous to unhiding the
// hypothetical non-stale hidden rows of hidden-exposure results.
this.controller.engagementEvent.acceptTentativeExposures();
}
#startRemoveStaleRowsTimer() {
this.#removeStaleRowsTimer = this.window.setTimeout(() => {
this.#removeStaleRowsTimer = null;
this.#removeStaleRows();
}, UrlbarView.removeStaleRowsTimeout);
}
#cancelRemoveStaleRowsTimer() {
if (this.#removeStaleRowsTimer) {
this.window.clearTimeout(this.#removeStaleRowsTimer);
this.#removeStaleRowsTimer = null;
}
}
#selectElement(
element,
{ updateInput = true, setAccessibleFocus = true } = {}
) {
if (element && !element.matches(KEYBOARD_SELECTABLE_ELEMENT_SELECTOR)) {
throw new Error("Element is not keyboard-selectable");
}
if (this.#selectedElement) {
this.#selectedElement.toggleAttribute("selected", false);
this.#selectedElement.removeAttribute("aria-selected");
this.#getSelectedRow()?.toggleAttribute("selected", false);
}
let row = this.#getRowFromElement(element);
if (element) {
element.toggleAttribute("selected", true);
element.setAttribute("aria-selected", "true");
if (row?.hasAttribute("row-selectable")) {
row?.toggleAttribute("selected", true);
}
}
let result = row?.result;
let provider = lazy.UrlbarProvidersManager.getProvider(
result?.providerName
);
if (provider) {
provider.tryMethod("onBeforeSelection", result, element);
}
this.#setAccessibleFocus(setAccessibleFocus && element);
this.#rawSelectedElement = element;
if (updateInput) {
let urlOverride = null;
if (element?.classList?.contains("urlbarView-button")) {
// Clear the input when a button is selected.
urlOverride = "";
}
this.input.setValueFromResult({ result, urlOverride });
} else {
this.input.setResultForCurrentValue(result);
}
if (provider) {
provider.tryMethod("onSelection", result, element);
}
}
/**
* Returns the element closest to the given element that can be
* selected/picked. If the element itself can be selected, it's returned. If
* there is no such element, null is returned.
*
* @param {Element} element
* An element in the view.
* @param {object} [options]
* Options object.
* @param {boolean} [options.byMouse]
* If true, include elements that are only selectable by mouse.
* @returns {Element}
* The closest element that can be picked including the element itself, or
* null if there is no such element.
*/
#getClosestSelectableElement(element, { byMouse = false } = {}) {
let closest = element.closest(
byMouse
? SELECTABLE_ELEMENT_SELECTOR
: KEYBOARD_SELECTABLE_ELEMENT_SELECTOR
);
if (closest && this.#isElementVisible(closest)) {
return closest;
}
// When clicking on a gap within a row or on its border or padding, treat
// this as if the main part was clicked.
if (
element.classList.contains("urlbarView-row") &&
element.hasAttribute("row-selectable")
) {
return element._content;
}
return null;
}
/**
* Returns true if the given element is keyboard-selectable.
*
* @param {Element} element
* The element to test.
* @returns {boolean}
* True if the element is selectable and false if not.
*/
#isSelectableElement(element) {
return this.#getClosestSelectableElement(element) == element;
}
/**
* Returns the first keyboard-selectable element in the view.
*
* @returns {Element}
* The first selectable element in the view.
*/
#getFirstSelectableElement() {
let element = this.#rows.firstElementChild;
if (element && !this.#isSelectableElement(element)) {
element = this.#getNextSelectableElement(element);
}
return element;
}
/**
* Returns the last keyboard-selectable element in the view.
*
* @returns {Element}
* The last selectable element in the view.
*/
#getLastSelectableElement() {
let element = this.#rows.lastElementChild;
if (element && !this.#isSelectableElement(element)) {
element = this.#getPreviousSelectableElement(element);
}
return element;
}
/**
* Returns the next keyboard-selectable element after the given element. If
* the element is the last selectable element, returns null.
*
* @param {Element} element
* An element in the view.
* @returns {Element}
* The next selectable element after `element` or null if `element` is the
* last selectable element.
*/
#getNextSelectableElement(element) {
let row = this.#getRowFromElement(element);
if (!row) {
return null;
}
let next = row.nextElementSibling;
let selectables = [
...row.querySelectorAll(KEYBOARD_SELECTABLE_ELEMENT_SELECTOR),
];
if (selectables.length) {
let index = selectables.indexOf(element);
if (index < selectables.length - 1) {
next = selectables[index + 1];
}
}
if (next && !this.#isSelectableElement(next)) {
next = this.#getNextSelectableElement(next);
}
return next;
}
/**
* Returns the previous keyboard-selectable element before the given element.
* If the element is the first selectable element, returns null.
*
* @param {Element} element
* An element in the view.
* @returns {Element}
* The previous selectable element before `element` or null if `element` is
* the first selectable element.
*/
#getPreviousSelectableElement(element) {
let row = this.#getRowFromElement(element);
if (!row) {
return null;
}
let previous = row.previousElementSibling;
let selectables = [
...row.querySelectorAll(KEYBOARD_SELECTABLE_ELEMENT_SELECTOR),
];
if (selectables.length) {
let index = selectables.indexOf(element);
if (index < 0) {
previous = selectables[selectables.length - 1];
} else if (index > 0) {
previous = selectables[index - 1];
}
}
if (previous && !this.#isSelectableElement(previous)) {
previous = this.#getPreviousSelectableElement(previous);
}
return previous;
}
/**
* Returns the currently selected row. Useful when this.#selectedElement may
* be a non-row element, such as a descendant element of RESULT_TYPE.TIP.
*
* @returns {Element}
* The currently selected row, or ancestor row of the currently selected
* item.
*/
#getSelectedRow() {
return this.#getRowFromElement(this.#selectedElement);
}
/**
* @param {Element} element
* An element that is potentially a row or descendant of a row.
* @returns {Element}
* The row containing `element`, or `element` itself if it is a row.
*/
#getRowFromElement(element) {
return element?.closest(".urlbarView-row");
}
#setAccessibleFocus(item) {
if (item) {
this.input.inputField.setAttribute("aria-activedescendant", item.id);
} else {
this.input.inputField.removeAttribute("aria-activedescendant");
}
}
/**
* Sets `result`'s title in `titleNode`'s DOM.
*
* @param {UrlbarResult} result
* The result for which the title is being set.
* @param {Element} titleNode
* The DOM node for the result's tile.
*/
#setResultTitle(result, titleNode) {
if (result.payload.titleL10n) {
this.#setElementL10n(titleNode, result.payload.titleL10n);
return;
}
// TODO: `text` is intended only for WebExtensions. We should remove it and
// the WebExtensions urlbar API since we're no longer using it.
if (result.payload.text) {
titleNode.textContent = result.payload.text;
return;
}
if (result.payload.providesSearchMode) {
// Keyword offers are the only result that require a localized title.
// We localize the title instead of using the action text as a title
// because some keyword offer results use both a title and action text
// (e.g. tab-to-search).
this.#setElementL10n(titleNode, {
id: "urlbar-result-action-search-w-engine",
args: { engine: result.payload.engine },
});
return;
}
this.#removeElementL10n(titleNode);
this.#addTextContentWithHighlights(
titleNode,
result.title,
result.titleHighlights
);
}
/**
* Offsets all highlight ranges by a given amount.
*
* @param {Array} highlights The highlights which should be offset.
* @param {int} startOffset
* The number by which we want to offset the highlights range starts.
* @returns {Array} The offset highlights.
*/
#offsetHighlights(highlights, startOffset) {
return highlights.map(highlight => [
highlight[0] + startOffset,
highlight[1],
]);
}
/**
* Sets the content of the 'Switch To Tab' chiclet.
*
* @param {UrlbarResult} result
* The result for which the userContext is being set.
* @param {Element} actionNode
* The DOM node for the result's action.
*/
#setSwitchTabActionChiclet(result, actionNode) {
if (
lazy.UrlbarPrefs.get("switchTabs.searchAllContainers") &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH &&
lazy.UrlbarProviderOpenTabs.isContainerUserContextId(
result.payload.userContextId
)
) {
let label = lazy.ContextualIdentityService.getUserContextLabel(
result.payload.userContextId
).toLowerCase();
// To avoid flicker don't update the label unless necessary.
if (
actionNode.classList.contains("urlbarView-userContext") &&
label &&
actionNode.querySelector("span")?.innerText == label
) {
return;
}
actionNode.innerHTML = "";
let identity = lazy.ContextualIdentityService.getPublicIdentityFromId(
result.payload.userContextId
);
if (identity) {
actionNode.classList.add("urlbarView-userContext");
if (identity.color) {
actionNode.className = actionNode.className.replace(
/identity-color-\w*/g,
""
);
actionNode.classList.add("identity-color-" + identity.color);
}
let textModeLabel = this.#createElement("div");
textModeLabel.classList.add("urlbarView-userContext-textMode");
if (label) {
this.#setElementL10n(textModeLabel, {
id: "urlbar-result-action-switch-tab-with-container",
args: {
container: label.toLowerCase(),
},
});
actionNode.appendChild(textModeLabel);
let iconModeLabel = this.#createElement("div");
iconModeLabel.classList.add("urlbarView-userContext-iconMode");
actionNode.appendChild(iconModeLabel);
if (identity.icon) {
let userContextIcon = this.#createElement("img");
userContextIcon.classList.add("urlbarView-userContext-icon");
userContextIcon.setAttribute("alt", label);
userContextIcon.src =
"resource://usercontext-content/" + identity.icon + ".svg";
this.#setElementL10n(iconModeLabel, {
id: "urlbar-result-action-switch-tab",
});
iconModeLabel.appendChild(userContextIcon);
}
actionNode.setAttribute("tooltiptext", label);
}
}
} else {
actionNode.classList.remove("urlbarView-userContext");
// identity needs to be removed as well..
actionNode
.querySelectorAll(
".urlbarView-userContext-textMode, .urlbarView-userContext-iconMode"
)
.forEach(node => node.remove());
this.#setElementL10n(actionNode, {
id: "urlbar-result-action-switch-tab",
});
}
}
/**
* Adds text content to a node, placing substrings that should be highlighted
* inside <em> nodes.
*
* @param {Element} parentNode
* The text content will be added to this node.
* @param {string} textContent
* The text content to give the node.
* @param {Array} highlights
* The matches to highlight in the text.
*/
#addTextContentWithHighlights(parentNode, textContent, highlights) {
parentNode.textContent = "";
if (!textContent) {
return;
}
highlights = (highlights || []).concat([[textContent.length, 0]]);
let index = 0;
for (let [highlightIndex, highlightLength] of highlights) {
if (highlightIndex - index > 0) {
parentNode.appendChild(
this.document.createTextNode(
textContent.substring(index, highlightIndex)
)
);
}
if (highlightLength > 0) {
let strong = this.#createElement("strong");
strong.textContent = textContent.substring(
highlightIndex,
highlightIndex + highlightLength
);
parentNode.appendChild(strong);
}
index = highlightIndex + highlightLength;
}
}
/**
* Adds markup for a tail suggestion prefix to a row.
*
* @param {Element} item
* The node for the result row.
* @param {UrlbarResult} result
* A UrlbarResult representing a tail suggestion.
*/
#fillTailSuggestionPrefix(item, result) {
let tailPrefixStrNode = item._elements.get("tailPrefixStr");
let tailPrefixStr = result.payload.suggestion.substring(
0,
result.payload.tailOffsetIndex
);
tailPrefixStrNode.textContent = tailPrefixStr;
let tailPrefixCharNode = item._elements.get("tailPrefixChar");
tailPrefixCharNode.textContent = result.payload.tailPrefix;
}
#enableOrDisableRowWrap() {
let wrap = getBoundsWithoutFlushing(this.input.textbox).width < 650;
this.#rows.toggleAttribute("wrap", wrap);
this.oneOffSearchButtons.container.toggleAttribute("wrap", wrap);
}
/**
* @param {Element} element
* The element
* @returns {boolean}
* Whether we track this element's overflow status in order to fade it out
* and add a tooltip when needed.
*/
#canElementOverflow(element) {
let { classList } = element;
return (
classList.contains("urlbarView-overflowable") ||
classList.contains("urlbarView-url")
);
}
/**
* Marks an element as overflowing or not overflowing.
*
* @param {Element} element
* The element
* @param {boolean} overflowing
* Whether the element is overflowing
*/
#setElementOverflowing(element, overflowing) {
element.toggleAttribute("overflow", overflowing);
this.#updateOverflowTooltip(element);
}
/**
* Sets an overflowing element's tooltip, or removes the tooltip if the
* element isn't overflowing. Also optionally updates the string that should
* be used as the tooltip in case of overflow.
*
* @param {Element} element
* The element
* @param {string} [tooltip]
* The string that should be used in the tooltip. This will be stored and
* re-used next time the element overflows.
*/
#updateOverflowTooltip(element, tooltip) {
if (typeof tooltip == "string") {
element._tooltip = tooltip;
}
if (element.hasAttribute("overflow") && element._tooltip) {
element.setAttribute("title", element._tooltip);
} else {
element.removeAttribute("title");
}
}
/**
* If the view is open and showing a single search tip, this method picks it
* and closes the view. This counts as an engagement, so this method should
* only be called due to user interaction.
*
* @param {event} event
* The user-initiated event for the interaction. Should not be null.
* @returns {boolean}
* True if this method picked a tip, false otherwise.
*/
#pickSearchTipIfPresent(event) {
if (
!this.isOpen ||
!this.#queryContext ||
this.#queryContext.results.length != 1
) {
return false;
}
let result = this.#queryContext.results[0];
if (result.type != lazy.UrlbarUtils.RESULT_TYPE.TIP) {
return false;
}
let buttons = this.#rows.firstElementChild._buttons;
let tipButton = buttons.get("tip") || buttons.get("0");
if (!tipButton) {
throw new Error("Expected a tip button");
}
this.input.pickElement(tipButton, event);
return true;
}
/**
* Caches some l10n strings used by the view. Strings that are already cached
* are not cached again.
*
* Note:
* Currently strings are never evicted from the cache, so do not cache
* strings whose arguments include the search string or other values that
* can cause the cache to grow unbounded. Suitable strings include those
* without arguments or those whose arguments depend on a small set of
* static values like search engine names.
*/
async #cacheL10nStrings() {
let idArgs = [
...this.#cacheL10nIDArgsForSearchService(),
{ id: "urlbar-result-action-search-bookmarks" },
{ id: "urlbar-result-action-search-history" },
{ id: "urlbar-result-action-search-in-private" },
{ id: "urlbar-result-action-search-tabs" },
{ id: "urlbar-result-action-switch-tab" },
{ id: "urlbar-result-action-visit" },
{ id: "urlbar-result-action-visit-from-clipboard" },
];
if (lazy.UrlbarPrefs.get("groupLabels.enabled")) {
idArgs.push({ id: "urlbar-group-firefox-suggest" });
idArgs.push({ id: "urlbar-group-best-match" });
if (lazy.UrlbarPrefs.get("quickSuggestEnabled")) {
if (lazy.UrlbarPrefs.get("addonsFeatureGate")) {
idArgs.push({ id: "urlbar-group-addon" });
}
if (lazy.UrlbarPrefs.get("mdn.featureGate")) {
idArgs.push({ id: "urlbar-group-mdn" });
}
if (lazy.UrlbarPrefs.get("pocketFeatureGate")) {
idArgs.push({ id: "urlbar-group-pocket" });
}
if (lazy.UrlbarPrefs.get("yelpFeatureGate")) {
idArgs.push({ id: "urlbar-group-local" });
}
}
}
if (
lazy.UrlbarPrefs.get("quickSuggestEnabled") &&
lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored")
) {
idArgs.push({ id: "urlbar-result-action-sponsored" });
}
await this.#l10nCache.ensureAll(idArgs);
}
/**
* A helper for l10n string caching that returns `{ id, args }` objects for
* strings that depend on the search service.
*
* @returns {Array}
* Array of `{ id, args }` objects, possibly empty.
*/
#cacheL10nIDArgsForSearchService() {
// The search service may not be initialized if the user opens the view very
// quickly after startup. Skip caching related strings in that case. Strings
// are cached opportunistically every time the view opens, so they'll be
// cached soon. We could use the search service's async methods, which
// internally await initialization, but that would allow previously cached
// out-of-date strings to appear in the view while the async calls are
// ongoing. Generally there's no reason for our string-caching paths to be
// async and it may even be a bad idea (except for the final necessary
// `this.#l10nCache.ensureAll()` call).
if (!Services.search.hasSuccessfullyInitialized) {
return [];
}
let idArgs = [];
let { defaultEngine, defaultPrivateEngine } = Services.search;
let engineNames = [defaultEngine?.name, defaultPrivateEngine?.name].filter(
name => name
);
if (defaultPrivateEngine) {
idArgs.push({
id: "urlbar-result-action-search-in-private-w-engine",
args: { engine: defaultPrivateEngine.name },
});
}
let engineStringIDs = [
"urlbar-result-action-tabtosearch-web",
"urlbar-result-action-tabtosearch-other-engine",
"urlbar-result-action-search-w-engine",
];
for (let id of engineStringIDs) {
idArgs.push(...engineNames.map(name => ({ id, args: { engine: name } })));
}
if (lazy.UrlbarPrefs.get("groupLabels.enabled")) {
idArgs.push(
...engineNames.map(name => ({
id: "urlbar-group-search-suggestions",
args: { engine: name },
}))
);
}
return idArgs;
}
/**
* Sets an element's textContent or attribute to a cached l10n string. If the
* string isn't cached, then this falls back to the async `l10n.setAttributes`
* using the given l10n ID and args. The string will pop in as a result, but
* there's no way around it.
*
* @param {Element} element
* The element to set.
* @param {object} options
* Options object.
* @param {string} options.id
* The l10n string ID.
* @param {object} options.args
* The l10n string arguments.
* @param {string} options.attribute
* If you're setting an attribute string, then pass the name of the
* attribute. In that case, the string in the Fluent file should define a
* value for the attribute, like ".foo = My value for the foo attribute".
* If you're setting the element's textContent, then leave this undefined.
* @param {boolean} options.excludeArgsFromCacheKey
* Pass true if the string was cached using a key that excluded arguments.
*/
#setElementL10n(
element,
{
id,
args = undefined,
attribute = undefined,
excludeArgsFromCacheKey = false,
}
) {
let message = this.#l10nCache.get({ id, args, excludeArgsFromCacheKey });
if (message) {
element.removeAttribute("data-l10n-id");
if (attribute) {
element.setAttribute(attribute, message.attributes[attribute]);
} else {
element.textContent = message.value;
}
} else {
if (attribute) {
element.setAttribute("data-l10n-attrs", attribute);
}
this.document.l10n.setAttributes(element, id, args);
}
}
/**
* Removes textContent and attributes set by `#setElementL10n`.
*
* @param {Element} element
* The element that should be acted on
* @param {object} options
* Options object
* @param {string} [options.attribute]
* If you passed an attribute to `#setElementL10n`, then pass it here too.
*/
#removeElementL10n(element, { attribute = undefined } = {}) {
if (attribute) {
element.removeAttribute(attribute);
element.removeAttribute("data-l10n-attrs");
} else {
element.textContent = "";
}
element.removeAttribute("data-l10n-id");
}
get #isShowingZeroPrefix() {
return !!this.#zeroPrefixStopwatchInstance;
}
#setIsShowingZeroPrefix(isShowing) {
if (!!isShowing == !!this.#zeroPrefixStopwatchInstance) {
return;
}
if (!isShowing) {
TelemetryStopwatch.finish(
ZERO_PREFIX_HISTOGRAM_DWELL_TIME,
this.#zeroPrefixStopwatchInstance
);
this.#zeroPrefixStopwatchInstance = null;
return;
}
this.#zeroPrefixStopwatchInstance = {};
TelemetryStopwatch.start(
ZERO_PREFIX_HISTOGRAM_DWELL_TIME,
this.#zeroPrefixStopwatchInstance
);
Services.telemetry.scalarAdd(ZERO_PREFIX_SCALAR_EXPOSURE, 1);
}
/**
* @param {UrlbarResult} result
* The result to get menu commands for.
* @returns {Array}
* Array of menu commands available for the result, null if there are none.
*/
#getResultMenuCommands(result) {
if (this.#resultMenuCommands.has(result)) {
return this.#resultMenuCommands.get(result);
}
let commands = lazy.UrlbarProvidersManager.getProvider(
result.providerName
)?.tryMethod("getResultCommands", result);
if (commands) {
this.#resultMenuCommands.set(result, commands);
return commands;
}
commands = [];
if (result.payload.isBlockable) {
commands.push({
name: RESULT_MENU_COMMANDS.DISMISS,
l10n: result.payload.blockL10n,
});
}
if (result.payload.helpUrl) {
commands.push({
name: RESULT_MENU_COMMANDS.HELP,
l10n: result.payload.helpL10n || {
id: "urlbar-result-menu-learn-more",
},
});
}
if (result.payload.isManageable) {
commands.push({
name: RESULT_MENU_COMMANDS.MANAGE,
l10n: {
id: "urlbar-result-menu-manage-firefox-suggest",
},
});
}
let rv = commands.length ? commands : null;
this.#resultMenuCommands.set(result, rv);
return rv;
}
#populateResultMenu(
menupopup = this.resultMenu,
commands = this.#getResultMenuCommands(this.#resultMenuResult)
) {
menupopup.textContent = "";
for (let data of commands) {
if (data.children) {
let popup = this.document.createXULElement("menupopup");
this.#populateResultMenu(popup, data.children);
let menu = this.document.createXULElement("menu");
this.#setElementL10n(menu, data.l10n);
menu.appendChild(popup);
menupopup.appendChild(menu);
continue;
}
if (data.name == "separator") {
menupopup.appendChild(this.document.createXULElement("menuseparator"));
continue;
}
let menuitem = this.document.createXULElement("menuitem");
menuitem.dataset.command = data.name;
menuitem.classList.add("urlbarView-result-menuitem");
this.#setElementL10n(menuitem, data.l10n);
menupopup.appendChild(menuitem);
}
}
// Event handlers below.
on_SelectedOneOffButtonChanged() {
if (!this.isOpen || !this.#queryContext) {
return;
}
let engine = this.oneOffSearchButtons.selectedButton?.engine;
let source = this.oneOffSearchButtons.selectedButton?.source;
let icon = this.oneOffSearchButtons.selectedButton?.image;
let localSearchMode;
if (source) {
localSearchMode = lazy.UrlbarUtils.LOCAL_SEARCH_MODES.find(
m => m.source == source
);
}
for (let item of this.#rows.children) {
let result = item.result;
let isPrivateSearchWithoutPrivateEngine =
result.payload.inPrivateWindow && !result.payload.isPrivateEngine;
let isSearchHistory =
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.source == lazy.UrlbarUtils.RESULT_SOURCE.HISTORY;
let isSearchSuggestion = result.payload.suggestion && !isSearchHistory;
// For one-off buttons having a source, we update the action for the
// heuristic result, or for any non-heuristic that is a remote search
// suggestion or a private search with no private engine.
if (
!result.heuristic &&
!isSearchSuggestion &&
!isPrivateSearchWithoutPrivateEngine
) {
continue;
}
// If there is no selected button and we are in full search mode, it is
// because the user just confirmed a one-off button, thus starting a new
// query. Don't change the heuristic result because it would be
// immediately replaced with the search mode heuristic, causing flicker.
if (
result.heuristic &&
!engine &&
!localSearchMode &&
this.input.searchMode &&
!this.input.searchMode.isPreview
) {
continue;
}
let action = item._elements.get("action");
let favicon = item._elements.get("favicon");
let title = item._elements.get("title");
// If a one-off button is the only selection, force the heuristic result
// to show its action text, so the engine name is visible.
if (
result.heuristic &&
!this.selectedElement &&
(localSearchMode || engine)
) {
item.setAttribute("show-action-text", "true");
} else {
item.removeAttribute("show-action-text");
}
// If an engine is selected, update search results to use that engine.
// Otherwise, restore their original engines.
if (result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH) {
if (engine) {
if (!result.payload.originalEngine) {
result.payload.originalEngine = result.payload.engine;
}
result.payload.engine = engine.name;
} else if (result.payload.originalEngine) {
result.payload.engine = result.payload.originalEngine;
delete result.payload.originalEngine;
}
}
// If the result is the heuristic and a one-off is selected (i.e.,
// localSearchMode || engine), then restyle it to look like a search
// result; otherwise, remove such styling. For restyled results, we
// override the usual result-picking behaviour in UrlbarInput.pickResult.
if (result.heuristic) {
title.textContent =
localSearchMode || engine
? this.#queryContext.searchString
: result.title;
// Set the restyled-search attribute so the action text and title
// separator are shown or hidden via CSS as appropriate.
if (localSearchMode || engine) {
item.setAttribute("restyled-search", "true");
} else {
item.removeAttribute("restyled-search");
}
}
// Update result action text.
if (localSearchMode) {
// Update the result action text for a local one-off.
let name = lazy.UrlbarUtils.getResultSourceName(localSearchMode.source);
this.#setElementL10n(action, {
id: `urlbar-result-action-search-${name}`,
});
if (result.heuristic) {
item.setAttribute("source", name);
}
} else if (engine && !result.payload.inPrivateWindow) {
// Update the result action text for an engine one-off.
this.#setElementL10n(action, {
id: "urlbar-result-action-search-w-engine",
args: { engine: engine.name },
});
} else {
// No one-off is selected. If we replaced the action while a one-off
// button was selected, it should be restored.
if (item._originalActionSetter) {
item._originalActionSetter();
if (result.heuristic) {
favicon.src = result.payload.icon || lazy.UrlbarUtils.ICON.DEFAULT;
}
} else {
console.error("An item is missing the action setter");
}
item.removeAttribute("source");
}
// Update result favicons.
let iconOverride = localSearchMode?.icon;
// If the icon is the default one-off search placeholder, assume we
// don't have an icon for the engine.
if (
!iconOverride &&
icon != "chrome://browser/skin/search-engine-placeholder.png"
) {
iconOverride = icon;
}
if (!iconOverride && (localSearchMode || engine)) {
// For one-offs without an icon, do not allow restyled URL results to
// use their own icons.
iconOverride = lazy.UrlbarUtils.ICON.SEARCH_GLASS;
}
if (
result.heuristic ||
(result.payload.inPrivateWindow && !result.payload.isPrivateEngine)
) {
// If we just changed the engine from the original engine and it had an
// icon, then make sure the result now uses the new engine's icon or
// failing that the default icon. If we changed it back to the original
// engine, go back to the original or default icon.
favicon.src = this.#iconForResult(result, iconOverride);
}
}
}
on_blur() {
// If the view is open without the input being focused, it will not close
// automatically when the window loses focus. We might be in this state
// after a Search Tip is shown on an engine homepage.
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.close();
}
}
on_mousedown(event) {
if (event.button == 2) {
// Ignore right clicks.
return;
}
let element = this.#getClosestSelectableElement(event.target, {
byMouse: true,
});
if (!element) {
// Ignore clicks on elements that can't be selected/picked.
return;
}
this.window.top.addEventListener("mouseup", this);
// Select the element and open a speculative connection unless it's a
// button. Buttons are special in the two ways listed below. Some buttons
// may be exceptions to these two criteria, but to provide a consistent UX
// and avoid complexity, we apply this logic to all of them.
//
// (1) Some buttons do not close the view when clicked, like the block and
// menu buttons. Clicking these buttons should not have any side effects in
// the view or input beyond their primary purpose. For example, the block
// button should remove the row but it should not change the input value or
// page proxy state, and ideally it shouldn't change the input's selection
// or caret either. It probably also shouldn't change the view's selection
// (if the removed row isn't selected), but that may be more debatable.
//
// It may be possible to select buttons on mousedown and then clear the
// selection on mouseup as usual while meeting these requirements. However,
// it's not simple because clearing the selection has surprising side
// effects in the input like the ones mentioned above.
//
// (2) Most buttons don't have URLs, so there's nothing to speculatively
// connect to. If a button does have a URL, it's typically different from
// the primary URL of its related result, so it's not critical to open a
// speculative connection anyway.
if (!element.classList.contains("urlbarView-button")) {
this.#mousedownSelectedElement = element;
this.#selectElement(element, { updateInput: false });
this.controller.speculativeConnect(
this.selectedResult,
this.#queryContext,
"mousedown"
);
}
}
on_mouseup(event) {
if (event.button == 2) {
// Ignore right clicks.
return;
}
this.window.top.removeEventListener("mouseup", this);
// When mouseup outside of browser, as the target will not be element,
// ignore it.
let element =
event.target.nodeType === event.target.ELEMENT_NODE
? this.#getClosestSelectableElement(event.target, { byMouse: true })
: null;
if (element) {
this.input.pickElement(element, event);
}
// If the element that was selected on mousedown is still in the view, clear
// the selection. Do it after calling `pickElement()` above since code that
// reacts to picks may assume the selected element is the picked element.
//
// If the element is no longer in the view, then it must be because its row
// was removed in response to the pick. If the element was not a button, we
// selected it on mousedown and then `onQueryResultRemoved()` selected the
// next row; we shouldn't unselect it here. If the element was a button,
// then we didn't select anything on mousedown; clearing the selection seems
// like it would be harmless, but it has side effects in the input we want
// to avoid (see `on_mousedown()`).
if (this.#mousedownSelectedElement?.isConnected) {
this.clearSelection();
}
this.#mousedownSelectedElement = null;
}
#isRelevantOverflowEvent(event) {
// We're interested only in the horizontal axis.
// 0 - vertical, 1 - horizontal, 2 - both
return event.detail != 0;
}
on_overflow(event) {
if (
this.#isRelevantOverflowEvent(event) &&
this.#canElementOverflow(event.target)
) {
this.#setElementOverflowing(event.target, true);
}
}
on_underflow(event) {
if (
this.#isRelevantOverflowEvent(event) &&
this.#canElementOverflow(event.target)
) {
this.#setElementOverflowing(event.target, false);
}
}
on_resize() {
this.#enableOrDisableRowWrap();
}
on_command(event) {
if (event.currentTarget == this.resultMenu) {
let result = this.#resultMenuResult;
this.#resultMenuResult = null;
let menuitem = event.target;
switch (menuitem.dataset.command) {
case RESULT_MENU_COMMANDS.HELP:
menuitem.dataset.url =
result.payload.helpUrl ||
Services.urlFormatter.formatURLPref("app.support.baseURL") +
"awesome-bar-result-menu";
break;
}
this.input.pickResult(result, event, menuitem);
}
}
on_popupshowing(event) {
if (event.target == this.resultMenu) {
this.#populateResultMenu();
}
}
}
/**
* Implements a QueryContext cache, working as a circular buffer, when a new
* entry is added at the top, the last item is remove from the bottom.
*/
class QueryContextCache {
#cache;
#size;
#topSitesContext;
#topSitesListener;
/**
* Constructor.
*
* @param {number} size The number of entries to keep in the cache.
*/
constructor(size) {
this.#size = size;
this.#cache = [];
// We store the top-sites context separately since it will often be needed
// and therefore shouldn't be evicted except when the top sites change.
this.#topSitesContext = null;
this.#topSitesListener = () => (this.#topSitesContext = null);
lazy.UrlbarProviderTopSites.addTopSitesListener(this.#topSitesListener);
}
/**
* @returns {number} The number of entries to keep in the cache.
*/
get size() {
return this.#size;
}
/**
* @returns {UrlbarQueryContext} The cached top-sites context or null if none.
*/
get topSitesContext() {
return this.#topSitesContext;
}
/**
* Adds a new entry to the cache.
*
* @param {UrlbarQueryContext} queryContext The UrlbarQueryContext to add.
* Note: QueryContexts without results are ignored and not added. Contexts
* with an empty searchString that are not the top-sites context are
* also ignored.
*/
put(queryContext) {
if (!queryContext.results.length) {
return;
}
let searchString = queryContext.searchString;
if (!searchString) {
// Cache the context if it's the top-sites context. An empty search string
// doesn't necessarily imply top sites since there are other queries that
// use it too, like search mode. If any result is from the top-sites
// provider, assume the context is top sites.
if (
queryContext.results?.some(
r => r.providerName == lazy.UrlbarProviderTopSites.name
)
) {
this.#topSitesContext = queryContext;
}
return;
}
let index = this.#cache.findIndex(e => e.searchString == searchString);
if (index != -1) {
if (this.#cache[index] == queryContext) {
return;
}
this.#cache.splice(index, 1);
}
if (this.#cache.unshift(queryContext) > this.size) {
this.#cache.length = this.size;
}
}
get(searchString) {
return this.#cache.find(e => e.searchString == searchString);
}
}
/**
* Adds a dynamic result type stylesheet to a specified window.
*
* @param {Window} window
* The window to which to add the stylesheet.
* @param {string} stylesheetURL
* The stylesheet's URL.
*/
async function addDynamicStylesheet(window, stylesheetURL) {
// Try-catch all of these so that failing to load a stylesheet doesn't break
// callers and possibly the urlbar. If a stylesheet does fail to load, the
// dynamic results that depend on it will appear broken, but at least we
// won't break the whole urlbar.
try {
let uri = Services.io.newURI(stylesheetURL);
let sheet = await lazy.styleSheetService.preloadSheetAsync(
uri,
Ci.nsIStyleSheetService.AGENT_SHEET
);
window.windowUtils.addSheet(sheet, Ci.nsIDOMWindowUtils.AGENT_SHEET);
} catch (ex) {
console.error("Error adding dynamic stylesheet:", ex);
}
}
/**
* Removes a dynamic result type stylesheet from the view's window.
*
* @param {Window} window
* The window from which to remove the stylesheet.
* @param {string} stylesheetURL
* The stylesheet's URL.
*/
function removeDynamicStylesheet(window, stylesheetURL) {
// Try-catch for the same reason as desribed in addDynamicStylesheet.
try {
window.windowUtils.removeSheetUsingURIString(
stylesheetURL,
Ci.nsIDOMWindowUtils.AGENT_SHEET
);
} catch (ex) {
console.error("Error removing dynamic stylesheet:", ex);
}
}
|