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

98 lines
2.4 KiB
TypeScript

import browser from 'webextension-polyfill';
import {Settings} from '../settings/settings.js';
import {updateBadge} from '../utilities/badge.js';
const contextMenus: browser.Menus.CreateCreatePropertiesType[] = [
{
id: 'queue-add-new-link',
title: 'Add to Queue',
contexts: ['link'],
},
{
id: 'queue-add-new-link-tab',
title: 'Add to Queue',
contexts: ['tab'],
},
{
id: 'queue-open-next-link-in-new-tab',
title: 'Open next link in new tab',
contexts: ['browser_action'],
},
{
id: 'queue-open-options-page',
title: 'Open the extension page',
contexts: ['browser_action'],
},
];
const contextMenuIds = new Set<string>(
contextMenus.map(({id}) => id ?? 'queue-unknown'),
);
export function initializeContextMenus(): void {
for (const contextMenu of contextMenus) {
browser.contextMenus.create(contextMenu, contextCreated);
}
browser.contextMenus.onClicked.addListener(contextClicked);
}
function contextCreated(): void {
const error = browser.runtime.lastError;
if (error !== null && error !== undefined) {
console.error('Queue', error);
}
}
async function contextClicked(
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);
}
} else if (id === 'queue-open-options-page') {
await browser.runtime.openOptionsPage();
}
}