Dynamic icons depending on edition status.

This commit is contained in:
Adsooi 2023-10-17 05:18:31 +02:00
parent d0255e7aaf
commit 76d80b1c6a
Signed by: Ad5001
GPG key ID: EF45F9C6AFE20160

View file

@ -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})
}