Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221/** * The browser's speech engine reads one utterance at a time. A single long * utterance stops early in desktop Chrome, and line breaks disappear, so the * scene becomes sentence-sized chunks and every block stays separate. */
import { sanitiseBody } from '#lib/body.ts';
export const MAX_SPEECH_CHARS = 140;
export interface SpeechEngine { readonly speaking: boolean; readonly paused: boolean; speak(utterance: SpeechSynthesisUtterance): void; cancel(): void; pause(): void; resume(): void;}
type DocNode = { type?: string; text?: string; content?: DocNode[];};
/** * `Intl.Segmenter` splits after `Mr.` and after an initial, so those pieces are * joined again. A wrong split adds an audible pause in the middle of a name; a * wrong join only makes one utterance longer. */const ABBREVIATION = /(?:\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|St|vs|etc|No|Vol|Ch|Fig|Ave|Rd|Mt|Ft)\.$|^(?:[A-Z]\.\s*)+$|(?:\b[A-Z]\.){2,}$|e\.g\.$|i\.e\.$)/;
export function speechChunks(body: unknown, maxChars = MAX_SPEECH_CHARS): string[] { const limit = Math.max(1, Math.floor(maxChars)); const chunks: string[] = [];
for (const block of blocks(body)) { for (const sentence of sentences(block)) { for (const piece of splitLong(sentence, limit)) { const text = piece.trim();
if (text.length > 0) chunks.push(text); } } }
return chunks;}
export function speechSupported(): boolean { return ( typeof window !== 'undefined' && typeof window.speechSynthesis === 'object' && window.speechSynthesis !== null && typeof SpeechSynthesisUtterance !== 'undefined' );}
export function browserSpeechEngine(): SpeechEngine | null { return speechSupported() ? window.speechSynthesis : null;}
export function preferredLanguage(): string { if (typeof document !== 'undefined' && document.documentElement.lang.length > 0) { return document.documentElement.lang; }
if (typeof navigator !== 'undefined' && navigator.language.length > 0) return navigator.language;
return 'en';}
export function sameLanguage(a: string, b: string): boolean { const primary = (tag: string) => tag.toLowerCase().split(/[-_]/)[0] ?? '';
return primary(a).length > 0 && primary(a) === primary(b);}
/** A voice that stays on the device and matches the page's language. */export function localVoiceFor( voices: readonly SpeechSynthesisVoice[], language: string): SpeechSynthesisVoice | null { const local = voices.filter((voice) => voice.localService && sameLanguage(voice.lang, language));
return local.find((voice) => voice.default) ?? local[0] ?? null;}
function blocks(body: unknown): string[] { const doc = sanitiseBody(body); if (!doc) return [];
const found: string[] = [];
for (const child of doc.content) walk(child, found);
return found;}
function walk(node: DocNode, found: string[]) { switch (node.type) { case 'paragraph': case 'heading': case 'codeBlock': case 'text': pushText(node, found); return;
case 'horizontalRule': return;
default: if (Array.isArray(node.content) && node.content.some(isBlock)) { for (const child of node.content) walk(child, found); } else { pushText(node, found); } }}
function isBlock(node: DocNode): boolean { return ( node.type === 'paragraph' || node.type === 'heading' || node.type === 'blockquote' || node.type === 'bulletList' || node.type === 'orderedList' || node.type === 'listItem' || node.type === 'codeBlock' || node.type === 'horizontalRule' );}
function pushText(node: DocNode, found: string[]) { const text = textOf(node).replace(/\s+/g, ' ').trim();
if (text.length > 0) found.push(text);}
function textOf(node: DocNode): string { if (typeof node.text === 'string') return node.text; if (node.type === 'hardBreak') return ' '; if (!Array.isArray(node.content)) return '';
return node.content.map(textOf).join('');}
function sentences(text: string): string[] { const parts = segment(text); const merged: string[] = [];
for (const part of parts) { const sentence = part.trim();
if (sentence.length === 0) continue;
const previous = merged.at(-1);
if (previous && ABBREVIATION.test(previous)) { merged[merged.length - 1] = `${previous} ${sentence}`; } else { merged.push(sentence); } }
return merged;}
function segment(text: string): string[] { if (typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function') { const segmenter = new Intl.Segmenter(undefined, { granularity: 'sentence' });
return Array.from(segmenter.segment(text), (part) => part.segment); }
return text.match(/[^.!?…]+(?:[.!?…]+["'”’)\]]*|$)/g) ?? [text];}
function splitLong(text: string, maxChars: number): string[] { const pieces: string[] = []; let rest = text;
while (rest.length > maxChars) { let cut = rest.lastIndexOf(' ', maxChars);
if (cut <= 0) cut = maxChars;
// Keep a surrogate pair together; a split inside one is not a character. if (isHighSurrogate(rest[cut - 1]) && isLowSurrogate(rest[cut])) cut -= 1;
if (cut <= 0) cut = Math.min(2, rest.length);
const piece = rest.slice(0, cut).trim();
if (piece.length > 0) pieces.push(piece);
rest = rest.slice(cut).trim(); }
if (rest.length > 0) pieces.push(rest);
return pieces;}
function isHighSurrogate(value: string | undefined): boolean { if (!value) return false;
const code = value.charCodeAt(0);
return code >= 0xd800 && code <= 0xdbff;}
function isLowSurrogate(value: string | undefined): boolean { if (!value) return false;
const code = value.charCodeAt(0);
return code >= 0xdc00 && code <= 0xdfff;}