earshelf / source /src /main.ts
WilburDev's picture
Deploy 2026-11-20T20:26Z
b1876f7 verified
Raw History Blame Contribute Delete
52.3 kB
import './style.css'; import { Engine, NATURAL_VOICES, synth, type Voice, type ModelState } from './engine'; import { parseFile, ParseError } from './parse'; import { deleteBook, getBook, kvGet, kvSet, listBooks, saveBook, updateProgress, type Book } from './db'; import { formatDuration, guessLanguage } from './text'; import SAMPLE_AUDIO from './sample-audio.json'; import { SAMPLE } from './sample'; import { PRO, FREE_MINUTES, addTrial, counts, grantBonus, isPro, mayListen, noteGate, paywallOn, recheck, savedLicense, storeLicense, trialLeft, trialUsed, verifyKey } from './pro'; const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T; const el = <K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }; const SPEEDS = [0.8, 1, 1.2, 1.5, 1.75, 2]; const PLAY_PATH = 'M8 5v14l11-7z'; const PAUSE_PATH = 'M7 5h4v14H7zm6 0h4v14h-4z'; const TRASH_SVG = '<svg class="ic sm2" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 3h6l1 2h4v2H4V5h4zm-3 6h12l-1 12H7z"/></svg>'; const MODEL_BYTES = 166_000_000; // fp16 model + tokenizer + one voice let current: Book | null = null; let sentenceEls: HTMLElement[] = []; let chapterOffset = 0; // characters in chapters before the current one let sentenceOffsets: number[] = []; let modelEverReady = false; let saveTimer: number | undefined; const engine = new Engine({ onSentence(chapter, index) { if (!current) return; if (chapter !== renderedChapter) renderChapter(); highlight(index); updateProgressUi(); clearTimeout(saveTimer); saveTimer = window.setTimeout(saveNow, 250); if (sleepLeft) renderSleep(); // a timed sleep also checks at every sentence (timers are throttled when hidden) }, onPlaying(p) { sleepRun(p); meterTick(); if (p && counts(current) && trialLeft() < 120) audioCtx(); // created inside a tap, so the end-of-trial sound may play $('play-path').setAttribute('d', p ? PAUSE_PATH : PLAY_PATH); $('play').setAttribute('aria-label', p ? 'Pause' : 'Play'); if ('mediaSession' in navigator) navigator.mediaSession.playbackState = p ? 'playing' : 'paused'; void keepAwake(p); if (p) firstPlayTip(); if (!p) saveTrial(); if (!p) saveNow(); }, onSleep() { sleepEnded(); }, onLimit(midway) { // the free minutes are used up: a soft sound when it stops a listening stretch, then the offer saveNow(); if (midway) chime(); noteGate(); openPaywall('limit'); }, onBuffering(b) { buffering = b; meterTick(); $('play').classList.toggle('buffering', b); }, onModel(m) { renderModel(m); }, onPrepare(done, total) { renderPrepare(done, total); }, onChapterEnd(next) { if (next === null) { toast('The end. You finished this book ✓'); saveNow(); updateProgressUi(); } else toast(`Chapter done ✓ Next: ${current?.chapters[next].title ?? ''}`); }, onError(msg, code) { if (code === 'device-unavailable' && current) { if (current.lang === 'en') { toast('Reading with Heart, the natural voice'); pendingAutoSwitch = false; engine.setVoice({ kind: 'natural', id: 'af_heart' }); updateVoiceLabel(); engine.play(); return; } toast('This phone or computer has no voice for this language. Try Chrome, or add voices in your device settings.', true); return; } toast(msg, true); }, }); engine.mayContinue = () => { meterTick(true); return mayListen(current); }; // the sample ships its sentences already read by Heart: the first thing a visitor hears is the natural voice, // before (and without) the 160 MB download engine.preclip = (key, chapter, i, text) => { if (!canOgg || current?.format !== 'sample' || key.split('|')[3] !== SAMPLE_AUDIO.voice) return undefined; if (SAMPLE_AUDIO.chapters[chapter]?.[i] !== text) return undefined; // sample text changed: the model reads it return fetch(`./sample-audio/s-${chapter}-${i}.ogg`).then((r) => (r.ok ? r.blob() : Promise.reject(new Error(String(r.status))))); }; /** A natural voice chosen in the sample that needs the download first (Heart reads meanwhile). */ let pendingSampleVoice: Voice | null = null; const voiceName = (id: string) => NATURAL_VOICES.find((v) => v.id === id)?.label.split(' ·')[0] || 'This voice'; /** Ogg/Opus clips (the sample and the previews) only where the browser can play them. */ const canOgg = typeof Audio !== 'undefined' && !!new Audio().canPlayType('audio/ogg; codecs=opus'); /** The sample can play the natural voice from its own clips while the model is not on this device. */ function samplePrerendered(b: Book) { return canOgg && b.format === 'sample' && !modelEverReady && engine.model.s !== 'ready'; } /* ---------- free listening meter (real playback time, any voice; the sample is not counted) ---------- */ let buffering = false; let meterFrom = 0; // when the current counted stretch started (0 = not counting) function chipShown() { try { return !!localStorage.getItem('earshelf.chip'); } catch { return true; } } /** atSentence: called at a sentence boundary (a long sentence really was heard); otherwise a 1 s timer tick. */ function meterTick(atSentence = false) { const now = Date.now(); if (meterFrom) { const gap = (now - meterFrom) / 1000; // a timer tick after a long gap means the page was frozen (screen locked, laptop asleep): nobody heard that addTrial(gap > 3 && !atSentence ? 0 : Math.min(30, gap)); } meterFrom = engine.playing && !buffering && counts(current) ? now : 0; if (meterFrom && !chipShown() && trialLeft() > 0 && trialLeft() <= 60) { try { localStorage.setItem('earshelf.chip', '1'); // once per device } catch { /* storage blocked */ } toast('1 minute of free listening left · your place is saved'); } } window.setInterval(meterTick, 1000); let trialSaved = 0; function saveTrial() { const v = trialUsed(); if (v !== trialSaved) (trialSaved = v), void kvSet('trial', v); // a second copy, so clearing one store is not enough } window.setInterval(saveTrial, 10_000); const trialRestored = kvGet<number>('trial') .then((v) => { if (typeof v === 'number' && v > trialUsed()) addTrial(0, v); }) .catch(() => {}); /* ---------- end-of-trial sound: a soft rising major third (G4 → B4), well under the voice ---------- */ let actx: AudioContext | null = null; function audioCtx() { try { actx ||= new AudioContext(); if (actx.state === 'suspended') void actx.resume(); } catch { /* no Web Audio */ } return actx; } let chimes = 0; function chime() { chimes++; const c = audioCtx(); if (!c) return; const t0 = c.currentTime + 0.2; // a beat of silence after the last word [392, 493.88].forEach((f, i) => { const o = c.createOscillator(); const g = c.createGain(); o.type = 'sine'; o.frequency.value = f; const t = t0 + i * 0.18; g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(0.09, t + 0.015); g.gain.exponentialRampToValueAtTime(0.0005, t + 0.42); o.connect(g).connect(c.destination); o.start(t); o.stop(t + 0.45); }); } function saveNow() { clearTimeout(saveTimer); if (!current) return; const done = engine.finished ? current.totalChars : doneChars(); // localStorage is synchronous, so it survives a reload or tab close; IndexedDB may not finish in time try { localStorage.setItem('earshelf.pos.' + current.id, JSON.stringify({ c: engine.chapter, s: engine.index, d: done, t: Date.now() })); } catch { /* storage full or blocked */ } void updateProgress(current.id, engine.chapter, engine.index, done); } /** Apply a newer position saved synchronously at unload, if IndexedDB missed it. */ function applyLocalPosition(b: Book) { try { const raw = localStorage.getItem('earshelf.pos.' + b.id); if (!raw) return; const pos = JSON.parse(raw); if (pos.t >= b.opened - 1000 && pos.c < b.chapters.length) { b.chapter = pos.c; b.sentence = pos.s; b.doneChars = pos.d; } } catch { /* ignore */ } } /* ================= library ================= */ const coverUrls: string[] = []; async function renderLibrary() { const books = await listBooks(); const ul = $('books'); ul.textContent = ''; coverUrls.splice(0).forEach((u) => URL.revokeObjectURL(u)); $('shelf-title').hidden = books.length === 0; $('library').classList.toggle('has-books', books.length > 0); books.forEach(applyLocalPosition); renderContinue(books.find((b) => !b.totalChars || b.doneChars < b.totalChars)); $('sample').hidden = books.some((b) => b.format === 'sample'); for (const b of books) { applyLocalPosition(b); const li = el('li', 'book'); li.dataset.id = b.id; const open = el('button', 'book-open'); open.setAttribute('aria-label', `Open ${b.title}`); let cover: HTMLElement; if (b.cover) { const img = el('img', 'cover') as HTMLImageElement; img.alt = ''; img.src = URL.createObjectURL(b.cover); coverUrls.push(img.src); cover = img; } else cover = el('div', 'cover', (b.title.trim()[0] || '?').toUpperCase()); const meta = el('div', 'book-meta'); meta.append(el('div', 'book-title', b.title)); const pct = b.totalChars ? Math.min(100, Math.round((b.doneChars / b.totalChars) * 100)) : 0; const totalMin = Math.max(1, Math.round(b.totalChars / 900)); const leftMin = Math.max(1, Math.round(((b.totalChars - b.doneChars) / b.totalChars) * totalMin)); const progress = pct >= 100 ? 'Finished ✓' : pct === 0 ? `${formatDuration(totalMin)} listen` : `${pct}% · ${formatDuration(leftMin)} left`; const sub = [b.author, progress].filter(Boolean).join(' · '); meta.append(el('div', 'book-sub', sub)); const bar = el('div', 'mini-bar'); const fill = el('div'); fill.style.width = pct + '%'; bar.append(fill); meta.append(bar); open.append(cover, meta); open.addEventListener('click', () => void openBook(b.id)); const del = el('button', 'del'); del.innerHTML = TRASH_SVG; del.setAttribute('aria-label', `Delete ${b.title}`); let armTimer: number | undefined; del.addEventListener('click', async (e) => { e.stopPropagation(); if (!del.classList.contains('armed')) { del.classList.add('armed'); del.textContent = 'Delete?'; del.setAttribute('aria-label', `Confirm: delete ${b.title}`); armTimer = window.setTimeout(() => { del.classList.remove('armed'); del.innerHTML = TRASH_SVG; del.setAttribute('aria-label', `Delete ${b.title}`); }, 3000); return; } clearTimeout(armTimer); const idx = [...ul.children].indexOf(li); await deleteBook(b.id); toast('Book removed'); await renderLibrary(); // keep keyboard focus nearby instead of dropping it to the page const next = ul.children[Math.min(idx, ul.children.length - 1)]?.querySelector<HTMLElement>('.book-open'); requestAnimationFrame(() => (next || $('file')).focus()); }); li.append(open, del); ul.append(li); } const line = books.length ? `${books.length} book${books.length === 1 ? '' : 's'} on this phone or computer` : ''; $('storage').textContent = line; } /** The most recent unfinished book, one tap from playing again. */ function renderContinue(b: Book | undefined) { const box = $('continue'); box.textContent = ''; const pct = b && b.totalChars ? Math.round((b.doneChars / b.totalChars) * 100) : 0; if (!b || pct >= 100) { box.hidden = true; return; } const ch = b.chapters[Math.min(b.chapter, b.chapters.length - 1)]; const info = el('div', 'continue-info'); const leftMin = Math.max(1, Math.round((b.totalChars - b.doneChars) / 900)); const where = b.chapters.length > 1 ? `Chapter ${Math.min(b.chapter, b.chapters.length - 1) + 1} of ${b.chapters.length} · ` : ''; info.append( el('div', 'continue-kicker', pct > 0 ? 'Continue listening' : 'Start listening'), el('div', 'continue-title', b.title), el('div', 'continue-sub', `${where}${ch?.title ?? ''}`), el('div', 'continue-sub', pct > 0 ? `${pct}% · ${formatDuration(leftMin)} left` : `${formatDuration(leftMin)} listen`), ); const play = el('button', 'continue-play'); play.setAttribute('aria-label', `Play ${b.title}`); play.innerHTML = `<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="${PLAY_PATH}"/></svg>`; play.addEventListener('click', () => void openBook(b.id, true)); box.append(info, play); box.hidden = false; } /** A failed file stays explained on the library until the next good file or Dismiss (a toast fades). */ function showLibError(msgs: string[]) { $('lib-error').hidden = msgs.length === 0; $('lib-error-text').textContent = msgs.join(' '); } async function addFiles(files: FileList | File[]) { const list = Array.from(files); if (!list.length) return; let lastId = ''; openNote = null; const errors: string[] = []; showLibError([]); for (const f of list) { busy(`Opening “${f.name}”…`, 0); try { const parsed = await parseFile(f, (p) => busy(`Opening “${f.name}”…`, p)); // the bar shows progress; the live text stays quiet const all = parsed.chapters.map((c) => c.text).join(' '); const dup = (await listBooks()).find((x) => x.title === parsed.title && x.totalChars === all.length); if (dup) { openNote = { id: dup.id, text: 'Already on your shelf' }; lastId = dup.id; continue; } const book: Book = { id: crypto.randomUUID?.() || String(Date.now() + Math.random()), title: parsed.title, author: parsed.author, format: parsed.format, lang: guessLanguage(all), cover: parsed.cover, chapters: parsed.chapters, added: Date.now(), opened: Date.now(), chapter: 0, sentence: 0, totalChars: all.length, doneChars: 0, }; await saveBook(book); lastId = book.id; } catch (e) { busy(null); const msg = e instanceof ParseError ? e.message : `Could not read “${f.name}”.`; errors.push(msg); errUntil = Date.now() + 5000; // keep tips away while the card is fresh if (!(e instanceof ParseError)) console.error(e); } } busy(null); if (navigator.storage?.persist) void navigator.storage.persist(); if (lastId) await openBook(lastId, true); else void renderLibrary(); showLibError(errors); // also after opening a good book, so going back still explains the bad one } async function addSample() { const book: Book = { id: 'sample-alice', title: SAMPLE.title, author: SAMPLE.author, format: 'sample', lang: 'en', chapters: SAMPLE.chapters, added: Date.now(), opened: Date.now(), chapter: 0, sentence: 0, totalChars: SAMPLE.chapters.map((c) => c.text).join(' ').length, doneChars: 0, }; await saveBook(book); await openBook(book.id, true); } /* ================= player ================= */ let renderedChapter = -1; // a message from the library for one book, shown once that book is open let openNote: { id: string; text: string } | null = null; async function openBook(id: string, autoplay = false) { const b = await getBook(id); if (!b) return; applyLocalPosition(b); $('toast').classList.remove('show'); // a message from the library does not follow into the player b.opened = Date.now(); void saveBook(b); // settings first, so a quick tap after the player appears is never overwritten const voice = await chooseVoice(b); const speed = (await kvGet<number>('speed')) || 1; current = b; renderedChapter = -1; engine.voice = voice; engine.setSpeed(speed); updateVoiceLabel(); updateSpeedLabel(); $('library').hidden = true; $('player').hidden = false; $('p-title').textContent = b.title; if (engine.artwork) URL.revokeObjectURL(engine.artwork); engine.artwork = b.cover ? URL.createObjectURL(b.cover) : ''; if (location.hash !== '#book=' + id) history.pushState({ book: id }, '', '#book=' + id); engine.open(b, Math.min(b.chapter, b.chapters.length - 1), b.sentence); if (b.totalChars && b.doneChars >= b.totalChars) { engine.finished = true; // a finished book: show it, and Play starts over updateProgressUi(); } if (samplePrerendered(b) && engine.voice.kind === 'natural') { // the sample's own clips play: no 160 MB download just for trying it (a real book starts it) } else if (engine.voice.kind === 'natural') engine.ensureModel(); else maybeWarmNatural(b); const notes = [openNote?.id === id ? openNote.text : '']; openNote = null; if ((b.chapter > 0 || b.sentence > 0) && !engine.finished) { notes.push(`picked up where you left off${b.chapters.length > 1 ? ` · chapter ${engine.chapter + 1}` : ''}`); } const note = notes.filter(Boolean).join(' · '); if (note) toast(note[0].toUpperCase() + note.slice(1)); if (autoplay) { // first win: start talking right away (a user gesture is still active) engine.play(); } } /** Natural voice when it is ready (or downloading) and the book is English; device voice otherwise. */ async function chooseVoice(b: Book): Promise<Voice> { const saved = await kvGet<Voice>('voice'); modelEverReady = !!(await kvGet<boolean>('modelReady')); const english = b.lang === 'en'; if (saved?.kind === 'device') { // a saved device voice only applies to books in its language const sv = synth?.getVoices().find((v) => v.voiceURI === saved.id); if (sv && b.lang !== 'und' && sv.lang.toLowerCase().startsWith(b.lang)) return saved; if (!english) return { kind: 'device', id: pickDeviceVoice(b.lang)?.voiceURI || '' }; if (!sv) return saved; } if (english && (modelEverReady || engine.model.s === 'ready')) return saved?.kind === 'natural' ? saved : { kind: 'natural', id: 'af_heart' }; if (english && b.format === 'sample' && saved?.kind !== 'device') return { kind: 'natural', id: SAMPLE_AUDIO.voice }; return { kind: 'device', id: pickDeviceVoice(b.lang)?.voiceURI || '' }; } /** While the device voice reads, download the natural voice in the background and switch when ready. */ function maybeWarmNatural(b: Book) { if (b.lang !== 'en' || engine.model.s === 'loading' || engine.model.s === 'ready') return; void kvGet<Voice>('voice').then((saved) => { if (saved?.kind === 'device') return; // the user picked the device voice on purpose try { if (localStorage.getItem('earshelf.noWarm')) return; // tests } catch { /* ignore */ } pendingAutoSwitch = true; if (metered()) offerDownload(); else engine.ensureModel(); }); } function metered(): boolean { const c = (navigator as any).connection; if (!c) return false; return !!c.saveData || c.type === 'cellular' || /(^|-)2g|3g/.test(c.effectiveType || ''); } function offerDownload() { const b = $('model-banner'); b.classList.remove('chip'); b.textContent = ''; const lead = pendingSampleVoice ? `${voiceName(pendingSampleVoice.id)} needs a one-time download, then every natural voice works without internet.` : 'Want the natural voice? It needs a one-time download, then it works without internet.'; b.append(el('div', '', `${lead} It's a big download and you seem to be on mobile data, so Wi-Fi is better.`)); const btn = el('button', 'pill-btn', 'Download it now'); btn.style.marginTop = '8px'; btn.addEventListener('click', () => engine.ensureModel()); b.append(btn); b.hidden = false; } let pendingAutoSwitch = false; function pickDeviceVoice(lang: string): SpeechSynthesisVoice | undefined { const vs = (synth?.getVoices() || []).filter((v) => lang !== 'und' && v.lang.toLowerCase().startsWith(lang)); if (!vs.length) return undefined; // unknown language: the browser picks its default voice // prefer the user's own locales in order (en-CA, then en-GB…), then US English, then the system default const norm = (l: string) => l.toLowerCase().replace('_', '-'); const wanted = [...navigator.languages.map(norm).filter((l) => l.startsWith(lang) && l.includes('-')), lang === 'en' ? 'en-us' : '']; for (const w of wanted) { const hit = vs.find((v) => norm(v.lang) === w && v.localService) || vs.find((v) => norm(v.lang) === w); if (hit) return hit; } return vs.find((v) => v.default) || vs.find((v) => v.localService) || vs[0]; } function renderChapter() { if (!current) return; renderedChapter = engine.chapter; const ch = current.chapters[engine.chapter]; $('p-chapter').textContent = `${engine.chapter + 1}/${current.chapters.length} · ${ch.title}`; const reader = $('reader'); reader.textContent = ''; reader.lang = current.lang === 'und' ? '' : current.lang; reader.dir = 'auto'; // add a heading unless the chapter text already opens with its title const norm = (x: string) => x.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim(); const first = norm(engine.sentences[0] || ''); const t = norm(ch.title).replace(/^\d+\s+/, ''); if (!t || !(first.startsWith(t) || (first.length > 2 && t.endsWith(first)))) reader.append(el('h2', '', ch.title)); // Rebuild paragraphs: walk the chapter text and wrap each sentence in a span. sentenceEls = []; sentenceOffsets = []; let acc = 0; const paras = ch.text.split(/\n{2,}/); let si = 0; const sentences = engine.sentences; for (const para of paras) { const p = el('p'); p.dir = 'auto'; const flat = para.replace(/\s*\n\s*/g, ' '); let pos = 0; while (si < sentences.length) { const s = sentences[si]; const at = flat.indexOf(s.slice(0, Math.min(24, s.length)), pos); if (at === -1) break; if (at > pos) p.append(flat.slice(pos, at)); const span = el('span', 's', s); const idx = si; span.addEventListener('click', () => { engine.jump(idx); if (!engine.playing) engine.play(); }); p.append(span, ' '); sentenceEls.push(span); sentenceOffsets.push(acc); acc += s.length + 1; pos = at + s.length; si++; } if (pos < flat.length && flat.slice(pos).trim()) p.append(flat.slice(pos)); if (p.childNodes.length) reader.append(p); } // any sentences not matched to paragraph text (rare): append them so every index has an element if (si < sentences.length) { const p = el('p'); p.dir = 'auto'; for (; si < sentences.length; si++) { const span = el('span', 's', sentences[si]); const idx = si; span.addEventListener('click', () => engine.jump(idx)); p.append(span, ' '); sentenceEls.push(span); sentenceOffsets.push(acc); acc += sentences[si].length + 1; } reader.append(p); } chapterOffset = current.chapters.slice(0, engine.chapter).reduce((n, c) => n + c.text.length + 1, 0); $<HTMLInputElement>('seek').max = String(Math.max(0, sentences.length - 1)); reader.scrollTop = 0; } let lastOn: HTMLElement | null = null; function highlight(i: number) { lastOn?.classList.remove('on'); const s = sentenceEls[i]; if (!s) return; s.classList.add('on'); lastOn = s; const r = $('reader'); const top = s.offsetTop - r.offsetTop; if (top < r.scrollTop + 40 || top > r.scrollTop + r.clientHeight * 0.6) { r.scrollTo({ top: Math.max(0, top - r.clientHeight * 0.3), behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' }); } } function doneChars() { return chapterOffset + (sentenceOffsets[engine.index] || 0); } let seeking = false; // while the thumb is held, playback must not move it back function chapterChars() { const n = sentenceOffsets.length; return n ? sentenceOffsets[n - 1] + (engine.sentences[n - 1]?.length || 0) : 0; } /** Bar and label for sentence `i` of this chapter (the current one, or the one under a held thumb). */ function paintProgress(i: number) { if (!current) return; const seek = $<HTMLInputElement>('seek'); if (engine.finished && !seeking) { $('bar-fill').style.width = '100%'; $('progress-label').textContent = 'Finished ✓'; seek.value = seek.max; seek.setAttribute('aria-valuetext', 'Finished'); return; } const total = chapterChars(); const at = sentenceOffsets[i] || 0; const max = Number(seek.max) || 0; $('bar-fill').style.width = (max ? (i / max) * 100 : 0).toFixed(1) + '%'; // same scale as the thumb const chLeft = Math.max(1, Math.round((total - at) / 900 / engine.speed)); // ≈155 words a minute at 1× const bookDone = chapterOffset + at; const bookPct = current.totalChars ? Math.round((bookDone / current.totalChars) * 100) : 0; const bookLeft = Math.max(1, Math.round((current.totalChars - bookDone) / 900 / engine.speed)); const label = $('progress-label'); label.textContent = `${formatDuration(chLeft)} left in chapter`; label.title = `${bookPct}% of the book · ${formatDuration(bookLeft)} left in the book`; if (!seeking) seek.value = String(i); seek.setAttribute('aria-valuetext', `${formatDuration(chLeft)} left in this chapter, ${bookPct}% of the book`); } function updateProgressUi() { if (!seeking) paintProgress(engine.index); } function renderModel(m: ModelState) { const b = $('model-banner'); if (m.s === 'loading') { // compressed responses report no real size: then use the known model size (≈165 MB) const total = m.total > m.loaded * 1.02 ? m.total : Math.max(MODEL_BYTES, m.loaded); const pct = Math.min(99, Math.round((m.loaded / total) * 100)); b.innerHTML = ''; const chip = el('div', 'chip-text', `Getting the natural voice ready… ${pct}%`); chip.title = engine.voice.kind === 'device' ? "Your device's own voice reads meanwhile. It switches by itself when it's ready." : ''; b.append(chip); b.classList.add('chip'); const bar = el('div', 'bar'); const fill = el('div'); fill.style.width = pct + '%'; bar.append(fill); b.append(bar); b.hidden = !current; } else if (m.s === 'ready') { b.hidden = true; b.classList.remove('chip'); if (!modelEverReady) { modelEverReady = true; void kvSet('modelReady', true); } if (pendingSampleVoice && current?.format === 'sample') { engine.queueVoice(pendingSampleVoice); updateVoiceLabel(pendingSampleVoice.id); toast(`Natural voice ready ✓ Switching to ${voiceName(pendingSampleVoice.id)}`); } pendingSampleVoice = null; if (pendingAutoSwitch && current?.lang === 'en' && engine.voice.kind === 'device') { pendingAutoSwitch = false; void decideSwitch(); } refreshVoiceSheet(); } else if (m.s === 'error') { b.classList.remove('chip'); b.hidden = !current; b.textContent = "The natural voice couldn't start on this phone or computer. Your device's own voice keeps reading."; if (m.message) console.warn('natural voice:', m.message); pendingSampleVoice = null; if (current && samplePrerendered(current) && engine.voice.kind === 'natural') { // the sample keeps reading with its own Heart clips if (engine.voice.id !== SAMPLE_AUDIO.voice) engine.setVoice({ kind: 'natural', id: SAMPLE_AUDIO.voice }), updateVoiceLabel(); return; } if (engine.voice.kind === 'natural' && current) { engine.setVoice({ kind: 'device', id: pickDeviceVoice(current.lang)?.voiceURI || '' }); updateVoiceLabel(); } } } /** Switch to the natural voice only if this device makes it faster than it is spoken. */ async function decideSwitch() { if (!current) return; const rtf = await engine.probe(); if (!current || engine.voice.kind !== 'device') return; if (rtf !== null && rtf < 0.9) { engine.queueVoice({ kind: 'natural', id: engine.naturalId }); updateVoiceLabel(engine.naturalId); toast('Natural voice ready ✓ Switching now'); } else if (rtf !== null) offerPrepare(rtf); } function offerPrepare(rtf: number) { const b = $('model-banner'); b.classList.remove('chip'); b.textContent = ''; console.info('natural voice speed vs real time:', rtf.toFixed(2)); b.append(el('div', '', "The natural voice is ready, but this phone can't keep up with it live. Your device's own voice keeps reading. Get this chapter ready in the background and switch when it's done.")); const btn = el('button', 'pill-btn', 'Get this chapter ready'); btn.style.marginTop = '8px'; btn.addEventListener('click', () => engine.prepare()); b.append(btn); b.hidden = false; } let prepSwitched = ''; function renderPrepare(done: number, total: number) { if (!current) return; const b = $('model-banner'); if (done >= total) { b.hidden = true; const k = `${current.id}|${engine.chapter}`; if (engine.voice.kind === 'device' && engine.preparing && prepSwitched !== k) { prepSwitched = k; engine.queueVoice({ kind: 'natural', id: engine.naturalId }); updateVoiceLabel(engine.naturalId); toast('Chapter ready ✓ The natural voice starts at the next sentence'); } return; } b.textContent = ''; b.classList.remove('chip'); const pct = Math.round((done / Math.max(1, total)) * 100); b.append(el('div', '', `Getting this chapter ready: ${pct}%. Keep EarShelf open.`)); const bar = el('div', 'bar'); const fill = el('div'); fill.style.width = pct + '%'; bar.append(fill); b.append(bar); b.hidden = false; } /* ---------- speed & voice ---------- */ function updateSpeedLabel() { $('speed').textContent = `${engine.speed}×`; $('speed').setAttribute('aria-label', `Playback speed ${engine.speed}×`); } function updateVoiceLabel(naturalId?: string) { const v = engine.voice; let label = 'Voice'; if (naturalId || v.kind === 'natural') label = NATURAL_VOICES.find((n) => n.id === (naturalId || v.id))?.label.split(' ·')[0] || 'Natural'; else label = (synth?.getVoices() || []).find((x) => x.voiceURI === v.id)?.name.replace(/^(Microsoft|Google)\s+/, '').split(/[ (-]/)[0] || 'Voice'; $('voice-btn').textContent = label; $('voice-btn').setAttribute('aria-label', `Voice: ${label}`); } function refreshVoiceSheet() { const dlg = $<HTMLDialogElement>('voices'); if (!dlg.open) return; buildVoiceSheet(); } function buildVoiceSheet() { stopPreview(); // the old buttons are about to be replaced const body = $('voice-body'); body.textContent = ''; const english = current?.lang === 'en'; const g1 = el('div', 'voice-group'); g1.append(el('h4', '', 'Natural voices (English books)')); if (!english) g1.append(el('p', '', "Natural voices speak English only. This book looks like another language, so your device's own voice is the better fit.")); else if (current && samplePrerendered(current)) g1.append(el('p', '', 'Heart reads this sample right away. The other voices download once (a minute or two on Wi-Fi), then work without internet. Tap ▶ to hear any of them now.')); else if (engine.model.s !== 'ready') g1.append(el('p', '', modelEverReady ? 'Getting ready…' : 'Downloads once (a minute or two on Wi-Fi), then works without internet.')); for (const v of NATURAL_VOICES) { const b = el('button', 'voice-opt'); const cur = engine.voice.kind === 'natural' && engine.voice.id === v.id; if (cur) b.classList.add('cur'); b.setAttribute('aria-pressed', String(cur)); b.append(el('span', '', v.label.split(' ·')[0]), el('small', '', v.label.split(' · ').slice(1).join(' · '))); const row = el('div', 'voice-row'); const hear = el('button', 'voice-hear'); hear.type = 'button'; hear.setAttribute('aria-label', `Hear ${v.label.split(' ·')[0]}`); setHear(hear, false); hear.hidden = !canOgg; hear.addEventListener('click', () => previewVoice(`./sample-audio/voice-${v.id}.ogg`, hear)); row.append(b, hear); b.addEventListener('click', () => { pendingAutoSwitch = false; const nv: Voice = { kind: 'natural', id: v.id }; void kvSet('voice', nv); if (current && samplePrerendered(current) && v.id !== SAMPLE_AUDIO.voice) { // only Heart is recorded for the sample: keep it reading until the chosen voice is on this device pendingSampleVoice = nv; if (engine.voice.kind !== 'natural') engine.setVoice({ kind: 'natural', id: SAMPLE_AUDIO.voice }), updateVoiceLabel(); toast(`${voiceName(v.id)} is downloading (a minute or two on Wi-Fi). Heart keeps reading meanwhile.`); if (metered()) offerDownload(); else engine.ensureModel(); buildVoiceSheet(); return; } if (current && samplePrerendered(current)) pendingSampleVoice = null; // back to Heart engine.setVoice(nv); updateVoiceLabel(); buildVoiceSheet(); }); g1.append(row); } const g2 = el('div', 'voice-group'); g2.append(el('h4', '', "Your device's voices (instant, every language)")); const sel = el('select', 'device-voices') as HTMLSelectElement; sel.setAttribute('aria-label', "Your device's voices"); const all = synth?.getVoices() || []; const lang = current?.lang || 'en'; const sorted = [...all].sort((a, b) => Number(b.lang.toLowerCase().startsWith(lang)) - Number(a.lang.toLowerCase().startsWith(lang)) || a.lang.localeCompare(b.lang)); const ph = el('option', '', all.length ? 'Choose a voice…' : 'None on this phone or computer'); ph.value = ''; sel.append(ph); for (const v of sorted) { const o = el('option', '', `${v.name} (${v.lang})`) as HTMLOptionElement; o.value = v.voiceURI; if (engine.voice.kind === 'device' && engine.voice.id === v.voiceURI) o.selected = true; sel.append(o); } sel.addEventListener('change', () => { if (!sel.value) return; pendingAutoSwitch = false; const nv: Voice = { kind: 'device', id: sel.value }; engine.setVoice(nv); void kvSet('voice', nv); updateVoiceLabel(); }); const devRow = el('div', 'voice-row'); const devHear = el('button', 'voice-hear'); devHear.type = 'button'; devHear.setAttribute('aria-label', 'Hear the chosen device voice'); setHear(devHear, false); devHear.disabled = !all.length; devHear.addEventListener('click', () => { const v = all.find((x) => x.voiceURI === sel.value) || all.find((x) => x.voiceURI === (engine.voice.kind === 'device' ? engine.voice.id : '')) || pickDeviceVoice(lang); if (!synth || !v) return; const again = previewBtn === devHear; stopPreview(); if (again) return; if (engine.playing) engine.pause(); const u = new SpeechSynthesisUtterance(SAMPLE_AUDIO.previewText); u.voice = v; u.lang = v.lang; u.onend = () => previewBtn === devHear && stopPreview(); synth.cancel(); previewBtn = devHear; devPreviewing = true; setHear(devHear, true); synth.speak(u); }); devRow.append(sel, devHear); g2.append(devRow); body.append(english ? g1 : g2, english ? g2 : g1); } /* ---------- voice previews (pre-rendered, so they work before the download) ---------- */ const previewAudio = new Audio(); let previewBtn: HTMLElement | null = null; let devPreviewing = false; const STOP_SVG = '<svg class="ic sm" viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7h10v10H7z"/></svg>'; const HEAR_SVG = `<svg class="ic sm" viewBox="0 0 24 24" aria-hidden="true"><path d="${PLAY_PATH}"/></svg>`; function setHear(btn: HTMLElement, on: boolean) { btn.classList.toggle('on', on); btn.setAttribute('aria-pressed', String(on)); btn.innerHTML = on ? STOP_SVG : HEAR_SVG; } function stopPreview() { previewAudio.pause(); if (devPreviewing) synth?.cancel(); // only our own preview: the engine is paused while one plays devPreviewing = false; if (previewBtn) setHear(previewBtn, false); previewBtn = null; } function previewVoice(src: string, btn: HTMLElement) { const again = previewBtn === btn; stopPreview(); if (again) return; // second tap stops it if (engine.playing) engine.pause(); // never two voices at once previewBtn = btn; setHear(btn, true); previewAudio.src = src; void previewAudio.play().catch(() => stopPreview()); } previewAudio.addEventListener('ended', stopPreview); $('voices').addEventListener('close', stopPreview); /* ---------- ui helpers ---------- */ let toastTimer: number | undefined; let errUntil = 0; // an error message on screen is never covered by a tip function toast(msg: string, err = false) { const t = $('toast'); if (err) errUntil = Date.now() + 5000; t.textContent = msg; t.classList.toggle('err', err); t.classList.add('show'); clearTimeout(toastTimer); toastTimer = window.setTimeout(() => t.classList.remove('show'), err ? 5000 : 2600); } function busy(text: string | null, progress?: number) { $('busy').hidden = text === null; if (text) $('busy-text').textContent = text; if (progress !== undefined) $('busy-fill').style.width = Math.round(Math.min(1, progress) * 100) + '%'; } function backToLibrary() { engine.pause(); setSleep(0); $('toast').classList.remove('show'); current = null; $('player').hidden = true; $('library').hidden = false; $('model-banner').hidden = true; void renderLibrary(); } /* ---------- full access / paywall (off unless paywallOn()) ---------- */ type PwReason = 'limit' | 'code'; function openPaywall(reason: PwReason) { if (!paywallOn() || isPro()) return; const d = $<HTMLDialogElement>('paywall'); d.classList.toggle('code-mode', reason === 'code'); // a buyer coming back sees only the code box $('pw-paste').className = reason === 'code' ? 'primary-btn' : 'link-btn'; $('pw-title').textContent = reason === 'code' ? 'Welcome back! Paste your code.' : 'Loved it? Keep listening'; $('pw-lead').textContent = reason === 'code' ? 'Your code is in your Gumroad receipt email, in the box called "License key". Copy it, then tap Paste my code.' : limitLead(); $('pw-later').textContent = reason === 'code' ? 'Close' : 'Not now'; $('pw-msg').textContent = ''; ($('pw-restore') as HTMLDetailsElement).open = reason === 'code'; if (!d.open) d.showModal(); if (reason === 'code') setTimeout(() => $('pw-key').focus(), 0); } /** Real numbers for the book in hand: how much is waiting. */ function limitLead(): string { const intro = `You've heard your ${FREE_MINUTES} free minutes.`; const none = `${intro} Get full access to keep listening to every book you add.`; if (!current || current.format === 'sample') return none; const heard = sentenceOffsets[engine.index] || 0; // part of the current chapter already heard const later = current.chapters.slice(engine.chapter + 1); const chars = chapterChars() - heard + later.reduce((n, c) => n + c.text.length, 0); if (chars <= 0) return none; const min = Math.max(1, Math.round(chars / 900 / engine.speed)); // ≈155 words a minute at 1× return `${intro} ${current.title} has about ${formatDuration(min)} to go, and your place is saved.`; } function renderProStatus() { const btn = $('pro-status'); btn.hidden = !paywallOn(); const l = savedLicense(); btn.textContent = l ? `Full access ✓${l.email ? ` · ${l.email}` : ''}` : 'Already paid? Enter your code'; } async function restorePro(key: string) { const msg = $('pw-msg'); if (!key.trim()) { msg.textContent = 'Paste your access code first.'; return; } msg.textContent = 'Checking your code…'; const r = await verifyKey(key); if (r.ok) { storeLicense(r.license); msg.textContent = 'Full access ✓'; renderProStatus(); const resume = !!current && !engine.playing && !engine.finished; setTimeout(() => $<HTMLDialogElement>('paywall').close(), 700); toast(resume ? 'Full access ✓ Picking up where you left off' : 'Full access ✓ Listen as much as you like'); if (current && engine.voice.kind === 'device' && current.lang === 'en') { if (engine.model.s === 'ready') { engine.queueVoice({ kind: 'natural', id: engine.naturalId }); updateVoiceLabel(engine.naturalId); } else { pendingAutoSwitch = true; // switch (or offer Prepare) once the voice is ready engine.ensureModel(); } } if (resume) engine.play(); return; } msg.textContent = r.reason === 'network' ? 'No internet right now. Connect and tap Unlock again.' : r.reason === 'refunded' ? 'This code was refunded, so it no longer unlocks EarShelf.' : 'That code didn\'t work. Copy it again from your receipt email (the box called "License key") and paste it here.'; } { for (const e of document.querySelectorAll('.pw-price')) e.textContent = PRO.price; $('pw-guarantee').textContent = String(PRO.guaranteeDays); ($('pw-buy') as HTMLAnchorElement).href = PRO.checkoutUrl; // Gumroad opens in a new tab: when they come back, the code box is already waiting $('pw-buy').addEventListener('click', () => { ($('pw-restore') as HTMLDetailsElement).open = true; $('pw-msg').textContent = 'After paying, check your email and paste the code from your receipt here.'; setTimeout(() => ($('pw-key') as HTMLInputElement).focus(), 0); }); const paste = $<HTMLButtonElement>('pw-paste'); paste.hidden = !navigator.clipboard?.readText; paste.addEventListener('click', async () => { try { const t = (await navigator.clipboard.readText()).trim(); if (!t) return void ($('pw-msg').textContent = 'Nothing copied yet. Copy the code from your email first.'); ($('pw-key') as HTMLInputElement).value = t; void restorePro(t); } catch { $('pw-msg').textContent = 'Press and hold the box, then tap Paste.'; $('pw-key').focus(); } }); $('pw-form').addEventListener('submit', (e) => { e.preventDefault(); void restorePro(($('pw-key') as HTMLInputElement).value); }); $('pw-later').addEventListener('click', () => $<HTMLDialogElement>('paywall').close()); $('pro-status').addEventListener('click', () => { if (isPro()) return; openPaywall('code'); }); renderProStatus(); if (paywallOn()) void recheck().then((r) => r === 'removed' && renderProStatus()); // after the second copy of the count is back, so the gift is measured from the real number void trialRestored.then(() => grantBonus() && setTimeout(() => toast('A little gift: 2 more free minutes. The next page is on us'), 600)); // the receipt email links to …/#unlock: the app opens with the code box ready window.addEventListener('hashchange', unlockFromLink); // the receipt link opened in a tab that was already open unlockFromLink(); } /** The receipt email links to …/#unlock: open the code box (keeps any ?tags in the address). */ function unlockFromLink() { if (location.hash !== '#unlock') return; history.replaceState(history.state, '', location.pathname + location.search + (current ? '#book=' + current.id : '')); if (isPro()) toast('Full access is already on ✓'); else openPaywall('code'); } /* ---------- screen wake lock ---------- */ // Phones pause web pages when the screen locks; live voices stop with them. Keep the screen awake while // playing (released on pause). let wakeLock: any = null; let wantAwake = false; let requesting = false; async function keepAwake(on: boolean) { wantAwake = on; try { if (on && !wakeLock && !requesting && 'wakeLock' in navigator && document.visibilityState === 'visible') { requesting = true; const lock = await (navigator as any).wakeLock.request('screen'); requesting = false; if (!wantAwake) { await lock.release(); // paused while the request was in flight return; } wakeLock = lock; lock.addEventListener?.('release', () => { if (wakeLock === lock) wakeLock = null; }); } else if (!on && wakeLock) { const lock = wakeLock; wakeLock = null; await lock.release(); } } catch { requesting = false; // battery saver or unsupported: nothing to do } } function firstPlayTip() { if (!matchMedia('(pointer: coarse)').matches) return; try { if (localStorage.getItem('earshelf.tipLock')) return; } catch { return; } setTimeout(() => { // only in the player, and never over an error; if skipped, it waits for the next first play if ($('player').hidden || Date.now() < errUntil) return; try { if (localStorage.getItem('earshelf.tipLock')) return; // several plays inside 3 s: show it once localStorage.setItem('earshelf.tipLock', '1'); } catch { /* storage blocked */ } toast('Tip: the screen stays on while EarShelf reads. A chapter you got ready ahead can play with the screen off.'); }, 3000); } /* ---------- sleep timer ---------- */ const SLEEP_STEPS = [0, 15, 30, 45, 60, -1]; // minutes; -1 = end of chapter let sleepIdx = 0; let sleepLeft = 0; // ms left on a timed sleep (0 = none); it only counts down while playing let sleepFrom = 0; // when the current playing stretch started (0 = paused) let sleepTick: number | undefined; function sleepRemaining() { return sleepLeft - (sleepFrom ? Date.now() - sleepFrom : 0); } function sleepRun(playing: boolean) { if (!sleepLeft) return; if (playing && !sleepFrom) sleepFrom = Date.now(); else if (!playing && sleepFrom) { sleepLeft = Math.max(1, sleepRemaining()); sleepFrom = 0; } } function cycleSleep() { sleepIdx = (sleepIdx + 1) % SLEEP_STEPS.length; setSleep(SLEEP_STEPS[sleepIdx]); const m = SLEEP_STEPS[sleepIdx]; toast(m === 0 ? 'Sleep timer off' : m === -1 ? 'Stops at the end of this chapter' : `Stops in ${m} minutes`); } function setSleep(min: number) { sleepIdx = Math.max(0, SLEEP_STEPS.indexOf(min)); clearInterval(sleepTick); engine.stopAtChapterEnd = min === -1; sleepLeft = min > 0 ? min * 60_000 : 0; sleepFrom = sleepLeft && engine.playing ? Date.now() : 0; if (sleepLeft) sleepTick = window.setInterval(renderSleep, 15_000); renderSleep(); } function renderSleep() { const btn = $('sleep'); const m = SLEEP_STEPS[sleepIdx]; let label = 'Sleep'; if (m === -1) label = 'End of ch.'; else if (sleepLeft) { const ms = sleepRemaining(); if (ms <= 0) { if (engine.playing) { engine.pause(); engine.prev(); // step back one sentence so the next play picks up the thread } return sleepEnded(); } label = `${Math.ceil(ms / 60_000)} min`; } $('sleep-label').textContent = label; btn.classList.toggle('on', m !== 0); btn.setAttribute('aria-label', `Sleep timer: ${m === 0 ? 'off' : label}`); } function sleepEnded() { setSleep(0); toast('Sleep timer: paused. Good night'); } /* ================= wiring ================= */ $('file').addEventListener('change', (e) => { const input = e.target as HTMLInputElement; if (input.files) void addFiles(input.files).finally(() => (input.value = '')); }); const drop = $('drop'); ['dragenter', 'dragover'].forEach((t) => document.addEventListener(t, (e) => { e.preventDefault(); drop.classList.add('over'); }), ); ['dragleave', 'drop'].forEach((t) => document.addEventListener(t, () => drop.classList.remove('over'))); document.addEventListener('drop', (e) => { e.preventDefault(); if (e.dataTransfer?.files.length) void addFiles(e.dataTransfer.files); }); $('sample').addEventListener('click', () => void addSample()); $('back').addEventListener('click', () => history.back()); window.addEventListener('popstate', () => { if (location.hash === '#unlock') return; // the receipt link: handled by unlockFromLink, the player stays open const id = location.hash.match(/^#book=(.+)$/)?.[1]; if (id && $('player').hidden) void openBook(decodeURIComponent(id)); else if (!id && !$('player').hidden) backToLibrary(); }); { const seek = $<HTMLInputElement>('seek'); seek.addEventListener('input', () => { seeking = true; paintProgress(Number(seek.value)); }); // Chrome sends pointerup BEFORE change, so the release itself commits the seek (resetting the thumb there // would cancel the change); a drag released where it started just repaints const commit = () => { if (!seeking) return; seeking = false; const v = Number(seek.value); if (v !== engine.index || engine.finished) engine.jump(v); else updateProgressUi(); }; for (const t of ['change', 'pointerup', 'pointercancel']) seek.addEventListener(t, commit); for (const t of ['keyup', 'blur']) { seek.addEventListener(t, () => { if (seeking) (seeking = false), updateProgressUi(); }); } } $('lib-error-close').addEventListener('click', () => showLibError([])); $('lib-error-retry').addEventListener('click', () => $('file').click()); $('play').addEventListener('click', () => engine.toggle()); $('next').addEventListener('click', () => engine.skip(30)); $('prev').addEventListener('click', () => engine.skip(-15)); $('sleep').addEventListener('click', () => cycleSleep()); $('speed').addEventListener('click', () => { const i = SPEEDS.indexOf(engine.speed); const s = SPEEDS[(i + 1) % SPEEDS.length]; engine.setSpeed(s); void kvSet('speed', s); updateSpeedLabel(); updateProgressUi(); }); $('chapter-btn').addEventListener('click', () => { if (!current) return; const ol = $('chapter-list'); ol.textContent = ''; current.chapters.forEach((c, i) => { const li = el('li'); const b = el('button'); if (i === engine.chapter) b.classList.add('cur'), b.setAttribute('aria-current', 'true'); else if (i < engine.chapter) b.classList.add('done'); const min = Math.max(1, Math.round(c.text.length / 900 / engine.speed)); b.dataset.meta = i === engine.chapter ? 'Now' : `${i < engine.chapter ? '✓ ' : ''}${formatDuration(min)}`; if (!/^\s*\d/.test(c.title)) b.append(el('span', 'num', String(i + 1))); b.append(el('span', '', c.title)); b.addEventListener('click', () => { $<HTMLDialogElement>('chapters').close(); engine.gotoChapter(i); }); li.append(b); ol.append(li); }); $<HTMLDialogElement>('chapters').showModal(); ol.querySelector<HTMLElement>('.cur')?.scrollIntoView({ block: 'center' }); }); $('voice-btn').addEventListener('click', () => { buildVoiceSheet(); $<HTMLDialogElement>('voices').showModal(); }); document.querySelectorAll('dialog').forEach((d) => { d.querySelector('.close')?.addEventListener('click', () => d.close()); d.addEventListener('click', (e) => { if (e.target === d) d.close(); // tap on backdrop }); }); document.addEventListener('keydown', (e) => { const onSeek = (e.target as HTMLElement).id === 'seek'; if ($('player').hidden || (!(onSeek && e.code === 'Space') && (e.target as HTMLElement).closest('input,select,textarea,dialog'))) return; if (e.code === 'Space' && (e.target as HTMLElement).closest('button')) return; // let the focused button handle it if (e.code === 'Space') { e.preventDefault(); engine.toggle(); } else if (e.key === 'ArrowRight') engine.next(); else if (e.key === 'ArrowLeft') engine.prev(); }); synth?.addEventListener?.('voiceschanged', () => { if (current && engine.voice.kind === 'device' && !engine.voice.id) { const v = pickDeviceVoice(current.lang); if (v) engine.voice = { kind: 'device', id: v.voiceURI }; } if (current) updateVoiceLabel(); refreshVoiceSheet(); }); // save the position the moment the page is left (reload, tab close, app switch) window.addEventListener('pagehide', saveNow); document.addEventListener('visibilitychange', () => { if (document.hidden) saveNow(); else { if (engine.playing) void keepAwake(true); // the browser drops the wake lock when the page is hidden if (sleepLeft) renderSleep(); } }); if ('serviceWorker' in navigator && import.meta.env.PROD) { void navigator.serviceWorker.register('./sw.js'); } void renderLibrary(); // a reload inside the player reopens the same book (paused, at the saved position) const startId = location.hash.match(/^#book=(.+)$/)?.[1]; if (startId) { history.replaceState({}, '', location.pathname); void getBook(decodeURIComponent(startId)).then((b) => b && openBook(b.id)); } // test hook (window as any).__earshelf = { engine, previewAudio, chimes: () => chimes };
import './style.css';
import { Engine, NATURAL_VOICES, synth, type Voice, type ModelState } from './engine';
import { parseFile, ParseError } from './parse';
import { deleteBook, getBook, kvGet, kvSet, listBooks, saveBook, updateProgress, type Book } from './db';
import { formatDuration, guessLanguage } from './text';
import SAMPLE_AUDIO from './sample-audio.json';
import { SAMPLE } from './sample';
import { PRO, FREE_MINUTES, addTrial, counts, grantBonus, isPro, mayListen, noteGate, paywallOn, recheck, savedLicense, storeLicense, trialLeft, trialUsed, verifyKey } from './pro';
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
const el = <K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string) => {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
};
const SPEEDS = [0.8, 1, 1.2, 1.5, 1.75, 2];
const PLAY_PATH = 'M8 5v14l11-7z';
const PAUSE_PATH = 'M7 5h4v14H7zm6 0h4v14h-4z';
const TRASH_SVG = '<svg class="ic sm2" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 3h6l1 2h4v2H4V5h4zm-3 6h12l-1 12H7z"/></svg>';
const MODEL_BYTES = 166_000_000; // fp16 model + tokenizer + one voice
let current: Book | null = null;
let sentenceEls: HTMLElement[] = [];
let chapterOffset = 0; // characters in chapters before the current one
let sentenceOffsets: number[] = [];
let modelEverReady = false;
let saveTimer: number | undefined;
const engine = new Engine({
onSentence(chapter, index) {
if (!current) return;
if (chapter !== renderedChapter) renderChapter();
highlight(index);
updateProgressUi();
clearTimeout(saveTimer);
saveTimer = window.setTimeout(saveNow, 250);
if (sleepLeft) renderSleep(); // a timed sleep also checks at every sentence (timers are throttled when hidden)
},
onPlaying(p) {
sleepRun(p);
meterTick();
if (p && counts(current) && trialLeft() < 120) audioCtx(); // created inside a tap, so the end-of-trial sound may play
$('play-path').setAttribute('d', p ? PAUSE_PATH : PLAY_PATH);
$('play').setAttribute('aria-label', p ? 'Pause' : 'Play');
if ('mediaSession' in navigator) navigator.mediaSession.playbackState = p ? 'playing' : 'paused';
void keepAwake(p);
if (p) firstPlayTip();
if (!p) saveTrial();
if (!p) saveNow();
},
onSleep() {
sleepEnded();
},
onLimit(midway) {
// the free minutes are used up: a soft sound when it stops a listening stretch, then the offer
saveNow();
if (midway) chime();
noteGate();
openPaywall('limit');
},
onBuffering(b) {
buffering = b;
meterTick();
$('play').classList.toggle('buffering', b);
},
onModel(m) {
renderModel(m);
},
onPrepare(done, total) {
renderPrepare(done, total);
},
onChapterEnd(next) {
if (next === null) {
toast('The end. You finished this book ✓');
saveNow();
updateProgressUi();
}
else toast(`Chapter done ✓ Next: ${current?.chapters[next].title ?? ''}`);
},
onError(msg, code) {
if (code === 'device-unavailable' && current) {
if (current.lang === 'en') {
toast('Reading with Heart, the natural voice');
pendingAutoSwitch = false;
engine.setVoice({ kind: 'natural', id: 'af_heart' });
updateVoiceLabel();
engine.play();
return;
}
toast('This phone or computer has no voice for this language. Try Chrome, or add voices in your device settings.', true);
return;
}
toast(msg, true);
},
});
engine.mayContinue = () => {
meterTick(true);