import './custom-select.css'; import toolbarStyles from '../header/studio-toolbar.module.css'; interface Choice { value: string; description?: string; badge?: string; imageUrl?: string; icon?: 'user-circle' | 'stack-simple' | 'upload-simple'; destructive?: boolean; separatorBefore?: boolean } interface SelectOptions { select: HTMLSelectElement; label: string; choices?: Choice[]; showSelectionPreview?: boolean; menuWidth?: 'content' | 'trigger' } interface SelectControl { element: HTMLElement; trigger: HTMLButtonElement; sync: () => void; destroy: () => void } interface SelectWindow extends Window { FotogenicAI?: { Shared?: { ui?: { select?: { create: typeof createSelect } } } }; } let sequence = 0; /** Keep the form value and change event in the owner; render one shared, keyboard-accessible chooser. */ const createSelect = ({ select, label, choices = [], showSelectionPreview = false, menuWidth = 'content' }: SelectOptions): SelectControl => { const targetStyle = (name: string): string => { const value = toolbarStyles[name]; if (!value) throw new Error(`Fotogenic AI: missing ${name} toolbar style.`); return value; }; const element = document.createElement('span'); element.className = 'fotogenic-ai-custom-select'; element.setAttribute('data-menu-width', menuWidth); const trigger = document.createElement('button'); trigger.type = 'button'; trigger.className = 'fotogenic-ai-custom-select__trigger'; trigger.setAttribute('role', 'combobox'); trigger.setAttribute('aria-label', label); trigger.setAttribute('aria-haspopup', 'listbox'); trigger.setAttribute('aria-expanded', 'false'); trigger.disabled = select.disabled; const focusKey = select.getAttribute('data-fa-focus-key'); if (focusKey) { trigger.setAttribute('data-fa-focus-key', focusKey); select.removeAttribute('data-fa-focus-key'); } const text = document.createElement('span'); text.className = 'fotogenic-ai-custom-select__value'; const caret = document.createElement('span'); caret.className = 'fotogenic-ai-icon fotogenic-ai-icon--caret-down fotogenic-ai-icon--bold fotogenic-ai-icon--size-15'; caret.setAttribute('aria-hidden', 'true'); trigger.append(text, caret); const menu = document.createElement('div'); menu.className = 'fotogenic-ai-custom-select__menu'; menu.setAttribute('data-menu-width', menuWidth); menu.id = `fotogenic-select-${++sequence}`; menu.setAttribute('popover', 'auto'); menu.setAttribute('role', 'listbox'); menu.setAttribute('aria-label', label); element.classList.add(targetStyle('selectorTheme')); trigger.setAttribute('data-fa-select-appearance', 'workflow'); menu.setAttribute('data-fa-select-appearance', 'workflow'); trigger.classList.add(targetStyle('trigger')); caret.classList.add(targetStyle('caret')); menu.classList.add(targetStyle('menu')); // Keep native top-layer/light dismissal, using the target menu's exact motion classes. menu.addEventListener('beforetoggle', (event: ToggleEvent) => { const opening = event.newState === 'open'; menu.classList.toggle(targetStyle('menuOpen'), opening); menu.classList.toggle(targetStyle('menuClosing'), !opening); element.classList.toggle(targetStyle('selectorOpen'), opening); trigger.setAttribute('aria-expanded', String(opening)); }); trigger.setAttribute('aria-controls', menu.id); select.hidden = true; select.tabIndex = -1; element.append(select, trigger, menu); let active = -1; let search = ''; let searchedAt = 0; let viewportEvents: AbortController | null = null; const isOpen = (): boolean => menu.matches(':popover-open'); const close = (): void => { if (isOpen()) menu.hidePopover(); }; // Native light dismissal happens before click. Remember trigger intent at pointerdown. let closeOnClick = false; trigger.addEventListener('pointerdown', () => { closeOnClick = isOpen(); }); trigger.addEventListener('pointercancel', () => { closeOnClick = false; }); trigger.addEventListener('keydown', () => { closeOnClick = false; }); const preview = (choice: Choice | undefined): HTMLElement | null => { if (choice?.imageUrl && URL.canParse(choice.imageUrl, window.location.href)) { const url = new URL(choice.imageUrl, window.location.href); if ((url.protocol === 'https:' || url.origin === window.location.origin) && !url.username && !url.password) { const image = document.createElement('img'); image.src = url.href; image.alt = ''; image.width = 36; image.height = 44; image.loading = 'lazy'; image.referrerPolicy = 'no-referrer'; image.addEventListener('error', () => image.remove(), { once: true }); return image; } } if (choice?.icon) { const icon = document.createElement('span'); icon.className = `fotogenic-ai-icon fotogenic-ai-icon--${choice.icon} fotogenic-ai-icon--regular fotogenic-ai-icon--size-20`; icon.setAttribute('aria-hidden', 'true'); return icon; } return null; }; const sync = (): void => { text.replaceChildren(); text.textContent = select.selectedOptions[0]?.textContent ?? ''; const choice = choices.find((item) => item.value === select.value); text.classList.toggle('has-badge', Boolean(choice?.badge)); if (choice?.badge) text.append(badge(choice.badge)); if (showSelectionPreview) { trigger.querySelector('.fotogenic-ai-custom-select__preview')?.remove(); const media = preview(choices.find((choice) => choice.value === select.value)); trigger.classList.toggle('has-preview', Boolean(media)); if (media) { media.classList.add('fotogenic-ai-custom-select__preview'); trigger.prepend(media); } } const description = select.getAttribute('aria-describedby'); if (description) trigger.setAttribute('aria-describedby', description); else trigger.removeAttribute('aria-describedby'); [...menu.children].forEach((node, index) => node.setAttribute('aria-selected', String(index === select.selectedIndex))); }; const badge = (label: string): HTMLElement => { const result = document.createElement('span'); result.className = 'fotogenic-ai-custom-select__badge'; result.textContent = label; return result; }; const highlight = (index: number): void => { active = index; [...menu.children].forEach((node, item) => node.classList.toggle('is-active', item === index)); const option = menu.children[index]; if (option) { trigger.setAttribute('aria-activedescendant', option.id); const bounds = option.getBoundingClientRect(); const viewport = menu.getBoundingClientRect(); if (bounds.top < viewport.top) menu.scrollTop -= viewport.top - bounds.top; else if (bounds.bottom > viewport.bottom) menu.scrollTop += bounds.bottom - viewport.bottom; } }; const choose = (index: number): void => { if (trigger.disabled || !select.options[index] || select.options[index].disabled) return; const changed = select.selectedIndex !== index; select.selectedIndex = index; sync(); close(); trigger.focus({ preventScroll: true }); if (changed) select.dispatchEvent(new Event('change', { bubbles: true })); }; const renderOptions = (): void => { menu.replaceChildren(); [...select.options].forEach((option, index) => { const row = document.createElement('div'); row.className = 'fotogenic-ai-custom-select__option'; row.classList.add(targetStyle('option')); row.id = `${menu.id}-${index}`; row.setAttribute('role', 'option'); row.setAttribute('aria-disabled', String(option.disabled)); row.hidden = option.hidden; const choice = choices.find((item) => item.value === option.value); row.classList.toggle('is-destructive', Boolean(choice?.destructive)); row.classList.toggle('has-separator', Boolean(choice?.separatorBefore)); row.classList.toggle('has-description', Boolean(choice?.description)); const media = preview(choice); if (media) { row.className += ' has-preview'; if (media.tagName !== 'IMG') media.classList.add(targetStyle('optionIcon')); row.append(media); } const copy = document.createElement('span'); copy.className = 'fotogenic-ai-custom-select__copy'; copy.classList.add(targetStyle('optionCopy')); const name = document.createElement('strong'); name.textContent = option.textContent; if (choice?.badge) { name.classList.add('has-badge'); name.append(badge(choice.badge)); } copy.append(name); if (choice?.description) { const description = document.createElement('small'); description.textContent = choice.description; copy.append(description); } const check = document.createElement('span'); check.className = 'fotogenic-ai-custom-select__check fotogenic-ai-icon fotogenic-ai-icon--check fotogenic-ai-icon--size-16'; check.classList.add(targetStyle('optionCheck')); check.setAttribute('aria-hidden', 'true'); row.append(copy, check); row.addEventListener('pointerdown', (event) => { // Keep mouse focus on the combobox without suppressing touch activation in WebKit. if (event.pointerType === 'mouse') event.preventDefault(); }); row.addEventListener('click', () => choose(index)); menu.append(row); }); }; const open = (): void => { if (trigger.disabled || isOpen()) return; renderOptions(); const rect = trigger.getBoundingClientRect(); const width = Math.min(window.innerWidth - 24, menuWidth === 'trigger' ? rect.width : Math.max(rect.width, choices.some((item) => item.imageUrl) ? 320 : 220)); const below = window.innerHeight - rect.bottom - 12; const above = rect.top - 12; const upwards = below < 220 && above > below; menu.style.width = `${width}px`; menu.style.maxHeight = `${Math.min(380, Math.max(80, upwards ? above : below))}px`; menu.style.left = `${Math.max(12, Math.min(rect.left, window.innerWidth - width - 12))}px`; menu.style.top = upwards ? 'auto' : `${rect.bottom + 6}px`; menu.style.bottom = upwards ? `${window.innerHeight - rect.top + 6}px` : 'auto'; menu.style.transformOrigin = upwards ? 'bottom left' : 'top left'; menu.showPopover(); trigger.focus({ preventScroll: true }); trigger.setAttribute('aria-expanded', 'true'); sync(); highlight(select.selectedIndex >= 0 ? select.selectedIndex : 0); viewportEvents?.abort(); viewportEvents = new AbortController(); window.addEventListener('resize', close, { signal: viewportEvents.signal }); window.addEventListener('scroll', (event) => { if (event.target instanceof Node && menu.contains(event.target)) return; const current = trigger.getBoundingClientRect(); if (current.top !== rect.top || current.bottom !== rect.bottom || current.left !== rect.left || current.width !== rect.width) close(); }, { capture: true, signal: viewportEvents.signal }); }; menu.addEventListener('toggle', () => { if (isOpen()) return; trigger.setAttribute('aria-expanded', 'false'); trigger.removeAttribute('aria-activedescendant'); viewportEvents?.abort(); }); trigger.addEventListener('click', () => { if (closeOnClick || isOpen()) close(); else open(); closeOnClick = false; }); trigger.addEventListener('keydown', (event) => { if (event.key === 'Tab') { close(); return; } if (event.key === 'Escape') { if (isOpen()) { close(); event.preventDefault(); event.stopPropagation(); } return; } if (['Enter', ' '].includes(event.key)) { event.preventDefault(); if (isOpen()) choose(active); else open(); return; } const options = [...select.options]; const available = options.map((option, index) => option.disabled ? -1 : index).filter((index) => index >= 0); if (!available.length) return; if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { event.preventDefault(); if (!isOpen()) open(); const current = available.indexOf(active); const next = event.key === 'Home' ? 0 : event.key === 'End' ? available.length - 1 : Math.max(0, Math.min(available.length - 1, current + (event.key === 'ArrowDown' ? 1 : -1))); const nextIndex = available[next]; if (nextIndex !== undefined) highlight(nextIndex); } else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) { event.preventDefault(); const now = Date.now(); search = now - searchedAt > 700 ? event.key : search + event.key; searchedAt = now; if (!isOpen()) open(); const match = available.find((index) => options[index]?.text.toLowerCase().startsWith(search.toLowerCase())); if (match !== undefined) highlight(match); } }); select.addEventListener('change', sync); const observer = new MutationObserver(() => { trigger.disabled = select.disabled; if (trigger.disabled) close(); if (isOpen()) { renderOptions(); highlight(select.selectedIndex >= 0 ? select.selectedIndex : 0); } sync(); }); observer.observe(select, { attributes: true, attributeFilter: ['disabled', 'aria-describedby'], childList: true, subtree: true }); sync(); return { element, trigger, sync, destroy: () => { close(); viewportEvents?.abort(); observer.disconnect(); select.removeEventListener('change', sync); } }; }; const runtime = window as SelectWindow; runtime.FotogenicAI = runtime.FotogenicAI ?? {}; runtime.FotogenicAI.Shared = runtime.FotogenicAI.Shared ?? {}; runtime.FotogenicAI.Shared.ui = runtime.FotogenicAI.Shared.ui ?? {}; runtime.FotogenicAI.Shared.ui.select = { ...runtime.FotogenicAI.Shared.ui.select, create: createSelect }; export { createSelect };