/** * Lead capture gate (Pro). * * "before": the form replaces the viewer until submitted. When the server * withheld the file URL (`gated`), the response carries a signed * stream URL to load. * "after": the viewer loads normally; once the reader passes `pages`, the * form covers the viewer until submitted. * * A signed visitor token is kept in local storage, so one sign-up unlocks * every gated PDF until it expires. */ export interface LeadGateConfig { mode: 'before' | 'after'; pages: number; heading: string; text: string; button: string; requireName: boolean; /** Consent label (may contain links); empty = no checkbox */ consent: string; submitUrl: string; resumeUrl: string; /** true when the file URL was withheld and must come from the server */ gated: boolean; } const TOKEN_KEY = 'pdfrack-lead-token'; interface StoredToken { token: string; expires: number; } export function storedLeadToken(): string | null { try { const raw = window.localStorage.getItem(TOKEN_KEY); if (!raw) return null; const t = JSON.parse(raw) as StoredToken; return t.expires * 1000 > Date.now() ? t.token : null; } catch { return null; } } function storeToken(token: string, expires: number): void { try { window.localStorage.setItem(TOKEN_KEY, JSON.stringify({ token, expires })); } catch { /* storage unavailable: the visitor will be asked again next time */ } } function forgetToken(): void { try { window.localStorage.removeItem(TOKEN_KEY); } catch { /* ignore */ } } async function post(url: string, body: unknown): Promise<{ ok: boolean; data: any; message?: string }> { try { const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), credentials: 'same-origin', }); const json = await res.json().catch(() => ({})); return { ok: res.ok, data: json?.data, message: json?.message }; } catch { return { ok: false, data: null, message: 'Could not reach the server. Please try again.' }; } } /** * Returning visitor with a remembered token: get the stream URL without * showing the form. Resolves null when the visitor must sign up again. */ export async function resumeLead(cfg: LeadGateConfig, pdfId: number): Promise<{ url: string | null } | null> { const token = storedLeadToken(); if (!token) return null; if (!cfg.gated) return { url: null }; // nothing to fetch, the token is enough const res = await post(cfg.resumeUrl, { pdfId, token }); if (!res.ok) { forgetToken(); return null; } return { url: res.data?.url ?? null }; } const MAIL_ICON = ''; const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] as string)); /** * Render the sign-up form. `overlay` covers a running viewer (after N pages); * otherwise it stands in for the viewer (before reading). * Calls onDone(url) after a successful submit (url is null when not gated). */ export function renderLeadForm( container: HTMLElement, cfg: LeadGateConfig, pdfId: number, onDone: (url: string | null) => void, overlay = false, ): () => void { const root = document.createElement('div'); root.className = `pdfrack-lock pdfrack-lead${overlay ? ' pdfrack-lead-overlay' : ''}`; const nameRequired = cfg.requireName; root.innerHTML = `
`; const form = root.querySelector('form') as HTMLFormElement; const name = form.querySelector('input[name="name"]') as HTMLInputElement; const email = form.querySelector('input[name="email"]') as HTMLInputElement; const consent = form.querySelector('input[name="consent"]') as HTMLInputElement | null; const button = form.querySelector('button') as HTMLButtonElement; const error = form.querySelector('.pdfrack-lock-error') as HTMLParagraphElement; const label = button.textContent ?? ''; const showError = (message: string, field?: HTMLInputElement) => { error.textContent = message; error.hidden = false; field?.focus(); root.classList.remove('pdfrack-lock-shake'); void root.offsetWidth; root.classList.add('pdfrack-lock-shake'); }; form.addEventListener('submit', async (e) => { e.preventDefault(); error.hidden = true; if (nameRequired && !name.value.trim()) return showError('Please enter your name.', name); if (!/^\S+@\S+\.\S+$/.test(email.value.trim())) return showError('Please enter a valid email address.', email); if (consent && !consent.checked) return showError('Please accept the terms to continue.'); button.disabled = true; button.textContent = 'Please wait…'; const res = await post(cfg.submitUrl, { pdfId, name: name.value.trim(), email: email.value.trim(), consent: !!consent?.checked, pageUrl: window.location.href.split('#')[0], }); button.disabled = false; button.textContent = label; if (!res.ok || !res.data?.token) { showError(res.message || 'Something went wrong. Please try again.'); return; } storeToken(res.data.token, res.data.expires); root.remove(); onDone(res.data.url ?? null); }); // Keep viewer/page shortcuts away while typing. form.addEventListener('keydown', (e) => e.stopPropagation()); container.appendChild(root); if (!overlay) window.setTimeout(() => (nameRequired ? name : email).focus({ preventScroll: true }), 50); return () => root.remove(); }