Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587<script lang="ts"> import { onMount, tick } from 'svelte'; import type { ReadAloud } from '#lib/read-aloud.svelte.ts'; import { localVoiceFor, preferredLanguage, speechSupported } from '#lib/speech.ts'; import { isSpeechRate, readOnlineConsent, readSpeechSettings, saveOnlineConsent, saveSpeechSettings, SPEECH_RATES } from '#lib/speech-settings.ts';
/** * The status bar's reading control. It reads the open scene only, and it * stays beside Proofread because both answer a question about the words in * front of the writer. */ let { controller, onstart }: { controller: ReadAloud; /** Returns the open scene's chunks at the moment of the press. */ onstart: () => string[]; } = $props();
let supported = $state(false); let voices = $state.raw<SpeechSynthesisVoice[]>([]); let settingsOpen = $state(false); let onlinePrompt = $state(false); let onlineConsent = $state(false); let voiceChosen = $state(false); let savedVoiceURI = $state<string | null>(null);
let root: HTMLDivElement | undefined = $state(); let listenButton: HTMLButtonElement | undefined = $state(); let settingsButton: HTMLButtonElement | undefined = $state(); let voiceField: HTMLSelectElement | undefined = $state(); let consentButton: HTMLButtonElement | undefined = $state();
const language = $derived(preferredLanguage()); const local = $derived(localVoiceFor(voices, language)); const reading = $derived(controller.status === 'playing' || controller.status === 'paused'); const selectedVoiceURI = $derived(controller.voice?.voiceURI ?? ''); const position = $derived( controller.total === 0 ? 0 : Math.min(controller.index + 1, controller.total) );
const label = $derived( controller.status === 'playing' ? 'Pause' : controller.status === 'paused' ? 'Resume' : 'Listen' );
const actionLabel = $derived.by(() => { if (controller.status === 'playing') return 'Pause reading'; if (controller.status === 'paused') return 'Resume reading'; if (controller.status === 'finished') return 'Listen again to this scene';
return 'Listen to this scene'; });
const actionTitle = $derived.by(() => { if (controller.status === 'playing') return 'Pause read aloud'; if (controller.status === 'paused') return 'Resume read aloud'; if (controller.status === 'finished') return 'Listen again from the top';
return 'Read this scene aloud'; });
const announcement = $derived.by(() => { if (controller.status === 'paused') return 'Read aloud paused.'; if (controller.status === 'finished') return 'Finished reading the scene.'; if (controller.status === 'error') return controller.error ?? 'Read aloud failed.';
return ''; });
const privacy = $derived.by(() => { if (controller.voice?.localService === false) { return 'This voice is online. The browser may send the scene to its speech service. Fablewright sends nothing.'; }
if (controller.voice) return 'This voice plays on this device.';
return 'The browser chooses the voice. A voice marked online may send the scene to a speech service. Fablewright sends nothing.'; });
const voiceMissing = $derived( savedVoiceURI !== null && !voices.some((voice) => voice.voiceURI === savedVoiceURI) );
const needsConsent = $derived( !onlineConsent && (controller.voice === null ? local === null : !controller.voice.localService) );
const localVoices = $derived(voices.filter((voice) => voice.localService).sort(byVoice)); const onlineVoices = $derived(voices.filter((voice) => !voice.localService).sort(byVoice));
function byVoice(a: SpeechSynthesisVoice, b: SpeechSynthesisVoice): number { return a.lang.localeCompare(b.lang) || a.name.localeCompare(b.name); }
function voiceLabel(voice: SpeechSynthesisVoice): string { return `${voice.name} (${voice.lang})`; }
function applyVoice() { const saved = savedVoiceURI ? (voices.find((voice) => voice.voiceURI === savedVoiceURI) ?? null) : null;
if (saved) { controller.setVoice(saved); return; }
if (voiceChosen && savedVoiceURI === null) { controller.setVoice(null); return; }
// A missing saved voice falls back to a local one; the consent check // covers a browser that has none. controller.setVoice(localVoiceFor(voices, language)); }
onMount(() => { supported = speechSupported(); if (!supported) return;
const settings = readSpeechSettings(); onlineConsent = readOnlineConsent(); voiceChosen = settings.voiceChosen; savedVoiceURI = settings.voiceURI; controller.setRate(settings.rate);
const refresh = () => { voices = window.speechSynthesis.getVoices(); applyVoice(); };
refresh(); window.speechSynthesis.addEventListener('voiceschanged', refresh);
return () => window.speechSynthesis.removeEventListener('voiceschanged', refresh); });
function openSettings() { settingsOpen = true; onlinePrompt = false; void tick().then(() => voiceField?.focus()); }
function closeSettings(returnFocus = true) { settingsOpen = false; onlinePrompt = false; if (returnFocus) void tick().then(() => settingsButton?.focus()); }
function toggleSettings() { if (settingsOpen) { closeSettings(); return; }
openSettings(); }
function startNow() { const started = controller.start(onstart());
if (started) return;
openSettings(); }
function begin() { if (needsConsent) { settingsOpen = true; onlinePrompt = true; void tick().then(() => consentButton?.focus()); return; }
startNow(); }
function toggle() { if (controller.status === 'playing') controller.pause(); else if (controller.status === 'paused') controller.resume(); else begin(); }
function confirmOnline() { onlineConsent = true; saveOnlineConsent(); onlinePrompt = false; settingsOpen = false; startNow(); void tick().then(() => { if (controller.status !== 'error') listenButton?.focus(); }); }
function cancelOnline() { onlinePrompt = false; settingsOpen = false; void tick().then(() => listenButton?.focus()); }
function chooseVoice(event: Event) { const uri = (event.currentTarget as HTMLSelectElement).value; const next = uri ? (voices.find((voice) => voice.voiceURI === uri) ?? null) : null;
savedVoiceURI = next?.voiceURI ?? null; voiceChosen = true; controller.setVoice(next);
if (next && !next.localService) { onlineConsent = true; saveOnlineConsent(); }
saveSpeechSettings({ voiceURI: savedVoiceURI, voiceChosen, rate: controller.rate }); }
function chooseRate(event: Event) { const next = Number((event.currentTarget as HTMLSelectElement).value);
if (!isSpeechRate(next)) return;
controller.setRate(next); saveSpeechSettings({ voiceURI: savedVoiceURI, voiceChosen, rate: next }); }
function onpointerdown(event: PointerEvent) { if (!settingsOpen) return; if (root?.contains(event.target as Node | null)) return;
closeSettings(false); }
function onkeydown(event: KeyboardEvent) { if (!settingsOpen || event.key !== 'Escape') return;
event.preventDefault(); closeSettings(); }</script>
<svelte:window {onpointerdown} {onkeydown} onpagehide={() => controller.stop()} />
{#if supported} <div class="read-aloud" bind:this={root}> <button bind:this={listenButton} class="status-key" class:on={reading} type="button" aria-label={actionLabel} title={controller.error ?? actionTitle} onclick={toggle} > {label} </button>
{#if reading} <button class="status-key" type="button" aria-label="Stop reading" title="Stop reading" onclick={() => controller.stop()} > Stop </button> {/if}
<button bind:this={settingsButton} class="status-key" class:on={settingsOpen} type="button" aria-expanded={settingsOpen} aria-haspopup="dialog" aria-controls="read-aloud-settings" title="Read aloud settings" onclick={toggleSettings} > Voice </button>
<span class="sr-only" role="status" aria-live="polite">{announcement}</span>
{#if settingsOpen} <div class="popover" id="read-aloud-settings" role="dialog" aria-label={onlinePrompt ? 'Online voice confirmation' : 'Read aloud settings'} data-read-aloud-popover > <div class="head"> <p class="title"> {onlinePrompt ? 'Read aloud with an online voice?' : 'Read aloud'} </p> <button class="close tap-area" type="button" aria-label="Close read aloud settings" onclick={() => closeSettings()} > × </button> </div>
{#if onlinePrompt} <p class="consent"> The browser did not report an on-device voice for this language. An online voice may send the scene to the browser's speech service. Fablewright sends nothing. </p> <div class="acts"> <button bind:this={consentButton} class="btn btn-sm btn-primary" type="button" onclick={confirmOnline} > Read aloud </button> <button class="btn btn-sm btn-ghost" type="button" onclick={cancelOnline}> Cancel </button> </div> {:else} {#if controller.error} <p class="problem" role="status">{controller.error}</p> {/if}
{#if controller.total > 0} <div class="progress"> <span class="tnum">{position} of {controller.total}</span> {#if controller.now} <span class="now">“{controller.now}”</span> {/if} </div>
{#if reading} <div class="skip"> <button class="btn btn-sm btn-ghost" type="button" disabled={controller.index <= 0} onclick={() => controller.previous()} > Previous sentence </button> <button class="btn btn-sm btn-ghost" type="button" disabled={controller.index >= controller.total - 1} onclick={() => controller.next()} > Next sentence </button> </div> {/if} {/if}
<label class="field-label" for="read-aloud-voice">Voice</label> <select bind:this={voiceField} id="read-aloud-voice" class="field" value={selectedVoiceURI} onchange={chooseVoice} > <option value="">System default</option> {#if localVoices.length > 0} <optgroup label="On this device"> {#each localVoices as voice (voice.voiceURI)} <option value={voice.voiceURI}>{voiceLabel(voice)}</option> {/each} </optgroup> {/if} {#if onlineVoices.length > 0} <optgroup label="Online"> {#each onlineVoices as voice (voice.voiceURI)} <option value={voice.voiceURI}>{voiceLabel(voice)}</option> {/each} </optgroup> {/if} </select>
{#if voiceMissing} <p class="note">That voice is not available here. The browser will use another one.</p> {/if}
<label class="field-label" for="read-aloud-rate">Speed</label> <select id="read-aloud-rate" class="field" value={String(controller.rate)} onchange={chooseRate} > {#each SPEECH_RATES as option (option)} <option value={String(option)}>{option}×</option> {/each} </select>
<p class="privacy">{privacy}</p> {/if} </div> {/if} </div>{/if}
<style> .read-aloud { display: inline-flex; align-items: center; gap: 0.125rem; position: relative; min-width: 0; /* A wrapped status row starts at the left. The auto margin keeps the popover, which opens from this control, inside the viewport. */ margin-left: auto; }
.status-key { padding: 0 0.375rem; min-height: 24px; min-width: 24px; border: 1px solid transparent; border-radius: var(--dr-radius-sm); background: transparent; color: var(--dr-text-muted); font-family: var(--dr-font-mono); font-size: var(--dr-text-xs); font-variant-numeric: tabular-nums; letter-spacing: 0.02em; cursor: pointer; }
.status-key:hover { background: var(--dr-surface-highlight); color: var(--dr-text-primary); }
.status-key:focus-visible { outline: var(--dr-focus-ring); outline-offset: 1px; }
.status-key.on { color: var(--dr-text-secondary); }
@media (pointer: coarse) { .status-key { min-height: 44px; min-width: 44px; } }
.popover { position: absolute; right: 0; bottom: calc(100% + 0.5rem); z-index: var(--fw-z-overlay); display: flex; flex-direction: column; gap: 0.375rem; width: min(22rem, calc(100vw - 2rem)); max-height: min(30rem, calc(100dvh - 4rem)); overflow-y: auto; padding: var(--dr-space-md); border: 2px solid var(--dr-border-color-container); border-radius: var(--dr-radius); background: var(--dr-surface-secondary); box-shadow: var(--dr-shadow-offset-md), var(--dr-shadow-inner-highlight); color: var(--dr-text-primary); font-family: var(--dr-font-body); font-size: var(--dr-text-sm); line-height: 1.5; text-align: left; }
.head { display: flex; align-items: center; justify-content: space-between; gap: var(--dr-space-sm); }
.title { margin: 0; font-family: var(--dr-font-heading); font-weight: 600; font-size: var(--fw-text-2xs); letter-spacing: 0.12em; text-transform: uppercase; color: var(--dr-heading-sub); }
.close { border: 1px solid transparent; border-radius: var(--dr-radius-sm); background: transparent; color: var(--dr-text-secondary); font-size: var(--dr-text-lg); line-height: 1; cursor: pointer; padding: 0 0.25rem; }
.close:hover { background: var(--dr-surface-highlight); color: var(--dr-text-primary); }
.close:focus-visible { outline: var(--dr-focus-ring); outline-offset: 1px; }
.consent, .privacy, .note, .problem { margin: 0; font-size: var(--dr-text-xs); line-height: 1.5; }
.consent, .privacy, .note { color: var(--dr-text-muted); }
.problem { color: var(--dr-text-secondary); }
.acts, .skip { display: flex; flex-wrap: wrap; gap: var(--dr-space-sm); }
.progress { display: flex; flex-direction: column; gap: 0.125rem; padding: 0.375rem 0; border-top: 1px solid var(--dr-border-color-container); border-bottom: 1px solid var(--dr-border-color-container); }
.progress .tnum { font-family: var(--dr-font-mono); font-size: var(--dr-text-xs); color: var(--dr-text-secondary); }
.now { display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; color: var(--dr-text-secondary); }
.field-label { margin-top: var(--dr-space-xs); margin-bottom: 0; }
.field { padding: 0.25rem 0.5rem; font-size: var(--dr-text-sm); }</style>