import { LitElement, html } from "lit"; import { customElement, query, state } from "lit/decorators.js"; import Countries from "./data/countries.json"; import { translateText } from "./Utils"; @customElement("flag-input-modal") export class FlagInputModal extends LitElement { @query("o-modal") private modalEl!: HTMLElement & { open: () => void; close: () => void; }; @state() private search = ""; @state() private isModalOpen = false; createRenderRoot() { return this; } render() { return html` ${this.isModalOpen ? Countries.filter( (country) => !country.restricted && this.includedInSearch(country), ).map( (country) => html` { this.setFlag(country.code); this.close(); }} class="text-center cursor-pointer border-none bg-none opacity-70 w-[calc(100%/2-15px)] sm:w-[calc(100%/4-15px)] md:w-[calc(100%/6-15px)] lg:w-[calc(100%/8-15px)] xl:w-[calc(100%/10-15px)] min-w-[80px]" > { const img = e.currentTarget as HTMLImageElement; const fallback = "/flags/xx.svg"; if (img.src && !img.src.endsWith(fallback)) { img.src = fallback; } }} /> ${country.name} `, ) : html``} `; } private includedInSearch(country: { name: string; code: string }): boolean { return ( country.name.toLowerCase().includes(this.search.toLowerCase()) || country.code.toLowerCase().includes(this.search.toLowerCase()) ); } private handleSearch(event: Event) { this.search = (event.target as HTMLInputElement).value; } private setFlag(flag: string) { localStorage.setItem("flag", flag); this.dispatchEvent( new CustomEvent("flag-change", { detail: { flag }, bubbles: true, composed: true, }), ); } public open() { this.isModalOpen = true; this.modalEl?.open(); } public close() { this.isModalOpen = false; this.modalEl?.close(); } connectedCallback() { super.connectedCallback(); window.addEventListener("keydown", this.handleKeyDown); } disconnectedCallback() { window.removeEventListener("keydown", this.handleKeyDown); super.disconnectedCallback(); } private handleKeyDown = (e: KeyboardEvent) => { if (e.code === "Escape") { e.preventDefault(); this.close(); } }; }