import browser from 'webextension-polyfill'; import {Settings} from '../settings/settings.js'; import {updateBadge} from '../utilities/badge.js'; export async function initializeContextMenus(): Promise { const actionContext = import.meta.env.VITE_BROWSER === 'chromium' ? 'action' : 'browser_action'; const contextMenus: browser.Menus.CreateCreatePropertiesType[] = [ { id: 'queue-add-new-link', title: 'Add to Queue', contexts: ['link'], }, { id: 'queue-open-next-link-in-new-tab', title: 'Open next link in new tab', contexts: [actionContext], }, { id: 'queue-open-options-page', title: 'Open the extension page', contexts: [actionContext], }, ]; if (import.meta.env.VITE_BROWSER === 'firefox') { contextMenus.push({ id: 'queue-add-new-link-tab', title: 'Add to Queue', contexts: ['tab'], }); } const contextMenuIds = new Set( contextMenus.map(({id}) => id ?? 'queue-unknown'), ); await browser.contextMenus.removeAll(); for (const contextMenu of contextMenus) { browser.contextMenus.create(contextMenu, contextCreated); } browser.contextMenus.onClicked.addListener(async (info, tab) => { await contextClicked(contextMenuIds, info, tab); }); } function contextCreated(): void { const error = browser.runtime.lastError; if (error !== null && error !== undefined) { console.error('Queue', error.message); } } async function contextClicked( contextMenuIds: Set, info: browser.Menus.OnClickData, tab?: browser.Tabs.Tab, ): Promise { const id = info.menuItemId.toString(); if (!contextMenuIds.has(id)) { return; } const settings = await Settings.fromSyncStorage(); if (id.startsWith('queue-add-new-link')) { let text: string | undefined; let url: string | undefined; switch (id) { case 'queue-add-new-link': text = info.linkText; url = info.linkUrl; break; case 'queue-add-new-link-tab': text = tab?.title; url = info.pageUrl; break; default: console.warn(`Encountered unknown context menu ID: ${id}`); return; } if (url === undefined) { console.warn('Cannot add a new item without a URL.'); return; } await settings.insertQueueItem(text ?? url, url); await updateBadge(settings); } else if (id === 'queue-open-next-link-in-new-tab') { const nextItem = settings.nextQueueItem(); if (nextItem === undefined) { await browser.runtime.openOptionsPage(); } else { await browser.tabs.create({active: true, url: nextItem.url}); await settings.removeQueueItem(nextItem.id); await updateBadge(settings); } } else if (id === 'queue-open-options-page') { await browser.runtime.openOptionsPage(); } }