hopefully this fixes #470

This commit is contained in:
gorhill 2015-01-10 11:23:28 -05:00
parent fdb87a40b3
commit 9fc136e7e8
6 changed files with 237 additions and 75 deletions

View File

@ -79,7 +79,7 @@ p {
#switch .fa:hover { #switch .fa:hover {
opacity: 0.9; opacity: 0.9;
} }
#switch .fa.off { #switch.off .fa {
color: #ccc; color: #ccc;
} }
#switch-hint { #switch-hint {
@ -116,18 +116,42 @@ p {
color: #444; color: #444;
} }
body.advancedUser #dfToggler {
cursor: pointer;
}
body.advancedUser #dfToggler:before { body.advancedUser #dfToggler:before {
color: gray; color: gray;
content: '\202F+\202F'; content: '+\202F';
cursor: pointer;
font-size: 14px; font-size: 14px;
line-height: 14px; line-height: 14px;
z-index: 10;
} }
body.advancedUser #panes.dfEnabled #dfToggler:before { body.advancedUser #panes.dfEnabled #dfToggler:before {
content: '\202F\2212\202F'; content: '\2212\202F';
} }
#refresh {
background-color: #ffe;
border: 1px solid #eec;
border-radius: 4px;
bottom: 4px;
color: #888;
cursor: pointer;
display: none;
font-size: 40px;
left: 4px;
line-height: 40px;
padding: 4px 8px;
position: absolute;
right: 4px;
text-align: center;
}
body.dirty #refresh {
display: block;
}
body.dirty #refresh:hover {
color: black;
}
#dynamicFilteringContainer { #dynamicFilteringContainer {
border: 0; border: 0;
font-size: 12px; font-size: 12px;

View File

