import * as pdfjs from './vendor/build/pdf.min.mjs'; import { EventBus, PDFViewer, PDFLinkService } from './vendor/web/pdf_viewer.mjs'; import { installBookTurns } from './book-turn.mjs?v=1.2.0'; // Supersample low-density screens; PDFViewer still enforces the per-page canvas budget. Object.defineProperty(pdfjs.OutputScale, 'pixelRatio', { configurable:true, get:()=>Math.max(2, window.devicePixelRatio || 1) }); const $ = id => document.getElementById(id); const params = new URLSearchParams(location.search); const title = params.get('title') || 'The digital edition'; $('editionTitle').textContent = title; document.title = `${title} · Admired Minds`; document.body.classList.add('highlight-links'); const phone = matchMedia('(max-width: 760px)'); let viewChosen=false; let pdf, viewer, links, mode = phone.matches ? 'scroll' : (params.get('mode') === 'scroll' ? 'scroll' : 'book'); const small = matchMedia('(max-width: 900px)'); const fail = message => { $('loading').hidden = true; $('error').hidden = false; $('errorMessage').textContent = message; $('readerStatus').textContent = 'Unable to open PDF'; }; const toast = text => { $('shareStatus').textContent = text; }; let file, shareURL; try { file = new URL(params.get('file')); if(file.origin !== location.origin || !/^https?:$/.test(file.protocol)) throw Error(); } catch { fail('Choose a PDF uploaded to this WordPress website.'); } try { shareURL = new URL(params.get('share')); if(shareURL.origin !== location.origin) throw Error(); } catch { shareURL = new URL(location.href); } $('download').href = file?.href || '#'; $('download').setAttribute('download', ''); const pageLink = () => { const url = new URL(shareURL); url.searchParams.set('amp_page', String(viewer?.currentPageNumber || 1)); url.hash=''; return url.href; }; function sync() { if(!pdf || !viewer) return; const current = viewer.currentPageNumber; $('page').value = current; $('page').max = pdf.numPages; $('pageCount').textContent = `/ ${pdf.numPages}`; $('previous').disabled = current <= 1; $('next').disabled = current >= pdf.numPages; $('readingProgress').style.width = `${current / pdf.numPages * 100}%`; $('readerStatus').textContent = `${mode === 'book' ? 'Book view' : 'Scroll view'} · ${Math.round(current / pdf.numPages * 100)}%`; } function setMode(next, preserve = true) { mode = next; document.body.dataset.mode = next; $('book').setAttribute('aria-pressed', String(next === 'book')); $('scroll').setAttribute('aria-pressed', String(next === 'scroll')); if(!viewer || !pdf) return; const current = viewer.currentPageNumber; viewer.scrollMode = next === 'book' ? 3 : 0; viewer.spreadMode = next === 'book' && !small.matches ? 2 : 0; viewer.currentScaleValue = 'page-width'; if(preserve) viewer.currentPageNumber = current; sync(); } function toggleContents(open) { const zoom = viewer?.currentScaleValue || 'page-width'; $('sidebar').hidden = !open; document.body.classList.toggle('contents-open', open); $('contents').setAttribute('aria-expanded', String(open)); if(viewer && pdf) requestAnimationFrame(() => viewer.currentScaleValue = zoom); } $('contents').onclick = () => toggleContents($('sidebar').hidden); $('closeContents').onclick = () => toggleContents(false); $('book').onclick = () => {viewChosen=true;setMode('book');}; $('scroll').onclick = () => {viewChosen=true;setMode('scroll');}; $('links').onclick = () => { const active = document.body.classList.toggle('highlight-links'); $('links').setAttribute('aria-pressed', String(active)); }; $('previous').onclick = () => viewer?.previousPage(); $('next').onclick = () => viewer?.nextPage(); $('page').onchange = () => { if(!pdf) return; const n=Number($('page').value); if(Number.isInteger(n) && n>=1 && n<=pdf.numPages) links.goToPage(n); else sync(); }; $('zoomIn').onclick = () => { if(viewer && pdf) viewer.currentScale = Math.min(4, viewer.currentScale * 1.2); }; $('zoomOut').onclick = () => { if(viewer && pdf) viewer.currentScale = Math.max(.25, viewer.currentScale / 1.2); }; $('scale').onchange = () => { if(viewer && pdf && $('scale').value !== 'custom') viewer.currentScaleValue=$('scale').value; }; let theaterActive=false; const fullscreenLabel=()=>{const active=!!document.fullscreenElement || theaterActive;$('fullscreen').setAttribute('aria-label',active ? 'Exit fullscreen':'Fullscreen reader');$('fullscreen').title=active ? 'Exit fullscreen':'Fullscreen reader';}; const requestTheater=active=>{if(parent!==window)parent.postMessage({type:'amp-reader-theater',active},location.origin);}; window.addEventListener('message',event=>{if(event.origin===location.origin && event.source===parent && event.data?.type==='amp-reader-theater-state'){theaterActive=event.data.active===true;fullscreenLabel();}}); $('fullscreen').onclick=async()=>{if(document.fullscreenElement){await document.exitFullscreen();return;}if(theaterActive){requestTheater(false);return;}try{await document.documentElement.requestFullscreen();}catch{requestTheater(true);}}; document.addEventListener('fullscreenchange',fullscreenLabel); $('retry').onclick = () => location.reload(); $('share').onclick = () => { $('shareUrl').value=shareURL.href; toast(''); $('shareDialog').showModal(); }; $('closeShare').onclick = () => $('shareDialog').close(); $('shareDialog').addEventListener('click', e => {if(e.target === $('shareDialog')) $('shareDialog').close();}); async function copy(value) { $('shareUrl').value = value; try {await navigator.clipboard.writeText(value);toast('Link copied.');} catch {$('shareUrl').focus();$('shareUrl').select();toast('Select and copy the link above.');} } $('copyEdition').onclick = () => copy(shareURL.href); $('copyPage').onclick = () => copy(pageLink()); $('copyPdf').onclick = () => copy(file.href); $('nativeShare').hidden = !navigator.share; $('nativeShare').onclick = async () => {try {await navigator.share({title,url:shareURL.href});}catch(e){if(e.name!=='AbortError')toast('Use Copy edition link to share this edition.');}}; $('shareLinkedIn').href = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareURL.href)}`; $('shareWhatsApp').href = `https://wa.me/?text=${encodeURIComponent(title+' '+shareURL.href)}`; small.addEventListener('change', () => setMode(mode)); phone.addEventListener('change', () => {if(!viewChosen)setMode(phone.matches ? 'scroll' : (params.get('mode') === 'scroll' ? 'scroll' : 'book'));}); document.addEventListener('keydown', e => { if(e.key==='Escape' && theaterActive){e.preventDefault();requestTheater(false);return;} if(e.target.closest('input,select,button,a,dialog') || !pdf) return; if(e.key === 'ArrowRight' || e.key === 'PageDown') {e.preventDefault();viewer.nextPage();} if(e.key === 'ArrowLeft' || e.key === 'PageUp') {e.preventDefault();viewer.previousPage();} if(e.key === 'Escape' && !$('sidebar').hidden) toggleContents(false); }); function safeExternal(url) {try {const parsed=new URL(url,location.href);return ['https:','http:','mailto:','tel:'].includes(parsed.protocol) ? parsed.href : null;}catch{return null;}} function buildOutline(items) { const list=document.createElement('ul'); for(const item of items) { const li=document.createElement('li'); let control; const external=item.url && safeExternal(item.url); if(external) {control=document.createElement('a');control.href=external;control.target='_blank';control.rel='noopener noreferrer';} else {control=document.createElement('button');control.type='button';control.addEventListener('click',async()=>{try {await links.goToDestination(item.dest);if(small.matches)toggleContents(false);}catch{$('readerStatus').textContent='This PDF bookmark has no valid destination';}});} control.textContent=item.title || 'Untitled section'; li.append(control); if(item.items?.length)li.append(buildOutline(item.items)); list.append(li); } return list; } if(file) { try { pdfjs.GlobalWorkerOptions.workerSrc=new URL('./vendor/build/pdf.worker.min.mjs',import.meta.url).href; const eventBus=new EventBus(); links=new PDFLinkService({eventBus,externalLinkTarget:2,externalLinkRel:'noopener noreferrer',ignoreDestinationZoom:true}); viewer=new PDFViewer({container:$('viewerContainer'),viewer:$('viewer'),eventBus,linkService:links,annotationMode:pdfjs.AnnotationMode.ENABLE,textLayerMode:1,maxCanvasPixels:8388608,enableAutoLinking:false}); links.setViewer(viewer); eventBus.on('pagesinit',()=>{ setMode(mode,false); const initial=Number(params.get('page')); if(Number.isInteger(initial) && initial>0 && initial<=pdf.numPages)links.goToPage(initial); $('loading').hidden=true;sync(); }); eventBus.on('pagechanging',sync); eventBus.on('scalechanging',({scale,presetValue})=>{ const selected=presetValue || String(scale); if([...$('scale').options].some(o=>o.value===selected))$('scale').value=selected; else {$('scale').value='custom';$('scale').querySelector('[value=custom]').textContent=`${Math.round(scale*100)}%`;} }); eventBus.on('annotationlayerrendered',()=>{ document.querySelectorAll('.annotationLayer .linkAnnotation a').forEach(anchor=>{ const external = anchor.getAttribute('href') && !anchor.getAttribute('href').startsWith('#'); anchor.title = external ? `Open link: ${anchor.href}` : 'Go to linked page'; if(!anchor.getAttribute('aria-label'))anchor.setAttribute('aria-label',anchor.title); }); }); const task=pdfjs.getDocument({url:file.href,cMapUrl:new URL('./vendor/cmaps/',import.meta.url).href,cMapPacked:true,standardFontDataUrl:new URL('./vendor/standard_fonts/',import.meta.url).href,wasmUrl:new URL('./vendor/wasm/',import.meta.url).href,isEvalSupported:false,enableXfa:false}); task.onProgress=({loaded,total})=>{if(total)$('loadProgress').value=Math.round(loaded/total*100);}; task.onPassword=(callback,reason)=>{ $('passwordMessage').textContent=reason===pdfjs.PasswordResponses.INCORRECT_PASSWORD ? 'That password was not accepted. Please try again.' : 'Enter this PDF’s password to open it.'; $('pdfPassword').value=''; if(!$('passwordDialog').open)$('passwordDialog').showModal(); $('passwordForm').onsubmit=e=>{e.preventDefault();const value=$('pdfPassword').value;$('passwordDialog').close();callback(value);}; }; pdf=await task.promise; links.setDocument(pdf,null); viewer.setDocument(pdf); installBookTurns({viewer,links,pdf,container:$('viewerContainer')}); const outline=await pdf.getOutline(); if(outline?.length)$('outline').append(buildOutline(outline)); else $('outlineEmpty').hidden=false; } catch(error) {console.error('Admired Minds PDF reader:',error);fail(error.name==='PasswordException' ? 'This PDF needs a valid password.' : 'The PDF is unavailable or could not be read. Try downloading it or choose another PDF in WordPress.');} }