/* OLAERC LAB 2026 — Lector de cartillas V2.1 * Cierre inmediato y seguro, lectura ampliada, modo libro con StPageFlip, * páginas de alta resolución preprocesadas y PDF.js para futuros documentos. */ const modal = document.getElementById('olbook-dialog'); const grid = document.querySelector('.lab26-resource-grid'); const $ = (id) => document.getElementById('olbook-' + id); const state = { books: new Map(), active: null, flip: null, pdf: null, pdfPromise: null, sourceList: [], pagePromises: new Map(), objectUrls: [], current: 0, mode: 'read', zoom: 1, sequence: 0, lastFocused: null }; let pdfJsPromise, flipLibraryPromise; const assetURL = path => new URL(path, document.baseURI).href; const available = () => Boolean(modal && grid && $('reader-image') && $('flip')); function setLoading(message, visible = true) { if (!$('loading')) return; $('loading').hidden = !visible; $('progress').textContent = message || ''; } function updateButtons() { const total = state.sourceList.length; const index = Math.max(0, Math.min(state.current, Math.max(0, total - 1))); $('page').textContent = total ? `${index + 1} / ${total}` : '— / —'; $('prev').disabled = index === 0 || !total; $('next').disabled = index >= total - 1; $('read-mode').setAttribute('aria-pressed', String(state.mode === 'read')); $('book-mode').setAttribute('aria-pressed', String(state.mode === 'book')); $('read-mode').classList.toggle('is-active', state.mode === 'read'); $('book-mode').classList.toggle('is-active', state.mode === 'book'); $('zoom-out').disabled = state.mode !== 'read' || state.zoom <= 1; $('zoom-in').disabled = state.mode !== 'read' || state.zoom >= 2.5; $('zoom-level').textContent = `${Math.round(state.zoom * 100)} %`; $('zoom-tools').hidden = state.mode !== 'read'; } async function loadCatalog() { if (!grid) return; try { const result = await fetch(new URL('../assets/cartillas/catalogo.json', import.meta.url), { cache: 'no-store' }); if (!result.ok) throw new Error(`Catálogo HTTP ${result.status}`); const {cartillas} = await result.json(); if (!Array.isArray(cartillas)) throw new Error('Catálogo inválido'); for (const book of cartillas) { if (!book?.publicada || !book?.id || !book?.pdf) continue; state.books.set(book.id, book); const existing = [...grid.querySelectorAll('[data-olbook-card]')] .find(node => node.dataset.olbookCard === book.id); if (existing) { const image = existing.querySelector('img'); if (image && book.portada) image.src = assetURL(book.portada); const button = existing.querySelector('button'); if (button) button.dataset.olbookId = book.id; const status = existing.querySelector('.olbook-available'); if (status) status.textContent = `PDF disponible${book.paginas ? ` · ${book.paginas} páginas` : ''}`; continue; } const article = document.createElement('article'); article.className = 'lab26-resource-card'; article.dataset.olbookCard = book.id; const image = document.createElement('img'); image.loading = 'lazy'; image.alt = `Portada de ${book.titulo || 'cartilla'}`; image.src = assetURL(book.portada || 'assets/lab2026/cartilla-general.webp'); const info = document.createElement('div'); const heading = document.createElement('h3'); heading.textContent = book.titulo || 'Cartilla'; const desc = document.createElement('p'); desc.textContent = book.descripcion || 'Recurso de OLAERC LAB 2026.'; const button = document.createElement('button'); button.type = 'button'; button.className = 'lab26-resource-button'; button.dataset.olbookId = book.id; button.textContent = 'Leer la cartilla ↗'; const status = document.createElement('span'); status.className = 'olbook-available'; status.textContent = `PDF disponible${book.paginas ? ` · ${book.paginas} páginas` : ''}`; info.append(heading, desc, button, status); article.append(image, info); grid.insertBefore(article, grid.querySelector('.lab26-resource-card:not([data-olbook-card])')); } } catch (error) { console.warn('OLAERC LAB: no se pudo cargar el catálogo.', error); } } function getStaticSources(book) { if (!book.paginas_previsualizacion || !Number.isInteger(book.paginas) || book.paginas < 1) return []; return Array.from({length: book.paginas}, (_, i) => assetURL(book.paginas_previsualizacion.replace('{n}', String(i + 1).padStart(2, '0')))); } async function getPdfJs() { if (!pdfJsPromise) { pdfJsPromise = import('../vendor/pdf.min.mjs').then(lib => { lib.GlobalWorkerOptions.workerSrc = new URL('../vendor/pdf.worker.min.mjs', import.meta.url).href; return lib; }).catch(error => { pdfJsPromise = null; throw error; }); } return pdfJsPromise; } async function getPageFlip() { if (window.St?.PageFlip) return window.St.PageFlip; if (!flipLibraryPromise) { flipLibraryPromise = new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = new URL('../vendor/page-flip.browser.js', import.meta.url).href; script.onload = () => window.St?.PageFlip ? resolve(window.St.PageFlip) : reject(new Error('StPageFlip no disponible')); script.onerror = () => reject(new Error('Falta la biblioteca StPageFlip')); document.head.appendChild(script); }).catch(error => { flipLibraryPromise = null; throw error; }); } return flipLibraryPromise; } function dropFlip() { const flip = state.flip; state.flip = null; if (flip) { try { flip.destroy(); } catch (e) { console.warn('Lector: limpieza del libro',e); } } try { $('flip').replaceChildren(); } catch (_) {} } function cleanupReader() { dropFlip(); const pdf = state.pdf; if (pdf) { try { Promise.resolve(pdf.destroy()).catch(() => {}); } catch (_) {} } state.pdf = null; state.pdfPromise = null; state.active = null; state.sourceList = []; state.pagePromises.clear(); $('reader-image').removeAttribute('src'); for (const url of state.objectUrls) URL.revokeObjectURL(url); state.objectUrls = []; setLoading('', false); } function closeBook() { // CRÍTICO: cerrar ANTES de desmontar el lector; el botón no depende de PDF.js ni PageFlip. ++state.sequence; if (modal?.open) { try { modal.close(); } catch (error) { console.warn('Cierre de diálogo',error); } } const priorFocus = state.lastFocused; state.lastFocused = null; // Limpieza por separado: un error de PageFlip/PDF nunca debe impedir el cierre. try { cleanupReader(); } catch (error) { console.warn('Limpieza del lector',error); } if (priorFocus?.isConnected) { try { priorFocus.focus({preventScroll:true}); } catch (_) {} } } async function loadPdf(book) { if (state.pdf) return state.pdf; if (state.pdfPromise) return state.pdfPromise; const seq = state.sequence; state.pdfPromise = (async () => { const pdfjs = await getPdfJs(); const task = pdfjs.getDocument({url:assetURL(book.pdf)}); const doc = await task.promise; if (seq !== state.sequence) { try { Promise.resolve(doc.destroy()).catch(() => {}); } catch (_) {} throw new Error('La cartilla ya no está abierta'); } state.pdf = doc; return doc; })().catch(err => {state.pdfPromise = null; throw err;}); return state.pdfPromise; } async function renderPage(index, seq) { if (state.sourceList[index]) return state.sourceList[index]; if (state.pagePromises.has(index)) return state.pagePromises.get(index); const book = state.active; const work = (async () => { const doc = await loadPdf(book); if (seq !== state.sequence) return null; const page = await doc.getPage(index + 1); const normal = page.getViewport({scale:1}); const viewport = page.getViewport({scale: Math.min(2.4, 1360 / normal.width)}); const canvas = document.createElement('canvas'); canvas.width = Math.ceil(viewport.width); canvas.height = Math.ceil(viewport.height); const ctx = canvas.getContext('2d', {alpha:false}); await page.render({canvasContext:ctx,canvas,viewport}).promise; if (seq !== state.sequence) {canvas.width=canvas.height=0;return null;} const blob = await new Promise((resolve,reject) => canvas.toBlob( value => value ? resolve(value) : reject(new Error('No se pudo preparar la imagen')), 'image/webp', .90)); canvas.width=canvas.height=0; page.cleanup(); if (seq !== state.sequence) return null; const source = URL.createObjectURL(blob); state.objectUrls.push(source); state.sourceList[index] = source; return source; })(); state.pagePromises.set(index, work); try { return await work; } finally { state.pagePromises.delete(index); } } function applyZoom() { const img = $('reader-image'); img.style.width = state.zoom === 1 ? 'min(100%, 820px)' : `${Math.round(state.zoom * 100)}%`; img.style.maxWidth = state.zoom === 1 ? '820px' : 'none'; updateButtons(); } async function showPage(index, {scroll=true} = {}) { if (!state.active) return; const seq = state.sequence; const count = state.sourceList.length; const next = Math.min(Math.max(index, 0), count - 1); state.current = next; updateButtons(); if (state.mode !== 'read') return; const img = $('reader-image'); const requestId = String(seq) + ':' + next; img.dataset.request = requestId; const source = state.sourceList[next]; if (!source) setLoading(`Cargando página ${next + 1} de ${count}…`); try { const url = source || await renderPage(next, seq); if (seq !== state.sequence || state.mode !== 'read' || img.dataset.request !== requestId || !url) return; img.src = url; await img.decode(); if (seq !== state.sequence || img.dataset.request !== requestId) return; setLoading('', false); if (scroll) $('reader').scrollTo({top:0,left:0,behavior:'instant'}); } catch(error) { if (seq !== state.sequence || img.dataset.request !== requestId) return; console.error('OLAERC LAB: error mostrando página',error); setLoading('No se pudo mostrar esta página. Puedes abrir el PDF original.'); } } function setMode(mode) { if (!state.active || !['read','book'].includes(mode)) return; if (mode === 'read') { dropFlip(); state.mode = 'read'; $('reader').hidden = false; $('flip').hidden = true; updateButtons(); showPage(state.current, {scroll:false}); } else { activateBook(); } } async function activateBook() { if (!state.active || state.mode === 'book') return; const seq = state.sequence; setLoading('Preparando el libro…'); try { const PageFlip = await getPageFlip(); if (seq !== state.sequence) return; // Preparamos primero TODOS los recursos: nunca mostrar una hoja vacía a medio cargar. for (let i = 0; i < state.sourceList.length; i++) { if (seq !== state.sequence) return; if (!state.sourceList[i]) { setLoading(`Preparando página ${i + 1} de ${state.sourceList.length}…`); await renderPage(i, seq); } } await Promise.all(state.sourceList.map(url => new Promise((resolve,reject) => { const img = new Image(); img.onload = resolve; img.onerror = () => reject(new Error('No se pudo cargar una imagen del libro')); img.src = url; if (img.complete && img.naturalWidth) resolve(); }))); if (seq !== state.sequence) return; state.mode = 'book'; $('reader').hidden = true; $('flip').hidden = false; dropFlip(); const flip = new PageFlip($('flip'), { width: 430, height: 608, size:'stretch', minWidth: 200, maxWidth: 468, minHeight: 283, maxHeight: 662, showCover:true, usePortrait:true, mobileScrollSupport:false, drawShadow:true, maxShadowOpacity:.18, flippingTime:600, showPageCorners:true, startPage:state.current }); flip.loadFromImages(state.sourceList); state.flip = flip; flip.on('flip', e => { if (seq !== state.sequence) return; state.current = e.data; updateButtons(); }); flip.on('changeOrientation', () => updateButtons()); setLoading('', false); updateButtons(); } catch(error) { if (seq !== state.sequence) return; console.warn('OLAERC LAB: modo libro no disponible; se mantiene lectura ampliada.', error); state.mode = 'read'; $('reader').hidden = false; $('flip').hidden = true; setLoading('', false); updateButtons(); showPage(state.current); $('reader-hint').textContent = 'Modo lectura disponible. Para el efecto libro, revisa la instalación de StPageFlip.'; } } function turn(direction) { if (!state.active) return; if (state.mode === 'book' && state.flip) { try { direction < 0 ? state.flip.flipPrev() : state.flip.flipNext(); } catch (error) { console.warn('Pasar página',error); setMode('read'); } } else showPage(state.current + direction); } function openBook(book) { if (!available()) return; if (modal.open) closeBook(); ++state.sequence; state.active = book; state.current = 0; state.mode = 'read'; // Legibilidad: primera página amplia, modo libro disponible con un toque. state.zoom = 1; state.lastFocused = document.activeElement; state.sourceList = getStaticSources(book); if (!state.sourceList.length) { state.sourceList = Array.from({length:Math.max(1, Number(book.paginas)||1)}, () => null); } $('title').textContent = book.titulo || 'Cartilla'; $('description').textContent = book.descripcion || 'Lee a tu ritmo o descarga el PDF original.'; $('meta').textContent = (book.categoria || 'CARTILLA DIGITAL').toUpperCase(); $('pdf-view').href = assetURL(book.pdf); $('pdf-download').href = assetURL(book.pdf); $('pdf-download').download = book.pdf.split('/').pop() || 'cartilla.pdf'; $('reader-hint').textContent = 'Desplázate para leer toda la página. También puedes ampliar el contenido.'; $('reader').hidden = false; $('flip').hidden = true; applyZoom(); updateButtons(); setLoading('Abriendo la cartilla…'); try { modal.showModal(); } catch (error) { console.error('No se pudo abrir el lector',error); return; } showPage(0); } // Los eventos del cierre se registran independientemente de la carga de PDF o del catálogo. if (available()) { grid.addEventListener('click', event => { const button = event.target.closest('[data-olbook-id]'); if (!button) return; const book = state.books.get(button.dataset.olbookId); if (book) openBook(book); else console.warn('Cartilla todavía no registrada:',button.dataset.olbookId); }); $('dialog-close').addEventListener('click', event => {event.preventDefault();closeBook();}); modal.addEventListener('cancel', event => {event.preventDefault();closeBook();}); modal.addEventListener('click', event => {if (event.target === modal) closeBook();}); modal.addEventListener('close', () => { if (state.active) {++state.sequence;try{cleanupReader();}catch(error){console.warn(error);} } }); $('prev').addEventListener('click', () => turn(-1)); $('next').addEventListener('click', () => turn(+1)); $('read-mode').addEventListener('click', () => setMode('read')); $('book-mode').addEventListener('click', () => setMode('book')); $('zoom-in').addEventListener('click', () => {state.zoom=Math.min(2.5, +(state.zoom+.25).toFixed(2));applyZoom();}); $('zoom-out').addEventListener('click', () => {state.zoom=Math.max(1,+(state.zoom-.25).toFixed(2));applyZoom();}); modal.addEventListener('keydown', event => { if (event.target?.closest?.('a')) return; if (event.key === 'ArrowLeft') {event.preventDefault();turn(-1);} if (event.key === 'ArrowRight') {event.preventDefault();turn(+1);} }); loadCatalog(); }