import { html, LitElement, type PropertyValues, TemplateResult } from "lit"; import { property, query, state } from "lit/decorators.js"; import { modalRouter } from "../ModalRouter"; import "./baseComponents/Modal"; import type { OModal, OModalTab } from "./baseComponents/Modal"; import "./ConfirmDialog"; /** * Static-ish configuration for the shell. * Subclasses return a fresh object from modalConfig(); avoid heavy work — it's * read on every render() and during open()/setActiveTab(). */ export interface ModalConfig { title?: string; tabs?: OModalTab[]; hideHeader?: boolean; hideCloseButton?: boolean; alwaysMaximized?: boolean; maxWidth?: string; sidePanel?: boolean; hideTabs?: boolean; showScrollToTop?: boolean; } /** * Base class for modal components. * * BaseModal renders the shell itself — subclasses provide content * via renderContent() (or renderTab() for tabbed modals) and declare * configuration via modalConfig(). * * Lifecycle: * open(args?) → onOpen(args) hook → shell visible * close(args?) → onClose(args) hook → shell hidden * * Tabs (optional): * Return a non-empty tabs[] from modalConfig(). BaseModal owns activeTab * state and dispatches rendering to renderTab(key). Subclasses can opt in * to onTabEnter(key) for per-tab lifecycle (e.g. lazy load). */ export abstract class BaseModal extends LitElement { @state() protected isModalOpen = false; @state() protected activeTab = ""; @property({ type: Boolean }) inline = false; // Pending close confirmation; when set, renders the inline confirm dialog. @state() private closeConfirm: { message: string; resolve: (ok: boolean) => void; } | null = null; // Re-entrancy guard: showPage() (for inline modals) re-invokes .open() // with no args after we call it. We must not re-run onOpen(undefined) // from that nested call, which would clobber state set by the outer call. private opening = false; @query("o-modal") protected modalEl?: OModal; // ---- Subclass configuration ---- // Override modalConfig() to configure the rendered . Defaults match // the most common shape (custom in-content header, no built-in close button). protected modalConfig(): ModalConfig { return {}; } /** * Optional router name. When set, BaseModal syncs URL state on open/close/ * tab change as `#modal=&tab=&...`. Modals that own their * own URL state (e.g. lobby modals) should leave this undefined. */ protected routerName?: string; /** Render slot="header" content. Default: no header slot. */ protected renderHeaderSlot(): TemplateResult | null { return null; } /** * Render the modal body. For tabbed modals, switch on `tab` to render the * appropriate panel. Modals without tabs can ignore the argument. */ protected renderBody(_tab: string): TemplateResult { return html``; } // ---- Lifecycle hooks ---- /** Called when the modal opens. Receives router args / direct-caller args. */ protected onOpen(_args?: Record): void {} /** Called when the modal closes. */ protected onClose(_args?: Record): void {} /** Called when the active tab changes (including initial set on open). */ protected onTabEnter(_key: string): void {} /** * Guard called before closing via Escape key or click-outside. * Return false (or a promise resolving false) to prevent closing. */ public confirmBeforeClose(): boolean | Promise { return true; } /** * Show a styled confirm dialog and resolve to the user's choice. Call from * confirmBeforeClose() to gate closing behind a confirm/cancel prompt. */ protected confirmClose(message: string): Promise { // Don't stack a second prompt if one is already open. if (this.closeConfirm) return Promise.resolve(false); return new Promise((resolve) => { this.closeConfirm = { message, resolve }; }); } private settleCloseConfirm(ok: boolean) { const pending = this.closeConfirm; this.closeConfirm = null; pending?.resolve(ok); } // ---- Rendering ---- createRenderRoot() { return this; } protected willUpdate(changed: PropertyValues): void { super.willUpdate(changed); // Default the active tab so the highlight is correct on first render, // before open() runs (matters for inline modals rendered on page mount). const tabs = this.modalConfig().tabs ?? []; if (tabs.length && this.activeTab === "") { this.activeTab = tabs[0].key; } } render(): TemplateResult { const cfg = this.modalConfig(); const tabs = cfg.tabs ?? []; const body = this.renderBody(this.activeTab); const headerSlot = this.renderHeaderSlot(); return html` this.setActiveTab(key)} > ${headerSlot ? html`
${headerSlot}
` : null} ${body}
${ this.closeConfirm ? html` this.settleCloseConfirm(true)} @cancel=${() => this.settleCloseConfirm(false)} >` : null } `; } // ---- Open / close ---- public isOpen(): boolean { return this.isModalOpen; } /** * Open the modal. `args` is a loose bag forwarded to onOpen(). The router * passes parsed URL params; direct callers can pass whatever they want. * * Recognized keys: * - tab: string — sets active tab (validated against modalTabs) */ public open(args?: Record): void { if (this.opening) return; this.opening = true; try { const tabs = this.modalConfig().tabs ?? []; if (tabs.length && this.activeTab === "") { this.activeTab = tabs[0].key; } const requestedTab = typeof args?.tab === "string" && tabs.some((t) => t.key === args.tab) ? args.tab : null; const wasOpen = this.isModalOpen; if (!wasOpen) { if (requestedTab) this.activeTab = requestedTab; this.registerEscapeHandler(); this.onOpen(args); if (this.activeTab) this.onTabEnter(this.activeTab); } else { this.onOpen(args); // Already open: route tab changes through setActiveTab so URL syncs. if (requestedTab && requestedTab !== this.activeTab) { this.setActiveTab(requestedTab); } } if (wasOpen) return; if (this.inline) { const needsShow = this.classList.contains("hidden") || this.style.display === "none"; if (needsShow && window.showPage) { const pageId = this.id || this.tagName.toLowerCase(); window.showPage?.(pageId); } this.style.pointerEvents = "auto"; this.modalEl?.syncScrollToTop(); } else { this.modalEl?.open(); } if (this.routerName) { modalRouter.syncOpened(this.routerName, args); } } finally { this.opening = false; } } public close(args?: Record): void { // If closing was triggered elsewhere while a confirm prompt is pending, // dismiss it (removes the dialog and resolves the awaiting guard as false). this.settleCloseConfirm(false); this.unregisterEscapeHandler(); this.onClose(args); if (this.inline) { this.style.pointerEvents = "none"; this.modalEl?.resetScrollToTop(); if (window.showPage) { window.showPage?.("page-play"); } } else { this.modalEl?.close(); } if (this.routerName) { modalRouter.syncClosed(this.routerName); } } // ---- Tab management ---- /** Programmatically change the active tab. Triggers onTabEnter. */ public setActiveTab(key: string): void { const tabs = this.modalConfig().tabs ?? []; if (!tabs.some((t) => t.key === key)) return; if (this.activeTab === key) return; this.activeTab = key; this.onTabEnter(key); if (this.routerName) { modalRouter.syncTab(this.routerName, key); } } // ---- Internals ---- protected firstUpdated(): void { if (this.modalEl) { this.modalEl.onClose = async () => { if (this.isModalOpen) { const confirmed = await this.confirmBeforeClose(); // Bail if a parallel close() settled things while we awaited — // otherwise we'd re-open an already-closed modal. if (!this.isModalOpen) return; if (!confirmed) { // Re-open the underlying o-modal since it already closed itself this.modalEl?.open(); return; } this.close(); } }; } } disconnectedCallback() { this.settleCloseConfirm(false); this.unregisterEscapeHandler(); super.disconnectedCallback(); } private handleKeyDown = async (e: KeyboardEvent) => { if (e.key === "Escape" && this.isModalOpen) { e.preventDefault(); const confirmed = await this.confirmBeforeClose(); // Bail if a parallel close() already closed us while we awaited. if (!confirmed || !this.isModalOpen) { return; } this.close(); } }; protected registerEscapeHandler() { this.isModalOpen = true; window.addEventListener("keydown", this.handleKeyDown); } protected unregisterEscapeHandler() { this.isModalOpen = false; window.removeEventListener("keydown", this.handleKeyDown); } protected renderLoadingSpinner( message?: string, spinnerColor: "blue" | "green" | "yellow" | "white" = "blue", ): TemplateResult { return renderLoadingSpinner(message, spinnerColor); } } const spinnerColorClasses: Record = { blue: "border-blue-500/30 border-t-blue-500", green: "border-green-500/30 border-t-green-500", yellow: "border-yellow-500/30 border-t-yellow-500", white: "border-white/20 border-t-white", }; /** * Renders a standardized loading spinner with optional custom message. * Use this for consistent loading states across all modals. */ export function renderLoadingSpinner( message?: string, spinnerColor: "blue" | "green" | "yellow" | "white" = "blue", ): TemplateResult { return html`
${ message ? html`

${message}

` : "" }
`; }