import './workflow-dialog.css'; import { createSecureUuid } from '../identity/secure-uuid'; interface Choice { id: string; label: string; description: string; disabled?: boolean } interface Options { title: string; closeLabel: string; choices: Choice[]; onSelect: (id: string) => void; onClose?: () => void } export const openWorkflowDialog = ({ title, closeLabel, choices, onSelect, onClose }: Options) => { const dialog = document.createElement('dialog'); dialog.className = 'fotogenic-ai-workflow-dialog'; const header = document.createElement('header'); const heading = document.createElement('h2'); heading.textContent = title; const identity = createSecureUuid(); if (identity) { heading.id = `fotogenic-workflow-${identity}`; dialog.setAttribute('aria-labelledby', heading.id); } else dialog.setAttribute('aria-label', title); const dismiss = document.createElement('button'); dismiss.type = 'button'; dismiss.textContent = '×'; dismiss.setAttribute('aria-label', closeLabel); const close = () => { if (dialog.open) dialog.close(); }; dismiss.addEventListener('click', close); header.append(heading, dismiss); dialog.append(header); const choiceElements = new Map(); choices.forEach((choice) => { const button = document.createElement('button'); button.type = 'button'; button.className = 'fotogenic-ai-workflow-choice'; const label = document.createElement('strong'); label.textContent = choice.label; const description = document.createElement('span'); button.append(label, description); button.addEventListener('click', () => { close(); onSelect(choice.id); }); dialog.append(button); choiceElements.set(choice.id, { button, description }); }); const syncChoices = (nextChoices: Choice[]): void => { nextChoices.forEach((choice) => { const elements = choiceElements.get(choice.id); if (!elements) return; const disabled = choice.disabled === true; if (disabled && document.activeElement === elements.button) dismiss.focus({ preventScroll: true }); if (elements.button.disabled !== disabled) elements.button.disabled = disabled; if (elements.description.textContent !== choice.description) elements.description.textContent = choice.description; }); }; syncChoices(choices); dialog.addEventListener('click', (event) => { if (event.target === dialog) { const rect = dialog.getBoundingClientRect(); if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) close(); } }); dialog.addEventListener('close', () => { dialog.remove(); onClose?.(); }, { once: true }); document.body.append(dialog); dialog.showModal(); return { close, syncChoices }; };