Popup and settings work, but all scripts can run doubly if uw.init() was called twice

This commit is contained in:
Tamius Han 2018-08-30 00:56:15 +02:00
parent 38a94e3bd3
commit 0c37c5a0e1
10 changed files with 298 additions and 249 deletions

View File

@ -7,8 +7,8 @@ Debug = {
keyboard: true,
debugResizer: true,
debugArDetect: true,
debugStorage: true,
comms: true,
debugStorage: false,
comms: false,
// showArDetectCanvas: true,
flushStoredSettings: false,
playerDetectDebug: true,

View File

@ -194,13 +194,15 @@ var ExtensionConf = {
status: "enabled", // should extension work on this site?
arStatus: "default", // should we enable autodetection
statusEmbedded: "enabled", // should extension work for this site when embedded on other sites?
override: false // ignore value localStorage in favour of this
override: false, // ignore value localStorage in favour of this
type: 'official' // is officially supported? (Alternatives are 'community' and 'user-defined')
},
"www.netflix.com" : {
status: "enabled",
arStatus: BrowserDetect.firefox ? "default" : "disabled",
statusEmbedded: "enabled",
override: false
override: false,
type: 'official'
},
}
}

View File

@ -13,24 +13,46 @@ class CommsClient {
}
var ths = this;
this.port.onMessage.addListener(m => ths.processReceivedMessage(m));
this._listener = m => ths.processReceivedMessage(m);
this.port.onMessage.addListener(this._listener);
this.settings = settings;
this.pageInfo = undefined;
this.commsId = (Math.random() * 20).toFixed(0);
}
destroy() {
this.pageInfo = null;
this.settings = null;
this.port.onMessage.removeListener(this._listener);
}
setPageInfo(pageInfo){
this.pageInfo = pageInfo;
if(Debug.debug) {
console.log(`[CommsClient::setPageInfo] <${this.commsId}>`, "SETTING PAGEINFO —", this.pageInfo, this)
}
var ths = this;
this._listener = m => ths.processReceivedMessage(m);
this.port.onMessage.removeListener(this._listener);
this.port.onMessage.addListener(this._listener);
}
processReceivedMessage(message){
if(Debug.debug && Debug.comms){
console.log("[CommsClient.js::processMessage] Received message from background script!", message);
console.log(`[CommsClient.js::processMessage] <${this.commsId}> Received message from background script!`, message);
}
if (! this.pageInfo || this.settings.active) {
if (!this.pageInfo || !this.settings.active) {
if(Debug.debug && Debug.comms){
console.log("[CommsClient.js::processMessage] this.pageInfo not defined. Extension is probably disabled for this site.");
console.log(`[CommsClient.js::processMessage] <${this.commsId}> this.pageInfo (or settings) not defined. Extension is probably disabled for this site.\npageInfo:`, this.pageInfo,
"\nsettings.active:", this.settings.active,
"\nnobj:", this
);
}
return;
}
@ -40,12 +62,6 @@ class CommsClient {
} else if (message.cmd === 'set-video-float') {
this.settings.active.miscFullscreenSettings.videoFloat = message.newFloat;
this.pageInfo.restoreAr();
} else if (message.cmd === "has-videos") {
} else if (message.cmd === "set-config") {
this.hasSettings = true;
this.settings.active = message.conf;
// this.pageInfo.reset();
} else if (message.cmd === "set-stretch") {
this.pageInfo.setStretchMode(StretchMode[message.mode]);
} else if (message.cmd === "autoar-start") {
@ -60,28 +76,7 @@ class CommsClient {
} else if (message.cmd === "resume-processing") {
// todo: autoArStatus
this.pageInfo.resumeProcessing(message.autoArStatus);
} else if (message.cmd === "reload-settings") {
this.settings.active = message.newConf;
this.pageInfo.reset();
if(this.settings.active.arDetect.mode === "disabled") {
this.pageInfo.stopArDetection();
} else {
this.pageInfo.startArDetection();
}
}
}
async waitForSettings(){
var t = this;
return new Promise( async (resolve, reject) => {
while(true){
await t.sleep(100);
if(this.hasSettings){
resolve();
break;
}
}
});
}
}
async sleep(n){
@ -131,10 +126,6 @@ class CommsClient {
return Promise.resolve(true);
}
async requestSettings_fallback(){
this.port.postMessage({cmd: "get-config"});
}
registerVideo(){
this.port.postMessage({cmd: "has-video"});
}
@ -236,6 +227,10 @@ class CommsServer {
console.log("[CommsServer.js::processMessage] Received message from background script!", message, "port", port, "\nsettings and server:", this.settings,this.server);
}
if(message.cmd === 'get-current-site') {
port.postMessage({cmd: 'set-current-site', site: this.server.currentSite});
}
if (message.cmd === 'get-config') {
if(Debug.debug) {
console.log("CommsServer: received get-config. Active settings?", this.settings.active, "\n(settings:", this.settings, ")")
@ -246,25 +241,17 @@ class CommsServer {
} else if (message.cmd === 'set-stretch-default') {
this.settings.active.stretch.initialMode = message.mode;
this.settings.save();
this.sendToAll({cmd: 'reload-settings', newConf: this.settings.active});
} else if (message.cmd === 'set-ar') {
this.sendToActive(message);
} else if (message.cmd === 'set-custom-ar') {
this.settings.active.keyboard.shortcuts.q.arg = message.ratio;
this.settings.save();
this.sendToAll({cmd: 'reload-settings', newConf: this.settings.active});
} else if (message.cmd === 'set-video-float') {
this.sendToActive(message);
this.settings.active.miscFullscreenSettings.videoFloat = message.newFloat;
this.settings.save();
this.sendToAll({cmd: 'reload-settings', newConf: this.settings.active});
} else if (message.cmd === 'autoar-start') {
this.sendToActive(message);
} else if (message.cmd === "autoar-enable") { // LEGACY - can be removed prolly?
this.settings.active.arDetect.mode = "blacklist";
this.settings.save();
this.sendToAll({cmd: 'reload-settings', newConf: this.settings.active});
} else if (message.cmd === "autoar-disable") { // LEGACY - can be removed prolly?
this.settings.active.arDetect.mode = "disabled";
if(message.reason){
@ -273,7 +260,6 @@ class CommsServer {
this.settings.active.arDetect.disabledReason = 'User disabled';
}
this.settings.save();
this.sendToAll({cmd: 'reload-settings', newConf: this.settings.active});
} else if (message.cmd === "autoar-set-interval") {
if(Debug.debug)
console.log("[uw-bg] trying to set new interval for autoAr. New interval is",message.timeout,"ms");
@ -282,15 +268,12 @@ class CommsServer {
var timeout = message.timeout < 4 ? 4 : message.timeout;
this.settings.active.arDetect.timer_playing = timeout;
this.settings.save();
this.sendToAll({cmd: 'reload-settings', newConf: this.settings.active});
} else if (message.cmd === "set-autoar-defaults") {
this.settings.active.arDetect.mode = message.mode;
this.settings.save();
this.sendToAll({cmd: "reload-settings", sender: "uwbg"})
} else if (message.cmd === "set-autoar-for-site") {
if (this.settings.active.sites[this.server.currentSite]) {
this.settings.active.sites[this.server.currentSite].arStatus = message.mode;
console.log("SAVING AUTOAR MODE FOR SITE", this.server.currentSite, "\nnew site obj",this.settings.active.sites[this.server.currentSite] )
this.settings.save();
} else {
this.settings.active.sites[this.server.currentSite] = {
@ -300,11 +283,9 @@ class CommsServer {
};
this.settings.save();
}
this.sendToAll({cmd: "reload-settings", sender: "uwbg"});
} else if (message.cmd === "set-extension-defaults") {
this.settings.active.extensionMode = message.mode;
this.settings.save();
this.sendToAll({cmd: "reload-settings", sender: "uwbg"})
} else if (message.cmd === "set-extension-for-site") {
if (this.settings.active.sites[this.server.currentSite]) {
this.settings.active.sites[this.server.currentSite].status = message.mode;
@ -315,14 +296,11 @@ class CommsServer {
arStatus: "default",
statusEmbedded: message.mode
};
this.settings.save();
console.log("SAVING PER-SITE OPTIONS,", this.server.currentSite, this.settings.active.sites[this.server.currentSite])
this.settings.save();
if(Debug.debug) {
console.log("SAVING PER-SITE OPTIONS,", this.server.currentSite, this.settings.active.sites[this.server.currentSite])
}
}
this.sendToAll({cmd: "reload-settings", sender: "uwbg"});
}
if (message.cmd.startsWith('set-')) {
port.postMessage({cmd: "set-config", conf: this.settings.active, site: this.server.currentSite});
}
}

View File

@ -1,16 +1,17 @@
class Settings {
constructor(activeSettings) {
constructor(activeSettings, updateCallback) {
this.active = activeSettings ? activeSettings : undefined;
this.default = ExtensionConf;
this.useSync = false;
this.version = undefined;
this.updateCallback = updateCallback;
const ths = this;
if(BrowserDetect.firefox) {
browser.storage.onChanged.addListener( (changes, area) => {
if (Debug.debug) {
if (Debug.debug && Debug.debugStorage) {
console.log("[Settings::<storage/on change>] Settings have been changed outside of here. Updating active settings. Changes:", changes, "storage area:", area);
if (changes['uwSettings'] && changes['uwSettings'].newValue) {
console.log("[Settings::<storage/on change>] new settings object:", JSON.parse(changes.uwSettings.newValue));
@ -19,10 +20,18 @@ class Settings {
if(changes['uwSettings'] && changes['uwSettings'].newValue) {
ths.active = JSON.parse(changes.uwSettings.newValue);
}
if(this.updateCallback) {
try {
updateCallback();
} catch (e) {
console.log("[Settings] CALLING UPDATE CALLBACK FAILED.")
}
}
});
} else if (BrowserDetect.chrome) {
chrome.storage.onChanged.addListener( (changes, area) => {
if (Debug.debug) {
if (Debug.debug && Debug.debugStorage) {
console.log("[Settings::<storage/on change>] Settings have been changed outside of here. Updating active settings. Changes:", changes, "storage area:", area);
if (changes['uwSettings'] && changes['uwSettings'].newValue) {
console.log("[Settings::<storage/on change>] new settings object:", JSON.parse(changes.uwSettings.newValue));
@ -31,7 +40,15 @@ class Settings {
if(changes['uwSettings'] && changes['uwSettings'].newValue) {
ths.active = JSON.parse(changes.uwSettings.newValue);
}
})
if(this.updateCallback) {
try {
updateCallback();
} catch (e) {
console.log("[Settings] CALLING UPDATE CALLBACK FAILED.")
}
}
});
}
}

View File

@ -40,6 +40,10 @@ class VideoData {
}
destroy() {
if(Debug.debug){
console.log("[VideoData::destroy] received destroy command");
}
this.destroyed = true;
if(this.arDetector){
this.arDetector.stop();
@ -49,9 +53,11 @@ class VideoData {
if(this.resizer){
this.resizer.destroy();
}
this.resizer = null;
if(this.player){
this.player.destroy();
}
this.player = null;
this.video = null;
}

View File

@ -3,8 +3,6 @@ if(Debug.debug)
class PageInfo {
constructor(comms, settings){
this.keybinds = new Keybinds(this);
this.keybinds.setup();
this.hasVideos = false;
this.siteDisabled = false;
this.videos = [];
@ -17,13 +15,21 @@ class PageInfo {
if(comms){
this.comms = comms;
this.comms.setPageInfo(this);
if(this.videos.length > 0){
comms.registerVideo();
}
}
if(this.videos.length > 0){
comms.registerVideo();
}
}
destroy() {
if(Debug.debug){
console.log("[PageInfo::destroy] destroying all videos!")
}
for (var video of this.videos) {
video.destroy();
}
}
reset() {
for(var video of this.videos) {
@ -128,7 +134,7 @@ class PageInfo {
ths.rescanTimer = null;
ths.rescan(rr);
ths = null;
}, rescanReason === settings.active.pageInfo.timeouts.rescan, RescanReason.PERIODIC)
}, rescanReason === this.settings.active.pageInfo.timeouts.rescan, RescanReason.PERIODIC)
} catch(e) {
if(Debug.debug){
console.log("[PageInfo::scheduleRescan] scheduling rescan failed. Here's why:",e)
@ -148,7 +154,7 @@ class PageInfo {
ths.rescanTimer = null;
ths.ghettoUrlCheck();
ths = null;
}, settings.active.pageInfo.timeouts.urlCheck)
}, this.settings.active.pageInfo.timeouts.urlCheck)
}catch(e){
if(Debug.debug){
console.log("[PageInfo::scheduleUrlCheck] scheduling URL check failed. Here's why:",e)

View File

@ -36,6 +36,8 @@ class Resizer {
this.lastAr = {type: 'original'};
this.destroyed = false;
this.resizerId = (Math.random(99)*100).toFixed(0);
}
start(){
@ -47,17 +49,23 @@ class Resizer {
}
destroy(){
if(Debug.debug){
console.log(`[Resizer::destroy] <rid:${this.resizerId}> received destroy command.`);
}
this.destroyed = true;
this.stopCssWatcher();
}
setAr(ar, lastAr){
if (this.destroyed) {
return;
}
this.startCssWatcher();
this.cssWatcherIncreasedFrequencyCounter = 20;
if(Debug.debug){
console.log('[Resizer::setAr] trying to set ar. New ar:', ar)
console.log('[Resizer::setAr] <rid:'+this.resizerId+'> trying to set ar. New ar:', ar)
}
if(lastAr) {
@ -89,7 +97,7 @@ class Resizer {
if(! stretchFactors || stretchFactors.error){
if(Debug.debug){
console.log("[Resizer::setAr] failed to set AR due to problem with calculating crop. Error:", (stretchFactors ? stretchFactors.error : stretchFactors));
console.log("[Resizer::setAr] <rid:"+this.resizerId+"> failed to set AR due to problem with calculating crop. Error:", (stretchFactors ? stretchFactors.error : stretchFactors));
}
if(stretchFactors.error === 'no_video'){
this.conf.destroy();
@ -142,6 +150,9 @@ class Resizer {
}
startCssWatcher(){
if (this.destroyed) {
return;
}
// this.haltCssWatcher = false;
if(!this.cssWatcherTimer){
this.scheduleCssWatcher(1);
@ -152,6 +163,10 @@ class Resizer {
}
scheduleCssWatcher(timeout, force_reset) {
if (this.destroyed) {
return;
}
if(timeout === undefined) {
console.log("?")
this.cssCheck(); // no timeout = one-off
@ -183,7 +198,7 @@ class Resizer {
restore() {
if(Debug.debug){
console.log("[Resizer::restore] attempting to restore aspect ratio. this & settings:", {'this': this, "settings": Settings} );
console.log("[Resizer::restore] <rid:"+this.resizerId+"> attempting to restore aspect ratio. this & settings:", {'this': this, "settings": this.settings} );
}
// this is true until we verify that css has actually been applied
@ -232,7 +247,7 @@ class Resizer {
computeOffsets(stretchFactors){
if(Debug.debug)
console.log("[Resizer::_res_computeOffsets] video will be aligned to ", settings.active.miscFullscreenSettings.videoFloat);
console.log("[Resizer::_res_computeOffsets] <rid:"+this.resizerId+"> video will be aligned to ", this.settings.active.miscFullscreenSettings.videoFloat);
var actualWidth = this.conf.video.offsetWidth * stretchFactors.xFactor;
var actualHeight = this.conf.video.offsetHeight * stretchFactors.yFactor;
@ -242,10 +257,10 @@ class Resizer {
if (this.pan) {
// todo: calculate translate
} else {
if (settings.active.miscFullscreenSettings.videoFloat == "left") {
if (this.settings.active.miscFullscreenSettings.videoFloat == "left") {
translate.x = (this.conf.player.dimensions.width - actualWidth) * -0.5;
}
else if (settings.active.miscFullscreenSettings.videoFloat == "right") {
else if (this.settings.active.miscFullscreenSettings.videoFloat == "right") {
translate.x = (this.conf.player.dimensions.width - actualWidth) * 0.5;
}
}
@ -257,7 +272,7 @@ class Resizer {
if (! this.video) {
if(Debug.debug)
console.log("[Resizer::_res_applyCss] Video went missing, doing nothing.");
console.log("[Resizer::_res_applyCss] <rid:"+this.resizerId+"> Video went missing, doing nothing.");
this.conf.destroy();
return;
}
@ -312,7 +327,7 @@ class Resizer {
if(! this.video){
if(Debug.debug)
console.log("[Resizer::_res_setStyleString] Video element went missing, nothing to do here.")
console.log("[Resizer::_res_setStyleString] <rid:"+this.resizerId+"> Video element went missing, nothing to do here.")
return;
}
@ -337,7 +352,7 @@ class Resizer {
}
else{
if(Debug.debug)
console.log("[Resizer::_res_setStyleString] css applied. Style string:", styleString);
console.log("[Resizer::_res_setStyleString] <rid:"+this.resizerId+"> css applied. Style string:", styleString);
}
}
@ -350,64 +365,29 @@ class Resizer {
// this means video went missing. videoData will be re-initialized when the next video is found
if(! this.video){
if(Debug.debug) {
console.log("[Resizer::cssCheck] <rid:"+this.resizerId+"> no video detecting, issuing destroy command");
}
this.conf.destroy();
return;
}
if(this.destroyed) {
if(Debug.debug) {
console.log("[Resizer::cssCheck] <rid:"+this.resizerId+"> destroyed flag is set, we shouldnt be running");
}
return;
}
var styleString = this.video.getAttribute('style');
// first, a quick test:
// if (this.currentVideoSettings.validFor == this.conf.player.dimensions ){
if (this.currentStyleString !== styleString){
this.restore();
this.scheduleCssWatcher(10);
return;
}
// }
// if (styleString){
// var styleArray = styleString.split(";");
// var stuffChecked = 0;
// var stuffToCheck = 2;
// for(var i in styleArray){
// styleArray[i] = styleArray[i].trim();
// if (styleArray[i].startsWith("top:")){
// // don't force css restore if currentCss.top is not defined
// if(this.currentCss.top && styleArray[i] != this.currentCss.top){
// if(Debug.debug){
// console.log("[Resizer::_res_antiCssOverride] SOMEBODY TOUCHED MA SPAGHETT (our CSS got overriden, restoring our css)");
// console.log("[Resizer::_res_antiCssOverride] MA SPAGHETT: top:", this.currentCss.top, "left:", this.currentCss.left, "thing that touched ma spaghett", styleString);
// }
// this.restore();
// return;
// }
// stuffChecked++;
// }
// else if(styleArray[i].startsWith("left:")){
// // don't force css restore if currentCss.left is not defined
// if(this.currentCss.left && styleArray[i] != this.currentCss.left){
// if(Debug.debug){
// console.log("[Resizer::_res_antiCssOverride] SOMEBODY TOUCHED MA SPAGHETT (our CSS got overriden, restoring our css)");
// console.log("[Resizer::_res_antiCssOverride] MA SPAGHETT: width:", this.currentCss.width, "height:", this.currentCss.height, "thing that touched ma spaghett", styleString);
// }
// this.restore();
// return;
// }
// stuffChecked++;
// }
// if(stuffChecked == stuffToCheck){
// // if(Debug.debug){
// // console.log("[Resizer::_res_antiCssOverride] My spaghett rests untouched. (nobody overrode our CSS, doing nothing)");
// // }
// return;
// }
// }
// }
if (this.currentStyleString !== styleString){
this.restore();
this.scheduleCssWatcher(10);
return;
}
if (this.cssWatcherIncreasedFrequencyCounter > 0) {
--this.cssWatcherIncreasedFrequencyCounter;
this.scheduleCssWatcher(20);

107
js/uw.js
View File

@ -13,57 +13,64 @@ if(Debug.debug){
}
var pageInfo;
var comms;
var settings;
class UW {
constructor(){
this.pageInfo = undefined;
this.comms = undefined;
this.settings = undefined;
this.keybinds = undefined;
}
async function init(){
if(Debug.debug)
console.log("[uw::main] loading configuration ...");
settings = new Settings();
await settings.init();
comms = new CommsClient('content-client-port', settings);
// load settings
// var settingsLoaded = await comms.requestSettings();
// if(!settingsLoaded){
// if(Debug.debug) {
// console.log("[uw::main] failed to get settings (settingsLoaded=",settingsLoaded,") Waiting for settings the old fashioned way");
// }
// comms.requestSettings_fallback();
// await comms.waitForSettings();
// if(Debug.debug){
// console.log("[uw::main] settings loaded.");
// }
// }
// if(Debug.debug)
// console.log("[uw::main] configuration should be loaded now");
console.log("SETTINGS SHOULD BE LOADED NOW!", settings)
// če smo razširitev onemogočili v nastavitvah, ne naredimo ničesar
// If extension is soft-disabled, don't do shit
if(! settings.canStartExtension()){
if(Debug.debug) {
console.log("[uw::init] EXTENSION DISABLED, THEREFORE WONT BE STARTED")
async init(){
if (Debug.debug) {
console.log("[uw::main] loading configuration ...");
}
return;
}
try {
pageInfo = new PageInfo(comms, settings);
} catch (e) {
console.log("[uw::init] FAILED TO START EXTENSION. Error:", e);
}
if(Debug.debug){
console.log("[uw.js::setup] pageInfo initialized. Here's the object:", pageInfo);
// init() is re-run any time settings change
if (this.pageInfo) {
if(Debug.debug){
console.log("[uw::init] Destroying existing pageInfo", this.pageInfo);
}
this.pageInfo.destroy();
}
if (this.comms) {
this.comms.destroy();
}
if (!this.settings) {
var ths = this;
this.settings = new Settings(undefined, () => ths.init());
await this.settings.init();
}
this.comms = new CommsClient('content-client-port', this.settings);
// če smo razširitev onemogočili v nastavitvah, ne naredimo ničesar
// If extension is soft-disabled, don't do shit
if(! this.settings.canStartExtension()){
if(Debug.debug) {
console.log("[uw::init] EXTENSION DISABLED, THEREFORE WONT BE STARTED")
}
return;
}
try {
this.pageInfo = new PageInfo(this.comms, this.settings);
if(Debug.debug){
console.log("[uw.js::setup] pageInfo initialized. Here's the object:", this.pageInfo);
}
this.comms.setPageInfo(this.pageInfo);
this.keybinds = new Keybinds(this.pageInfo);
this.keybinds.setup();
} catch (e) {
console.log("[uw::init] FAILED TO START EXTENSION. Error:", e);
}
}
}
init();
var uw = new UW();
uw.init();

View File

@ -5,7 +5,6 @@ document.getElementById("uw-version").textContent = browser.runtime.getManifest(
var Menu = {};
// Menu.noVideo = document.getElementById("no-videos-display");
Menu.general = document.getElementById("extension-mode");
Menu.thisSite = document.getElementById("settings-for-current-site");
Menu.arSettings = document.getElementById("aspect-ratio-settings");
Menu.autoAr = document.getElementById("autoar-basic-settings");
@ -57,40 +56,31 @@ StretchPanel.global.hybrid = document.getElementById("_stretch_global_hybri
StretchPanel.global.conditional = document.getElementById("_stretch_global_conditional");
var selectedMenu = "arSettings";
var selectedMenu = "";
var hasVideos = false;
var _config;
var _changeAr_button_shortcuts = { "autoar":"none", "reset":"none", "219":"none", "189":"none", "169":"none", "custom":"none" }
var comms = new Comms();
var settings = new Settings();
var settings = new Settings(undefined, () => updateConfig());
var site = undefined;
var port = browser.runtime.connect({name: 'popup-port'});
port.onMessage.addListener( (m,p) => processReceivedMessage(m,p));
// let's init settings and check if they're loaded
await settings.init();
if (Debug.debug) {
console.log("[popup] Are settings loaded?", settings)
async function processReceivedMessage(message, port){
if(message.cmd === 'set-current-site'){
site = message.site;
loadConfig(message.site);
}
}
async function processReceivedMessage(message, port){
if(message.cmd === 'set-config'){
if(Debug.debug){
console.log("[popup.js] setting config. Message was:", message)
}
this.loadConfig(message.conf, message.site);
async function updateConfig() {
if (site) {
loadConfig(site);
}
}
@ -116,12 +106,43 @@ function stringToKeyCombo(key_in){
return keys_out;
}
async function loadConfig(){
async function loadConfig(site){
if(Debug.debug)
console.log("[popup.js::loadConfig] loading config. conf object:", settings.active, "\n\n\n\n\n\n\n\n-------------------------------------");
// -----------------------
//#region tab-disabled
//
// if extension is disabled on current site, we can't do shit. Therefore, the following tabs will be disabled:
// * AutoAR options
// * Crop settings
// * Stretch settings
var canStartExtension = settings.canStartExtension(site);
if (canStartExtension) {
MenuTab.arSettings.classList.remove('disabled');
MenuTab.autoAr.classList.remove('disabled');
MenuTab.stretchSettings.classList.remove('disabled');
// only switch when popup is being opened for the first time
if(! selectedMenu) {
openMenu('arSettings');
}
} else {
MenuTab.arSettings.classList.add('disabled');
MenuTab.autoAr.classList.add('disabled');
MenuTab.stretchSettings.classList.add('disabled');
// if popup isn't being opened for the first time, there's no reason to switch
// we're already in this tab
if(! selectedMenu) {
openMenu('thisSite');
}
}
//#endregion
//
// ----------------------
//#region extension-basics - SET BASIC EXTENSION OPTIONS
if(Debug.debug)
@ -252,8 +273,8 @@ async function loadConfig(){
console.log("[popup.js::loadConfig] config loaded");
}
async function getConf(){
port.postMessage({cmd: 'get-config'});
async function getSite(){
port.postMessage({cmd: 'get-current-site'});
}
function openMenu(menu){
@ -337,9 +358,9 @@ function validateCustomAr(){
function validateAutoArTimeout(){
const inputField = document.getElementById("_input_autoAr_timer");
const valueSaveButton = document.getElementById("_b_autoar_save_autoar_frequency");
const valueSaveButton = document.getElementById("_b_autoar_save_autoar_timer");
if (! isNaN(parseInt(inputField.trim().value()))) {
if (! isNaN(parseInt(inputField.value.trim().value()))) {
inputField.classList.remove("invalid-input");
valueSaveButton.classList.remove("disabled-button");
} else {
@ -348,13 +369,6 @@ function validateAutoArTimeout(){
}
}
function toggleSite(option){
if(Debug.debug)
console.log("[popup::toggleSite] toggling extension 'should I work' status to", option, "on current site");
Comms.sendToBackgroundScript({cmd:"enable-for-site", option:option});
}
document.addEventListener("click", (e) => {
@ -367,9 +381,6 @@ document.addEventListener("click", (e) => {
return;
if(e.target.classList.contains("menu-item")){
if(e.target.classList.contains("_menu_general")){
openMenu("general");
}
if(e.target.classList.contains("_menu_this_site")){
openMenu("thisSite");
}
@ -405,15 +416,28 @@ document.addEventListener("click", (e) => {
settings.save();
return;
} else if (e.target.classList.contains("_ext_site_options")) {
command.cmd = "set-extension-for-site";
var mode;
if(e.target.classList.contains("_blacklist")){
command.mode = "disabled";
mode = "disabled";
} else if(e.target.classList.contains("_whitelist")) {
command.mode = "enabled";
mode = "enabled";
} else {
command.mode = "default";
mode = "default";
}
return command;
if(settings.active.sites[site]) {
settings.active.sites[site].status = mode;
settings.active.sites[site].statusEmbedded = mode;
} else {
settings.active.sites[site] = {
status: mode,
statusEmbedded: mode,
arStatus: 'default',
type: 'user-defined'
}
}
settings.save();
return;
}
}
if(e.target.classList.contains("_changeAr")){
@ -511,8 +535,8 @@ document.addEventListener("click", (e) => {
}
settings.save();
return;
} else if (e.target.classList.contains("_save_autoAr_frequency")) {
var value = parseInt(document.getElementById("_input_autoAr_frequency").value.trim());
} else if (e.target.classList.contains("_save_autoAr_timer")) {
var value = parseInt(document.getElementById("_input_autoAr_timer").value.trim());
if(! isNaN(value)){
var timeout = parseInt(value);
@ -521,15 +545,27 @@ document.addEventListener("click", (e) => {
}
return;
} else if (e.target.classList.contains("_ar_site_options")) {
command.cmd = "set-autoar-for-site";
var mode;
if(e.target.classList.contains("_disabled")){
command.mode = "disabled";
mode = "disabled";
} else if(e.target.classList.contains("_enabled")) {
command.mode = "enabled";
mode = "enabled";
} else {
command.mode = "default";
mode = "default";
}
return command;
if(settings.active.sites[site]) {
settings.active.sites[site].arStatus = mode;
} else {
settings.active.sites[site] = {
status: settings.active.extensionMode,
statusEmbedded: settings.active.extensionMode,
arStatus: mode,
type: 'user-defined'
}
}
settings.save();
return;
}
}
@ -557,23 +593,39 @@ document.addEventListener("click", (e) => {
return true;
});
const customArInputField = document.getElementById("_input_custom_ar");
const autoarFrequencyInputField = document.getElementById("_input_autoAr_timer");
customArInputField.addEventListener("blur", (event) => {
validateCustomAr();
});
customArInputField.addEventListener("mouseleave", (event) => {
validateCustomAr();
});
autoarFrequencyInputField.addEventListener("blur", (event) => {
validateAutoArTimeout();
});
autoarFrequencyInputField.addEventListener("mouseleave", (event) => {
validateAutoArTimeout();
});
hideWarning("script-not-running-warning");
openMenu(selectedMenu);
getConf();
async function popup_init() {
// let's init settings and check if they're loaded
await settings.init();
if (Debug.debug) {
console.log("[popup] Are settings loaded?", settings)
}
const customArInputField = document.getElementById("_input_custom_ar");
const autoarFrequencyInputField = document.getElementById("_input_autoAr_timer");
customArInputField.addEventListener("blur", (event) => {
validateCustomAr();
});
customArInputField.addEventListener("mouseleave", (event) => {
validateCustomAr();
});
autoarFrequencyInputField.addEventListener("blur", (event) => {
validateAutoArTimeout();
});
autoarFrequencyInputField.addEventListener("mouseleave", (event) => {
validateAutoArTimeout();
});
hideWarning("script-not-running-warning");
getSite();
}
popup_init();

View File

@ -166,7 +166,7 @@
</div>
<!-- <p><small class="color_warn" id="_autoAr_disabled_reason"></small><br/> -->
<p>Check every <input id="_input_autoAr_timer" class="_autoAr _autoAr_timer" type="number" min="5" max="10000"> ms — <span id="_b_autoar_save_autoar_frequency" class="button _save_autoAr_frequency _autoAr">Save</span></p>
<p>Check every <input id="_input_autoAr_timer" class="_autoAr _autoAr_timer" type="number" min="5" max="10000"> ms — <span id="_b_autoar_save_autoar_timer" class="button _save_autoAr_timer _autoAr">Save</span></p>
<div class="row">
<span class="label">Options for this site:</span>
@ -259,6 +259,7 @@
<script src="../../js/lib/BrowserDetect.js"></script>
<script src="../../js/lib/Comms.js"></script>
<script src="../../js/conf/ExtensionConf.js"></script>
<script src="../../js/lib/Settings.js"></script>
<script src="./js/popup.js"></script>