From 76d80b1c6a0e1f12652df0f22cb263b11a509a8c Mon Sep 17 00:00:00 2001 From: Ad5001 Date: Tue, 17 Oct 2023 05:18:31 +0200 Subject: [PATCH] Dynamic icons depending on edition status. --- background.js | 54 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/background.js b/background.js index 29cbc98..5ea0e0c 100644 --- a/background.js +++ b/background.js @@ -17,6 +17,9 @@ * **/ +const TITLE_EDITING = "Simple Content Editor (editing)" +const TITLE_NOT_EDITING = "Simple Content Editor" + const exportTabHTMLToLink = () => { let fullHTML = document.body.parentNode.outerHTML return { @@ -37,18 +40,25 @@ const queryEditionStatus = () => { return document.body.contentEditable == "true" } -async function execute(func, tabId) { +async function execute(func) { let tabs = await browser.tabs.query({currentWindow: true, active: true}) return await browser.scripting.executeScript({ func: func, - target: { - tabId: tabs[0].id - } + target: {tabId: tabs[0].id} }).then((results) => results[0].result) } -// Message listener from browser scripts. +async function getEditionStatus(tabId) { + return await browser.scripting.executeScript({ + func: queryEditionStatus, + target: {tabId: tabId} + }).then((results) => results[0].result) +} + +/** + * Message listener from browser scripts. + */ function receiveMessage(message, sender, sendResponse) { if(!message.request) { console.error(`Couldn't parse message ${JSON.stringify(message)}. No 'request' field.`) @@ -58,9 +68,15 @@ function receiveMessage(message, sender, sendResponse) { switch(message.request) { case 'start-editing': ret = execute(enableEdition) + browser.tabs.query({currentWindow: true, active: true}).then((tabs) => { + toggleIcon(tabs[0].id, true) + }) break case 'end-editing': ret = execute(disableEdition) + browser.tabs.query({currentWindow: true, active: true}).then((tabs) => { + toggleIcon(tabs[0].id, false) + }) break case 'export-html': ret = execute(exportTabHTMLToLink) @@ -74,3 +90,31 @@ function receiveMessage(message, sender, sendResponse) { browser.runtime.onMessage.addListener(receiveMessage); +/** + * Icon change listener + */ +let darkTheme = !!matchMedia('(prefers-color-scheme: dark)').matches +matchMedia('(prefers-color-scheme: dark)').addListener(({matches}) => { + console.log("New dark theme:", !!matches) + darkTheme = !!matches + browser.tabs.query({}).then((tabs) => { + for(let tab of tabs) { + getEditionStatus(tab.id).then((editing) => toggleIcon(tab.id, editing)) + } + }) +}) + +async function toggleIcon(tabId, editing) { + let title = await browser.action.getTitle({tabId: tabId}) + let icon = "icons/editor-photon" + if(darkTheme) + icon += "-dark" + if(editing) { + icon += "-editing" + browser.action.setTitle({tabId: tabId, title: TITLE_EDITING}) + } else + browser.action.setTitle({tabId: tabId, title: TITLE_NOT_EDITING}) + icon += ".svg" + console.log(icon) + browser.action.setIcon({tabId: tabId, path: icon}) +}