Files
wov-assassins-convention-tw…/src/content.ts

51 lines
1.5 KiB
TypeScript

import { State, STORAGE_KEY } from "./types";
let enabled = false;
const findButtonForKey = (key: string): HTMLElement | null => {
if (key.length !== 1 || !/[a-zA-Z]/.test(key)) return null;
const letter = key.toUpperCase();
const label = Array.from(document.querySelectorAll<HTMLElement>("div[dir=\"auto\"]"))
.find(el => el.textContent === letter);
return label?.closest<HTMLElement>("[tabindex=\"0\"]") ?? null;
};
const onKeyDown = (event: KeyboardEvent): void => {
if (!enabled) return;
const target = event.target as HTMLElement;
if (
target.tagName === "INPUT" ||
target.tagName === "TEXTAREA" ||
target.isContentEditable
) return;
const btn = findButtonForKey(event.key);
if (btn) {
event.preventDefault();
const rect = btn.getBoundingClientRect();
chrome.runtime.sendMessage({
type: "simulate-click",
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
});
}
};
const init = async (): Promise<void> => {
const result = await chrome.storage.local.get(STORAGE_KEY);
const state = result[STORAGE_KEY] as State | undefined;
enabled = state?.keybinds ?? true;
document.addEventListener("keydown", onKeyDown, { capture: true });
chrome.storage.onChanged.addListener((changes) => {
if (STORAGE_KEY in changes) {
const next = changes[STORAGE_KEY].newValue as State;
enabled = next.keybinds;
}
});
};
init();