import { LitElement, html } from "lit"; import { customElement, query, state } from "lit/decorators.js"; import Countries from "./data/countries.json"; @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` `, ) : 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(); } }; }