92 lines
2.0 KiB
TypeScript
92 lines
2.0 KiB
TypeScript
import {
|
|
Communicator,
|
|
type commandFunction,
|
|
type commandList,
|
|
} from "./communicator";
|
|
import browser from "webextension-polyfill";
|
|
|
|
interface BackgroundCommands extends commandList {
|
|
setEnabled: setEnabled;
|
|
getEnabled: getEnabled;
|
|
translate: translate;
|
|
addFlashcard: addFlashcard;
|
|
removeFlashcard: removeFlashcard;
|
|
getLanguages: getLanguages;
|
|
getCurrentLanguages: getCurrentLanguages;
|
|
setCurrentLanguages: setCurrentLanguages;
|
|
}
|
|
|
|
interface FrontendCommands extends commandList {
|
|
setEnabled: setEnabled;
|
|
}
|
|
|
|
interface setEnabled extends commandFunction {
|
|
args: boolean;
|
|
}
|
|
|
|
interface getEnabled extends commandFunction {
|
|
return: boolean;
|
|
}
|
|
|
|
interface getLanguages extends commandFunction {
|
|
return: Array<Language>;
|
|
}
|
|
|
|
interface translate extends commandFunction {
|
|
args: string;
|
|
return: Promise<Translation | Flashcard>;
|
|
}
|
|
|
|
interface getCurrentLanguages extends commandFunction {
|
|
return: LanguagePair;
|
|
}
|
|
|
|
interface addFlashcard extends commandFunction {
|
|
args: Translation | Flashcard;
|
|
return: Flashcard;
|
|
}
|
|
|
|
interface removeFlashcard extends commandFunction {
|
|
args: Flashcard;
|
|
}
|
|
|
|
interface setCurrentLanguages extends commandFunction {
|
|
args: Partial<LanguagePair>;
|
|
}
|
|
|
|
export class BackgroundMessenger extends Communicator<
|
|
BackgroundCommands,
|
|
FrontendCommands
|
|
> {
|
|
constructor() {
|
|
super();
|
|
browser.runtime.onMessage.addListener((m, s) => this.onMessage(m, s));
|
|
}
|
|
runCommand<K extends keyof BackgroundCommands>(
|
|
command: K,
|
|
args: BackgroundCommands[K]["args"],
|
|
tabID: number
|
|
) {
|
|
const msg = this.getCommandMessage(command, args);
|
|
return browser.tabs.sendMessage(tabID, msg);
|
|
}
|
|
}
|
|
|
|
export class FrontendMessenger extends Communicator<
|
|
FrontendCommands,
|
|
BackgroundCommands
|
|
> {
|
|
constructor() {
|
|
super();
|
|
browser.runtime.onMessage.addListener((m, s) => this.onMessage(m, s));
|
|
}
|
|
|
|
runCommand<K extends keyof BackgroundCommands>(
|
|
command: K,
|
|
args: BackgroundCommands[K]["args"]
|
|
): Promise<BackgroundCommands[K]["return"]> {
|
|
const message = this.getCommandMessage(command, args);
|
|
return browser.runtime.sendMessage(message);
|
|
}
|
|
}
|