forked from gorhill/uBlock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1149 lines (969 loc) · 37.8 KB
/
Copy pathpopup.js
File metadata and controls
1149 lines (969 loc) · 37.8 KB
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
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
Copyright (C) 2014-present Raymond Hill
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
/* global punycode, uDom */
'use strict';
/******************************************************************************/
(( ) => {
/******************************************************************************/
let popupFontSize = vAPI.localStorage.getItem('popupFontSize');
if ( typeof popupFontSize === 'string' && popupFontSize !== 'unset' ) {
document.body.style.setProperty('font-size', popupFontSize);
}
// https://github.com/gorhill/uBlock/issues/3032
// Popup panel can be in one of two modes:
// - not responsive: viewport is expected to adjust to popup panel size
// - responsive: popup panel must adjust to viewport size -- this happens
// when the viewport is not resized by the browser to perfectly fits uBO's
// popup panel.
if (
vAPI.webextFlavor.soup.has('mobile') ||
/[\?&]responsive=1/.test(window.location.search)
) {
document.body.classList.add('responsive');
}
// https://github.com/chrisaljoudi/uBlock/issues/996
// Experimental: mitigate glitchy popup UI: immediately set the firewall
// pane visibility to its last known state. By default the pane is hidden.
let dfPaneVisibleStored =
vAPI.localStorage.getItem('popupFirewallPane') === 'true';
if ( dfPaneVisibleStored ) {
document.getElementById('panes').classList.add('dfEnabled');
}
/******************************************************************************/
const messaging = vAPI.messaging;
const reIP = /^\d+(?:\.\d+){1,3}$/;
const scopeToSrcHostnameMap = {
'/': '*',
'.': ''
};
const hostnameToSortableTokenMap = new Map();
const statsStr = vAPI.i18n('popupBlockedStats');
const domainsHitStr = vAPI.i18n('popupHitDomainCount');
let popupData = {};
let dfPaneBuilt = false;
let dfHotspots = null;
let allDomains = {};
let allDomainCount = 0;
let allHostnameRows = [];
let touchedDomainCount = 0;
let cachedPopupHash = '';
// https://github.com/gorhill/uBlock/issues/2550
// Solution inspired from
// - https://bugs.chromium.org/p/chromium/issues/detail?id=683314
// - https://bugzilla.mozilla.org/show_bug.cgi?id=1332714#c17
// Confusable character set from:
// - http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%D0%B0%D1%81%D4%81%D0%B5%D2%BB%D1%96%D1%98%D3%8F%D0%BE%D1%80%D4%9B%D1%95%D4%9D%D1%85%D1%83%D1%8A%D0%AC%D2%BD%D0%BF%D0%B3%D1%B5%D1%A1%5D&g=gc&i=
// Linked from:
// - https://www.chromium.org/developers/design-documents/idn-in-google-chrome
const reCyrillicNonAmbiguous = /[\u0400-\u042b\u042d-\u042f\u0431\u0432\u0434\u0436-\u043d\u0442\u0444\u0446-\u0449\u044b-\u0454\u0457\u0459-\u0460\u0462-\u0474\u0476-\u04ba\u04bc\u04be-\u04ce\u04d0-\u0500\u0502-\u051a\u051c\u051e-\u052f]/;
const reCyrillicAmbiguous = /[\u042c\u0430\u0433\u0435\u043e\u043f\u0440\u0441\u0443\u0445\u044a\u0455\u0456\u0458\u0461\u0475\u04bb\u04bd\u04cf\u0501\u051b\u051d]/;
/******************************************************************************/
// The padlock/eraser must be manually positioned:
// - Its vertical position depends on the height of the popup title bar
// - Its horizontal position depends on whether there is a vertical scrollbar.
const positionRulesetTools = function() {
const vpos = document.getElementById('appinfo')
.getBoundingClientRect()
.bottom + window.scrollY + 3;
const hpos = document.getElementById('firewallContainer')
.getBoundingClientRect()
.left + window.scrollX + 3;
const style = document.getElementById('rulesetTools').style;
style.setProperty('top', (vpos >>> 0) + 'px');
style.setProperty('left', (hpos >>> 0) + 'px');
};
/******************************************************************************/
const cachePopupData = function(data) {
popupData = {};
scopeToSrcHostnameMap['.'] = '';
hostnameToSortableTokenMap.clear();
if ( typeof data !== 'object' ) {
return popupData;
}
popupData = data;
scopeToSrcHostnameMap['.'] = popupData.pageHostname || '';
const hostnameDict = popupData.hostnameDict;
if ( typeof hostnameDict !== 'object' ) {
return popupData;
}
for ( const hostname in hostnameDict ) {
if ( hostnameDict.hasOwnProperty(hostname) === false ) { continue; }
let domain = hostnameDict[hostname].domain;
let prefix = hostname.slice(0, 0 - domain.length - 1);
// Prefix with space char for 1st-party hostnames: this ensure these
// will come first in list.
if ( domain === popupData.pageDomain ) {
domain = '\u0020';
}
hostnameToSortableTokenMap.set(
hostname,
domain + ' ' + prefix.split('.').reverse().join('.')
);
}
return popupData;
};
/******************************************************************************/
const hashFromPopupData = function(reset) {
// It makes no sense to offer to refresh the behind-the-scene scope
if ( popupData.pageHostname === 'behind-the-scene' ) {
uDom('body').toggleClass('dirty', false);
return;
}
const hasher = [];
const rules = popupData.firewallRules;
for ( const key in rules ) {
const rule = rules[key];
if ( rule === null ) { continue; }
hasher.push(
rule.src + ' ' +
rule.des + ' ' +
rule.type + ' ' +
rule.action
);
}
hasher.sort();
hasher.push(uDom('body').hasClass('off'));
hasher.push(uDom.nodeFromId('no-large-media').classList.contains('on'));
hasher.push(uDom.nodeFromId('no-cosmetic-filtering').classList.contains('on'));
hasher.push(uDom.nodeFromId('no-remote-fonts').classList.contains('on'));
hasher.push(uDom.nodeFromId('no-scripting').classList.contains('on'));
const hash = hasher.join('');
if ( reset ) {
cachedPopupHash = hash;
}
uDom('body').toggleClass('dirty', hash !== cachedPopupHash);
};
/******************************************************************************/
const formatNumber = function(count) {
return typeof count === 'number' ? count.toLocaleString() : '';
};
/******************************************************************************/
const rulekeyCompare = function(a, b) {
let ha = a.slice(2, a.indexOf(' ', 2));
if ( !reIP.test(ha) ) {
ha = hostnameToSortableTokenMap.get(ha) || ' ';
}
let hb = b.slice(2, b.indexOf(' ', 2));
if ( !reIP.test(hb) ) {
hb = hostnameToSortableTokenMap.get(hb) || ' ';
}
const ca = ha.charCodeAt(0);
const cb = hb.charCodeAt(0);
if ( ca !== cb ) {
return ca - cb;
}
return ha.localeCompare(hb);
};
/******************************************************************************/
const updateFirewallCell = function(scope, des, type, rule) {
const row = document.querySelector(
`#firewallContainer div[data-des="${des}"][data-type="${type}"]`
);
if ( row === null ) { return; }
const cells = row.querySelectorAll(`:scope > span[data-src="${scope}"]`);
if ( cells.length === 0 ) { return; }
if ( rule !== null ) {
cells.forEach(el => { el.setAttribute('class', rule.action + 'Rule'); });
} else {
cells.forEach(el => { el.removeAttribute('class'); });
}
// Use dark shade visual cue if the rule is specific to the cell.
if (
(rule !== null) &&
(rule.des !== '*' || rule.type === type) &&
(rule.des === des) &&
(rule.src === scopeToSrcHostnameMap[scope])
) {
cells.forEach(el => { el.classList.add('ownRule'); });
}
if ( scope !== '.' || des === '*' ) { return; }
// Remember this may be a cell from a reused row, we need to clear text
// content if we can't compute request counts.
if ( popupData.hostnameDict.hasOwnProperty(des) === false ) {
cells.forEach(el => {
el.removeAttribute('data-acount');
el.removeAttribute('data-bcount');
});
return;
}
const hnDetails = popupData.hostnameDict[des];
let cell = cells[0];
if ( hnDetails.allowCount !== 0 ) {
cell.setAttribute('data-acount', Math.min(Math.ceil(Math.log(hnDetails.allowCount + 1) / Math.LN10), 3));
} else {
cell.removeAttribute('data-acount');
}
if ( hnDetails.blockCount !== 0 ) {
cell.setAttribute('data-bcount', Math.min(Math.ceil(Math.log(hnDetails.blockCount + 1) / Math.LN10), 3));
} else {
cell.removeAttribute('data-bcount');
}
if ( hnDetails.domain !== des ) {
return;
}
cell = cells[1];
if ( hnDetails.totalAllowCount !== 0 ) {
cell.setAttribute('data-acount', Math.min(Math.ceil(Math.log(hnDetails.totalAllowCount + 1) / Math.LN10), 3));
} else {
cell.removeAttribute('data-acount');
}
if ( hnDetails.totalBlockCount !== 0 ) {
cell.setAttribute('data-bcount', Math.min(Math.ceil(Math.log(hnDetails.totalBlockCount + 1) / Math.LN10), 3));
} else {
cell.removeAttribute('data-bcount');
}
};
/******************************************************************************/
const updateAllFirewallCells = function() {
const rules = popupData.firewallRules;
for ( const key in rules ) {
if ( rules.hasOwnProperty(key) === false ) { continue; }
updateFirewallCell(
key.charAt(0),
key.slice(2, key.indexOf(' ', 2)),
key.slice(key.lastIndexOf(' ') + 1),
rules[key]
);
}
const dirty = popupData.matrixIsDirty === true;
if ( dirty ) {
positionRulesetTools();
}
uDom.nodeFromId('firewallContainer').classList.toggle('dirty', dirty);
};
/******************************************************************************/
const buildAllFirewallRows = function() {
// Do this before removing the rows
if ( dfHotspots === null ) {
dfHotspots = uDom('#actionSelector')
.toggleClass('colorBlind', popupData.colorBlindFriendly)
.on('click', 'span', setFirewallRuleHandler);
}
dfHotspots.detach();
// Update incrementally: reuse existing rows if possible.
let rowContainer = document.getElementById('firewallContainer');
let toAppend = document.createDocumentFragment();
let rowTemplate = document.querySelector('#templates > div:nth-of-type(1)');
let row = rowContainer.querySelector('div:nth-of-type(7) + div');
for ( const des of allHostnameRows ) {
if ( row === null ) {
row = rowTemplate.cloneNode(true);
toAppend.appendChild(row);
}
row.setAttribute('data-des', des);
const hnDetails = popupData.hostnameDict[des] || {};
const isDomain = des === hnDetails.domain;
const prettyDomainName = punycode.toUnicode(des);
const isPunycoded = prettyDomainName !== des;
const span = row.querySelector('span:first-of-type');
span.classList.toggle(
'isIDN',
isPunycoded &&
reCyrillicAmbiguous.test(prettyDomainName) === true &&
reCyrillicNonAmbiguous.test(prettyDomainName) === false
);
span.querySelector('span').textContent = prettyDomainName;
span.title = isDomain && isPunycoded ? des : '';
const classList = row.classList;
classList.toggle('isDomain', isDomain);
classList.toggle('isSubDomain', !isDomain);
classList.toggle('allowed', hnDetails.allowCount !== 0);
classList.toggle('blocked', hnDetails.blockCount !== 0);
classList.toggle('totalAllowed', hnDetails.totalAllowCount !== 0);
classList.toggle('totalBlocked', hnDetails.totalBlockCount !== 0);
row = row.nextElementSibling;
}
// Remove unused trailing rows
if ( row !== null ) {
while ( row.nextElementSibling !== null ) {
rowContainer.removeChild(row.nextElementSibling);
}
rowContainer.removeChild(row);
}
// Add new rows all at once
if ( toAppend.childElementCount !== 0 ) {
rowContainer.appendChild(toAppend);
}
if ( dfPaneBuilt !== true && popupData.advancedUserEnabled ) {
uDom('#firewallContainer')
.on('click', 'span[data-src]', unsetFirewallRuleHandler)
.on('mouseenter', '[data-src]', mouseenterCellHandler)
.on('mouseleave', '[data-src]', mouseleaveCellHandler);
dfPaneBuilt = true;
}
updateAllFirewallCells();
};
/******************************************************************************/
const renderPrivacyExposure = function() {
allDomains = {};
allDomainCount = touchedDomainCount = 0;
allHostnameRows = [];
// Sort hostnames. First-party hostnames must always appear at the top
// of the list.
const desHostnameDone = {};
const keys = Object.keys(popupData.firewallRules)
.sort(rulekeyCompare);
for ( const key of keys ) {
const des = key.slice(2, key.indexOf(' ', 2));
// Specific-type rules -- these are built-in
if ( des === '*' || desHostnameDone.hasOwnProperty(des) ) { continue; }
const hnDetails = popupData.hostnameDict[des] || {};
if ( allDomains.hasOwnProperty(hnDetails.domain) === false ) {
allDomains[hnDetails.domain] = false;
allDomainCount += 1;
}
if ( hnDetails.allowCount !== 0 ) {
if ( allDomains[hnDetails.domain] === false ) {
allDomains[hnDetails.domain] = true;
touchedDomainCount += 1;
}
}
allHostnameRows.push(des);
desHostnameDone[des] = true;
}
const summary = domainsHitStr
.replace('{{count}}', touchedDomainCount.toLocaleString())
.replace('{{total}}', allDomainCount.toLocaleString());
uDom.nodeFromId('popupHitDomainCount').textContent = summary;
};
/******************************************************************************/
const updateHnSwitches = function() {
uDom.nodeFromId('no-popups').classList.toggle(
'on',
popupData.noPopups === true
);
uDom.nodeFromId('no-large-media').classList.toggle(
'on', popupData.noLargeMedia === true
);
uDom.nodeFromId('no-cosmetic-filtering').classList.toggle(
'on',
popupData.noCosmeticFiltering === true
);
uDom.nodeFromId('no-remote-fonts').classList.toggle(
'on',
popupData.noRemoteFonts === true
);
uDom.nodeFromId('no-scripting').classList.toggle(
'on',
popupData.noScripting === true
);
};
/******************************************************************************/
// Assume everything has to be done incrementally.
const renderPopup = function() {
if ( popupData.tabTitle ) {
document.title = popupData.appName + ' - ' + popupData.tabTitle;
}
let elem = document.body;
elem.classList.toggle(
'advancedUser',
popupData.advancedUserEnabled === true
);
elem.classList.toggle(
'off',
popupData.pageURL === '' || popupData.netFilteringSwitch !== true
);
let canElementPicker = popupData.canElementPicker === true &&
popupData.netFilteringSwitch === true;
uDom.nodeFromId('gotoPick').classList.toggle('enabled', canElementPicker);
uDom.nodeFromId('gotoZap').classList.toggle('enabled', canElementPicker);
let blocked = popupData.pageBlockedRequestCount,
total = popupData.pageAllowedRequestCount + blocked,
text;
if ( total === 0 ) {
text = formatNumber(0);
} else {
text = statsStr.replace('{{count}}', formatNumber(blocked))
.replace('{{percent}}', formatNumber(Math.floor(blocked * 100 / total)));
}
uDom.nodeFromId('page-blocked').textContent = text;
blocked = popupData.globalBlockedRequestCount;
total = popupData.globalAllowedRequestCount + blocked;
if ( total === 0 ) {
text = formatNumber(0);
} else {
text = statsStr.replace('{{count}}', formatNumber(blocked))
.replace('{{percent}}', formatNumber(Math.floor(blocked * 100 / total)));
}
uDom.nodeFromId('total-blocked').textContent = text;
// This will collate all domains, touched or not
renderPrivacyExposure();
// Extra tools
updateHnSwitches();
// Report blocked popup count on badge
total = popupData.popupBlockedCount;
uDom.nodeFromSelector('#no-popups > span.fa-icon-badge')
.textContent = total ? Math.min(total, 99).toLocaleString() : '';
// Report large media count on badge
total = popupData.largeMediaCount;
uDom.nodeFromSelector('#no-large-media > span.fa-icon-badge')
.textContent = total ? Math.min(total, 99).toLocaleString() : '';
// Report remote font count on badge
total = popupData.remoteFontCount;
uDom.nodeFromSelector('#no-remote-fonts > span.fa-icon-badge')
.textContent = total ? Math.min(total, 99).toLocaleString() : '';
// https://github.com/chrisaljoudi/uBlock/issues/470
// This must be done here, to be sure the popup is resized properly
const dfPaneVisible = popupData.dfEnabled;
// https://github.com/chrisaljoudi/uBlock/issues/1068
// Remember the last state of the firewall pane. This allows to
// configure the popup size early next time it is opened, which means a
// less glitchy popup at open time.
if ( dfPaneVisible !== dfPaneVisibleStored ) {
dfPaneVisibleStored = dfPaneVisible;
vAPI.localStorage.setItem('popupFirewallPane', dfPaneVisibleStored);
}
uDom.nodeFromId('panes').classList.toggle(
'dfEnabled',
dfPaneVisible === true
);
elem = uDom.nodeFromId('firewallContainer');
elem.classList.toggle(
'minimized',
popupData.firewallPaneMinimized === true
);
elem.classList.toggle(
'colorBlind',
popupData.colorBlindFriendly === true
);
// Build dynamic filtering pane only if in use
if ( dfPaneVisible ) {
buildAllFirewallRows();
}
renderTooltips();
};
/******************************************************************************/
// https://github.com/gorhill/uBlock/issues/2889
// Use tooltip for ARIA purpose.
const renderTooltips = function(selector) {
for ( const entry of tooltipTargetSelectors ) {
if ( selector !== undefined && entry[0] !== selector ) { continue; }
const text = vAPI.i18n(
entry[1].i18n +
(uDom.nodeFromSelector(entry[1].state) === null ? '1' : '2')
);
const elem = uDom.nodeFromSelector(entry[0]);
elem.setAttribute('aria-label', text);
elem.setAttribute('data-tip', text);
if ( selector !== undefined ) {
uDom.nodeFromId('tooltip').textContent =
elem.getAttribute('data-tip');
}
}
};
const tooltipTargetSelectors = new Map([
[
'#switch',
{
state: 'body.off',
i18n: 'popupPowerSwitchInfo',
}
],
[
'#no-popups',
{
state: '#no-popups.on',
i18n: 'popupTipNoPopups'
}
],
[
'#no-large-media',
{
state: '#no-large-media.on',
i18n: 'popupTipNoLargeMedia'
}
],
[
'#no-cosmetic-filtering',
{
state: '#no-cosmetic-filtering.on',
i18n: 'popupTipNoCosmeticFiltering'
}
],
[
'#no-remote-fonts',
{
state: '#no-remote-fonts.on',
i18n: 'popupTipNoRemoteFonts'
}
],
[
'#no-scripting',
{
state: '#no-scripting.on',
i18n: 'popupTipNoScripting'
}
],
]);
/******************************************************************************/
// All rendering code which need to be executed only once.
let renderOnce = function() {
renderOnce = function(){};
if ( popupData.fontSize !== popupFontSize ) {
popupFontSize = popupData.fontSize;
if ( popupFontSize !== 'unset' ) {
document.body.style.setProperty('font-size', popupFontSize);
vAPI.localStorage.setItem('popupFontSize', popupFontSize);
} else {
document.body.style.removeProperty('font-size');
vAPI.localStorage.removeItem('popupFontSize');
}
}
uDom.nodeFromId('appname').textContent = popupData.appName;
uDom.nodeFromId('version').textContent = popupData.appVersion;
// https://github.com/uBlockOrigin/uBlock-issues/issues/22
if ( popupData.advancedUserEnabled !== true ) {
uDom('#firewallContainer [data-i18n-tip][data-src]').removeAttr('data-tip');
}
// https://github.com/gorhill/uBlock/issues/2274
// Make use of the whole viewport when in responsive mode.
if ( document.body.classList.contains('responsive') ) { return; }
// For large displays: we do not want the left pane -- optional and
// hidden by defaut -- to dictate the height of the popup. The right pane
// dictates the height of the popup, and the left pane will have a
// scrollbar if ever its height is more than what is available.
// For small displays: we use the whole viewport.
const rpane = uDom.nodeFromSelector('#panes > div:first-of-type');
const lpane = uDom.nodeFromSelector('#panes > div:last-of-type');
lpane.style.setProperty('height', rpane.offsetHeight + 'px');
// Be prepared to fall into responsive mode if ever it is found the
// viewport is not a perfect match for the popup panel.
let resizeTimer;
const resize = function() {
resizeTimer = undefined;
// Do not use equality, fractional pixel dimension occurs and must
// be ignored.
// https://www.reddit.com/r/uBlockOrigin/comments/8qodpw/how_to_hide_the_info_shown_of_what_is_currently/e0lglrr/
// Tolerance of 2px fixes the issue.
if (
Math.abs(document.body.offsetWidth - window.innerWidth) <= 2 &&
Math.abs(document.body.offsetHeight - window.innerHeight) <= 2
) {
return;
}
document.body.classList.add('responsive');
lpane.style.removeProperty('height');
window.removeEventListener('resize', resizeAsync);
};
const resizeAsync = function() {
if ( resizeTimer !== undefined ) {
clearTimeout(resizeTimer);
}
resizeTimer = vAPI.setTimeout(resize, 67);
};
window.addEventListener('resize', resizeAsync);
resizeAsync();
};
/******************************************************************************/
const renderPopupLazy = (( ) => {
let mustRenderCosmeticFilteringBadge = true;
// https://github.com/uBlockOrigin/uBlock-issues/issues/756
// Launch potentially expensive hidden elements-counting scriptlet on
// demand only.
{
const sw = uDom.nodeFromId('no-cosmetic-filtering');
const badge = sw.querySelector(':scope > span.fa-icon-badge');
badge.textContent = '\u22EF';
const render = ( ) => {
if ( mustRenderCosmeticFilteringBadge === false ) { return; }
mustRenderCosmeticFilteringBadge = false;
if ( sw.classList.contains('hnSwitchBusy') ) { return; }
sw.classList.add('hnSwitchBusy');
messaging.send('popupPanel', {
what: 'getHiddenElementCount',
tabId: popupData.tabId,
}).then(count => {
let text;
if ( (count || 0) === 0 ) {
text = '';
} else if ( count === -1 ) {
text = '?';
} else {
text = Math.min(count, 99).toLocaleString();
}
badge.textContent = text;
sw.classList.remove('hnSwitchBusy');
});
};
sw.addEventListener('mouseenter', render, { passive: true });
}
return async function() {
const count = await messaging.send('popupPanel', {
what: 'getScriptCount',
tabId: popupData.tabId,
});
uDom.nodeFromSelector('#no-scripting > span.fa-icon-badge')
.textContent = (count || 0) !== 0
? Math.min(count, 99).toLocaleString()
: '';
mustRenderCosmeticFilteringBadge = true;
};
})();
/******************************************************************************/
const toggleNetFilteringSwitch = function(ev) {
if ( !popupData || !popupData.pageURL ) { return; }
messaging.send('popupPanel', {
what: 'toggleNetFiltering',
url: popupData.pageURL,
scope: ev.ctrlKey || ev.metaKey ? 'page' : '',
state: !uDom('body').toggleClass('off').hasClass('off'),
tabId: popupData.tabId,
});
renderTooltips('#switch');
hashFromPopupData();
};
/******************************************************************************/
const gotoZap = function() {
messaging.send('popupPanel', {
what: 'launchElementPicker',
tabId: popupData.tabId,
zap: true,
});
vAPI.closePopup();
};
/******************************************************************************/
const gotoPick = function() {
messaging.send('popupPanel', {
what: 'launchElementPicker',
tabId: popupData.tabId,
});
vAPI.closePopup();
};
/******************************************************************************/
const gotoURL = function(ev) {
if ( this.hasAttribute('href') === false ) { return; }
ev.preventDefault();
let url = this.getAttribute('href');
if (
url === 'logger-ui.html#_' &&
typeof popupData.tabId === 'number'
) {
url += '+' + popupData.tabId;
}
messaging.send('popupPanel', {
what: 'gotoURL',
details: {
url: url,
select: true,
index: -1,
shiftKey: ev.shiftKey
},
});
vAPI.closePopup();
};
/******************************************************************************/
const toggleFirewallPane = function() {
popupData.dfEnabled = !popupData.dfEnabled;
messaging.send('popupPanel', {
what: 'userSettings',
name: 'dynamicFilteringEnabled',
value: popupData.dfEnabled,
});
// https://github.com/chrisaljoudi/uBlock/issues/996
// Remember the last state of the firewall pane. This allows to
// configure the popup size early next time it is opened, which means a
// less glitchy popup at open time.
dfPaneVisibleStored = popupData.dfEnabled;
vAPI.localStorage.setItem('popupFirewallPane', dfPaneVisibleStored);
// Dynamic filtering pane may not have been built yet
uDom.nodeFromId('panes').classList.toggle('dfEnabled', popupData.dfEnabled);
if ( popupData.dfEnabled && dfPaneBuilt === false ) {
buildAllFirewallRows();
}
};
/******************************************************************************/
const mouseenterCellHandler = function() {
if ( uDom(this).hasClass('ownRule') === false ) {
dfHotspots.appendTo(this);
}
};
const mouseleaveCellHandler = function() {
dfHotspots.detach();
};
/******************************************************************************/
const setFirewallRule = async function(src, des, type, action, persist) {
// This can happen on pages where uBlock does not work
if (
typeof popupData.pageHostname !== 'string' ||
popupData.pageHostname === ''
) {
return;
}
const response = await messaging.send('popupPanel', {
what: 'toggleFirewallRule',
tabId: popupData.tabId,
pageHostname: popupData.pageHostname,
srcHostname: src,
desHostname: des,
requestType: type,
action: action,
persist: persist,
});
cachePopupData(response);
updateAllFirewallCells();
hashFromPopupData();
};
/******************************************************************************/
const unsetFirewallRuleHandler = function(ev) {
const cell = ev.target;
const row = cell.closest('[data-des]');
setFirewallRule(
cell.getAttribute('data-src') === '/' ? '*' : popupData.pageHostname,
row.getAttribute('data-des'),
row.getAttribute('data-type'),
0,
ev.ctrlKey || ev.metaKey
);
dfHotspots.appendTo(cell);
};
/******************************************************************************/
const setFirewallRuleHandler = function(ev) {
const hotspot = ev.target;
const cell = hotspot.closest('[data-src]');
if ( cell === null ) { return; }
const row = cell.closest('[data-des]');
let action = 0;
if ( hotspot.id === 'dynaAllow' ) {
action = 2;
} else if ( hotspot.id === 'dynaNoop' ) {
action = 3;
} else {
action = 1;
}
setFirewallRule(
cell.getAttribute('data-src') === '/' ? '*' : popupData.pageHostname,
row.getAttribute('data-des'),
row.getAttribute('data-type'),
action,
ev.ctrlKey || ev.metaKey
);
dfHotspots.detach();
};
/******************************************************************************/
const reloadTab = function(ev) {
messaging.send('popupPanel', {
what: 'reloadTab',
tabId: popupData.tabId,
select: vAPI.webextFlavor.soup.has('mobile'),
bypassCache: ev.ctrlKey || ev.metaKey || ev.shiftKey,
});
// Polling will take care of refreshing the popup content
// https://github.com/chrisaljoudi/uBlock/issues/748
// User forces a reload, assume the popup has to be updated regardless
// if there were changes or not.
popupData.contentLastModified = -1;
// No need to wait to remove this.
uDom('body').toggleClass('dirty', false);
};
uDom('#refresh').on('click', reloadTab);
// https://github.com/uBlockOrigin/uBlock-issues/issues/672
document.addEventListener(
'keydown',
ev => {
if ( ev.code !== 'F5' ) { return; }
reloadTab(ev);
ev.preventDefault();
ev.stopPropagation();
},
{ capture: true }
);
/******************************************************************************/
const toggleMinimize = function(ev) {
// Special display mode: in its own tab/window, with no vertical restraint.
// Useful to take snapshots of the whole list of domains -- example:
// https://github.com/gorhill/uBlock/issues/736#issuecomment-178879944
if ( ev.shiftKey && ev.ctrlKey ) {
messaging.send('popupPanel', {
what: 'gotoURL',
details: {
url: 'popup.html?tabId=' + popupData.tabId + '&responsive=1',
select: true,
index: -1
},
});
vAPI.closePopup();
return;
}
popupData.firewallPaneMinimized =
uDom.nodeFromId('firewallContainer').classList.toggle('minimized');
messaging.send('popupPanel', {
what: 'userSettings',
name: 'firewallPaneMinimized',
value: popupData.firewallPaneMinimized,
});
positionRulesetTools();
};
/******************************************************************************/
const saveFirewallRules = function() {
messaging.send('popupPanel', {
what: 'saveFirewallRules',
srcHostname: popupData.pageHostname,
desHostnames: popupData.hostnameDict,
});
uDom.nodeFromId('firewallContainer').classList.remove('dirty');
};
/******************************************************************************/
const revertFirewallRules = async function() {
uDom.nodeFromId('firewallContainer').classList.remove('dirty');
const response = await messaging.send('popupPanel', {
what: 'revertFirewallRules',
srcHostname: popupData.pageHostname,
desHostnames: popupData.hostnameDict,
tabId: popupData.tabId,
});
cachePopupData(response);
updateAllFirewallCells();
updateHnSwitches();
hashFromPopupData();
};
/******************************************************************************/
const toggleHostnameSwitch = async function(ev) {
const target = ev.currentTarget;
const switchName = target.getAttribute('id');
if ( !switchName ) { return; }
// For touch displays, process click only if the switch is not "busy".
if (
vAPI.webextFlavor.soup.has('mobile') &&
target.classList.contains('hnSwitchBusy')
) {
return;
}
target.classList.toggle('on');
renderTooltips('#' + switchName);
const response = await messaging.send('popupPanel', {
what: 'toggleHostnameSwitch',
name: switchName,
hostname: popupData.pageHostname,