// ── Book → multi-speaker audiobook ──────────────────────────────────────────
//
// Bridges the Read Aloud reader and the Script Rehearser: an LLM scans the
// document (in the current scope — selection / page range / whole book),
// attributes every segment to a speaker ("Narrator" or a character) with an
// emotion, then hands the result to the Script Rehearser as a cast-able script
// so each character gets its own voice. The rehearser is the editable preview:
// you fix any mis-attribution, cast voices, and synthesise there.
//
// Reuses: /api/attribute-dialogue (LLM), readerState + readerScopeIndices()
// (reader.js), parseScript / detectCharacters / rehState / rehDefaultLlmUrl
// (rehearser.js), splitTextIntoChunks (generation.js), $ / toast (utils.js).
const AUDIOBOOK_CHUNK_CHARS = 3000; // passage size per LLM attribution call
const _audiobook = { running: false, cancel: false };
// Same hue algorithm as library.js _charHue so avatar colours match across views
function _abCharHue(name) {
return Math.abs((name || '?').split('').reduce(function (h, c) { return (h * 31 + c.charCodeAt(0)) % 360; }, 0));
}
// String coercer (mirrors library.js _libStr)
function _abStr(v) {
if (v == null) return '';
if (typeof v === 'string') return v;
if (Array.isArray(v)) return v.filter(Boolean).join(', ');
return String(v);
}
// ── Autosave / draft recovery ─────────────────────────────────────────────────
// Saves the accumulated segments to localStorage after every chunk so a page
// refresh or browser crash doesn't lose hours of casting work.
const _AB_DRAFT_KEY = 'ttsvc_ab_draft';
// The book this casting session belongs to. When a saved library book is open,
// the draft is keyed by its id so reopening the SAME book always restores its
// cast — independent of any drift in the extracted text fingerprint (the old
// text-only key silently lost the cast whenever PDF re-extraction differed even
// slightly). Falls back to the global key for unsaved/ad-hoc documents.
function _abBookId() {
return (window.readerState && readerState.savedId) || _audiobook.bookId || null;
}
function _abDraftKey(bookId) {
return bookId ? (_AB_DRAFT_KEY + '_' + bookId) : _AB_DRAFT_KEY;
}
function _abTextId(text) {
// Cheap fingerprint — no need for a full hash; length + first/last chars is enough
// to detect doc changes without storing the source text itself.
const s = (text.slice(0, 300) + text.slice(-300)).replace(/\s+/g, '');
let h = 5381;
for (let i = 0; i < s.length; i++) h = (((h << 5) + h) ^ s.charCodeAt(i)) >>> 0;
return h.toString(36) + '_' + text.length;
}
function _abSaveDraft(segs, roster, text, done, total) {
const bookId = _abBookId();
const payload = {
bookId: bookId,
title: window.readerState?.title || '',
textId: _abTextId(text),
segments: segs,
roster: roster,
pageMarks: _audiobook.pageMarks || [],
rehId: _audiobook.rehId || null,
done: done,
total: total,
savedAt: Date.now()
};
try { localStorage.setItem(_abDraftKey(bookId), JSON.stringify(payload)); } catch (_) {}
// Mirror to server when a library book is open (fire-and-forget)
if (bookId) {
fetch(`/api/reader/docs/${encodeURIComponent(bookId)}/scripts/cast`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
}).catch(() => {});
}
}
async function _abLoadDraftServer(bookId) {
if (!bookId) return null;
try {
const r = await fetch(`/api/reader/docs/${encodeURIComponent(bookId)}/scripts/cast`);
if (!r.ok) return null;
const d = await r.json();
if (d && Array.isArray(d.segments) && d.segments.length) return d;
} catch (_) {}
return null;
}
function _abLoadDraft(text) {
const bookId = _abBookId();
try {
// 1. Per-book localStorage — fastest, no network
if (bookId) {
const raw = localStorage.getItem(_abDraftKey(bookId));
if (raw) {
const d = JSON.parse(raw);
if (d && Array.isArray(d.segments) && d.segments.length) return d;
}
}
// 2. Global draft (ad-hoc docs) — must match the text fingerprint
const raw = localStorage.getItem(_AB_DRAFT_KEY);
if (!raw) return null;
const d = JSON.parse(raw);
if (!d || !Array.isArray(d.segments) || !d.segments.length) return null;
if (d.textId !== _abTextId(text)) return null;
return d;
} catch (_) { return null; }
}
function _abClearDraft() {
const bookId = _abBookId();
try { localStorage.removeItem(_abDraftKey(bookId)); } catch (_) {}
if (bookId) {
fetch(`/api/reader/docs/${encodeURIComponent(bookId)}/scripts/cast`, { method: 'DELETE' }).catch(() => {});
}
}
// Opening/closing quote glyphs across book conventions: English "..."/“...”,
// German »...«/„...“, French «...», single ‘...’/›...‹, CJK 「...」『...』, em-dash speech.
const AB_DIALOGUE_RE = /[«»„“”"‟‚‘’›‹『「<]|(?:^|\n)\s*[—–]\s/;
function audiobookHasDialogue(t) { return AB_DIALOGUE_RE.test(t || ''); }
// Join words hyphenated across a PDF line break ("Schwer- tes" → "Schwertes")
// so the audiobook reads cleanly and speaker tags aren't split.
function audiobookDehyphenate(t) { return (t || '').replace(/([a-zäöüß])-\s+(?=[a-zäöüßA-ZÄÖÜ])/g, '$1'); }
// Speech-tag heuristic so the book still casts with REAL names when the LLM is down.
const AB_SPEECH_VERBS = '(?:sagte|fragte|rief|antwortete|erwiderte|entgegnete|meinte|flüsterte|wisperte|raunte|murmelte|brummte|knurrte|brüllte|schrie|stammelte|fauchte|zischte|seufzte|lachte|kicherte|befahl|wiederholte|fuhr\\s+fort|said|asked|replied|answered|whispered|murmured|muttered|shouted|cried|called|exclaimed|added|continued)';
const AB_NOTNAME = new Set([
'Der', 'Die', 'Das', 'Den', 'Dem', 'Ein', 'Eine', 'Einen', 'Er', 'Sie', 'Es', 'Ich', 'Du', 'Wir', 'Ihr', 'Man',
'Und', 'Aber', 'Da', 'Dann', 'Doch', 'So', 'Nun', 'Jetzt', 'The', 'He', 'She', 'It', 'They', 'A', 'An', 'And', 'But', 'Then', 'Now',
// common sentence-initial adverbs / interjections / abstractions that are NOT characters
'Sofort', 'Plötzlich', 'Endlich', 'Schließlich', 'Stille', 'Schweigen', 'Stimme', 'Stimmen', 'Frage', 'Antwort',
'Gelächter', 'Wieder', 'Gleich', 'Sogleich', 'Langsam', 'Leise', 'Laut', 'Kaum', 'Vielleicht', 'Natürlich', 'Wirklich',
'Ja', 'Nein', 'Komm', 'Warte', 'Halt', 'Geh', 'Hier', 'Dort', 'Oben', 'Unten', 'Schon', 'Noch', 'Auch', 'Nur', 'Immer', 'Nie']);
const _AB_NAME = "([A-ZÄÖÜ][A-Za-zäöüß'\\-]+)";
function audiobookGuessSpeaker(after, before) {
let m;
const ok = n => (n && !AB_NOTNAME.has(n)) ? n : null;
// NOTE: no 'i' flag — names must be genuinely capitalized; German speech verbs
// after a quote are lowercase, so this rejects pronouns like "sagte er".
// after the quote: ", sagte Riskan" / "sagte Riskan" (verb → name)
if ((m = new RegExp('^[\\s,;–-]*' + AB_SPEECH_VERBS + '\\s+(?:der|die|das|ein|eine)?\\s*' + _AB_NAME).exec(after || ''))) { const r = ok(m[1]); if (r) return r; }
// after the quote: ", Riskan sagte" (name → verb)
if ((m = new RegExp('^[\\s,;–-]*' + _AB_NAME + '\\s+' + AB_SPEECH_VERBS).exec(after || ''))) { const r = ok(m[1]); if (r) return r; }
// before the quote: "Riskan sagte:" / "Riskan fragte"
if ((m = new RegExp(_AB_NAME + '\\s+' + AB_SPEECH_VERBS + '[\\s:,–-]*$').exec(before || ''))) { const r = ok(m[1]); if (r) return r; }
return null;
}
// Deterministic fallback: split a passage into narration + dialogue by quotation
// spans and attribute speakers from the surrounding speech tags. Used when the LLM
// is unavailable so dialogue — and as many speakers as possible — are never lost.
const AB_QUOTE_SPAN = /»([^«]+)«|«([^»]+)»|„([^“”]+)[“”]|“([^”]+)”|"([^"]+)"|「([^」]+)」|『([^』]+)』/g;
function audiobookSplitByQuotes(text) {
const spans = []; let m;
AB_QUOTE_SPAN.lastIndex = 0;
while ((m = AB_QUOTE_SPAN.exec(text))) {
spans.push({ start: m.index, end: AB_QUOTE_SPAN.lastIndex, quote: (m[1] || m[2] || m[3] || m[4] || m[5] || m[6] || m[7] || '').trim() });
}
if (!spans.length) return [{ speaker: 'Narrator', type: 'narration', text, emotion: '' }];
const out = []; let last = 0;
for (let k = 0; k < spans.length; k++) {
const sp = spans[k];
const pre = text.slice(last, sp.start);
if (pre.trim()) out.push({ speaker: 'Narrator', type: 'narration', text: pre.trim(), emotion: '' });
if (sp.quote) {
const after = text.slice(sp.end, k + 1 < spans.length ? spans[k + 1].start : text.length);
const speaker = audiobookGuessSpeaker(after, pre) || 'Unknown';
out.push({ speaker, type: 'dialogue', text: sp.quote, emotion: '' });
}
last = sp.end;
}
const tail = text.slice(last).trimEnd();
if (tail) {
// If the tail starts with an unclosed opening quote (PDF line-break cut it off),
// treat the quoted portion as dialogue rather than narrator.
const unclosed = tail.match(/^([\s\S]*?)(»)([\s\S]+)$/);
if (unclosed && !tail.includes('«')) {
if (unclosed[1].trim()) out.push({ speaker: 'Narrator', type: 'narration', text: unclosed[1].trim(), emotion: '' });
const speaker = audiobookGuessSpeaker('', unclosed[1]) || 'Unknown';
out.push({ speaker, type: 'dialogue', text: unclosed[3].trim(), emotion: '' });
} else if (tail.trim()) {
out.push({ speaker: 'Narrator', type: 'narration', text: tail.trim(), emotion: '' });
}
}
return audiobookTurnTaking(out);
}
// Fill 'Unknown' dialogue speakers by two-person alternation — but only once TWO
// distinct named speakers are established nearby (conservative: won't guess in a
// monologue, so it rarely invents a wrong name).
function audiobookTurnTaking(segs) {
let a = null, b = null; // two most recent distinct named speakers (b = latest)
for (const s of segs) {
if (s.type !== 'dialogue') continue;
if (s.speaker && !/^Unknown|Unbekannt/i.test(s.speaker)) {
if (s.speaker !== b) { a = b; b = s.speaker; }
} else if (a && b && a !== b) {
s.speaker = a; // the other of the two → alternate
const t = a; a = b; b = t; // rotate so the next Unknown alternates back
}
}
return segs;
}
function audiobookLlmUrl() { return $('reh-llm-url')?.value.trim() || (typeof rehDefaultLlmUrl === 'function' ? rehDefaultLlmUrl() : ''); }
function audiobookLlmModel() { return $('reh-llm-model')?.value || ''; }
function audiobookLang() { return $('reh-design-lang')?.value || ''; }
// Gather the plain text of the current reader scope (selection > page range > all).
// Also records PDF page boundaries as character offsets in the returned text
// (_audiobook.pageMarks) so saving to the Rehearser can reconstruct page breaks.
function audiobookScopeText() {
_audiobook.pageMarks = [];
if (typeof readerScopeIndices !== 'function' || !readerState?.sentences?.length) return '';
const idxs = readerScopeIndices();
const anchors = []; // {page, anchor} — first sentence of each new page
let lastPage = null;
for (const i of idxs) {
const u = readerState.sentences[i];
const pg = u?.words?.[0]?.page;
if (pg != null && pg !== lastPage) {
anchors.push({ page: pg, anchor: (u.text || '').trim().slice(0, 40) });
lastPage = pg;
}
}
const raw = idxs.map(i => readerState.sentences[i].text).join(' ').replace(/\s+/g, ' ').trim();
const text = audiobookDehyphenate(raw); // mend PDF line-break hyphenation for clean speech + tag matching
// Locate each page anchor in the final text → page-break offsets.
let from = 0;
for (const a of anchors) {
const probe = audiobookDehyphenate(a.anchor).slice(0, 24);
if (!probe) continue;
const pos = text.indexOf(probe, from);
if (pos >= 0) { _audiobook.pageMarks.push({ offset: pos, page: a.page }); from = pos; }
}
return text;
}
// ── Progress overlay ─────────────────────────────────────────────────────────
function audiobookProgress(total) {
let ov = document.getElementById('audiobook-overlay');
if (!ov) {
ov = document.createElement('div');
ov.id = 'audiobook-overlay';
ov.className = 'audiobook-overlay';
ov.innerHTML = `
Casting audiobook
Analysing…
`;
document.body.appendChild(ov);
ov.querySelector('#audiobook-cancel').addEventListener('click', () => { _audiobook.cancel = true; });
}
ov.hidden = false;
const fill = ov.querySelector('#audiobook-fill');
const msg = ov.querySelector('#audiobook-msg');
return {
update(done, label) { if (fill) fill.style.width = (done / total * 100) + '%'; if (msg && label) msg.textContent = label; },
done() { ov.hidden = true; },
};
}
const _AB_PALETTE = ['#3b82f6', '#10b981', '#8b5cf6', '#f59e0b', '#ef4444', '#ec4899', '#06b6d4', '#84cc16', '#f97316', '#14b8a6', '#6366f1', '#d946ef'];
// Escape a segment's text and underline any known character names. Module-level
// so the review/preview overlay (audiobookShowPreview) can use it too — the cast
// view (audiobookCastView) defines its own roster-coloured version that shadows
// this inside its closure. Names default to the current run's roster.
function highlightText(text, names) {
if (!text) return '';
let html = escHtml(text);
const list = (names || (_audiobook && _audiobook.roster) || [])
.filter(n => n && n.toLowerCase() !== 'narrator' && !/^Unknown|Unbekannt/i.test(n))
.sort((a, b) => b.length - a.length);
list.forEach((name, idx) => {
if (name.length < 2) return;
const safe = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const color = _AB_PALETTE[idx % _AB_PALETTE.length];
html = html.replace(new RegExp(`\\b(${safe})\\b`, 'gi'),
m => `${m}`);
});
return html;
}
// Live casting view: a scrolling feed of attributed lines + a character roster
// that fills up as speakers are discovered. Far clearer than a bare bar.
function audiobookCastView(total, llmUrl, defaultModel, isIdle = false) {
const panel = document.getElementById('reader-audiobook-panel');
if (!panel) return;
if (typeof window.navReaderView === 'function') window.navReaderView('cast');
else if (typeof window.showReaderView === 'function') window.showReaderView('cast');
else {
const mainView = document.getElementById('reader-main-view');
if (mainView) mainView.hidden = true;
panel.hidden = false;
}
panel.className = 'ab-castpanel-inline card';
panel.style.display = '';
panel.style.flexDirection = '';
panel.style.minHeight = '';
panel.innerHTML = `
Casting audiobookpassage 0 / ${total}
Characters found
${[38,62,45,28,54,35].map(w => `
`).join('')}
Ready to cast.
`;
const AB_DEFAULT_PROMPT = `Du bist ein erfahrener Drehbuchautor und Hörbuch-Regisseur. Deine Aufgabe ist es, einen Auszug aus einem deutschen Roman zu analysieren und ihn perfekt in einzelne Segmente für Erzähler und Dialoge (wörtliche Rede) zu unterteilen.
WICHTIGE DEFINITION VON DIALOG:
Text ist NUR dann 'dialogue', wenn er explizit in Anführungszeichen steht (z.B. »...«, „...“, "...", «...», <<...>>) oder mit einem Gedankenstrich (—) beginnt. ALLES ANDERE, einschließlich Handlungsbeschreibungen (Inquit-Formeln), inneren Gedanken und Beschreibungen, MUSS als 'narration' (Erzähler) deklariert werden.
Markiere Text NIEMALS als Dialog, nur weil der Name eines Charakters erwähnt wird! (z.B. "Karyla rannte zur Tür." ist Narration, KEIN Dialog).
ANALYSE-REGELN FÜR DIE ZUORDNUNG DES SPRECHERS (Sei deduktiv):
1. Direkte Zuordnung: Achte auf Wörter wie "sagte [Name]", "fragte er", "rief sie". Löse Pronomen (er/sie) zum tatsächlichen Namen auf.
2. Handlungs-Hinweise (Action Beats): Wenn ein Charakter eine Handlung ausführt und direkt davor/danach wörtliche Rede steht, spricht meist dieser Charakter (z.B. "Thomas trat ans Fenster. »Es regnet.«").
3. Das Ping-Pong-Prinzip: Wenn zwei Personen sprechen, wechseln sie sich ab. Verfolge diese Kette lückenlos zurück zur letzten eindeutigen Nennung.
4. Gruppen-Dialoge (3+ Personen): An wen richtet sich die Aussage? Passt die Aussage zum Wissen oder Tonfall eines bestimmten Charakters?
5. Wiederverwendung: Nutze EXAKT die Namen aus der Liste der bekannten Charaktere, FALLS der Name dort aufgeführt ist. Wenn ein neuer Charakter spricht, extrahiere seinen Namen direkt aus dem Text (z.B. 'Karyla', 'Uriens').
6. Unbekannte Sprecher: Nur wenn eine Zuordnung durch Kontext absolut nicht möglich ist, verwende 'Unknown'. Rate nicht blind, aber bevorzuge immer einen namentlich genannten Charakter gegenüber 'Unknown'.
FÜR JEDES SEGMENT GIBST DU FOLGENDES AUS:
- speaker: 'Narrator' für Narration/Erzählertext, oder den EXAKTEN Namen des Charakters für gesprochene Dialoge.
- type: 'narration' oder 'dialogue'
- text: Der EXAKTE, wortwörtliche Text aus dem Auszug. Bei 'dialogue' ENTFERNST du die umschließenden Anführungszeichen.
- emotion: Bei Dialogen 1-2 deutsche Wörter, die den Tonfall beschreiben (z.B. wütend, flüsternd, ängstlich). Bei Narration leer lassen ('').
STRIKTE FORMAT- UND TEXTREGELN:
- Mische NIEMALS Narration und Dialog im selben Segment! Trenne sie strikt. Wenn ein Zitat durch eine Handlungsanweisung unterbrochen wird (»Nein«, sagte sie, »halt.«), erstelle 3 Segmente: dialogue ("Nein"), narration (", sagte sie, "), dialogue ("halt.").
- »Text?« und »Text!« sind vollständige Dialoge — das ?« bzw. !« schließt das Zitat ab, auch wenn es ungewohnt aussieht.
- Wenn ein Auszug mit einem offenen »-Zitat endet (kein schließendes «), behandle den Text ab » bis Textende als 'dialogue'.
- Lasse NIEMALS Wörter aus, fasse nicht zusammen, dupliziere nichts und erfinde keinen Text. Der kombinierte Text all deiner Segmente MUSS den Originaltext exakt und lückenlos Wort für Wort rekonstruieren!`;
const globalPrompt = (typeof _appSettings !== 'undefined' && _appSettings.audiobook_prompt) ? _appSettings.audiobook_prompt : AB_DEFAULT_PROMPT;
panel.querySelector('#ab-cv-prompt-text').value = globalPrompt;
const closePanel = () => {
panel.hidden = true;
panel.innerHTML = '';
if (typeof window.setNavCastingBadge === 'function') window.setNavCastingBadge(false);
if (typeof window.navReaderView === 'function') window.navReaderView('main');
else if (typeof window.showReaderView === 'function') window.showReaderView('main');
else {
const mv = document.getElementById('reader-main-view');
if (mv) mv.hidden = false;
}
};
const setStoppingState = () => {
const cancelBtn = panel.querySelector('#ab-cv-cancel');
if (cancelBtn) {
cancelBtn.disabled = true;
cancelBtn.innerHTML = ' Stopping...';
cancelBtn.title = 'Stopping the current casting request';
}
const status = panel.querySelector('#ab-cv-status-msg');
if (status) {
status.style.display = 'inline-block';
status.textContent = 'Stopping... completed passages will stay saved.';
}
};
panel.querySelector('#ab-cv-cancel').addEventListener('click', () => {
if (_audiobook.running) {
_audiobook.cancel = true;
setStoppingState();
if (typeof _audiobook.abort === 'function') _audiobook.abort();
return;
}
closePanel();
});
panel.querySelector('#ab-cv-prompt-btn').addEventListener('click', () => {
const p = panel.querySelector('#ab-cv-prompt-panel');
p.hidden = !p.hidden;
const chevron = panel.querySelector('#ab-cv-prompt-chevron');
if (chevron) {
chevron.className = p.hidden ? 'mdi mdi-chevron-down' : 'mdi mdi-chevron-up';
}
});
// Collapse the whole settings block (LLM engine + prompt) to free vertical space.
(function () {
const tBtn = panel.querySelector('#ab-cv-settings-toggle');
const sBox = panel.querySelector('#ab-cv-settings');
const chev = panel.querySelector('#ab-cv-settings-chevron');
function apply(collapsed) {
if (sBox) sBox.style.display = collapsed ? 'none' : 'flex';
if (collapsed) { const p = panel.querySelector('#ab-cv-prompt-panel'); if (p) p.hidden = true; }
if (chev) chev.className = 'mdi ' + (collapsed ? 'mdi-chevron-down' : 'mdi-chevron-up');
}
let collapsed = false;
try { collapsed = localStorage.getItem('ttsvc_ab_settings_collapsed') === '1'; } catch (_) {}
apply(collapsed);
if (tBtn) tBtn.addEventListener('click', () => {
collapsed = !collapsed;
try { localStorage.setItem('ttsvc_ab_settings_collapsed', collapsed ? '1' : '0'); } catch (_) {}
apply(collapsed);
});
})();
// Prompt Library logic
let savedPrompts = [];
try { savedPrompts = JSON.parse(localStorage.getItem('ttsvc_ab_prompts') || '[]'); } catch (_) { savedPrompts = []; }
const libSelect = panel.querySelector('#ab-cv-prompt-lib');
const delBtn = panel.querySelector('#ab-cv-prompt-del');
const promptText = panel.querySelector('#ab-cv-prompt-text');
const renderPromptLib = (selectedIdx = -1) => {
libSelect.innerHTML = '' +
savedPrompts.map((p, i) => ``).join('');
if (selectedIdx >= 0) {
libSelect.value = selectedIdx;
delBtn.style.display = 'block';
} else {
libSelect.value = '';
delBtn.style.display = 'none';
}
};
renderPromptLib();
libSelect.addEventListener('change', () => {
const idx = parseInt(libSelect.value);
const nameInput = panel.querySelector('#ab-cv-prompt-name');
if (!isNaN(idx) && savedPrompts[idx]) {
promptText.value = savedPrompts[idx].prompt;
if (nameInput) nameInput.value = savedPrompts[idx].name;
delBtn.style.display = 'block';
} else {
if (nameInput) nameInput.value = '';
delBtn.style.display = 'none';
}
});
delBtn.addEventListener('click', () => {
const idx = parseInt(libSelect.value);
if (isNaN(idx)) return;
if (confirm('Delete this saved prompt preset?')) {
savedPrompts.splice(idx, 1);
localStorage.setItem('ttsvc_ab_prompts', JSON.stringify(savedPrompts));
renderPromptLib();
toast('Prompt deleted', 'success');
}
});
panel.querySelector('#ab-cv-prompt-save').addEventListener('click', async () => {
const val = promptText.value.trim();
if (!val) { toast('Prompt is empty', 'error'); return; }
const nameInput = panel.querySelector('#ab-cv-prompt-name');
const name = nameInput.value.trim() || 'Custom Prompt ' + (savedPrompts.length + 1);
let targetIdx = parseInt(libSelect.value);
if (!isNaN(targetIdx) && savedPrompts[targetIdx] && savedPrompts[targetIdx].name === name) {
savedPrompts[targetIdx].prompt = val;
} else {
savedPrompts.push({ name, prompt: val });
targetIdx = savedPrompts.length - 1;
}
localStorage.setItem('ttsvc_ab_prompts', JSON.stringify(savedPrompts));
renderPromptLib(targetIdx);
toast('Prompt preset saved', 'success');
// Also save as global default for next time
if (typeof _appSettings !== 'undefined') _appSettings.audiobook_prompt = val;
try { await fetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ audiobook_prompt: val }) }); } catch (e) {}
});
// Sync the LLM engine dropdown with global options
const syncEngineSelect = () => {
const localSel = panel.querySelector('#ab-cv-llm-url');
const globalSel = document.getElementById('llm-active-url');
if (globalSel && localSel) {
const currentVal = localSel.value;
localSel.innerHTML = globalSel.innerHTML;
localSel.value = currentVal || globalSel.value || '';
}
};
syncEngineSelect();
// Fetch available models and populate the select drop-down
const loadModels = () => {
const urlInput = panel.querySelector('#ab-cv-llm-url');
const sel = panel.querySelector('#ab-cv-llm-select');
if (!sel || !urlInput) return;
const currentUrl = urlInput.value.trim();
const oldVal = sel.value;
sel.innerHTML = '';
fetch('/api/conversation/llm-models' + (currentUrl ? '?url=' + encodeURIComponent(currentUrl) : ''))
.then(r => r.json())
.then(d => {
if (d.models && d.models.length) {
sel.innerHTML = d.models.map(m => ``).join('');
if (oldVal && d.models.includes(oldVal)) sel.value = oldVal;
else if (d.models.includes(defaultModel)) sel.value = defaultModel;
} else {
sel.innerHTML = ``;
}
}).catch(() => {
sel.innerHTML = ``;
});
};
loadModels();
panel.querySelector('#ab-cv-llm-refresh').addEventListener('click', loadModels);
const urlInput = panel.querySelector('#ab-cv-llm-url');
if (urlInput) urlInput.addEventListener('change', loadModels);
const applyPromptAndRun = (callback) => {
const newPrompt = panel.querySelector('#ab-cv-prompt-text').value;
const currentUrl = panel.querySelector('#ab-cv-llm-url')?.value.trim();
const currentModel = panel.querySelector('#ab-cv-llm-select')?.value;
if (typeof _appSettings !== 'undefined') _appSettings.audiobook_prompt = newPrompt;
fetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ audiobook_prompt: newPrompt }) })
.finally(() => {
if (callback) callback(currentUrl, currentModel);
});
};
if (isIdle) {
const hasSegs = _audiobook.segments && _audiobook.segments.length > 0;
panel.querySelector('#ab-cv-status-msg').style.display = 'inline-block';
if (hasSegs) {
const recastUnkBtn = panel.querySelector('#ab-cv-start-recast-unk');
const recastBtn = panel.querySelector('#ab-cv-start-recast');
recastUnkBtn.style.display = 'inline-block';
recastBtn.style.display = 'inline-block';
recastUnkBtn.addEventListener('click', () => applyPromptAndRun(audiobookRecastUnknown));
recastBtn.addEventListener('click', () => applyPromptAndRun(audiobookCast));
panel.querySelector('#ab-cv-status-msg').textContent = 'Ready to recast.';
} else {
const castBtn = panel.querySelector('#ab-cv-start-cast');
castBtn.style.display = 'inline-block';
castBtn.addEventListener('click', () => applyPromptAndRun(audiobookCast));
}
} else {
panel.querySelector('#ab-cv-cancel').innerHTML = ' Stop Casting';
}
const fill = panel.querySelector('#ab-cv-fill'), count = panel.querySelector('#ab-cv-count');
const feed = panel.querySelector('#ab-cv-feed'), chars = panel.querySelector('#ab-cv-chars');
const roster = new Map(); // name -> { count, color }
const colorFor = name => {
if (!roster.has(name)) roster.set(name, { count: 0, color: _AB_PALETTE[roster.size % _AB_PALETTE.length] });
return roster.get(name).color;
};
const highlightText = (text) => {
if (!text) return '';
let html = escHtml(text);
const names = [...roster.keys()]
.filter(n => n.toLowerCase() !== 'narrator' && !/^Unknown|Unbekannt/i.test(n))
.sort((a, b) => b.length - a.length);
for (const name of names) {
if (name.length < 2) continue;
const safeName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`\\b(${safeName})\\b`, 'gi');
html = html.replace(regex, (match) => {
return `${match}`;
});
}
return html;
};
// ── Character selection bar ────────────────────────────────────────────────
// Clicking a character shows a compact bar above the feed with avatar, name,
// prev/next line navigation, a search box, and a "Profil" button that opens
// the full character sheet (hiding the feed temporarily).
const feedWrap = panel.querySelector('.ab-cv-feed-wrap');
const jumpBtn = panel.querySelector('#ab-cv-jump-btn');
// Insert bar above the feed (once)
const _abBar = document.createElement('div');
_abBar.className = 'ab-char-bar';
_abBar.hidden = true;
feedWrap.insertBefore(_abBar, feedWrap.firstChild);
let _abCharRows = []; // rows in feed for selected character
let _abNavIdx = 0;
let _abDetailEl = null; // full profile panel (when Profil is open)
const _abClearHL = () => {
feed.querySelectorAll('.ab-cv-row.ab-char-hl, .ab-cv-row.ab-char-focus')
.forEach(r => r.classList.remove('ab-char-hl', 'ab-char-focus'));
};
const _abCloseProfile = () => {
if (_abDetailEl) { _abDetailEl.remove(); _abDetailEl = null; }
feed.style.display = '';
if (jumpBtn && typeof _userScrolled !== 'undefined') jumpBtn.hidden = !_userScrolled;
_abCharRows.forEach(r => r.classList.add('ab-char-hl'));
const btn = _abBar.querySelector('.ab-char-bar-profile');
if (btn) btn.innerHTML = ' Profil';
};
const _abCloseBar = () => {
_abBar.hidden = true;
_abBar.innerHTML = '';
_abCloseProfile();
_abClearHL();
_abCharRows = [];
chars.querySelectorAll('.ab-char-item').forEach(el => el.classList.remove('is-active'));
};
const _abNav = (dir, pool) => {
const rows = pool || _abCharRows;
if (!rows.length) return;
_abNavIdx = ((_abNavIdx + dir) + rows.length) % rows.length;
feed.querySelectorAll('.ab-cv-row.ab-char-focus').forEach(r => r.classList.remove('ab-char-focus'));
rows[_abNavIdx].classList.add('ab-char-focus');
rows[_abNavIdx].scrollIntoView({ behavior: 'smooth', block: 'center' });
const pos = _abBar.querySelector('.ab-char-bar-pos');
if (pos) pos.textContent = (_abNavIdx + 1) + ' / ' + rows.length;
};
// Open the full character profile (hides feed)
const _abShowProfile = async (name) => {
_abCloseProfile();
feed.style.display = 'none';
if (jumpBtn) jumpBtn.hidden = true;
const profileBtn = _abBar.querySelector('.ab-char-bar-profile');
if (profileBtn) profileBtn.innerHTML = ' Skript';
const title = window.readerState?.title || '';
let rec = null;
try {
const all = typeof clGetAllByTagOrBook === 'function'
? await clGetAllByTagOrBook(title)
: (typeof clGetAll === 'function' ? await clGetAll() : []);
rec = all.find(r => (r.name || '').toLowerCase() === name.toLowerCase());
} catch (_) {}
const detail = document.createElement('div');
detail.className = 'ab-char-detail-panel';
_abDetailEl = detail;
if (!rec) {
detail.innerHTML = ''
+ '
Kein Charakterblatt – zuerst „Cast Characters" ausführen.