queue/source/background-scripts/context-menus.ts

107 lines
2.7 KiB
TypeScript
Raw Permalink Normal View History

2022-03-05 13:10:45 +00:00
import browser from 'webextension-polyfill';
import {Settings} from '../settings/settings.js';
import {updateBadge} from '../utilities/badge.js';
export function getContextMenus(): browser.Menus.CreateCreatePropertiesType[] {
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'],
});
}
return contextMenus;
}
export async function initializeContextMenus(): Promise<void> {
const contextMenus = getContextMenus();
await browser.contextMenus.removeAll();
2022-03-05 13:10:45 +00:00
for (const contextMenu of contextMenus) {
browser.contextMenus.create(contextMenu, contextCreated);
}
}
function contextCreated(): void {
const error = browser.runtime.lastError;
if (error !== null && error !== undefined) {
console.error('Queue', error.message);
2022-03-05 13:10:45 +00:00
}
}
export async function contextClicked(
contextMenuIds: Set<string>,
2022-03-05 13:10:45 +00:00
info: browser.Menus.OnClickData,
tab?: browser.Tabs.Tab,
): Promise<void> {
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);
2022-03-05 13:10:45 +00:00
}
} else if (id === 'queue-open-options-page') {
await browser.runtime.openOptionsPage();
}
}