@ -193,6 +193,7 @@ var getStats = function(tabId) {
r.pageAllowedRequestCount = pageStore.perLoadAllowedRequestCount; r.pageAllowedRequestCount = pageStore.perLoadAllowedRequestCount;
r.netFilteringSwitch = pageStore.getNetFilteringSwitch(); r.netFilteringSwitch = pageStore.getNetFilteringSwitch();
r.hostnameDict = getHostnameDict(pageStore.hostnameToCountMap); r.hostnameDict = getHostnameDict(pageStore.hostnameToCountMap);
r.contentLastModified = pageStore.contentLastModified;
r.dynamicFilterRules = getDynamicFilterRules(pageStore.pageHostname, r.hostnameDict); r.dynamicFilterRules = getDynamicFilterRules(pageStore.pageHostname, r.hostnameDict);
} else { } else {
r.hostnameDict = {}; r.hostnameDict = {};
@ -206,7 +207,7 @@ var getStats = function(tabId) {
var onMessage = function(request, sender, callback) { var onMessage = function(request, sender, callback) {
// Async // Async
switch ( request.what ) { switch ( request.what ) {
case 'activeTabStats': case 'getPopupData':
vAPI.tabs.get(null, function(tab) { vAPI.tabs.get(null, function(tab) {
var tabId = tab && tab.id; var tabId = tab && tab.id;
callback(getStats(tabId)); callback(getStats(tabId));
@ -228,6 +229,17 @@ var onMessage = function(request, sender, callback) {
µb.elementPickerExec(request.tabId); µb.elementPickerExec(request.tabId);
break; break;
case 'hasPopupContentChanged':
var pageStore = µb.pageStoreFromTabId(request.tabId);
var lastModified = pageStore ? pageStore.contentLastModified : 0;
response = lastModified !== request.contentLastModified;
break;
case 'toggleDynamicFilter':
µb.toggleDynamicFilter(request);
response = getStats(request.tabId);
break;
case 'toggleNetFiltering': case 'toggleNetFiltering':
µb.toggleNetFilteringSwitch( µb.toggleNetFilteringSwitch(
request.url, request.url,
@ -237,11 +249,6 @@ var onMessage = function(request, sender, callback) {
µb.updateBadgeAsync(request.tabId); µb.updateBadgeAsync(request.tabId);
break; break;
case 'toggleDynamicFilter':
µb.toggleDynamicFilter(request);
response = getStats(request.tabId);
break;
default: default:
return vAPI.messaging.UNHANDLED; return vAPI.messaging.UNHANDLED;
} }

View File

@ -484,6 +484,7 @@ PageStore.prototype.init = function(tabId, pageURL) {
this.requestURL = this.requestHostname = this.requestType = ''; this.requestURL = this.requestHostname = this.requestType = '';
this.hostnameToCountMap = {}; this.hostnameToCountMap = {};
this.contentLastModified = 0;
this.frames = {}; this.frames = {};
this.netFiltering = true; this.netFiltering = true;
this.netFilteringReadTime = 0; this.netFilteringReadTime = 0;
@ -655,6 +656,7 @@ PageStore.prototype.cacheResult = function(context, result) {
var requestHostname = context.requestHostname; var requestHostname = context.requestHostname;
if ( this.hostnameToCountMap.hasOwnProperty(requestHostname) === false ) { if ( this.hostnameToCountMap.hasOwnProperty(requestHostname) === false ) {
this.hostnameToCountMap[requestHostname] = 0; this.hostnameToCountMap[requestHostname] = 0;
this.contentLastModified = Date.now();
} }
var c = result.charAt(1); var c = result.charAt(1);
if ( c === '' || c === 'a' ) { if ( c === '' || c === 'a' ) {

View File

@ -31,16 +31,9 @@
var popupData; var popupData;
var dfPaneBuilt = false; var dfPaneBuilt = false;
var dfTypes = [
'image',
'inline-script',
'1p-script',
'3p-script',
'3p-frame'
];
var popupHeight; var popupHeight;
var reIP = /^\d+(?:\.\d+){1,3}$/; var reIP = /^\d+(?:\.\d+){1,3}$/;
var reSrcHostnameFromResult = /^d[abn]:([^ ]+) ([^ ]+)/; var reSrcHostnameFromRule = /^d[abn]:([^ ]+) ([^ ]+)/;
var scopeToSrcHostnameMap = { var scopeToSrcHostnameMap = {
'/': '*', '/': '*',
'.': '' '.': ''
@ -53,6 +46,8 @@ var hostnameToSortableTokenMap = {};
var allDomains = {}; var allDomains = {};
var allDomainCount = 0; var allDomainCount = 0;
var touchedDomainCount = 0; var touchedDomainCount = 0;
var rowsToRecycle = uDom();
var cachedPopupHash = '';
/******************************************************************************/ /******************************************************************************/
@ -93,11 +88,32 @@ var cachePopupData = function(data) {
/******************************************************************************/ /******************************************************************************/
var formatNumber = function(count) { var hashFromPopupData = function(reset) {
if ( typeof count !== 'number' ) { var hasher = [];
return ''; var rules = popupData.dynamicFilterRules;
var rule;
for ( var key in rules ) {
if ( rules.hasOwnProperty(key) === false ) {
continue;
}
rule = rules[key];
if ( rule !== '' ) {
hasher.push(rule);
}
} }
return count.toLocaleString(); hasher.push(uDom('#switch').hasClass('off'));
var hash = hasher.sort().join('');
if ( reset ) {
cachedPopupHash = hash;
}
uDom('body').toggleClass('dirty', hash !== cachedPopupHash);
};
/******************************************************************************/
var formatNumber = function(count) {
return typeof count === 'number' ? count.toLocaleString() : '';
}; };
/******************************************************************************/ /******************************************************************************/
@ -114,31 +130,33 @@ var rulekeyCompare = function(a, b) {
return ha.localeCompare(hb); return ha.localeCompare(hb);
}; };
var reRulekeyCompareNoise = /[^a-z0-9.]/g;
/******************************************************************************/ /******************************************************************************/
var addDynamicFilterRow = function(des) { var addDynamicFilterRow = function(des) {
var row = uDom('#templates > div:nth-of-type(1)').clone(); var row = rowsToRecycle.pop();
if ( row.length === 0 ) {
row = uDom('#templates > div:nth-of-type(1)').clone();
}
row.descendants('[data-des]').attr('data-des', des); row.descendants('[data-des]').attr('data-des', des);
row.descendants('span:nth-of-type(1)').text(des); row.descendants('span:nth-of-type(1)').text(des);
var hnDetails = popupData.hostnameDict[des] || {}; var hnDetails = popupData.hostnameDict[des] || {};
var isDomain = des === hnDetails.domain;
row.toggleClass('isDomain', isDomain); row.toggleClass('isDomain', des === hnDetails.domain);
row.toggleClass('allowed', hnDetails.allowCount !== 0);
row.toggleClass('blocked', hnDetails.blockCount !== 0);
if ( allDomains.hasOwnProperty(hnDetails.domain) === false ) { if ( allDomains.hasOwnProperty(hnDetails.domain) === false ) {
allDomains[hnDetails.domain] = false; allDomains[hnDetails.domain] = false;
allDomainCount += 1; allDomainCount += 1;
} }
if ( hnDetails.allowCount !== 0 ) { if ( hnDetails.allowCount !== 0 ) {
if ( allDomains[hnDetails.domain] === false ) { if ( allDomains[hnDetails.domain] === false ) {
allDomains[hnDetails.domain] = true; allDomains[hnDetails.domain] = true;
touchedDomainCount += 1; touchedDomainCount += 1;
} }
row.addClass('allowed');
}
if ( hnDetails.blockCount !== 0 ) {
row.addClass('blocked');
} }
row.appendTo('#dynamicFilteringContainer'); row.appendTo('#dynamicFilteringContainer');
@ -157,24 +175,24 @@ var addDynamicFilterRow = function(des) {
/******************************************************************************/ /******************************************************************************/
var syncDynamicFilterCell = function(scope, des, type, result) { var updateDynamicFilterCell = function(scope, des, type, rule) {
var selector = '#dynamicFilteringContainer span[data-src="' + scope + '"][data-des="' + des + '"][data-type="' + type + '"]'; var selector = '#dynamicFilteringContainer span[data-src="' + scope + '"][data-des="' + des + '"][data-type="' + type + '"]';
var cell = uDom(selector); var cell = uDom(selector);
// Create the row? // This should not happen
if ( cell.length === 0 ) { if ( cell.length === 0 ) {
cell = addDynamicFilterRow(des).descendants(selector); return;
} }
cell.removeClass(); cell.removeClass();
var action = result.charAt(1); var action = rule.charAt(1);
if ( action !== '' ) { if ( action !== '' ) {
cell.toggleClass(action + 'Rule', true); cell.toggleClass(action + 'Rule', true);
} }
// Use dark shade visual cue if the filter is specific to the cell. // Use dark shade visual cue if the filter is specific to the cell.
var ownRule = false; var ownRule = false;
var matches = reSrcHostnameFromResult.exec(result); var matches = reSrcHostnameFromRule.exec(rule);
if ( matches !== null ) { if ( matches !== null ) {
ownRule = matches[2] === des && ownRule = matches[2] === des &&
matches[1] === scopeToSrcHostnameMap[scope]; matches[1] === scopeToSrcHostnameMap[scope];
@ -205,33 +223,52 @@ var syncDynamicFilterCell = function(scope, des, type, result) {
/******************************************************************************/ /******************************************************************************/
var syncAllDynamicFilters = function() { var updateAllDynamicFilters = function() {
var hasRule = false;
var rules = popupData.dynamicFilterRules; var rules = popupData.dynamicFilterRules;
var type, result; for ( var key in rules ) {
var types = dfTypes; updateDynamicFilterCell(
var i = types.length; key.charAt(0),
while ( i-- ) { key.slice(2, key.indexOf(' ', 2)),
type = types[i]; key.slice(key.lastIndexOf(' ') + 1),
syncDynamicFilterCell('/', '*', type, rules['/ * ' + type] || ''); rules[key]
result = rules['. * ' + type] || ''; );
if ( result.charAt(1) !== '' ) {
hasRule = true;
}
syncDynamicFilterCell('.', '*', type, result);
} }
};
/******************************************************************************/
var buildAllDynamicFilters = function() {
// Do this before removing the rows
if ( dfHotspots === null ) {
dfHotspots = uDom('#actionSelector').on('click', 'span', setDynamicFilterHandler);
}
dfHotspots.detach();
// Remove and reuse all rows: the order may have changed, we can't just
// reuse them in-place.
rowsToRecycle = uDom('#privacyInfo ~ div').detach();
allDomains = {};
allDomainCount = touchedDomainCount = 0;
// Sort hostnames. First-party hostnames must always appear at the top // Sort hostnames. First-party hostnames must always appear at the top
// of the list. // of the list.
var keys = Object.keys(rules).sort(rulekeyCompare); var desHostnameDone = {};
var key; var keys = Object.keys(popupData.dynamicFilterRules)
.sort(rulekeyCompare);
var key, des;
for ( var i = 0; i < keys.length; i++ ) { for ( var i = 0; i < keys.length; i++ ) {
key = keys[i]; key = keys[i];
// Specific-type rules -- they were processed above // Specific-type rules -- these are built-in
if ( key.slice(-1) !== '*' ) { if ( key.slice(-1) !== '*' ) {
continue; continue;
} }
syncDynamicFilterCell(key.charAt(0), key.slice(2, key.indexOf(' ', 2)), '*', rules[key]); des = key.slice(2, key.indexOf(' ', 2));
if ( desHostnameDone.hasOwnProperty(des) ) {
continue;
}
addDynamicFilterRow(des);
desHostnameDone[des] = true;
} }
var summary = vAPI.i18n('popupHitDomainCountPrompt') var summary = vAPI.i18n('popupHitDomainCountPrompt')
@ -244,15 +281,16 @@ var syncAllDynamicFilters = function() {
.on('click', 'span[data-src]', unsetDynamicFilterHandler) .on('click', 'span[data-src]', unsetDynamicFilterHandler)
.on('mouseenter', '[data-src]', mouseenterCellHandler) .on('mouseenter', '[data-src]', mouseenterCellHandler)
.on('mouseleave', '[data-src]', mouseleaveCellHandler); .on('mouseleave', '[data-src]', mouseleaveCellHandler);
dfHotspots = uDom('#actionSelector')
.on('click', 'span', setDynamicFilterHandler)
.detach();
dfPaneBuilt = true; dfPaneBuilt = true;
} }
updateAllDynamicFilters();
}; };
/******************************************************************************/ /******************************************************************************/
// Assume everything has to be done incrementally.
var renderPopup = function() { var renderPopup = function() {
uDom('#appname').text(popupData.appName); uDom('#appname').text(popupData.appName);
uDom('#version').text(popupData.appVersion); uDom('#version').text(popupData.appVersion);
@ -261,8 +299,11 @@ var renderPopup = function() {
// Condition for dynamic filtering toggler: // Condition for dynamic filtering toggler:
// - Advanced user // - Advanced user
uDom('body').removeClass('dirty');
uDom('body').toggleClass('advancedUser', popupData.advancedUserEnabled); uDom('body').toggleClass('advancedUser', popupData.advancedUserEnabled);
uDom('#switch').toggleClass('off', popupData.pageURL === '' || !popupData.netFilteringSwitch);
// Conditions for request log: // Conditions for request log:
// - `http` or `https` scheme // - `http` or `https` scheme
uDom('#gotoLog').toggleClass('enabled', isHTTP); uDom('#gotoLog').toggleClass('enabled', isHTTP);
@ -306,13 +347,16 @@ var renderPopup = function() {
} }
uDom('#total-blocked').html(html.join('')); uDom('#total-blocked').html(html.join(''));
// Build dynamic filtering pane only if in use // https://github.com/gorhill/uBlock/issues/470
if ( popupData.dfEnabled && popupData.advancedUserEnabled ) { // This must be done here, to be sure the popup is resized properly
syncAllDynamicFilters(); var dfPaneVisible = popupData.dfEnabled && popupData.advancedUserEnabled;
}
uDom('#switch .fa').toggleClass('off', popupData.pageURL === '' || !popupData.netFilteringSwitch); uDom('#panes').toggleClass('dfEnabled', dfPaneVisible);
uDom('#panes').toggleClass('dfEnabled', popupData.dfEnabled && popupData.advancedUserEnabled);
// Build dynamic filtering pane only if in use
if ( dfPaneVisible ) {
buildAllDynamicFilters();
}
}; };
/******************************************************************************/ /******************************************************************************/
@ -328,6 +372,8 @@ var toggleNetFilteringSwitch = function(ev) {
state: !uDom(this).toggleClass('off').hasClass('off'), state: !uDom(this).toggleClass('off').hasClass('off'),
tabId: popupData.tabId tabId: popupData.tabId
}); });
hashFromPopupData();
}; };
/******************************************************************************/ /******************************************************************************/
@ -387,17 +433,23 @@ var gotoLink = function(ev) {
/******************************************************************************/ /******************************************************************************/
var toggleDynamicFiltering = function(ev) { var toggleDynamicFiltering = function() {
if ( uDom('body').hasClass('advancedUser') === false ) { if ( popupData.advancedUserEnabled === false ) {
return; return;
} }
var el = uDom('#panes');
popupData.dfEnabled = !popupData.dfEnabled; popupData.dfEnabled = !popupData.dfEnabled;
messager.send({ messager.send({
what: 'userSettings', what: 'userSettings',
name: 'dynamicFilteringEnabled', name: 'dynamicFilteringEnabled',
value: popupData.dfEnabled value: popupData.dfEnabled
}, renderPopup); });
// Dynamic filtering pane may not have been built yet
uDom('#panes').toggleClass('dfEnabled', popupData.dfEnabled);
if ( popupData.dfEnabled && dfPaneBuilt === false ) {
buildAllDynamicFilters();
}
}; };
/******************************************************************************/ /******************************************************************************/
@ -421,7 +473,8 @@ var setDynamicFilter = function(src, des, type, action) {
} }
var onDynamicFilterChanged = function(response) { var onDynamicFilterChanged = function(response) {
cachePopupData(response); cachePopupData(response);
syncAllDynamicFilters(); updateAllDynamicFilters();
hashFromPopupData();
}; };
messager.send({ messager.send({
what: 'toggleDynamicFilter', what: 'toggleDynamicFilter',
@ -475,21 +528,90 @@ var setDynamicFilterHandler = function() {
/******************************************************************************/ /******************************************************************************/
var reloadTab = function() {
messager.send({ what: 'reloadTab', tabId: popupData.tabId });
// Polling will take care of refreshing the popup content
};
/******************************************************************************/
// Poll for changes.
//
// I couldn't find a better way to be notified of changes which can affect
// popup content, as the messaging API doesn't support firing events accurately
// from the main extension process to a specific auxiliary extension process:
//
// - broadcasting() is not an option given there could be a lot of tabs opened,
// and maybe even many frames within these tabs, i.e. unacceptable overhead
// regardless of whether the popup is opened or not).
//
// - Modifying the messaging API is not an option, as this would require
// revisiting all platform-specific code to support targeted broadcasting,
// which who knows could be not so trivial for some platforms.
//
// A well done polling is a better anyways IMO, I prefer that data is pulled
// on demand rather than having the main process assumes somebody may need to
// be expressly notified.
var pollForContentChange = (function() {
var pollTimer = null;
var pollCallback = function() {
pollTimer = null;
messager.send(
{
what: 'hasPopupContentChanged',
tabId: popupData.tabId,
contentLastModified: popupData.contentLastModified
},
queryCallback
);
};
var queryCallback = function(response) {
if ( response ) {
getPopupData();
return;
}
poll();
};
var poll = function() {
if ( pollTimer !== null ) {
return;
}
pollTimer = setTimeout(pollCallback, 1500);
};
return poll;
})();
/******************************************************************************/
var getPopupData = function() {
var onDataReceived = function(response) {
cachePopupData(response);
renderPopup();
hashFromPopupData(true);
pollForContentChange();
};
messager.send({ what: 'getPopupData' }, onDataReceived);
};
/******************************************************************************/
// Make menu only when popup html is fully loaded // Make menu only when popup html is fully loaded
uDom.onLoad(function() { uDom.onLoad(function() {
messager.send({ what: 'activeTabStats' }, function(response) { getPopupData();
if ( !cachePopupData(response) ) {
return;
}
renderPopup();
});
uDom('h1,h2,h3,h4').on('click', gotoDashboard); uDom('h1,h2,h3,h4').on('click', gotoDashboard);
uDom('#switch .fa').on('click', toggleNetFilteringSwitch); uDom('#switch').on('click', toggleNetFilteringSwitch);
uDom('#gotoLog').on('click', gotoDevTools); uDom('#gotoLog').on('click', gotoDevTools);
uDom('#gotoPick').on('click', gotoPick); uDom('#gotoPick').on('click', gotoPick);
uDom('a[href^=http]').on('click', gotoLink); uDom('a[href^=http]').on('click', gotoLink);
uDom('#dfToggler').on('click', toggleDynamicFiltering); uDom('#dfToggler').on('click', toggleDynamicFiltering);
uDom('#refresh').on('click', reloadTab);
}); });
/******************************************************************************/ /******************************************************************************/

View File

@ -225,6 +225,12 @@ DOMList.prototype.toArray = function() {
/******************************************************************************/ /******************************************************************************/
DOMList.prototype.pop = function() {
return addNodeToList(new DOMList(), this.nodes.pop());
};
/******************************************************************************/
DOMList.prototype.forEach = function(fn) { DOMList.prototype.forEach = function(fn) {
var n = this.nodes.length; var n = this.nodes.length;
for ( var i = 0; i < n; i++ ) { for ( var i = 0; i < n; i++ ) {

View File

@ -23,6 +23,7 @@
<p id="page-blocked">?</p> <p id="page-blocked">?</p>
<p class="stats" data-i18n="popupBlockedSinceInstallPrompt"></p> <p class="stats" data-i18n="popupBlockedSinceInstallPrompt"></p>
<p id="total-blocked">?</p> <p id="total-blocked">?</p>
<div id="refresh" class="fa">&#xf021;</div>
</div><!-- DO NOT REMOVE --><div> </div><!-- DO NOT REMOVE --><div>
<div id="dynamicFilteringContainer"> <div id="dynamicFilteringContainer">
<div><span data-i18n="popupImageRulePrompt"></span><span data-src="/" data-des="*" data-type="image"> </span><span data-src="." data-des="*" data-type="image"></span></div> <div><span data-i18n="popupImageRulePrompt"></span><span data-src="/" data-des="*" data-type="image"> </span><span data-src="." data-des="*" data-type="image"></span></div>