import { openSharePanel } from './share'; import { applyBrand, type BrandOptions } from './brand'; import { applyToolbarMode, resolveToolbarMode } from './toolbarMode'; import { buildHotspotOverlay, type HotspotConfig } from './hotspots'; import { mountBackgroundAudio, playPageTurn, type AudioTrack } from './audio'; import { createResumeWriter, resolveResumeMode, resumeKey, savedPage, showResumePrompt } from './resume'; import type { FlipbookAssets, ToolbarOptions, ViewerMode } from '../flipper/config'; import type { WatermarkOptions } from '../flipper/reader/watermark'; import { cachedUnlockUrl, renderLock, type ProtectedInfo } from './lock'; import { ReadingTracker } from './analytics'; import { renderLeadForm, resumeLead, storedLeadToken, type LeadGateConfig } from './leadGate'; /** * Configuration accepted by window.PDFViewer. * * Shape matches what the shortcode / block (includes/Frontend/Shortcode.php) * serialises into `data-config`, so existing embeds keep working. */ export interface PDFRackViewerConfig { containerId?: string; container?: HTMLElement; pdfUrl: string; assetsUrl?: string; mode?: ViewerMode | string; theme?: string; background?: string; isRTL?: boolean; coverflow?: boolean; enableCoverPage?: boolean; coverPaddingPercent?: number; coverInsideColor?: string; pageFlexibility?: number; pageTurnSpeed?: number; download?: boolean; print?: boolean; /** Show the search button (default true) */ search?: boolean; /** Show the Share button (default true) */ share?: boolean; /** 1-based page to open at (shortcode page="N" or a #page=N link) */ page?: number; /** Document title, used when sharing */ title?: string; /** Resume at the last page read: ask (default) | auto | off */ resume?: string; /** Pro: page-turn sound for this embed (default: site setting) */ sound?: boolean; /** Pro: background audio track */ audio?: AudioTrack; /** Pro: interactive hotspots */ hotspots?: HotspotConfig; /** Toolbar visibility: visible (default) | autohide | minimize */ toolbarMode?: string; /** Media Library attachment ID (analytics, password protection). */ pdfId?: number; /** Pro: set when the PDF is password protected (pdfUrl is then empty). */ protected?: ProtectedInfo; /** Pro: watermark for this embed; false disables it, undefined uses the site setting. */ watermark?: WatermarkOptions | false; /** Pro: lead capture gate for this PDF. */ lead?: LeadGateConfig; } interface Disposable { destroy?: () => void; dispose?: () => void; goToPage?: (page: number) => void; } interface PDFRackSettings { assetsUrl?: string; pluginUrl?: string; isPro?: boolean | string; autoInterceptPdfLinks?: boolean | string; /** Site default for "resume where you left off": ask | auto | off */ resume?: string; /** Pro: page-turn sound (site setting) */ sound?: { enabled?: boolean; volume?: number }; /** Pro: brand theme for every viewer */ brand?: BrandOptions; /** Site default toolbar mode: visible | autohide | minimize */ toolbarMode?: string; watermark?: WatermarkOptions | false; analytics?: { endpoint: string }; } declare global { interface Window { pdfRackSettings?: PDFRackSettings; pdfRack?: { assetsUrl?: string; pluginUrl?: string }; } } /** * Read a boolean from pdfRackSettings. Accepts the string forms ("1" / "") * that wp_localize_script() produces, in case a theme or older code * localizes the settings instead of printing them as JSON. */ export const settingEnabled = (value: unknown, fallback = false): boolean => { if (value === undefined || value === null) return fallback; return value === true || value === 1 || value === '1' || value === 'true'; }; const isPro = (): boolean => settingEnabled(window.pdfRackSettings?.isPro); const resolveAssetsUrl = (config: PDFRackViewerConfig): string => { const url = config.assetsUrl || window.pdfRackSettings?.assetsUrl || window.pdfRack?.assetsUrl || (window.pdfRackSettings?.pluginUrl ? `${window.pdfRackSettings.pluginUrl}assets/` : ''); return url.endsWith('/') || url === '' ? url : `${url}/`; }; const parseHexColor = (value?: string): number | undefined => { if (!value) return undefined; const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value.trim()); if (!match) return undefined; let hex = match[1]; if (hex.length === 3) hex = hex.split('').map((c) => c + c).join(''); return parseInt(hex, 16); }; /** Drop undefined keys so they don't override the library defaults when spread. */ const compact = (obj: T): T => { const out = { ...obj }; (Object.keys(out) as (keyof T)[]).forEach((key) => { if (out[key] === undefined) delete out[key]; }); return out; }; /** * Thin wrapper around the Flipper viewers. * * Each mode is loaded on demand so the reader never downloads three.js. * If the flipbook chunk fails to load (e.g. no WebGL bundle) we fall back * to the reader. */ export class Viewer { readonly config: PDFRackViewerConfig; readonly container: HTMLElement; readonly mode: ViewerMode; readonly ready: Promise; private instance: Disposable | null = null; private destroyed = false; private tracker: ReadingTracker | null = null; private removeLock: (() => void) | null = null; /** "after N pages" lead gate still waiting to be shown */ private pendingLeadGate = false; private currentPage = 1; private stopAudio: (() => void) | null = null; private removeBrand: (() => void) | null = null; private removeToolbarMode: (() => void) | null = null; constructor(config: PDFRackViewerConfig) { this.config = config; const container = config.container ?? (config.containerId ? document.getElementById(config.containerId) : null); if (!container) { throw new Error(`PDF Rack: container "${config.containerId ?? ''}" not found`); } this.container = container; this.mode = Viewer.resolveMode(config.mode); this.ready = this.start().catch((error) => { console.error('PDF Rack: viewer failed to load', error); }); } /** Unlock (if protected), start analytics, then mount the viewer. */ private async start(): Promise { const config = this.config; const pdfId = Number(config.pdfId) || 0; // Brand first, so lock and sign-up screens use it too. this.removeBrand = applyBrand(this.container, isPro() ? window.pdfRackSettings?.brand : null); this.removeToolbarMode = applyToolbarMode(this.container, resolveToolbarMode(config.toolbarMode || window.pdfRackSettings?.toolbarMode)); if (config.protected && !config.pdfUrl) { const cached = pdfId ? cachedUnlockUrl(pdfId) : null; if (cached) { config.pdfUrl = cached; } else { await new Promise((resolve) => { this.removeLock = renderLock(this.container, pdfId, config.protected as ProtectedInfo, (url) => { config.pdfUrl = url; this.removeLock = null; resolve(); }); }); } if (this.destroyed) return; } const lead = config.lead; if (lead && isPro()) { if (lead.mode === 'before') { const resumed = await resumeLead(lead, pdfId); if (resumed) { if (resumed.url) config.pdfUrl = resumed.url; } else { await new Promise((resolve) => { this.removeLock = renderLeadForm(this.container, lead, pdfId, (url) => { if (url) config.pdfUrl = url; this.removeLock = null; resolve(); }); }); } if (this.destroyed) return; } else if (lead.mode === 'after' && !storedLeadToken()) { this.pendingLeadGate = true; } } const endpoint = window.pdfRackSettings?.analytics?.endpoint; if (endpoint && isPro() && (pdfId || config.pdfUrl)) { this.tracker = new ReadingTracker(endpoint, pdfId, config.pdfUrl); } await this.mount(this.mode); if (!this.destroyed && isPro() && config.audio?.url) { this.stopAudio = mountBackgroundAudio(this.container, config.audio); } } static resolveMode(mode?: string): ViewerMode { if (mode === 'slider') return 'slider'; if (mode === 'flipbook') return 'flipbook'; return 'reader'; } private async mount(mode: ViewerMode): Promise { const config = this.config; const pro = isPro(); const assetsUrl = resolveAssetsUrl(config); const pdfjsBaseUrl = `${assetsUrl}vendor/pdfjs/`; const assets: FlipbookAssets = { pdfjsUrl: `${pdfjsBaseUrl}build/pdf.min.js`, pdfWorkerUrl: `${pdfjsBaseUrl}build/pdf.worker.min.js`, pdfjsBaseUrl, }; // Hiding download/print is a Pro option; free always shows both. const toolbar: ToolbarOptions = { download: pro ? config.download !== false : true, print: pro ? config.print !== false : true, search: config.search !== false, share: config.share !== false ? () => this.share() : undefined, }; // Start page: an explicit page (shortcode, #page link) wins over the saved one. const explicitPage = Math.floor(Number(config.page) || 0); const resumeMode = resolveResumeMode(config.resume || window.pdfRackSettings?.resume); const key = resumeMode !== 'off' ? resumeKey(Number(config.pdfId) || 0, config.pdfUrl) : null; const lastPage = key && explicitPage < 1 ? savedPage(key) : 0; const initialPage = explicitPage > 0 ? explicitPage : (resumeMode === 'auto' && lastPage) || 1; // Pro: hotspots drawn over every page (reader, slider, flipbook, zoom view). const pageOverlay = pro && config.hotspots?.items?.length ? buildHotspotOverlay(config.hotspots, { container: this.container, pdfId: Number(config.pdfId) || 0, goToPage: (page) => this.goToPage(page), }) : undefined; this.currentPage = initialPage; const remember = key ? createResumeWriter(key) : null; // Nothing is saved until the reader moves, so loading at page 1 doesn't // wipe the saved page before they decide. let moved = false; let prompted = !(resumeMode === 'ask' && lastPage > 1); let closePrompt: (() => void) | null = null; // Pro: page-turn sound for page-by-page modes (not the scrolling reader). const siteSound = window.pdfRackSettings?.sound; const soundOn = pro && mode !== 'reader' && (config.sound ?? !!siteSound?.enabled); const soundVolume = siteSound?.volume ?? 0.6; let lastReported = 0; const readingDirection: 'ltr' | 'rtl' = pro && config.isRTL ? 'rtl' : 'ltr'; const background = pro ? config.background : undefined; if (background && mode !== 'flipbook') { this.container.style.background = background; } // Watermark (Pro): this embed's setting, else the site-wide one. const { setWatermark } = await import('../flipper/reader/watermark'); const watermark = config.watermark !== undefined ? config.watermark : window.pdfRackSettings?.watermark; setWatermark(pro ? watermark : null); // Pro: downloads and prints get the same watermark (unless turned off in Settings). const { setFileTransform } = await import('../flipper/reader/fileActions'); const stampFiles = pro && !!watermark && watermark.files !== false; setFileTransform(stampFiles ? (await import('./watermarkFile')).watermarkTransform(this.container) : null); const callbacks = { onPageChange: (page: number, total: number) => { if (soundOn && lastReported && page !== lastReported) playPageTurn(soundVolume); lastReported = page; this.currentPage = page; if (page !== initialPage) moved = true; if (moved) remember?.(page, total); if (!prompted && total > 0) { prompted = true; closePrompt = showResumePrompt(this.container, Math.min(lastPage, total), () => this.goToPage(lastPage)); } else if (closePrompt && page === lastPage) { closePrompt(); closePrompt = null; } this.tracker?.page(page, total); this.maybeShowLeadGate(page); }, onAction: (action: 'download' | 'print') => this.tracker?.action(action), }; let instance: Disposable; if (mode === 'flipbook') { let FlipperApp; try { ({ default: FlipperApp } = await import('./flipbook')); } catch (error) { console.warn('PDF Rack: flipbook unavailable, using reader', error); return this.mount('reader'); } if (this.destroyed) return; instance = new FlipperApp(compact({ container: this.container, assets, pdfSource: config.pdfUrl, readingDirection, // Hardcover first/last pages are Pro; the basic flipbook uses soft covers. enableCoverPage: pro ? config.enableCoverPage ?? true : false, coverPaddingPercent: config.coverPaddingPercent, coverInsideColor: config.coverInsideColor, pageFlexibility: config.pageFlexibility, pageTurnSpeed: config.pageTurnSpeed, toolbar, initialPage, pageOverlay, scene: { backgroundColor: parseHexColor(background) ?? 0xf5f5f5 }, ...callbacks, })); } else if (mode === 'slider') { const { default: SliderViewer } = await import('../flipper/slider/sliderViewer'); if (this.destroyed) return; instance = new SliderViewer({ container: this.container, pdfSource: config.pdfUrl, assets, reader: { pdfjsBaseUrl, theme: config.theme }, readingDirection, isCoverFlow: pro && !!config.coverflow, toolbar, initialPage, pageOverlay, ...callbacks, }); } else { const { default: ReaderViewer } = await import('../flipper/reader/readerViewer'); if (this.destroyed) return; instance = new ReaderViewer({ container: this.container, pdfSource: config.pdfUrl, assets, reader: { pdfjsBaseUrl, theme: config.theme }, toolbar, initialPage, pageOverlay, ...callbacks, }); } this.instance = instance; } /** Show a page (used by #page links while the viewer is open). */ goToPage(page: number): void { this.instance?.goToPage?.(page); } private share(): void { openSharePanel(this.container, { pdfId: Number(this.config.pdfId) || 0, page: this.currentPage, title: this.config.title || document.title, }); } /** "After N pages" gate: cover the viewer once the reader passes the preview. */ private maybeShowLeadGate(page: number): void { const lead = this.config.lead; if (!this.pendingLeadGate || !lead || page <= lead.pages) return; this.pendingLeadGate = false; this.removeLock = renderLeadForm(this.container, lead, Number(this.config.pdfId) || 0, () => { this.removeLock = null; }, true); } destroy(): void { this.destroyed = true; this.stopAudio?.(); this.stopAudio = null; this.removeBrand?.(); this.removeBrand = null; this.removeToolbarMode?.(); this.removeToolbarMode = null; this.tracker?.stop(); this.tracker = null; this.removeLock?.(); this.removeLock = null; const instance = this.instance; this.instance = null; if (!instance) return; if (typeof instance.destroy === 'function') instance.destroy(); else if (typeof instance.dispose === 'function') instance.dispose(); } }