107 lines
2.7 KiB
TypeScript
107 lines
2.7 KiB
TypeScript
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();
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
export async function contextClicked(
|
|
contextMenuIds: Set<string>,
|
|
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();
|
|
}
|
|
}
|