const TAB_TITLE_TARGET = "code-server"; // Allow the content-script running in the code-server context to set session storage entries const CHROMIUM_ACCESS_LEVEL_ENUM = "TRUSTED_AND_UNTRUSTED_CONTEXTS"; const STATUS = Object.freeze({ UPDATE : "update", SUCCESS : "success", NO_TARGET : "no-target" }); const CLASSNAME = Object.freeze({ ACTIVE : "active" }); const SELECTOR = Object.freeze({ TRY_AGAIN : "a[href='#']", OPEN_EDITOR : "button.success", MAIN_ELEMENT : "main", CARD_ELEMENT : "article", }); class Popup { constructor() { // Set session storage access to content-scripts chrome.storage.session.setAccessLevel({ accessLevel: CHROMIUM_ACCESS_LEVEL_ENUM }); this.#bindTryAgain(); this.#bindOpenEditor(); this.update(); } /** * Set the current status * * @param {STATUS} status */ set #status(status) { const mainElement = document.querySelector(SELECTOR.MAIN_ELEMENT); // Unset current status Object.values(STATUS).forEach(classname => mainElement.classList.remove(classname)); mainElement.classList.add(status); } /** * Query active tabs for a code-server tab * * @returns {STATUS} */ async update() { this.#status = STATUS.UPDATE; const tab = await this.#activeTab(); console.log(tab); if (!tab) { return this.#status = STATUS.NO_TARGET; } document.querySelector(SELECTOR.OPEN_EDITOR).querySelector("span").innerText = tab.title.split(" ", 1)[0]; return this.#status = STATUS.SUCCESS; } /** * Opens the current code-server tab in the editor and closes this popup * * @returns {Promise|false} */ async openActiveTab() { const tab = await this.#activeTab(); if (!tab) { return false; } // Inject content script on the target page chrome.scripting.executeScript({ files : ["assets/js/script.js"], target : { tabId: tab.id } }); window.close(); } /** * Query active tabs for a code-server tab * * @returns {Promise} */ async #activeTab() { return await new Promise((resolve) => { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { let activeTab = null; tabs.forEach(tab => { // Use the last part of the tab title to determine if this tab is a code-server instance if (tab.title.slice(TAB_TITLE_TARGET.length * -1) === TAB_TITLE_TARGET) { activeTab = tab; } }); return resolve(activeTab); }); }); } /** * Bind try again button */ #bindTryAgain() { document.querySelector(SELECTOR.TRY_AGAIN).addEventListener("click", (event) => { event.preventDefault(); this.update(); }); } /** * Bind open editor button */ #bindOpenEditor() { document.querySelector(SELECTOR.OPEN_EDITOR).addEventListener("click", () => this.openActiveTab()); } } globalThis._Popup = new Popup();