/* Canonical context commands for the PWA shell and explicitly opted-in workspaces. Original controls/providers own availability, execution and confirmations. */ (() => { const shell = document.querySelector('[data-ribbon-shell]'); if (!shell) return; const semantic = window.PlotDirectorCommands; const icons = shell.querySelector('[data-pwa-icon-catalog]')?.content; const boundary = '[data-pd-context]'; const providers=window.PlotDirectorContextProviders||[];window.PlotDirectorContextProviders=providers; window.PlotDirectorContextMenus={register(selector,provider){providers.push({selector,provider});},open:(target)=>open(target,0,0,true)}; let popup = null, child = null, owner = null, invoker = null, pointerType = '', sequence = 0; const create = (tag, attributes = {}, text = '') => { const node = document.createElement(tag); for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value); node.textContent = text; return node; }; const unavailable = source => !source.isConnected || source.matches(':disabled, .disabled, [aria-disabled="true"]') || !!source.closest('[inert]'); const label = source => source.dataset.pdContextLabel || source.getAttribute('aria-label') || source.textContent.trim().replace(/\s+/g, ' ').slice(0, 85); const icon = (key = 'writer') => { const original = icons?.querySelector(`[data-icon-key="${CSS.escape(key)}"]`); if (!original) return create('span', { class: 'pd-icon', 'aria-hidden': 'true' }); const copy = original.cloneNode(true); copy.removeAttribute('data-icon-key'); return copy; }; function closeSubmenu() { child?.remove(); child = null; if (owner) owner.setAttribute('aria-expanded', 'false'); owner = null; } function close(restore = false) { sequence++; closeSubmenu(); popup?.remove(); popup = null; if (restore && invoker?.isConnected) invoker.focus({ preventScroll: true }); } const items = menu => [...menu.querySelectorAll(':scope > [role="menuitem"]')]; function position(menu, x, y) { const width = document.documentElement.clientWidth || innerWidth; menu.style.maxWidth = `${Math.min(310, width - 12)}px`; menu.style.minWidth = `${Math.min(205, width - 12)}px`; menu.style.left = '0px'; menu.style.top = '0px'; const rect = menu.getBoundingClientRect(); menu.style.left = `${Math.max(6, Math.min(x, width - rect.width - 6))}px`; menu.style.top = `${Math.max(6, Math.min(y, innerHeight - rect.height - 6))}px`; } function openSubmenu(button, commands, keyboard = false) { if (owner === button && child) { if (keyboard) items(child)[0]?.focus(); return; } closeSubmenu(); owner = button; button.setAttribute('aria-expanded', 'true'); child = render(commands, button.textContent.trim()); child.id = button.getAttribute('aria-controls'); document.body.append(child); const rect = button.getBoundingClientRect(), width = child.getBoundingClientRect().width; position(child, rect.right + width + 6 > (document.documentElement.clientWidth || innerWidth) ? rect.left - width - 3 : rect.right + 3, rect.top); if (keyboard) items(child)[0]?.focus(); } function render(commands, name) { const menu = create('div', { class: 'pd-context-popup', role: 'menu', 'aria-label': name }); for (const command of commands) { if (command.separator) { if (menu.childElementCount) menu.append(create('div', { role: 'separator' })); continue; } const button = create('button', { type: 'button', role: 'menuitem', tabindex: '-1', 'aria-label': command.label, 'aria-disabled': String(!!command.disabled) }); button.append(icon(command.icon), create('span', { class: 'pd-context-item-label' }, command.label)); if (command.destructive) button.dataset.destructive = 'true'; if (command.children) { button.setAttribute('aria-haspopup', 'menu'); button.setAttribute('aria-expanded', 'false'); button.setAttribute('aria-controls', `pd-context-submenu-${++sequence}`); button.addEventListener('pointerenter', () => openSubmenu(button, command.children)); button.addEventListener('click', () => openSubmenu(button, command.children, true)); button.addEventListener('keydown', event => { if (event.key === 'ArrowRight') { event.preventDefault(); openSubmenu(button, command.children, true); } }); } else { button.addEventListener('pointerenter', () => { if (menu === popup) closeSubmenu(); }); button.addEventListener('click', () => { if (command.disabled || (command.source && unavailable(command.source))) return; close(true); command.run(); }); } menu.append(button); } menu.addEventListener('keydown', event => { const rows = items(menu), index = rows.indexOf(document.activeElement); if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { event.preventDefault(); const next = event.key === 'Home' ? 0 : event.key === 'End' ? rows.length - 1 : (index + (event.key === 'ArrowUp' ? -1 : 1) + rows.length) % rows.length; rows[next]?.focus(); } else if (event.key === 'ArrowLeft' && menu === child) { event.preventDefault(); const previous = owner; closeSubmenu(); previous?.focus(); } else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(true); } else if (event.key === 'Tab') close(true); }); return menu; } function commandsFor(sources) { const seen = new Set(), result = []; for (const source of sources) { if (source.matches('[data-bs-toggle="dropdown"], input, select, textarea') || source.closest('[hidden], [data-pd-context-ignore]')) continue; const form = source.closest('form'); // A local field-dependent workflow must be completed in its own UI, not submitted by a shortcut. if (form?.querySelector('input:not([type="hidden"]):not([type="submit"]),select,textarea')) continue; const identity = semantic?.identity(source) || source.href || source; if (seen.has(identity)) continue; seen.add(identity); const caption = label(source); if (!caption) continue; const destructive = source.matches('.btn-outline-danger,.text-danger,.btn-danger') || /\.(archive|delete|remove)/i.test(source.dataset.commandOperation || form?.dataset.commandOperation || ''); result.push({ identity, label: caption, icon: semantic?.iconKey(source), source, disabled: unavailable(source), destructive, run: () => { if (!unavailable(source)) semantic ? semantic.invoke(source, invoker) : source.click(); } }); } return result; } function objectCommands(region) { const scope = region.dataset.pdContextScope ? [...region.children].find(node => node.matches(region.dataset.pdContextScope)) : region; if (!scope) return []; const sources = [...(scope.matches('a,button') ? [scope] : []), ...scope.querySelectorAll('a[data-command-operation],a.btn,a[data-pd-context-command],button.btn,button.dropdown-item,button[data-pd-context-command]')] .filter(source => source.closest(boundary) === region); const commands = commandsFor(sources); for (const command of commands) { if (command.source.matches('a:not(.btn):not(.dropdown-item)') && !command.source.dataset.pdContextLabel) { const action = (command.source.dataset.commandOperation || '').split('.').at(-1); if (action === 'details' || action === 'edit') command.label = `${action === 'edit' ? 'Edit' : 'Open'} ${region.dataset.pdContext}`; } } const primary = [], secondary = [], manage = []; for (const command of commands) { const operation = command.source.dataset.commandOperation || command.source.closest('form')?.dataset.commandOperation || ''; if (command.destructive) manage.push(command); else if (operation.startsWith('exports.')) secondary.push(command); else primary.push(command); } const result = primary.slice(0, 7); if (primary.length > 7) result.push({ label: 'More actions', icon: 'list', children: primary.slice(7, 14) }); if (secondary.length) result.push({ label: 'Export', icon: 'export', children: secondary.slice(0, 8) }); if (manage.length) result.push({ separator: true }, ...manage.slice(0, 3)); return result; } function pageCommands() { const panel = shell.querySelector('.pd-ribbon-panel:not([hidden])'); if (!panel) return []; const sources = [...panel.querySelectorAll('.pd-context-command, .pd-ribbon-command[data-command-operation]')] .filter(source => !source.matches('[data-help-open]') && (source.classList.contains('pd-context-command') || /\.(create|edit|settings)$/.test(source.dataset.commandOperation || ''))); const result = commandsFor(sources); const exports = result.filter(command => command.source.closest('.pd-context-group')?.querySelector(':scope > .pd-ribbon-group-label')?.textContent === 'Export' || command.source.dataset.commandOperation?.startsWith('exports.')); const jumps = result.filter(command => command.source.getAttribute('href')?.startsWith('#')); const other = result.filter(command => !exports.includes(command) && !jumps.includes(command)).slice(0, 6); if (jumps.length) other.push({ label: 'Jump to', icon: 'point', children: jumps.slice(0, 8) }); if (exports.length) other.push({ label: 'Export', icon: 'export', children: exports.slice(0, 8) }); return other; } let feedback; function announce(message) { feedback?.remove(); feedback = create('div', { class: 'pd-context-feedback', role: 'status' }, message); document.body.append(feedback); setTimeout(() => feedback?.remove(), 5000); } function editingCommands(target) { const field = target.closest('input,textarea'); if (field && (field.matches('textarea') || /^(text|search|url|email|tel|password)$/.test(field.type))) { const start = field.selectionStart ?? 0, end = field.selectionEnd ?? 0, original = field.value; const selected = original.slice(start, end), writable = !field.matches(':disabled') && !field.readOnly; const protectedField = field.type === 'password'; function replace(text, inputType) { if (!field.isConnected || field.matches(':disabled') || field.readOnly || field.value !== original || field.selectionStart !== start || field.selectionEnd !== end || document.activeElement !== field) return; if (inputType === 'insertFromPaste' && field.maxLength >= 0) text = text.slice(0, Math.max(0, field.maxLength - original.length + end - start)); const event = new InputEvent('beforeinput', { bubbles: true, cancelable: true, inputType, data: text }); if (!field.dispatchEvent(event)) return; field.setRangeText(text, start, end, 'end'); field.dispatchEvent(new InputEvent('input', { bubbles: true, inputType, data: text })); field.dispatchEvent(new Event('change', { bubbles: true })); } return [ { label: 'Cut', icon: 'cut', disabled: !writable || !selected || protectedField || !navigator.clipboard?.writeText, run: async () => { try { await navigator.clipboard.writeText(selected); replace('', 'deleteByCut'); } catch { announce('Cut unavailable. Use Ctrl+X in the field.'); } } }, { label: 'Copy', icon: 'copy', disabled: !selected || protectedField || !navigator.clipboard?.writeText, run: async () => { try { await navigator.clipboard.writeText(selected); } catch { announce('Copy unavailable. Use Ctrl+C in the field.'); } } }, { label: 'Paste', icon: 'paste', disabled: !writable || field.selectionStart === null || !navigator.clipboard?.readText, run: async () => { try { replace(await navigator.clipboard.readText(), 'insertFromPaste'); } catch { announce('Paste unavailable. Use Ctrl+V in the field.'); } } }, { label: 'Select All', icon: 'select-all', disabled: field.matches(':disabled') || !original, run: () => { field.focus({ preventScroll: true }); field.select(); } } ]; } const selection = window.getSelection(); if (!selection?.isCollapsed && selection?.toString() && selection.containsNode(target, true)) { const text = selection.toString(), scope = target.closest(boundary) || target.closest('p,article,section') || target; return [ { label: 'Copy', icon: 'copy', disabled: !navigator.clipboard?.writeText, run: async () => { try { await navigator.clipboard.writeText(text); } catch { announce('Copy unavailable. Use Ctrl+C.'); } } }, { label: 'Select All', icon: 'select-all', run: () => { const range = document.createRange(); range.selectNodeContents(scope); selection.removeAllRanges(); selection.addRange(range); } } ]; } return []; } function open(target, x, y, keyboard) { const start = performance.now(); close(); const region = target.closest(boundary); let editing = editingCommands(target); invoker = target.closest('input,textarea,select,button,a,[tabindex]') || region?.querySelector('a[href],button:not(:disabled),[tabindex]') || document.activeElement; const provider=providers.find(p=>target.closest(p.selector)); const supplied=provider?.provider(target);if(supplied)editing=[]; if(supplied?.invoker)invoker=supplied.invoker; const commands = supplied?.commands || (region ? objectCommands(region) : []); if (!region && !editing.length) { const control = target.closest('a,button'); if (control) commands.push(...commandsFor([control])); } const objectIdentities = new Set(commands.flatMap(command => command.children || [command]).map(command => command.identity)); const page = (region ? [] : pageCommands()).map(command => command.children ? { ...command, children: command.children.filter(item => !objectIdentities.has(item.identity)) } : command) .filter(command => command.children ? command.children.length : !objectIdentities.has(command.identity)); const all = [...editing]; if (editing.length && commands.length) all.push({ separator: true }); all.push(...commands); if (!all.length) all.push(...page); else if (commands.length && page.length) all.push({ separator: true }, { label: 'Page actions', icon: 'list', children: page.flatMap(command => command.children || [command]).slice(0, 8) }); if (!all.length) return; popup = render(all, region?.dataset.pdContextLabel || region?.dataset.pdContext || 'PlotDirector'); document.body.append(popup); if (keyboard) { const rect = target.getBoundingClientRect(); x = rect.left; y = rect.bottom; } position(popup, x, y); items(popup)[0]?.focus({ preventScroll: true }); performance.measure('pd-context-menu-open', { start, end: performance.now() }); } document.addEventListener('contextmenu', event => { // Absolute escape hatch: do not invoke selection, menu composition or preventDefault. if (event.ctrlKey || (!window.PlotDirectorPwa?.standalone&&!event.target.closest?.('[data-pd-context-web]')) || event.pointerType === 'touch' || pointerType === 'touch') return; const target = event.target instanceof Element ? event.target : event.target.parentElement; if (target.closest('.pd-context-popup')) { event.preventDefault(); return; } event.preventDefault(); open(target, event.clientX, event.clientY, event.clientX === 0 && event.clientY === 0); }); document.addEventListener('keydown', event => { if ((!window.PlotDirectorPwa?.standalone&&!document.activeElement?.closest('[data-pd-context-web]')) || event.ctrlKey) return; if (event.key === 'ContextMenu' || (event.shiftKey && event.key === 'F10')) { event.preventDefault(); const target = document.activeElement; if (target instanceof Element) open(target, 0, 0, true); } }); document.addEventListener('pointerdown', event => { pointerType = event.pointerType; if (!event.target.closest('.pd-context-popup')) close(); }, true); document.addEventListener('scroll', event => { if (!event.target.closest?.('.pd-context-popup')) close(); }, true); document.addEventListener('click', event => { if (popup && !event.target.closest('.pd-context-popup')) close(); }, true); for (const name of ['resize', 'blur', 'pagehide', 'popstate', 'plotdirector:pwa-mode-changed', 'plotdirector:context-changed', 'plotdirector:ribbon-layout-changed']) window.addEventListener(name, () => close()); // The currently targeted component may be replaced by an async partial update. new MutationObserver(() => { if (popup && invoker && !invoker.isConnected) close(); }).observe(document.body, { childList: true, subtree: true }); })();