/** * Interactive hotspots (Pro): clickable areas on PDF pages. * * buildHotspotOverlay() returns the Flipper page-overlay callback; it is * painted on reader/slider pages, in the zoom view and on the flipbook. */ import type { PageOverlay } from '../flipper/reader/pageOverlay'; export interface Hotspot { id: string; page: number; x: number; y: number; w: number; h: number; action: 'link' | 'page' | 'note' | 'video' | 'product'; label?: string; url?: string; newTab?: boolean; target?: number; text?: string; productId?: number; product?: { name: string; price: string; url: string; image: string; canAdd: boolean }; } export interface HotspotConfig { items: Hotspot[]; clickUrl?: string; cart?: { addUrl: string; cartUrl: string } | null; } interface Host { container: HTMLElement; pdfId: number; goToPage: (page: number) => void; } const ICONS: Record = { link: '', page: '', note: '', video: '', product: '', }; const icon = (name: Hotspot['action'], size = 14) => ``; const CLOSE = ''; const DEFAULT_LABEL: Record = { link: 'Open link', page: 'Go to page', note: 'More information', video: 'Play video', product: 'View product', }; const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] as string)); /** YouTube / Vimeo page URL → embeddable player URL; null for a plain video file. */ export function embedUrl(url: string): string | null { try { const u = new URL(url); const host = u.hostname.replace(/^www\.|^m\./, ''); let id = ''; if (host === 'youtu.be') id = u.pathname.slice(1); else if (host.endsWith('youtube.com') || host.endsWith('youtube-nocookie.com')) { id = u.searchParams.get('v') || (u.pathname.match(/\/(?:embed|shorts|live)\/([^/?]+)/)?.[1] ?? ''); } if (id) return `https://www.youtube-nocookie.com/embed/${encodeURIComponent(id)}?autoplay=1&rel=0`; if (host.endsWith('vimeo.com')) { const vid = u.pathname.match(/(\d{6,})/)?.[1]; if (vid) return `https://player.vimeo.com/video/${vid}?autoplay=1`; } } catch { /* not a URL */ } return null; } function track(cfg: HotspotConfig, pdfId: number, id: string): void { if (!cfg.clickUrl || !pdfId) return; const body = JSON.stringify({ pdfId, id }); try { if (navigator.sendBeacon) navigator.sendBeacon(cfg.clickUrl, new Blob([body], { type: 'application/json' })); else void fetch(cfg.clickUrl, { method: 'POST', body, headers: { 'Content-Type': 'application/json' }, keepalive: true }); } catch { /* never break the viewer */ } } /** Remove any open hotspot popover or video. */ function closePopups(container: HTMLElement): void { container.querySelectorAll('.pdfrack-hs-popover, .pdfrack-hs-modal').forEach((el) => el.remove()); } function onEscape(container: HTMLElement, el: HTMLElement): void { const handler = (e: KeyboardEvent) => { if (e.key !== 'Escape' || !el.isConnected) { if (!el.isConnected) document.removeEventListener('keydown', handler, true); return; } e.stopPropagation(); el.remove(); document.removeEventListener('keydown', handler, true); }; document.addEventListener('keydown', handler, true); void container; } /** A small card next to the hotspot (notes and products). */ function popover(host: Host, anchor: HTMLElement, html: string): HTMLElement { const { container } = host; closePopups(container); const pop = document.createElement('div'); pop.className = 'pdfrack-hs-popover'; pop.setAttribute('role', 'dialog'); pop.innerHTML = `${html}`; ['pointerdown', 'mousedown', 'touchstart', 'wheel'].forEach((t) => pop.addEventListener(t, (e) => e.stopPropagation())); pop.addEventListener('keydown', (e) => e.stopPropagation()); pop.querySelector('.pdfrack-hs-close')?.addEventListener('click', () => pop.remove()); container.appendChild(pop); // Below the hotspot when there is room, else above; kept inside the viewer. const c = container.getBoundingClientRect(); const a = anchor.getBoundingClientRect(); const p = pop.getBoundingClientRect(); let left = a.left - c.left + a.width / 2 - p.width / 2; left = Math.max(10, Math.min(c.width - p.width - 10, left)); let top = a.bottom - c.top + 10; if (top + p.height > c.height - 10) top = Math.max(10, a.top - c.top - p.height - 10); pop.style.left = `${left}px`; pop.style.top = `${top}px`; onEscape(container, pop); (pop.querySelector('a, button:not(.pdfrack-hs-close)') as HTMLElement | null)?.focus({ preventScroll: true }); return pop; } function openVideo(host: Host, url: string, title: string): void { const { container } = host; closePopups(container); const modal = document.createElement('div'); modal.className = 'pdfrack-hs-modal'; modal.setAttribute('role', 'dialog'); modal.setAttribute('aria-label', title); const embed = embedUrl(url); modal.innerHTML = `
${embed ? `` : ``}
`; ['pointerdown', 'mousedown', 'touchstart', 'wheel'].forEach((t) => modal.addEventListener(t, (e) => e.stopPropagation())); modal.addEventListener('keydown', (e) => e.stopPropagation()); modal.addEventListener('click', (e) => { if (e.target === modal) modal.remove(); }); modal.querySelector('.pdfrack-hs-close')?.addEventListener('click', () => modal.remove()); container.appendChild(modal); onEscape(container, modal); (modal.querySelector('.pdfrack-hs-close') as HTMLElement).focus({ preventScroll: true }); } async function addToCart(cfg: HotspotConfig, h: Hotspot, button: HTMLButtonElement): Promise { if (!cfg.cart || !h.productId) return; button.disabled = true; const label = button.textContent; button.textContent = 'Adding…'; try { const body = new URLSearchParams({ product_id: String(h.productId), quantity: '1' }); const res = await fetch(cfg.cart.addUrl, { method: 'POST', body, credentials: 'same-origin' }); const json = await res.json().catch(() => null); if (!res.ok || !json || json.error) throw new Error('add failed'); // Let the theme refresh its mini-cart. const jq = (window as unknown as { jQuery?: (el: unknown) => { trigger: (e: string, a: unknown[]) => void } }).jQuery; jq?.(document.body).trigger('added_to_cart', [json.fragments, json.cart_hash, null]); button.replaceWith(Object.assign(document.createElement('a'), { className: 'pdfrack-hs-btn is-done', href: cfg.cart.cartUrl, textContent: 'Added · View cart', })); } catch { button.disabled = false; button.textContent = label; if (h.product?.url) window.location.href = h.product.url; } } function activate(cfg: HotspotConfig, host: Host, h: Hotspot, el: HTMLElement): void { track(cfg, host.pdfId, h.id); const title = h.label || DEFAULT_LABEL[h.action]; if (h.action === 'page' && h.target) { closePopups(host.container); host.goToPage(h.target); } else if (h.action === 'note') { popover(host, el, `${h.label ? `

${escapeHtml(h.label)}

` : ''}

${escapeHtml(h.text || '')}

`); } else if (h.action === 'video' && h.url) { openVideo(host, h.url, title); } else if (h.action === 'product' && h.product) { const p = h.product; const pop = popover(host, el, `
${p.image ? `` : ''}

${escapeHtml(p.name)}

${escapeHtml(p.price)}

${p.canAdd && cfg.cart ? '' : ''} View product
`); const add = pop.querySelector('[data-add]') as HTMLButtonElement | null; add?.addEventListener('click', () => void addToCart(cfg, h, add)); } } export function buildHotspotOverlay(cfg: HotspotConfig, host: Host): PageOverlay | undefined { const byPage = new Map(); cfg.items.forEach((h) => byPage.set(h.page, [...(byPage.get(h.page) ?? []), h])); if (!byPage.size) return undefined; return (layer, pageNumber) => { for (const h of byPage.get(pageNumber) ?? []) { const label = h.label || (h.action === 'product' && h.product ? h.product.name : DEFAULT_LABEL[h.action]); const isLink = h.action === 'link' && h.url; const el = document.createElement(isLink ? 'a' : 'button') as HTMLAnchorElement & HTMLButtonElement; el.className = `pdfrack-hotspot pdfrack-hotspot--${h.action}`; if (isLink) { el.href = h.url as string; if (h.newTab) { el.target = '_blank'; el.rel = 'noopener noreferrer'; } // Keep the lightbox link interceptor away from PDF links. el.setAttribute('data-pdfrack-lightbox-ignore', ''); } else { el.type = 'button'; } el.setAttribute('aria-label', label); el.dataset.label = label; Object.assign(el.style, { left: `${h.x * 100}%`, top: `${h.y * 100}%`, width: `${h.w * 100}%`, height: `${h.h * 100}%`, }); el.innerHTML = `${icon(h.action, 12)}`; el.addEventListener('click', (e) => { e.stopPropagation(); if (isLink) { track(cfg, host.pdfId, h.id); return; // let the browser follow it } e.preventDefault(); activate(cfg, host, h, el); }); layer.appendChild(el); } }; }