/* Declarative page contributions. Sources retain ownership of routes, forms and handlers; the shell renders accessible bindings, never relocates page controls or clones their handlers/IDs. */ (() => { const shell = document.querySelector('[data-ribbon-shell]'); const host = shell?.querySelector('[data-pwa-context-host]'); const controls = host?.querySelector('[data-pwa-context-controls]'); performance.mark('pd-ribbon-initial-start'); const initial = document.querySelector('[data-pwa-initial-contributions]'); let main = document.querySelector('[data-pwa-page-content]') || initial?.content; if (!host || !main) return; const liveSources = []; let sourceRoots = initial ? [...initial.content.children] : [main]; const querySources = selector => sourceRoots.flatMap(region => [...(region.matches?.(selector) ? [region] : []), ...region.querySelectorAll(selector)]); const sourceSelector = '[data-pwa-header], [data-pwa-context], [data-pwa-help], [data-pwa-task]'; const icons = shell.querySelector('[data-pwa-icon-catalog]')?.content; let queued = false, bindings = [], lastInvoker = null, nextKey = 0; const sourceKeys = new WeakMap(); const boundCommands = new WeakSet(); const borrowedCommands = new Map(); function restoreRibbonCommands() { for (const [command, marker] of borrowedCommands) marker.replaceWith(command); borrowedCommands.clear(); } const bindingKey = source => { if (!sourceKeys.has(source)) sourceKeys.set(source, `source-${++nextKey}`); return sourceKeys.get(source); }; const make = (tag, className, text) => { const node = document.createElement(tag); if (className) node.className = className; if (text) node.textContent = text; return node; }; const caption = node => node.dataset.pwaLabel || node.getAttribute('aria-label') || node.textContent.trim(); function routeKey(href) { const url = new URL(href, location.href); const query = [...url.searchParams].map(([k, v]) => [k.toLowerCase(), v]).sort((a, b) => a[0].localeCompare(b[0])); return `${url.origin}${url.pathname.toLowerCase().replace(/\/$/, '')}?${JSON.stringify(query)}${url.hash}`; } function commandIdentity(source) { const form = source.closest('form'); if (source.matches('button') && !form) return `handler:${source.dataset.commandOperation || source.dataset.bsTarget || source.id || bindingKey(source)}`; const href = source.getAttribute('href') || form?.getAttribute('action') || location.href; const operation = source.dataset.commandOperation || form?.dataset.commandOperation; const url = new URL(href, location.href); const values = [...url.searchParams].map(([key, value]) => [key.toLowerCase(), value]); let path = url.pathname.toLowerCase().replace(/\/$/, ''); if (operation) { const [controller, action] = operation.split('.'); const parts = path.split('/').filter(Boolean); if (parts[0] === controller && (parts[1] || 'index') === action && parts.length <= 3) { if (parts[2]) values.push(['id', decodeURIComponent(parts[2])]); path = ''; } } values.sort((a, b) => a[0].localeCompare(b[0])); if (source.matches('button') && form) { const method = (form.method || 'get').toLowerCase(); const fields = [...form.querySelectorAll('input[type="hidden"][name]:not([name="__RequestVerificationToken"])')].map(input => [input.name.toLowerCase(), input.value]).sort((a, b) => a[0].localeCompare(b[0])); return `${method}:${operation || path}:${JSON.stringify(values)}:${JSON.stringify(fields)}:${source.name || ''}:${source.value || ''}`; } return `${operation || 'navigate'}:${url.origin}:${path}:${JSON.stringify(values)}:${url.hash}`; } function iconKey(source) { if (source.dataset.ribbonIcon) return source.dataset.ribbonIcon; if (source.dataset.pwaIcon) return source.dataset.pwaIcon; if (source.closest('form')?.dataset.pwaIcon) return source.closest('form').dataset.pwaIcon; const operation = source.dataset.commandOperation || source.closest('form')?.dataset.commandOperation || ''; const href = source.getAttribute('href') || ''; const fragments = { '#characters': 'characters', '#threads': 'threads', '#assets': 'assets', '#relationships': 'relationships', '#locations': 'locations', '#timeline-summary': 'timeline', '#attention': 'warnings', '#revision': 'review' }; if (fragments[href]) return fragments[href]; if (/^\/help(?:\/|$)/i.test(href)) return 'help'; const sameOperation = [...shell.querySelectorAll('.pd-ribbon-command[data-command-operation]')].find(command => command.dataset.commandOperation === operation); if (sameOperation?.dataset.ribbonIcon) return sameOperation.dataset.ribbonIcon; const controller = operation.split('.')[0]; return { characters: 'characters', locations: 'locations', storyassets: 'assets', floorplans: 'floorplans', relationshipmap: 'relationships', plotlines: 'plotlines', plotthreads: 'threads', warnings: 'warnings', analytics: 'health', projectmetrics: 'metrics', timeline: 'timeline', scenarios: 'scenarios', help: 'help', featurerequests: 'review' }[controller] || 'writer'; } function decorate(node, text, key) { const svg = icons?.querySelector(`[data-icon-key="${key}"]`)?.cloneNode(true); if (svg) { svg.removeAttribute('data-icon-key'); node.append(svg); } node.append(make('span', '', text)); } let fitQueued = false; const activePanel = () => shell.querySelector('.pd-ribbon-panel:not([hidden])'); function positionMenu(details) { if (!details.open || details.dataset.compact !== 'true') return; const panel = details.querySelector(':scope > .pd-context-menu-content'); const anchor = details.querySelector(':scope > summary').getBoundingClientRect(); const width = Math.min(360, innerWidth - 24); panel.style.width = `${width}px`; panel.style.left = `${Math.max(12, Math.min(anchor.left, innerWidth - width - 12))}px`; panel.style.top = `${anchor.bottom + 8}px`; } function wireMenu(details) { details.addEventListener('toggle', () => { details.querySelector(':scope > summary').setAttribute('aria-expanded', String(details.open)); if (details.open && details.dataset.compact === 'true') { activePanel()?.querySelectorAll('details[data-compact="true"][open]').forEach(other => { if (other !== details) other.open = false; }); positionMenu(details); } }); } function compact(details, value) { const focused = details.contains(document.activeElement); const wasCompact = details.dataset.compact === 'true'; details.dataset.compact = String(value); if (!value) { const content = details.querySelector(':scope > .pd-context-menu-content'); for (const property of ['width', 'left', 'top']) content.style.removeProperty(property); } details.open = !value; details.querySelector(':scope > summary').setAttribute('aria-expanded', String(!value)); if (value && !wasCompact && focused) details.querySelector(':scope > summary').focus({ preventScroll: true }); } function wrapBaseGroup(group, index) { if (group.querySelector(':scope > details')) return; const row = group.querySelector(':scope > .pd-ribbon-commands'); const label = group.querySelector('.pd-ribbon-group-label').textContent.trim(); const details = make('details', 'pd-context-menu pd-base-overflow'); details.dataset.compact = 'false'; details.dataset.priority = String(-10 + index); details.open = true; const summary = make('summary', 'pd-ribbon-command'); const svg = row.querySelector('svg')?.cloneNode(true); if (svg) summary.append(svg); summary.append(make('span', '', 'More')); summary.setAttribute('aria-label', `${label} commands`); row.classList.add('pd-context-menu-content'); group.prepend(details); details.append(summary, row); wireMenu(details); } function fitRibbon() { fitQueued = false; const panel = activePanel(); if (!panel || host.hidden || !panel.clientWidth) return; // The shell owns these groups. No page DOM or command handlers are relocated. if (host.parentElement !== panel) panel.append(host); const base = [...panel.querySelectorAll(':scope > .pd-ribbon-group')]; base.forEach(wrapBaseGroup); const menuKey = details => { const summary = details.querySelector(':scope > summary'); return summary.dataset.pwaBinding || summary.getAttribute('aria-label'); }; const open = new Set([...panel.querySelectorAll('details[data-compact="true"][open]')].map(menuKey)); const menus = [...panel.querySelectorAll('.pd-context-group > details, :scope > .pd-ribbon-group > details')]; const expanded = new Map(); for (const details of menus) { compact(details, details.dataset.alwaysCompact === 'true'); expanded.set(details, details.parentElement.getBoundingClientRect().width); } const candidates = menus.filter(details => details.dataset.alwaysCompact !== 'true') .sort((a, b) => Number(b.dataset.priority || 0) - Number(a.dataset.priority || 0)); const available = panel.clientWidth; const used = () => [...base, ...controls.querySelectorAll(':scope > .pd-context-group')] .filter(group => !group.hidden).reduce((sum, group) => sum + group.getBoundingClientRect().width, 0); // Less frequent contextual groups collapse first, then existing navigation groups if necessary. for (const details of candidates) { if (used() <= available + 1) break; if (details.dataset.essential === 'true') continue; const wide = expanded.get(details); compact(details, true); if (details.parentElement.getBoundingClientRect().width >= wide - 1) compact(details, false); } // A coarse navigation-group collapse may release enough room to show useful context again. for (const details of [...candidates].reverse()) { if (details.dataset.compact !== 'true') continue; const current = details.parentElement.getBoundingClientRect().width; if (used() + expanded.get(details) - current <= available + 1) compact(details, false); } for (const details of menus) if (details.dataset.compact === 'true' && open.has(menuKey(details))) details.open = true; panel.querySelectorAll('details[data-compact="true"][open]').forEach(positionMenu); } function queueFit() { if (!fitQueued) { fitQueued = true; requestAnimationFrame(fitRibbon); } } function menu(label, priority = 50, alwaysCompact = false) { const group = make('div', 'pd-ribbon-group pd-context-group'); group.setAttribute('role', 'group'); group.setAttribute('aria-label', label); const details = make('details', 'pd-context-menu'); details.dataset.priority = String(priority); details.dataset.alwaysCompact = String(alwaysCompact); details.dataset.compact = 'false'; details.open = true; const summary = make('summary', 'pd-ribbon-command'); const shortLabel = label.replace(/^Timeline /, '').replace('Page tools', 'Tools').replace(/^./, value => value.toUpperCase()); decorate(summary, shortLabel, label === 'Export' ? 'export' : label === 'Jump to' ? 'point' : label === 'Manage' ? 'archive' : 'writer'); summary.setAttribute('aria-expanded', 'true'); summary.dataset.pwaBinding = `menu-${label}`; const content = make('div', 'pd-ribbon-commands pd-context-menu-content'); content.setAttribute('role', 'group'); content.setAttribute('aria-label', label); details.append(summary, content); wireMenu(details); group.append(details, make('span', 'pd-ribbon-group-label', label)); controls.append(group); return content; } function bindState(source, target) { boundCommands.add(source); const update = () => { const sourceHidden = !!source.closest('[hidden]'); const keepVisible = source.dataset.pwaKeepVisible === 'true'; const disabled = source.matches(':disabled, .disabled, [aria-disabled="true"]') || (keepVisible && sourceHidden); if ('disabled' in target) target.disabled = disabled; target.setAttribute('aria-disabled', String(disabled)); target.tabIndex = disabled ? -1 : 0; target.hidden = sourceHidden && !keepVisible; for (const attribute of ['aria-pressed', 'aria-current', 'aria-selected', 'aria-expanded']) { if (source.hasAttribute(attribute)) target.setAttribute(attribute, source.getAttribute(attribute)); else target.removeAttribute(attribute); } target.classList.toggle('is-active', source.getAttribute('aria-pressed') === 'true'); if (source.matches('button')) { const label = caption(source); if (target.querySelector('span').textContent !== label) target.querySelector('span').textContent = label; target.title = label; } }; bindings.push(update); update(); } function liveSource(source) { if (source.isConnected) return source; const region = source.closest('[data-pwa-source]'); let target = liveSources.find(node => node.dataset.pwaSource === region?.dataset.pwaSource); if (!target) return source; const path = []; for (let node = source; node !== region; node = node.parentElement) path.unshift([...node.parentElement.children].indexOf(node)); for (const index of path) target = target?.children[index]; return target || source; } function invoke(source, proxy) { source = liveSource(source); if (!source.isConnected || source.matches(':disabled, .disabled, [aria-disabled="true"]')) return; lastInvoker = proxy.closest('details[data-compact="true"]')?.querySelector('summary') || proxy; activePanel()?.querySelectorAll('details[data-compact="true"][open]').forEach(item => item.open = false); source.click(); // Existing submit listeners, submitter name/value, confirmations and antiforgery. } window.PlotDirectorCommands = Object.freeze({ identity: source => source.dataset.commandIdentity || commandIdentity(source), iconKey, invoke }); function renderCommand(source, group, equivalents, composed) { const identity = commandIdentity(source); if (composed.has(identity)) return; composed.add(identity); const href = source.getAttribute('href'); const equivalent = href && !href.startsWith('#') ? equivalents.get(identity) || equivalents.get(routeKey(href)) : null; if (equivalent && !source.matches(':disabled, .disabled, [aria-disabled="true"]')) { // Reuse the existing shell-owned command itself, once, with an exact scoped route. // Page content remains untouched. A marker restores its normal category/order on tab/mode changes. if (equivalent.closest('.pd-ribbon-panel') !== activePanel() && !borrowedCommands.has(equivalent)) { const marker = document.createComment('ribbon command home'); equivalent.before(marker); borrowedCommands.set(equivalent, marker); group.element.append(equivalent); } return; } const node = make(source.matches('a') ? 'a' : 'button', 'pd-ribbon-command pd-context-command'); node.dataset.pwaBinding = bindingKey(source); node.dataset.commandIdentity = identity; node.addEventListener('click', event => { if (source.matches(':disabled, .disabled, [aria-disabled="true"]')) { event.preventDefault(); event.stopImmediatePropagation(); } }, true); if (href) { node.href = href; if (source.target) { node.target = source.target; node.rel = source.rel; } if (source.hasAttribute('download')) node.setAttribute('download', source.getAttribute('download')); // Native links retain modifier/middle-click semantics. Data-driven buttons use original handlers. if (!href.startsWith('#')) { node.addEventListener('click', event => { if (!event.ctrlKey && !event.metaKey && !event.shiftKey && event.button === 0) { event.preventDefault(); invoke(source, node); } }); } if (href.startsWith('#')) node.addEventListener('click', () => { activePanel()?.querySelectorAll('details[data-compact="true"][open]').forEach(item => item.open = false); const target = document.getElementById(decodeURIComponent(href.slice(1))); if (target) { target.setAttribute('tabindex', '-1'); target.focus({ preventScroll: true }); } }); } else { node.type = 'button'; node.addEventListener('click', () => invoke(source, node)); } const key = iconKey(source); node.dataset.ribbonIcon = key; decorate(node, caption(source), key); if (source.matches('.text-danger, .btn-outline-danger') || source.closest('form[data-confirm-message]')) node.classList.add('pd-context-destructive'); group.element.append(node); bindState(source, node); } function renderForm(form, group) { const fields = [...form.querySelectorAll('select, input:not([type="hidden"]), textarea')]; if (fields.length === 0) return false; // Explicitly fail open for complex editors/multiple/file/range fields: the workspace owns them. if (fields.some(field => field.matches('textarea, select[multiple], input[type="file"], input[type="range"]'))) throw new Error('Unsupported contextual form'); const proxy = make('form', 'pd-context-form'); const stacked = form.dataset.pwaFields === 'stacked'; if (stacked) proxy.dataset.pwaFields = 'stacked'; const submit = form.querySelector('button[type="submit"], button:not([type]), input[type="submit"]'); const isSearch = fields.length === 1 && fields[0].matches('input') && (fields[0].type === 'search' || /^(q|query|search|searchTerm)$/i.test(fields[0].name) || form.hasAttribute('data-pwa-search')); if (isSearch) proxy.classList.add('pd-context-search'); for (const source of fields) { const label = source.dataset.pwaLabel || source.getAttribute('aria-label') || source.labels?.[0]?.textContent.trim() || source.placeholder || source.name; const wrapper = make(isSearch ? 'div' : 'label', 'pd-context-field'); if (isSearch || stacked) wrapper.append(make('span', '', label)); else decorate(wrapper, label, source.dataset.ribbonIcon || (source.matches('select') ? /project/i.test(source.name) ? 'projects' : /book/i.test(source.name) ? 'bible' : 'point' : 'search')); const target = make(source.tagName.toLowerCase(), source.matches('select') ? 'pd-context-select' : 'pd-context-input'); if (stacked) target.setAttribute('aria-label', label); if (source.matches('select')) [...source.options].forEach(option => { const copy = new Option(option.text, option.value, false, option.selected); copy.disabled = option.disabled; target.add(copy); }); else { target.type = source.type === 'checkbox' ? 'checkbox' : source.type === 'search' ? 'search' : 'text'; target.placeholder = source.placeholder; } target.dataset.pwaBinding = bindingKey(source); const sync = () => { target.value = source.value; target.disabled = source.matches(':disabled'); if ('readOnly' in target) target.readOnly = source.readOnly; if (source.type === 'checkbox') target.checked = source.checked; }; sync(); bindings.push(sync); for (const name of ['input', 'change']) target.addEventListener(name, () => { const original = liveSource(source); original.value = target.value; if (original.type === 'checkbox') original.checked = target.checked; original.dispatchEvent(new Event(name, { bubbles: true })); }); if (source.matches('select') && source.options.length > 12 && !stacked) { const picker = make('details', 'pd-context-menu pd-context-selector'); picker.dataset.compact = 'true'; wireMenu(picker); const summary = make('summary'); summary.dataset.pwaBinding = `picker-${bindingKey(source)}`; summary.setAttribute('aria-expanded', 'false'); const panel = make('div', 'pd-context-menu-content'); const search = make('input', 'form-control form-control-sm'); search.type = 'search'; search.placeholder = `Find ${label.toLowerCase()}`; search.setAttribute('aria-label', search.placeholder); search.dataset.pwaBinding = `find-${bindingKey(source)}`; search.addEventListener('input', () => { [...target.options].forEach(option => { option.hidden = !option.text.toLowerCase().includes(search.value.toLowerCase()); }); }); const update = () => { summary.textContent = target.selectedOptions[0]?.text || label; summary.setAttribute('aria-disabled', String(source.matches(':disabled'))); }; update(); bindings.push(update); target.addEventListener('change', update); target.size = 6; target.setAttribute('aria-label', label); summary.addEventListener('click', event => { if (source.matches(':disabled')) event.preventDefault(); }); picker.addEventListener('toggle', () => summary.setAttribute('aria-expanded', String(picker.open))); panel.append(search, target); picker.append(summary, panel); wrapper.append(picker); } else wrapper.append(target); if (isSearch) { target.type = 'search'; target.setAttribute('aria-label', label); const field = make('span', 'pd-context-search-field'); target.replaceWith(field); field.append(target); const button = make('button', 'pd-context-search-submit'); button.type = 'submit'; button.setAttribute('aria-label', label); button.title = label; const icon = icons.querySelector('[data-icon-key="search"]').cloneNode(true); icon.removeAttribute('data-icon-key'); button.append(icon); field.append(button); const syncButton = () => button.disabled = target.disabled || !!submit?.matches(':disabled'); bindings.push(syncButton); syncButton(); } proxy.append(wrapper); } if (submit && !isSearch) { const button = make('button', 'pd-ribbon-command pd-context-submit'); decorate(button, caption(submit), submit.dataset.ribbonIcon || (fields.some(field => field.matches('select')) ? 'timeline' : 'search')); button.type = 'submit'; proxy.append(button); button.disabled = submit.matches(':disabled'); } proxy.addEventListener('submit', event => { event.preventDefault(); lastInvoker = proxy.querySelector('button') || proxy.querySelector('input, select'); if (submit) liveSource(submit).click(); else liveSource(form).requestSubmit(); }); group.append(proxy); return true; } function refresh() { queued = false; bindings = []; restoreRibbonCommands(); const focused = controls.contains(document.activeElement) ? document.activeElement.dataset.pwaBinding : null; const openMenus = [...controls.querySelectorAll('details[data-compact="true"][open] summary')].map(node => node.dataset.pwaBinding); controls.replaceChildren(); querySources('[data-pwa-accounted]').forEach(node => node.removeAttribute('data-pwa-accounted')); const contributions = [...querySources(sourceSelector)].sort((a, b) => Number(a.dataset.pwaPriority || 50) - Number(b.dataset.pwaPriority || 50)); host.hidden = !window.PlotDirectorPwa?.standalone || contributions.length === 0; if (host.hidden) { shell.querySelectorAll('.pd-base-overflow').forEach(details => { const row = details.querySelector('.pd-ribbon-commands'); row.classList.remove('pd-context-menu-content'); details.replaceWith(row); }); return; } const panel = activePanel(); if (panel && host.parentElement !== panel) panel.append(host); const baseCommands = [...shell.querySelectorAll('.pd-ribbon-command[href]:not(.pd-context-command):not([aria-disabled="true"])')]; const equivalents = new Map(); // The active category always wins over an equivalent in an inactive category. for (const command of [...baseCommands.filter(node => !panel.contains(node)), ...baseCommands.filter(node => panel.contains(node))]) { command.dataset.commandIdentity = commandIdentity(command); equivalents.set(command.dataset.commandIdentity, command); equivalents.set(routeKey(command.href), command); } const composed = new Set(baseCommands.filter(node => panel.contains(node)).map(commandIdentity)); const groups = new Map(); const group = (label, priority = 50, alwaysCompact = false) => { if (!groups.has(label)) groups.set(label, { element: menu(label, priority, alwaysCompact) }); const entry = groups.get(label); if (alwaysCompact) entry.element.parentElement.dataset.alwaysCompact = 'true'; return entry; }; let helpSource; for (const region of contributions) { if (region.parentElement?.closest('[data-pwa-header], [data-pwa-context]')) continue; const label = region.dataset.pwaContext || region.dataset.pwaTools || 'Page tools'; if (region.dataset.pwaEssential === 'true') group(label).element.parentElement.dataset.essential = 'true'; if (region.dataset.pwaMenuIcon) group(label, 50, region.dataset.pwaCompact === 'true').icon = region.dataset.pwaMenuIcon; if (region.matches('[data-pwa-help]')) { helpSource ||= region.querySelector(region.matches('h1') ? '[data-help-icon]' : 'h1 [data-help-icon]'); continue; } const commands = region.matches('a, button') ? [region] : region.matches('[data-pwa-context]') ? [...region.querySelectorAll('a, button')] : [...region.querySelectorAll('a.btn, a.dropdown-item, button.btn, button.dropdown-item')]; const supported = commands.filter(node => !node.matches('[data-bs-toggle="dropdown"]')); const forms = region.matches('form') ? [region] : [...region.querySelectorAll('form')]; // Validate before hiding anything; unsupported editors remain fully usable in the page. if (forms.some(form => form.querySelector('textarea, select[multiple], input[type="file"], input[type="range"]'))) continue; helpSource ||= region.querySelector(region.matches('h1') ? '[data-help-icon]' : 'h1 [data-help-icon]'); const formFields = new Set(forms.filter(form => { if (!form.querySelector('select, input:not([type="hidden"]), textarea')) return false; const scopeLabel = region.dataset.pwaScope || (form.querySelector('select') ? 'Scope' : 'Find'); const target = group(scopeLabel, 10, region.dataset.pwaCompact === 'true').element; target.parentElement.dataset.essential = 'true'; return renderForm(form, target); })); region.querySelectorAll('[data-pwa-context-status]').forEach(source => { const status = make('span', 'pd-context-status', source.textContent.trim()); status.setAttribute('role', 'status'); group('Status', 0).element.append(status); bindings.push(() => { status.textContent = source.textContent.trim(); }); }); for (const command of supported) { if (command.closest('[data-help-icon]') || formFields.has(command.closest('form'))) continue; const destructive = command.matches('.text-danger, .btn-outline-danger') || /\/(Archive|Delete)(?:[/?]|$)/i.test(command.closest('form')?.action || ''); const commandGroup = destructive ? 'Manage' : command.dataset.pwaGroup || label; renderCommand(command, group(commandGroup, Number(region.dataset.pwaPriority ?? (commandGroup === 'Jump to' ? 90 : commandGroup === 'Export' || /management/i.test(commandGroup) ? 80 : 50)), destructive || region.dataset.pwaCompact === 'true'), equivalents, composed); } region.querySelectorAll('[data-pwa-ribbon-content]').forEach(source => { // Explicitly declared, passive content (for example a category legend). // Interactive fields must use renderForm / renderCommand and their live bindings. if (source.matches('a,button,input,select,textarea') || source.querySelector('a,button,input,select,textarea')) return; const copy = source.cloneNode(true); copy.removeAttribute('id'); copy.querySelectorAll('[id]').forEach(node => node.removeAttribute('id')); group(label, Number(region.dataset.pwaPriority || 50), region.dataset.pwaCompact === 'true').element.append(copy); }); if (region.hasAttribute('data-pwa-task')) { supported.forEach(command => command.dataset.pwaAccounted = 'true'); region.querySelectorAll('.dropdown, .button-row, h1 [data-help-icon], .eyebrow').forEach(node => node.dataset.pwaAccounted = 'true'); } else region.dataset.pwaAccounted = 'true'; } for (const [label, entry] of groups) { if (label !== 'Jump to' && label !== 'Export') { const icon = entry.icon ? icons?.querySelector(`[data-icon-key="${entry.icon}"]`) : entry.element.querySelector('.pd-icon'); if (icon) { const copy = icon.cloneNode(true); copy.removeAttribute('data-icon-key'); entry.element.parentElement.querySelector(':scope > summary .pd-icon')?.replaceWith(copy); } } if (!entry.element.childElementCount) { entry.element.closest('.pd-context-group').remove(); groups.delete(label); } } if (helpSource?.dataset.helpUrl) { const help = make('a', 'pd-ribbon-command pd-context-help pd-context-command'); help.dataset.pwaBinding = 'page-help'; help.href = helpSource.dataset.helpUrl; help.dataset.helpOpen = helpSource.dataset.helpKey; help.setAttribute('aria-label', `Page help: ${helpSource.dataset.helpTitle}`); decorate(help, 'Help', 'help'); group('Help', 0).element.append(help); // Page help is accounted independently on headers deliberately retained as meaningful content. querySources('[data-pwa-help] h1 [data-help-icon]').forEach(node => node.dataset.pwaAccounted = 'true'); } querySources('[data-pwa-identity]').forEach(node => node.dataset.pwaAccounted = 'true'); controls.querySelectorAll('details summary').forEach(summary => { if (openMenus.includes(summary.dataset.pwaBinding)) summary.parentElement.open = true; }); if (focused) [...controls.querySelectorAll('[data-pwa-binding]')].find(node => node.dataset.pwaBinding === focused)?.focus({ preventScroll: true }); queueFit(); } function queueRefresh() { if (!queued) { queued = true; requestAnimationFrame(refresh); } } const observer = new MutationObserver(records => { const structural = records.some(record => { if (record.type !== 'childList') return false; const command = record.target.closest?.('button'); const nodes = [...record.addedNodes, ...record.removedNodes]; const declarations = `${sourceSelector},a,button,form,input,select,textarea`; // A bound button's caption is live state, not a new contribution. // Keep its ribbon node, accounted markers and fitted groups intact. if (command && boundCommands.has(command) && nodes.every(node => node.nodeType === 3 || (node.nodeType === 1 && !node.matches(declarations) && !node.querySelector(declarations)))) return false; return record.target.closest?.(sourceSelector) || nodes.some(node => node.nodeType === 1 && (node.matches(sourceSelector) || node.querySelector(sourceSelector))); }); if (structural) { sourceRoots = [main]; queueRefresh(); } else bindings.forEach(update => update()); }); function observe() { observer.observe(main, { childList: true, subtree: true, attributes: true, attributeFilter: ['disabled', 'hidden', 'aria-disabled', 'aria-pressed', 'aria-current', 'aria-selected', 'aria-expanded', 'class'] }); } window.addEventListener('plotdirector:pwa-mode-changed', () => { refresh(); prepareInitialPresentation(); }); window.addEventListener('plotdirector:context-changed', refresh); document.addEventListener('click', event => { activePanel()?.querySelectorAll('details[data-compact="true"][open]').forEach(item => { if (!item.contains(event.target)) item.open = false; }); }); shell.addEventListener('keydown', event => { if (event.key !== 'Escape') return; const details = event.target.closest('details'); if (details?.open && details.dataset.compact === 'true') { details.open = false; details.querySelector('summary').focus(); event.preventDefault(); event.stopPropagation(); } }); document.addEventListener('hidden.bs.modal', () => { if (lastInvoker?.isConnected) lastInvoker.focus(); lastInvoker = null; }); window.addEventListener('resize', queueFit); window.addEventListener('plotdirector:ribbon-layout-changed', () => { if (host.parentElement !== activePanel()) refresh(); else queueFit(); }); let measuredWidth = 0; new ResizeObserver(() => { const width = shell.clientWidth; if (width !== measuredWidth) { measuredWidth = width; queueFit(); } }).observe(shell); document.fonts?.ready.then(queueFit); // The small server-declared snapshot is composed before workspace parsing. Derive // exact suppression selectors from validated/accounted contributions, not a blanket // rule that could hide an unsupported editor or its commands. const initialStyle = document.createElement('style'); initialStyle.dataset.pwaInitialPresentation = ''; function prepareInitialPresentation() { if (!initial || main !== initial.content) return; const selectors = [...main.querySelectorAll('[data-pwa-accounted="true"]')].map(node => { const region = node.closest('[data-pwa-source]'); if (!region) return null; const path = []; for (let current = node; current !== region; current = current.parentElement) path.unshift(`> :nth-child(${[...current.parentElement.children].indexOf(current) + 1})`); return `html[data-standalone="true"] [data-pwa-page-content] [data-pwa-source="${region.dataset.pwaSource}"] ${path.join(' ')}`; }).filter(Boolean); initialStyle.textContent = selectors.length ? `${selectors.join(',')} { display: none !important; }` : ''; } window.PlotDirectorPageContext = Object.freeze({ register(region) { if (region) liveSources.push(region); }, activate() { const content = document.querySelector('[data-pwa-page-content]'); if (!content || main === content) return; performance.mark('pd-ribbon-activate-start'); observer.disconnect(); main = content; sourceRoots = liveSources.length ? liveSources : [main]; refresh(); fitRibbon(); initialStyle.remove(); initial?.remove(); observe(); performance.measure('pd-ribbon-activate', 'pd-ribbon-activate-start'); } }); refresh(); prepareInitialPresentation(); document.head.append(initialStyle); fitRibbon(); if (main !== initial?.content) observe(); performance.measure('pd-ribbon-initial-compose', 'pd-ribbon-initial-start'); })();