import styles from './studio-toolbar.module.css'; import { openWorkflowDialog } from './workflow-dialog'; type ToolbarMode = 'studio' | 'settings' | 'home'; interface CanonicalRoute { workflow: string; sourceType: string; scope: string; } interface WorkflowSource { requiresWooCommerce?: boolean; scopes?: unknown[]; } interface WorkflowManifestEntry { id?: string; sources?: WorkflowSource[]; } interface WorkflowManifest { workflows?: WorkflowManifestEntry[]; optionSources?: { generation?: { features?: Record; featureReasons?: Record; operationalLimits?: { workflows?: Record } } }; } interface ToolbarSyncContext { workflowSelected?: boolean; manifest?: WorkflowManifest; route?: Partial; wooAvailable?: boolean; configurationState?: 'disconnected' | 'loading' | 'error' | 'ready'; } interface ToolbarController { open: (onSelect?: () => void) => void; sync: (context?: ToolbarSyncContext) => void; close: (restoreFocus?: boolean) => void; setDisabled: (disabled: boolean) => void; destroy: () => void; } interface ToolbarApi { create: (context?: { root?: HTMLElement | null }) => ToolbarController | null; get: (root?: HTMLElement | null) => ToolbarController | null; signedAdminUrl: (value: unknown, expectedPage: string) => URL | null; routeUrl: (baseUrl: unknown, expectedPage: string, route?: Partial) => string; } interface RuntimeWindow extends Window { wp?: { i18n?: { __: (text: string, domain: string) => string } }; FotogenicAI?: { Studio?: { app?: { blocked?: boolean } }; Shared?: { ui?: { studioToolbar?: ToolbarApi; }; }; }; } const instances = new WeakMap(); const canonicalKeys: Array = ['workflow', 'sourceType', 'scope']; const __ = (text: string, domain: string): string => (window as RuntimeWindow).wp?.i18n?.__(text, domain) ?? text; const css = (name: string): string => { const value = styles[name]; if (!value) throw new Error(`Fotogenic AI: missing ${name} toolbar style.`); return value; }; const signedAdminUrl = (value: unknown, expectedPage: string): URL | null => { try { const url = new URL(String(value ?? ''), window.location.href); if ( !['http:', 'https:'].includes(url.protocol) || url.origin !== window.location.origin || !url.pathname.endsWith('/wp-admin/admin.php') || url.searchParams.get('page') !== expectedPage || !url.searchParams.get('_fotogenic_ai_nav') ) return null; return url; } catch { return null; } }; const routeUrl = ( baseUrl: unknown, expectedPage: string, route: Partial = {}, ): string => { const url = signedAdminUrl(baseUrl, expectedPage); if (!url || !canonicalKeys.every((key) => String(route[key] ?? '').trim())) return ''; canonicalKeys.forEach((key) => url.searchParams.set(key, String(route[key]))); return url.href; }; const workflowIsEnabled = ( workflow: WorkflowManifestEntry | undefined, wooAvailable: boolean, ): boolean => Boolean(workflow?.sources?.some((source) => ( (!source.requiresWooCommerce || wooAvailable) && Array.isArray(source.scopes) && source.scopes.length > 0 ))); const createStudioToolbar = ( context: { root?: HTMLElement | null } = {}, ): ToolbarController | null => { const root = context.root; if (!(root instanceof HTMLElement)) return null; const existing = instances.get(root); if (existing) return existing; const mode: ToolbarMode = root.dataset.faToolbarMode === 'home' ? 'home' : root.dataset.faToolbarMode === 'settings' ? 'settings' : 'studio'; const toolbar = root.querySelector('[data-fa-studio-toolbar]'); const identity = root.querySelector('[data-fa-studio-identity]'); const logo = root.querySelector('[data-fa-studio-logo]'); const divider = root.querySelector('[data-fa-studio-divider]'); const name = root.querySelector('[data-fa-studio-name]'); const selectorScope = mode === 'studio' ? root.closest('[data-fa-studio-root]') ?? root : root; const selector = selectorScope.querySelector('[data-fa-workflow-selector]'); const control = selectorScope.querySelector('[data-fa-control="workflow"]'); const trigger = selectorScope.querySelector('[data-fa-workflow-trigger]'); const menu = selectorScope.querySelector('[data-fa-workflow-menu]'); const label = selectorScope.querySelector('[data-fa-workflow-label]'); const caret = selectorScope.querySelector('[data-fa-workflow-caret]'); const options = [...selectorScope.querySelectorAll('[data-fa-workflow-option]')]; const optionIcons = [...selectorScope.querySelectorAll('[data-fa-workflow-option-icon]')]; const optionCopies = [...selectorScope.querySelectorAll('[data-fa-workflow-option-copy]')]; const optionChecks = [...selectorScope.querySelectorAll('[data-fa-workflow-option-check]')]; if ( !toolbar || !identity || !logo || !divider || !name || !selector || !control || !trigger || !menu || !label || !caret || options.length === 0 || optionIcons.length !== options.length || optionCopies.length !== options.length || optionChecks.length !== options.length ) throw new Error('Fotogenic AI: Studio toolbar anatomy is unavailable.'); root.className = css('header'); toolbar.className = css('toolbar'); identity.className = css('identity'); logo.className = css('logo'); divider.className = css('divider'); name.className = css('name'); selector.className = css('selector'); trigger.className = css('trigger'); trigger.setAttribute('aria-haspopup', 'dialog'); trigger.removeAttribute('aria-controls'); caret.className = 'fotogenic-ai-icon fotogenic-ai-icon--arrow-right fotogenic-ai-icon--size-15'; menu.className = css('menu'); options.forEach((option) => { option.className = css('option'); option.classList.toggle(css('optionSelected'), option.getAttribute('aria-checked') === 'true'); }); optionIcons.forEach((icon) => { icon.classList.add(css('optionIcon')); }); optionCopies.forEach((copy) => { copy.className = css('optionCopy'); }); optionChecks.forEach((check) => { check.classList.add(css('optionCheck')); }); let open = false; let forcedDisabled = false; let destroyed = false; let workflowDialog: ReturnType | null = null; let afterWorkflowSelection: (() => void) | undefined; const enabledOptions = (): HTMLButtonElement[] => options.filter((option) => !option.disabled); const dialogChoices = () => options.map((option) => ({ id: option.dataset.faWorkflowOption || '', label: option.querySelector('strong')?.textContent || '', description: option.disabled && option.title ? option.title : option.querySelector('small')?.textContent || '', disabled: option.disabled, })); const close = (restoreFocus = false): void => { workflowDialog?.close(); workflowDialog = null; open = false; menu.hidden = true; trigger.setAttribute('aria-expanded', 'false'); selector.classList.remove(css('selectorOpen')); if (restoreFocus && trigger.isConnected && !trigger.disabled) { trigger.focus({ preventScroll: true }); } }; const syncDisabled = (): void => { trigger.disabled = forcedDisabled || control.disabled || enabledOptions().length === 0; if (trigger.disabled) close(); }; const openMenu = (): HTMLButtonElement[] => { if (trigger.disabled) return []; const enabled = enabledOptions(); if (enabled.length === 0) return []; open = true; menu.hidden = true; trigger.setAttribute('aria-expanded', 'true'); selector.classList.add(css('selectorOpen')); workflowDialog = openWorkflowDialog({ title: root.dataset.faWorkflowDialogTitle || 'What would you like to create?', closeLabel: root.dataset.faCloseLabel || 'Close', choices: dialogChoices(), onSelect: (id) => { const option = options.find((item) => item.dataset.faWorkflowOption === id); if (!option || option.disabled) return; const continueSelection = afterWorkflowSelection; afterWorkflowSelection = undefined; selectOption(option); continueSelection?.(); }, onClose: () => { open = false; workflowDialog = null; afterWorkflowSelection = undefined; trigger.setAttribute('aria-expanded', 'false'); selector.classList.remove(css('selectorOpen')); if (trigger.isConnected && !trigger.disabled && trigger.getClientRects().length) trigger.focus({ preventScroll: true }); window.dispatchEvent(new CustomEvent('fotogenic-ai:studio-idle')); }, }); return []; }; const selectOption = (option: HTMLButtonElement): void => { if (option.disabled) return; const workflow = String(option.dataset.faWorkflowOption ?? ''); if (!workflow) return; if (option.getAttribute('aria-checked') === 'true') { close(true); return; } if (mode !== 'studio') { const destination = signedAdminUrl(option.dataset.faWorkflowUrl, 'fotogenic-studio'); if (!destination) { close(true); return; } close(); window.location.assign(destination.href); return; } control.value = workflow; close(true); control.dispatchEvent(new Event('change', { bubbles: true })); }; const handleTriggerClick = (): void => { if (open) close(true); else openMenu(); }; const handleTriggerKeydown = (event: KeyboardEvent): void => { if (event.key === 'Escape' && open) { event.preventDefault(); close(true); return; } if (!['ArrowDown', 'ArrowUp'].includes(event.key)) return; event.preventDefault(); openMenu(); }; const optionHandlers = options.map((option) => { const handler = (): void => selectOption(option); option.addEventListener('click', handler); return [option, handler] as const; }); trigger.addEventListener('click', handleTriggerClick); const navigation = root.querySelector('.fotogenic-ai-app-navigation'); const handleNavigation = (event: MouseEvent): void => { if (mode !== 'studio' || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; if ((window as RuntimeWindow).FotogenicAI?.Studio?.app?.blocked !== false) return; const link = event.target instanceof Element ? event.target.closest('a') : null; if (link?.hasAttribute('data-fa-nav-history') || link?.hasAttribute('data-fa-nav-studio')) { event.preventDefault(); window.dispatchEvent(new CustomEvent(link.hasAttribute('data-fa-nav-history') ? 'fotogenic-ai:open-history' : 'fotogenic-ai:open-select')); } }; navigation?.addEventListener('click', handleNavigation); trigger.addEventListener('keydown', handleTriggerKeydown); syncDisabled(); const sync = ({ manifest, route, wooAvailable = false, workflowSelected = true, configurationState }: ToolbarSyncContext = {}): void => { const workflows = Array.isArray(manifest?.workflows) ? manifest.workflows : []; if (!workflowSelected) label.textContent = root.dataset.faSelectModeLabel || 'Select mode'; if (route?.workflow) control.value = route.workflow; options.forEach((option) => { const workflowId = String(option.dataset.faWorkflowOption ?? ''); const workflow = workflows.find((entry) => entry.id === workflowId); const feature = workflowId === 'campaign_set' ? 'generateCampaignSet' : ''; const generation = manifest?.optionSources?.generation; const accountEnabled = !feature || generation?.features?.[feature] === true; const enabled = option.dataset.faServerEnabled === '1' && workflowIsEnabled(workflow, wooAvailable) && accountEnabled; const reason = feature ? generation?.featureReasons?.[feature] : null; option.title = ''; if (!accountEnabled) { if (configurationState === 'disconnected') { option.title = __( 'Connect Fotogenic AI to check access to Campaign Set.', 'fotogenic-ai' ); } else if (configurationState === 'loading') { option.title = __( 'Checking your access to Campaign Set…', 'fotogenic-ai' ); } else if (configurationState === 'error') { option.title = __( 'Could not check access to Campaign Set. Reload Studio to try again.', 'fotogenic-ai' ); } else { const accountReason = typeof reason === 'string' ? reason : reason?.message; option.title = (typeof accountReason === 'string' && accountReason.trim()) || __( 'Campaign Set is unavailable for this account.', 'fotogenic-ai' ); } } const selected = workflowSelected && workflowId === route?.workflow; option.disabled = !enabled; option.classList.toggle(css('optionSelected'), selected); option.setAttribute('aria-checked', selected ? 'true' : 'false'); const nativeOption = [...control.options].find((entry) => entry.value === workflowId); if (nativeOption) nativeOption.disabled = !enabled; if (selected) { label.textContent = option.querySelector('strong')?.textContent || workflowId; } }); root.dataset.workflow = String(route?.workflow ?? ''); root.dataset.sourceType = String(route?.sourceType ?? ''); root.dataset.scope = String(route?.scope ?? ''); const settingsUrl = routeUrl(root.dataset.faSettingsBaseUrl, 'fotogenic-ai', route); if (settingsUrl) { root.querySelectorAll('[data-fa-settings-route-link]').forEach((link) => { link.href = settingsUrl; }); } if (enabledOptions().length === 0) { label.textContent = String(root.dataset.faUnavailableLabel ?? ''); } syncDisabled(); workflowDialog?.syncChoices(dialogChoices()); }; const controller: ToolbarController = Object.freeze({ open: (onSelect?: () => void) => { if (!open) { afterWorkflowSelection = onSelect; openMenu(); } }, sync, close, setDisabled(disabled: boolean): void { forcedDisabled = disabled; syncDisabled(); }, destroy(): void { if (destroyed) return; destroyed = true; close(); trigger.removeEventListener('click', handleTriggerClick); navigation?.removeEventListener('click', handleNavigation); trigger.removeEventListener('keydown', handleTriggerKeydown); optionHandlers.forEach(([option, handler]) => option.removeEventListener('click', handler)); instances.delete(root); }, }); instances.set(root, controller); return controller; }; const api: ToolbarApi = Object.freeze({ create: createStudioToolbar, get: (root?: HTMLElement | null): ToolbarController | null => ( root instanceof HTMLElement ? instances.get(root) ?? null : null ), signedAdminUrl, routeUrl, }); const initialize = (): void => { document.querySelectorAll('[data-fa-shared-toolbar]').forEach((root) => { createStudioToolbar({ root }); }); }; const runtimeWindow = window as RuntimeWindow; runtimeWindow.FotogenicAI = runtimeWindow.FotogenicAI ?? {}; runtimeWindow.FotogenicAI.Shared = runtimeWindow.FotogenicAI.Shared ?? {}; runtimeWindow.FotogenicAI.Shared.ui = runtimeWindow.FotogenicAI.Shared.ui ?? {}; runtimeWindow.FotogenicAI.Shared.ui.studioToolbar = api; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initialize, { once: true }); } else { initialize(); } export type { ToolbarApi, ToolbarController, ToolbarSyncContext }; export { createStudioToolbar, routeUrl, signedAdminUrl };