about summary refs log tree commit diff stats
path: root/src/pages
diff options
context:
space:
mode:
authorManeraKai <manerakai@protonmail.com>2023-01-21 14:29:10 +0300
committerManeraKai <manerakai@protonmail.com>2023-01-21 14:29:10 +0300
commit57e32c8d7ac8a9fb34a6c5d76b677a9df7dc714f (patch)
treebbde34f9224c9944c26f9cb67575a32d71e773f9 /src/pages
parentUX/UI tweaks (diff)
downloadlibredirect-57e32c8d7ac8a9fb34a6c5d76b677a9df7dc714f.zip
Cleaned code. Fixed settings conversion not working
Diffstat (limited to '')
-rw-r--r--src/pages/background/background.js54
-rw-r--r--src/pages/options/index.js98
-rw-r--r--src/pages/options/init.js55
-rw-r--r--src/pages/options/widgets/general.js82
-rw-r--r--src/pages/popup/popup.js27
-rw-r--r--src/pages/stylesheets/styles.css4
6 files changed, 129 insertions, 191 deletions
diff --git a/src/pages/background/background.js b/src/pages/background/background.js
index 021ad4cc..5c6ec521 100644
--- a/src/pages/background/background.js
+++ b/src/pages/background/background.js
@@ -9,33 +9,17 @@ window.browser = window.browser || window.chrome
 browser.runtime.onInstalled.addListener(async details => {
 	if (details.previousVersion != browser.runtime.getManifest().version) {
 		// ^Used to prevent this running when debugging with auto-reload
-		browser.runtime.openOptionsPage()
-		switch (details.reason) {
-			case "install":
-				browser.storage.local.get("options", async r => {
-					if (!r.options) {
-						await generalHelper.initDefaults()
-						await servicesHelper.initDefaults()
-					}
-				})
-				break
-			case "update":
-				switch (details.previousVersion) {
-					case "2.3.4":
-						browser.storage.local.get("options", async r => {
-							if (!r.options) {
-								await servicesHelper.backupOptions()
-								await generalHelper.initDefaults()
-								await servicesHelper.initDefaults()
-								await servicesHelper.upgradeOptions()
-							}
-						})
-						break
-					default:
-						await servicesHelper.processUpdate()
-				}
+		if (details.reason == "install") {
+			if (!(await utils.getOptions())) {
+				await servicesHelper.initDefaults()
+			}
+		}
+		else if (details.reason == "update") {
+			await servicesHelper.upgradeOptions()
+			// await servicesHelper.processUpdate()
 		}
 	}
+	browser.runtime.openOptionsPage()
 })
 
 let tabIdRedirects = {}
@@ -86,8 +70,8 @@ browser.tabs.onRemoved.addListener(tabId => {
 })
 
 browser.commands.onCommand.addListener(command => {
-	if (command === "switchInstance") utils.switchInstance()
-	else if (command == "copyRaw") utils.copyRaw()
+	if (command === "switchInstance") servicesHelper.switchInstance()
+	else if (command == "copyRaw") servicesHelper.copyRaw()
 })
 
 browser.contextMenus.create({
@@ -134,7 +118,7 @@ browser.contextMenus.onClicked.addListener((info, tab) => {
 	return new Promise(async resolve => {
 		switch (info.menuItemId) {
 			case "switchInstance":
-				utils.switchInstance()
+				servicesHelper.switchInstance()
 				resolve()
 				return
 			case "settings":
@@ -142,7 +126,7 @@ browser.contextMenus.onClicked.addListener((info, tab) => {
 				resolve()
 				return
 			case "copyRaw":
-				utils.copyRaw()
+				servicesHelper.copyRaw()
 				resolve()
 				return
 			case "toggleTab":
@@ -155,13 +139,11 @@ browser.contextMenus.onClicked.addListener((info, tab) => {
 					const url = new URL(tab.url)
 					const service = await servicesHelper.computeService(url)
 					if (service) {
-						browser.storage.local.get("options", async r => {
-							if (r.options[service].enabled) tabIdRedirects[tab.id] = false
-							else tabIdRedirects[tab.id] = true
-							await handleToggleTab(tab)
-							resolve()
-							return
-						})
+						if ((await utils.getOptions())[service].enabled) tabIdRedirects[tab.id] = false
+						else tabIdRedirects[tab.id] = true
+						await handleToggleTab(tab)
+						resolve()
+						return
 					} else {
 						tabIdRedirects[tab.id] = false
 						await handleToggleTab(tab)
diff --git a/src/pages/options/index.js b/src/pages/options/index.js
index 81cccb44..a7be0418 100644
--- a/src/pages/options/index.js
+++ b/src/pages/options/index.js
@@ -13,19 +13,9 @@ for (const a of document.getElementById("links").getElementsByTagName("a")) {
 	})
 }
 
-await new Promise(resolve => {
-	fetch("/config.json").then(response => response.text())
-		.then(data => {
-			config = JSON.parse(data)
-			resolve()
-		})
-})
-await new Promise(resolve => {
-	browser.storage.local.get("options", r => {
-		options = r.options
-		resolve()
-	})
-})
+
+config = await utils.getConfig()
+options = await utils.getOptions()
 
 function changeFrontendsSettings(service) {
 	for (const frontend in config.services[service].frontends) {
@@ -46,12 +36,15 @@ function loadPage(path) {
 	for (const section of document.getElementById("pages").getElementsByTagName("section")) section.style.display = "none"
 	document.getElementById(`${path}_page`).style.display = "block"
 
-	for (const a of document.getElementById("links").getElementsByTagName("a"))
-		if (a.getAttribute("href") == `#${path}`) a.classList.add("selected")
-		else a.classList.remove("selected")
+	for (const a of document.getElementById("links").getElementsByTagName("a")) {
+		if (a.getAttribute("href") == `#${path}`) {
+			a.classList.add("selected")
+		} else {
+			a.classList.remove("selected")
+		}
+	}
 
-	let stateObj = { id: "100" }
-	window.history.pushState(stateObj, "Page 2", `/pages/options/index.html#${path}`)
+	window.history.pushState({ id: "100" }, "Page 2", `/pages/options/index.html#${path}`)
 
 	if (path != 'general' && path != 'about') {
 		const service = path;
@@ -62,16 +55,14 @@ function loadPage(path) {
 			if (typeof config.services[service].options[option] == "boolean") divs[service][option].checked = options[service][option]
 			else divs[service][option].value = options[service][option]
 
-			divs[service][option].addEventListener("change", () => {
-				browser.storage.local.get("options", r => {
-					let options = r.options
-					if (typeof config.services[service].options[option] == "boolean")
-						options[service][option] = divs[service][option].checked
-					else
-						options[service][option] = divs[service][option].value
-					browser.storage.local.set({ options })
-					changeFrontendsSettings(service)
-				})
+			divs[service][option].addEventListener("change", async () => {
+				let options = await utils.getOptions()
+				if (typeof config.services[service].options[option] == "boolean")
+					options[service][option] = divs[service][option].checked
+				else
+					options[service][option] = divs[service][option].value
+				browser.storage.local.set({ options })
+				changeFrontendsSettings(service)
 			})
 		}
 
@@ -88,7 +79,7 @@ function loadPage(path) {
 
 		for (const frontend in config.services[service].frontends) {
 			if (config.services[service].frontends[frontend].instanceList) {
-				processDefaultCustomInstances(frontend, document)
+				processCustomInstances(frontend, document)
 			}
 		}
 
@@ -104,18 +95,9 @@ function loadPage(path) {
 	}
 }
 
-async function processDefaultCustomInstances(frontend, document) {
-	let customInstances = []
-	let options
-	await new Promise(async resolve =>
-		browser.storage.local.get(["options"], r => {
-			customInstances = r.options[frontend]
-			options = r.options
-			resolve()
-		})
-	)
-
-	localise.localisePage()
+async function processCustomInstances(frontend, document) {
+	let options = await utils.getOptions()
+	let customInstances = options[frontend]
 
 	function calcCustomInstances() {
 		document.getElementById(frontend).getElementsByClassName("custom-checklist")[0].innerHTML = customInstances
@@ -133,10 +115,12 @@ async function processDefaultCustomInstances(frontend, document) {
 			)
 			.join("\n")
 
+		customInstances = options[frontend]
 		for (const item of customInstances) {
 			document.getElementById(frontend).getElementsByClassName(`clear-${item}`)[0].addEventListener("click", async () => {
 				let index = customInstances.indexOf(item)
 				if (index > -1) customInstances.splice(index, 1)
+				options = await utils.getOptions()
 				options[frontend] = customInstances
 				browser.storage.local.set({ options }, () => calcCustomInstances())
 			})
@@ -144,7 +128,6 @@ async function processDefaultCustomInstances(frontend, document) {
 	}
 	calcCustomInstances()
 	document.getElementById(frontend).getElementsByClassName("custom-instance-form")[0].addEventListener("submit", async event => {
-		event.preventDefault();
 		event.preventDefault()
 		let frontendCustomInstanceInput = document.getElementById(frontend).getElementsByClassName("custom-instance")[0]
 		let url
@@ -157,6 +140,7 @@ async function processDefaultCustomInstances(frontend, document) {
 		if (frontendCustomInstanceInput.validity.valid) {
 			if (!customInstances.includes(protocolHostVar)) {
 				customInstances.push(protocolHostVar)
+				options = await utils.getOptions()
 				options[frontend] = customInstances
 				browser.storage.local.set({ options }, () => {
 					frontendCustomInstanceInput.value = ""
@@ -172,32 +156,32 @@ function createList(frontend, networks, document, redirects, blacklist) {
 		if (redirects[frontend]) {
 			if (redirects[frontend][network].length > 0) {
 				document.getElementById(frontend).getElementsByClassName(network)[0].getElementsByClassName("checklist")[0].innerHTML = [
-					`
-				<div class="some-block option-block">
-					<h4>${utils.camelCase(network)}</h4>
-				</div>
-				`,
+					`<div class="some-block option-block">
+						<h4>${utils.camelCase(network)}</h4>
+					</div>`,
 					...redirects[frontend][network]
 						.sort((a, b) =>
 							(blacklist.cloudflare.includes(a) && !blacklist.cloudflare.includes(b))
 						)
 						.map(x => {
-							const cloudflare = blacklist.cloudflare.includes(x) ? ' <a target="_blank" href="https://libredirect.github.io/docs.html#instances"><span style="color:red;">cloudflare</span></a>' : ""
-
-							let warnings = [cloudflare].join(" ")
-							return `
-						<div>
-							<x>
-								<a href="${x}" target="_blank">${x}</a>${warnings}
-							</x>
-						  </div>`
+							const cloudflare = blacklist.cloudflare.includes(x) ?
+								` <a target="_blank" href="https://libredirect.github.io/docs.html#instances">
+							 		<span style="color:red;">cloudflare</span>
+								</a>` : ""
+
+							const warnings = [cloudflare].join(" ")
+							return `<div>
+										<x>
+											<a href="${x}" target="_blank">${x}</a>${warnings}
+										</x>
+						  			</div>`
 						}),
 					'<br>'
 				].join("\n<hr>\n")
 			}
 		} else {
 			document.getElementById(frontend).getElementsByClassName(network)[0].getElementsByClassName("checklist")[0].innerHTML =
-				`<div class="some-block option-block">No instances found...</div>`
+				`<div class="some-block option-block">No instances found.</div>`
 			break
 		}
 
diff --git a/src/pages/options/init.js b/src/pages/options/init.js
index 015daac7..aab66f93 100644
--- a/src/pages/options/init.js
+++ b/src/pages/options/init.js
@@ -1,42 +1,41 @@
 window.browser = window.browser || window.chrome
 
 import localise from "../../assets/javascripts/localise.js"
+import utils from "../../assets/javascripts/utils.js"
 
 function changeTheme() {
-	return new Promise(resolve => {
-		browser.storage.local.get("options", r => {
-			switch (r.options.theme) {
-				case "dark":
-					document.body.classList.add("dark-theme")
-					document.body.classList.remove("light-theme")
-					for (const element of document.body.getElementsByClassName('dark')) {
-						element.style.display = 'none';
-					}
-					break
-				case "light":
+	return new Promise(async resolve => {
+		switch ((await utils.getOptions()).theme) {
+			case "dark":
+				document.body.classList.add("dark-theme")
+				document.body.classList.remove("light-theme")
+				for (const element of document.body.getElementsByClassName('dark')) {
+					element.style.display = 'none';
+				}
+				break
+			case "light":
+				document.body.classList.add("light-theme")
+				document.body.classList.remove("dark-theme")
+				for (const element of document.body.getElementsByClassName('light')) {
+					element.style.display = 'none';
+				}
+				break
+			default:
+				if (matchMedia("(prefers-color-scheme: light)").matches) {
 					document.body.classList.add("light-theme")
 					document.body.classList.remove("dark-theme")
 					for (const element of document.body.getElementsByClassName('light')) {
 						element.style.display = 'none';
 					}
-					break
-				default:
-					if (matchMedia("(prefers-color-scheme: light)").matches) {
-						document.body.classList.add("light-theme")
-						document.body.classList.remove("dark-theme")
-						for (const element of document.body.getElementsByClassName('light')) {
-							element.style.display = 'none';
-						}
-					} else {
-						document.body.classList.add("dark-theme")
-						document.body.classList.remove("light-theme")
-						for (const element of document.body.getElementsByClassName('dark')) {
-							element.style.display = 'none';
-						}
+				} else {
+					document.body.classList.add("dark-theme")
+					document.body.classList.remove("light-theme")
+					for (const element of document.body.getElementsByClassName('dark')) {
+						element.style.display = 'none';
 					}
-			}
-			resolve()
-		})
+				}
+		}
+		resolve()
 	})
 }
 
diff --git a/src/pages/options/widgets/general.js b/src/pages/options/widgets/general.js
index f08d8313..8e999a42 100644
--- a/src/pages/options/widgets/general.js
+++ b/src/pages/options/widgets/general.js
@@ -5,44 +5,29 @@ import utils from "../../../assets/javascripts/utils.js"
 import generalHelper from "../../../assets/javascripts/general.js"
 import servicesHelper from "../../../assets/javascripts/services.js"
 
-let config
-
-async function getConfig() {
-	return new Promise(resolve => {
-		fetch("/config.json")
-			.then(response => response.text())
-			.then(data => {
-				config = JSON.parse(data)
-				resolve()
-			})
-	})
-}
 
-function setOption(option, type, event) {
-	browser.storage.local.get("options", r => {
-		let options = r.options
-		if (type == "select") {
-			options[option] = event.target.options[event.target.options.selectedIndex].value
-		} else if (type == "checkbox") {
-			options[option] = event.target.checked
-		} else if (type == "range") {
-			options[option] = event.target.value
-		}
 
-		browser.storage.local.set({ options })
-	})
+async function setOption(option, type, event) {
+	let options = await utils.getOptions()
+	if (type == "select") {
+		options[option] = event.target.options[event.target.options.selectedIndex].value
+	} else if (type == "checkbox") {
+		options[option] = event.target.checked
+	} else if (type == "range") {
+		options[option] = event.target.value
+	}
+	browser.storage.local.set({ options })
 }
 
 let exportSettingsElement = document.getElementById("export-settings")
 
-function exportSettings() {
-	browser.storage.local.get("options", result => {
-		result.options.version = browser.runtime.getManifest().version
-		let resultString = JSON.stringify(result.options, null, "  ")
-		exportSettingsElement.href = "data:application/json;base64," + btoa(resultString)
-		exportSettingsElement.download = "libredirect-settings.json"
-		return
-	})
+async function exportSettings() {
+	const options = await utils.getOptions()
+	options.version = browser.runtime.getManifest().version
+	let resultString = JSON.stringify(options, null, "  ")
+	exportSettingsElement.href = "data:application/json;base64," + btoa(resultString)
+	exportSettingsElement.download = "libredirect-settings.json"
+	return
 }
 exportSettings()
 
@@ -62,8 +47,6 @@ importSettingsElement.addEventListener("change", () => {
 			&& data.version == browser.runtime.getManifest().version
 		) {
 			browser.storage.local.clear(async () => {
-				await generalHelper.initDefaults()
-				await servicesHelper.initDefaults()
 				browser.storage.local.set({ options: data }, () => {
 					location.reload()
 				})
@@ -88,7 +71,6 @@ const resetSettings = document.getElementById("reset-settings")
 resetSettings.addEventListener("click", async () => {
 	resetSettings.innerHTML = "..."
 	browser.storage.local.clear(async () => {
-		await generalHelper.initDefaults()
 		await servicesHelper.initDefaults()
 		location.reload()
 	})
@@ -104,25 +86,23 @@ let nameCustomInstanceInput = document.getElementById("exceptions-custom-instanc
 let instanceTypeElement = document.getElementById("exceptions-custom-instance-type")
 let instanceType = "url"
 
-await getConfig()
+let config = await utils.getConfig()
 
 for (const service in config.services) {
-	document.getElementById(service).addEventListener("change", event => {
-		browser.storage.local.get("options", r => {
-			let options = r.options
-			if (event.target.checked && !options.popupServices.includes(service)) options.popupServices.push(service)
-			else if (options.popupServices.includes(service)) {
-				var index = options.popupServices.indexOf(service)
-				if (index !== -1) options.popupServices.splice(index, 1)
-			}
-			browser.storage.local.set({ options })
-		})
+	document.getElementById(service).addEventListener("change", async event => {
+		let options = await utils.getOptions()
+		if (event.target.checked && !options.popupServices.includes(service)) options.popupServices.push(service)
+		else if (options.popupServices.includes(service)) {
+			var index = options.popupServices.indexOf(service)
+			if (index !== -1) options.popupServices.splice(index, 1)
+		}
+		browser.storage.local.set({ options })
 	})
 }
 
-browser.storage.local.get("options", r => {
-	themeElement.value = r.options.theme
-	let options = r.options
+!async function () {
+	const options = await utils.getOptions()
+	themeElement.value = options.theme
 
 	instanceTypeElement.addEventListener("change", event => {
 		instanceType = event.target.options[instanceTypeElement.selectedIndex].value
@@ -134,7 +114,7 @@ browser.storage.local.get("options", r => {
 			nameCustomInstanceInput.setAttribute("placeholder", "https?://(www.|)youtube.com/")
 		}
 	})
-	let exceptionsCustomInstances = r.options.exceptions
+	let exceptionsCustomInstances = options.exceptions
 	function calcExceptionsCustomInstances() {
 		document.getElementById("exceptions-custom-checklist").innerHTML = [...exceptionsCustomInstances.url, ...exceptionsCustomInstances.regex]
 			.map(
@@ -190,4 +170,4 @@ browser.storage.local.get("options", r => {
 	})
 
 	for (const service in config.services) document.getElementById(service).checked = options.popupServices.includes(service)
-})
+}
\ No newline at end of file
diff --git a/src/pages/popup/popup.js b/src/pages/popup/popup.js
index aa3fb0d7..4cd59ebe 100644
--- a/src/pages/popup/popup.js
+++ b/src/pages/popup/popup.js
@@ -1,35 +1,24 @@
 "use strict"
 window.browser = window.browser || window.chrome
 
+import servicesHelper from "../../assets/javascripts/services.js"
 import utils from "../../assets/javascripts/utils.js"
-import serviceHelper from "../../assets/javascripts/services.js"
 
 let config,
 	divs = {}
 
-async function getConfig() {
-	return new Promise(resolve => {
-		fetch("/config.json")
-			.then(response => response.text())
-			.then(data => {
-				config = JSON.parse(data)
-				resolve()
-			})
-	})
-}
-
-await getConfig()
+config = await utils.getConfig()
 
-utils.switchInstance(true).then(r => {
+servicesHelper.switchInstance(true).then(r => {
 	if (!r) document.getElementById("change_instance_div").style.display = "none"
-	else document.getElementById("change_instance").addEventListener("click", () => utils.switchInstance(false))
+	else document.getElementById("change_instance").addEventListener("click", () => servicesHelper.switchInstance(false))
 })
 
-utils.copyRaw(true).then(r => {
+servicesHelper.copyRaw(true).then(r => {
 	if (!r) document.getElementById("copy_raw_div").style.display = "none"
 	else {
 		const copy_raw = document.getElementById("copy_raw")
-		copy_raw.addEventListener("click", () => utils.copyRaw(false, copy_raw))
+		copy_raw.addEventListener("click", () => servicesHelper.copyRaw(false, copy_raw))
 	}
 })
 document.getElementById("more-options").addEventListener("click", () => browser.runtime.openOptionsPage())
@@ -55,7 +44,7 @@ await setDivs()
 
 const currentSiteIsFrontend = document.getElementById("current_site_divider")
 
-browser.storage.local.get(["options", "redirects"], r => {
+browser.storage.local.get(["options"], r => {
 	browser.tabs.query({ active: true, currentWindow: true }, async tabs => {
 		for (const service in config.services) {
 			if (!r.options.popupServices.includes(service)) allSites.getElementsByClassName(service)[0].classList.add("hide")
@@ -76,7 +65,7 @@ browser.storage.local.get(["options", "redirects"], r => {
 			return
 		}
 
-		let service = await serviceHelper.computeService(url, true)
+		let service = await servicesHelper.computeService(url, true)
 		let frontend
 		let instance
 		if (service) {
diff --git a/src/pages/stylesheets/styles.css b/src/pages/stylesheets/styles.css
index 7d1b93ba..fc089728 100644
--- a/src/pages/stylesheets/styles.css
+++ b/src/pages/stylesheets/styles.css
@@ -411,6 +411,10 @@ body.light-theme a {
 	color: black;
 }
 
+body.light-theme a:hover {
+	color: var(--active)
+}
+
 section.general {
 	display: flex;
 	flex-wrap: wrap;