import '../flipper/style.css'; import './frontend.css'; import { Viewer, settingEnabled, type PDFRackViewerConfig } from './viewer'; import { initShelves } from './shelf'; import { parseDeepLink, type DeepLink } from './share'; type ViewerRegistry = Record; declare global { interface Window { PDFViewer: typeof Viewer; PDFViewerInstances: ViewerRegistry; PDFRackLightbox: typeof PDFRackLightbox; pdfrackAttachmentHooked?: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any wp?: any; } } window.PDFViewer = Viewer; window.PDFViewerInstances = window.PDFViewerInstances || {}; const destroyInstance = (id: string | null): void => { if (!id) return; const instance = window.PDFViewerInstances[id]; if (instance) { try { instance.destroy(); } catch { /* ignore */ } delete window.PDFViewerInstances[id]; } }; const parseConfig = (raw?: string | null): Partial => { if (!raw) return {}; try { return JSON.parse(raw); } catch { return {}; } }; /** * PDF Rack Lightbox Controller */ const PDFRackLightbox = { activeInstanceId: null as string | null, backdropEl: null as HTMLDivElement | null, escHandler: null as ((e: KeyboardEvent) => void) | null, open({ pdfUrl, config = {} }: { pdfUrl: string; title?: string; config?: Partial }): void { if (!pdfUrl) return; this.closeImmediate(); document.body.classList.add('pdfrack-lightbox-open'); const backdrop = document.createElement('div'); backdrop.className = 'pdfrack-lightbox-backdrop'; this.backdropEl = backdrop; const modal = document.createElement('div'); modal.className = 'pdfrack-lightbox-modal'; const closeBtn = document.createElement('button'); closeBtn.className = 'pdfrack-lightbox-close'; closeBtn.type = 'button'; closeBtn.title = 'Close (Esc)'; closeBtn.innerHTML = ` `; closeBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); this.close(); }); const body = document.createElement('div'); body.className = 'pdfrack-lightbox-body'; const viewerId = `pdfrack-lightbox-viewer-${Date.now()}`; const container = document.createElement('div'); container.id = viewerId; container.className = 'pdfrack-viewer-container'; container.dataset.initialized = 'true'; body.appendChild(container); modal.append(closeBtn, body); backdrop.appendChild(modal); document.body.appendChild(backdrop); requestAnimationFrame(() => backdrop.classList.add('pdfrack-lightbox-active')); try { this.activeInstanceId = viewerId; window.PDFViewerInstances[viewerId] = new Viewer({ ...config, // Protected PDFs are unlocked inside the viewer; the trigger only // carries a placeholder instead of the file URL. pdfUrl: config.protected || config.lead?.gated ? '' : pdfUrl, containerId: viewerId, }); } catch (err) { console.error('PDF Rack Lightbox: Init error', err); } backdrop.addEventListener('click', (e) => { if (e.target === backdrop) this.close(); }); this.escHandler = (e: KeyboardEvent) => { // The zoom overlay handles Escape itself while open. if (e.key === 'Escape' && !document.querySelector('.pdfrack-zoom-overlay.pdfrack-zoom-open')) { this.close(); } }; document.addEventListener('keydown', this.escHandler); }, close(): void { const backdrop = this.backdropEl; if (!backdrop) return; this.backdropEl = null; backdrop.classList.remove('pdfrack-lightbox-active'); this.removeEscHandler(); const instanceId = this.activeInstanceId; this.activeInstanceId = null; window.setTimeout(() => { destroyInstance(instanceId); backdrop.remove(); if (!this.backdropEl) { document.body.classList.remove('pdfrack-lightbox-open'); } }, 250); }, closeImmediate(): void { if (!this.backdropEl) return; this.removeEscHandler(); destroyInstance(this.activeInstanceId); this.activeInstanceId = null; this.backdropEl.remove(); this.backdropEl = null; document.body.classList.remove('pdfrack-lightbox-open'); }, removeEscHandler(): void { if (this.escHandler) { document.removeEventListener('keydown', this.escHandler); this.escHandler = null; } }, }; window.PDFRackLightbox = PDFRackLightbox; /** * Intercept clicks on lightbox triggers and (optionally) plain PDF links. */ const initLightboxInterceptors = (): void => { document.addEventListener('click', (e) => { const target = e.target as Element | null; const trigger = target?.closest('[data-pdfrack-lightbox], .pdfrack-lightbox, a[href]'); if (!trigger) return; if (trigger.hasAttribute('data-pdfrack-lightbox-ignore') || trigger.classList.contains('pdfrack-no-lightbox')) { return; } // Links inside a viewer (annotation links, toolbar) are handled by the viewer. if (trigger.closest('.pdfrack-viewer-container')) return; // Explicit downloads (including the viewer's own Download button, // which clicks a temporary ) must not open a popup. if (trigger.tagName === 'A' && trigger.hasAttribute('download')) return; const isExplicitTrigger = trigger.hasAttribute('data-pdfrack-lightbox') || trigger.classList.contains('pdfrack-lightbox'); let pdfUrl = trigger.getAttribute('data-pdfrack-lightbox') || trigger.getAttribute('data-pdf-url'); if (!pdfUrl && trigger.tagName === 'A') { pdfUrl = trigger.getAttribute('href'); } if (!pdfUrl) return; const isPdfLink = /\.pdf(\?.*)?$/i.test(pdfUrl); const autoIntercept = settingEnabled(window.pdfRackSettings?.autoInterceptPdfLinks, true); if (!isExplicitTrigger && !(autoIntercept && isPdfLink)) return; e.preventDefault(); e.stopPropagation(); PDFRackLightbox.open({ pdfUrl, config: parseConfig(trigger.getAttribute('data-config')), }); }, true); // Enclosed-content triggers are spans with role="button": open them with Enter / Space too. document.addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; const trigger = (e.target as Element | null)?.closest?.('span.pdfrack-lightbox[role="button"]'); if (!trigger || e.target !== trigger) return; e.preventDefault(); trigger.click(); }); }; /** * Mount every `.pdfrack-viewer-container[data-config]` that isn't running yet. */ /* ── Deep links: #page=N and #pdf=&page=N ─────────────────────────── */ let pendingLink: DeepLink | null = parseDeepLink(); let linkTarget: HTMLElement | null = null; /** The inline viewer a link points at (popup viewers excluded). */ const findLinkedViewer = (link: DeepLink): HTMLElement | null => { const viewers = Array.from(document.querySelectorAll('.pdfrack-viewer-container[data-config]')) .filter((c) => !c.closest('.pdfrack-lightbox-backdrop')); if (!link.pdfId) return viewers[0] ?? null; return viewers.find((c) => Number(parseConfig(c.dataset.config).pdfId) === link.pdfId) ?? null; }; /** No inline viewer for the linked PDF: open its popup trigger (button, shelf cover) instead. */ const openLinkedPopup = (link: DeepLink): boolean => { if (!link.pdfId) return false; const active = PDFRackLightbox.activeInstanceId ? window.PDFViewerInstances[PDFRackLightbox.activeInstanceId] : null; if (active && Number(active.config.pdfId) === link.pdfId) { if (link.page) active.goToPage(link.page); return true; } const trigger = Array.from(document.querySelectorAll('[data-pdfrack-lightbox][data-config]')) .find((t) => Number(parseConfig(t.dataset.config).pdfId) === link.pdfId); const pdfUrl = trigger?.getAttribute('data-pdfrack-lightbox'); if (!trigger || !pdfUrl) return false; PDFRackLightbox.open({ pdfUrl, config: { ...parseConfig(trigger.dataset.config), ...(link.page ? { page: link.page } : {}) }, }); return true; }; const followLink = (link: DeepLink): void => { const target = findLinkedViewer(link); const instance = target ? window.PDFViewerInstances[target.id] : null; if (target && instance) { if (link.page) instance.goToPage(link.page); target.scrollIntoView({ behavior: 'smooth', block: 'center' }); return; } openLinkedPopup(link); }; const initDeepLinks = (): void => { // A link to a PDF that is only on the page as a popup trigger. if (pendingLink && !linkTarget && openLinkedPopup(pendingLink)) pendingLink = null; window.addEventListener('hashchange', () => { const link = parseDeepLink(); if (link) followLink(link); }); }; const initViewers = (): void => { if (pendingLink) linkTarget = findLinkedViewer(pendingLink); // Page builders (Elementor, block editor) replace embeds while editing: // free viewers whose container left the page. Object.keys(window.PDFViewerInstances).forEach((id) => { if (!document.getElementById(id)) destroyInstance(id); }); document.querySelectorAll('.pdfrack-viewer-container[data-config]').forEach((container) => { if (container.dataset.initialized === 'true') return; try { const config = parseConfig(container.dataset.config); if (!container.id) { container.id = `pdf-rack-${Math.random().toString(36).slice(2, 11)}`; } destroyInstance(container.id); if (pendingLink && container === linkTarget) { if (pendingLink.page) config.page = pendingLink.page; pendingLink = null; window.setTimeout(() => container.scrollIntoView({ behavior: 'smooth', block: 'center' }), 50); } window.PDFViewerInstances[container.id] = new Viewer({ ...config, pdfUrl: config.pdfUrl ?? '', containerId: container.id, }); container.dataset.initialized = 'true'; } catch (e) { console.error('PDF Rack: Error initializing viewer', e); } }); }; /* ── WP Media modal: show PDFs in the attachment details preview ───────── */ let currentMediaId: number | null = null; let isFrameHooked = false; let pollInterval: number | null = null; const hookAttachmentDetails = (): void => { const AttachmentDetails = window.wp?.media?.view?.AttachmentDetails; if (!AttachmentDetails || window.pdfrackAttachmentHooked) return; const oldRender = AttachmentDetails.prototype.render; AttachmentDetails.prototype.render = function (this: { model?: { id?: number } }, ...args: unknown[]) { const result = oldRender.apply(this, args); if (this.model && this.model.id) { window.setTimeout(() => handleMediaModalInjection(this.model), 10); } return result; }; window.pdfrackAttachmentHooked = true; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const handleMediaModalInjection = (providedModel: any = null): void => { const detailsModal = document.querySelector('.attachment-details'); if (!detailsModal) { currentMediaId = null; isFrameHooked = false; if (pollInterval) { clearInterval(pollInterval); pollInterval = null; } return; } hookAttachmentDetails(); if (!pollInterval) { pollInterval = window.setInterval(() => handleMediaModalInjection(), 2000); } const media = window.wp?.media; if (!media) return; try { let model = providedModel; if (!model) { let frame = media.frame; if (!frame && media.frames) { for (const key in media.frames) { const f = media.frames[key]; if (f && f.state && f.state()) { frame = f; break; } } } if (frame) { const state = frame.state(); model = frame.model || (state ? state.get('model') : null); if (!model && state) { const selection = state.get('selection'); model = selection && selection.first ? selection.first() : null; } if (!isFrameHooked) { const events = 'selection:select selection:update selection:single edit:attachment active:attachment ready'; frame.on(events, () => window.setTimeout(() => handleMediaModalInjection(), 50)); isFrameHooked = true; } } } if (!model || !model.id) return; const isPDF = model.get('type') === 'application' && model.get('subtype') === 'pdf'; const previewArea = detailsModal.querySelector('.attachment-media-view'); if (!previewArea) return; const viewerExists = previewArea.querySelector('.pdfrack-viewer-container'); const idMatch = !!viewerExists && viewerExists.id.startsWith(`pdf-rack-media-${model.id}`); if (currentMediaId === model.id && (!isPDF || idMatch)) return; if (viewerExists) destroyInstance(viewerExists.id); currentMediaId = model.id; if (!isPDF) return; const pdfUrl = model.get('pdfrack_pdf_url') || model.get('url'); if (!pdfUrl) return; previewArea.innerHTML = ''; const viewerId = `pdf-rack-media-${model.id}-${Date.now()}`; const container = document.createElement('div'); container.id = viewerId; container.className = 'pdfrack-viewer-container'; container.style.cssText = 'width: 100%; height: 100%; min-height: 500px; background: #f0f0f1; margin: 0;'; container.dataset.initialized = 'true'; previewArea.appendChild(container); window.setTimeout(() => { try { destroyInstance(viewerId); window.PDFViewerInstances[viewerId] = new Viewer({ containerId: viewerId, pdfUrl, assetsUrl: model.get('pdfrack_assets_url') || undefined, mode: 'reader', }); } catch (e) { console.error('PDF Rack: media preview failed', e); } }, 50); } catch { /* ignore */ } }; const boot = (): void => { initViewers(); initShelves(); initLightboxInterceptors(); initDeepLinks(); // Watch for dynamically inserted viewers (media modal, AJAX content, block editor). let scheduled = false; const observer = new MutationObserver((mutations) => { if (!mutations.some((m) => m.addedNodes.length > 0 || m.removedNodes.length > 0)) return; handleMediaModalInjection(); if (scheduled) return; scheduled = true; window.setTimeout(() => { scheduled = false; initViewers(); initShelves(); }, 150); }); observer.observe(document.body, { childList: true, subtree: true }); }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); }