feat(stories): timeline dock with speaker tracks and a following playhead (#4606)

* feat(stories): screenplay-style script editor with timecodes and icon controls

- Lines show an estimated start time and the speaker in a gutter, named only
  when the speaker changes; characters get a colour bar, the narrator stays
  neutral.
- Voice and speed chips appear under a line only when it overrides them;
  defaults live in the hover toolbar.
- Auto-cast no longer invents speakers from one-off "Phrase: text" labels or
  from pronouns ("she said" goes to the last named speaker), and its panel
  folds away after a successful cast.
- Script and speed controls use icons with tooltips instead of text buttons
  and help paragraphs; Cover and Loudness match the other setup sections.

* changelog: add fragment for #4605

* feat(stories): timeline dock with speaker tracks and a following playhead

- A dock pinned under the script holds the last render's play bar and one
  track per speaker, each line a clip. Clicking a clip selects its line and
  moves the playhead there; the ruler and lanes seek on click; zoom with the
  buttons or +/-.
- Clip positions and the gutter timecodes come from the render's real chapter
  durations (or its total length) once there is one, and from the word-rate
  estimate before; the dock says when positions are estimates.
- The script highlights the line being played.
- The runtime under the script matches the timeline, including per-line
  speeds.

* test(longform): check the script instructions behind their info button

* changelog: add fragment for #4606

* fix(stories): stop casting determiners and offer to fold old pronoun speakers

- "said our host" / "her mother replied" name the noun, not the determiner,
  so auto-cast no longer creates speakers like "Our".
- Stories auto-cast before the pronoun fix kept members such as "She", "He"
  and "I". The script now names them and offers one click to remove them and
  give their lines to the last named speaker (first person to the narrator),
  keeping each line's own voice override.

* fix(stories): make the timeline readable on long stories

- Lay the tracks out in pixels with the ruler pinned to the top and speaker
  names pinned to the left, so both stay in view while scrolling.
- Clips too narrow to read show only their colour instead of a cut-off "L…";
  the full line stays in the tooltip and accessible name.
- Ruler labels keep about 90 px apart at any zoom; zoom goes up to 32x and the
  view follows the playhead.
- The track area can be resized from a handle (mouse or arrow keys); the
  height is remembered and the area never pads past its tracks.

* perf(stories): keep long scripts fast and add a line inspector

- A keystroke re-rendered and re-measured every line: about 2 s per key in a
  400-line story. Rows are now memoised (their handlers read the current
  draft through a ref, so a skipped render can't write stale lines) and
  off-screen rows skip layout with content-visibility. Typing drops to
  ~35 ms of script work per key; first load halves.
- A right-hand inspector shows the selected line's timing, speaker, voice and
  speed, editable in place, or a per-speaker line/runtime summary.
- The Stories editor uses the full window width instead of max-w-6xl.
- The "older saved result" notice becomes a one-line row with its detail
  in an info tooltip, instead of a large card in the sidebar footer.

* fix(stories): address review findings on the screenplay editor

- A pronoun after a screenplay label ("BOB: Hi." then "he said") now refers
  to that speaker instead of an earlier prose one.
- Consecutive legacy lines stored with no speaker read as one speaker.
- Folding pronoun cast members also reassigns chapter markers that named
  them, without a chapter counting as the last named speaker.
- The speed popup stays open while a line's first speed is set; the chip
  moves under the text only after the popup closes.
- Disabled icon actions stay focusable so their tooltip still names them.
- The book speed explanation is a keyboard-reachable info button.

* fix(stories): address review findings on the timeline

- A render's timing maps only onto the script it was made from: renders now
  save a timing key of the lines, and after edits the timeline falls back to
  estimates and stops linking clips and highlights to the audio.
- [pause] markers count as silence, so pause-only lines and chapters keep
  their place on the timeline.
- A failed chapter takes no time; a partial render without per-chapter
  durations is not spread over the whole script.
- The time grid runs left to right in right-to-left languages, so the
  playhead lines up with clips and ruler.
- Resize drags use pointer capture and end on cancel, lost capture or unmount.
- The inspector keeps an explicit unassigned speaker choice.
- A failed saved-audio check is shown, not only announced.
- Off-screen rows skip layout per column, so the hover toolbar isn't clipped.

* feat(stories): clip waveforms, playback keys and changed-line markers

- Clips show the render's waveform. A new GET /audio-peaks/{name} decodes a
  saved output with ffmpeg at 1 kHz mono and returns its loudness outline,
  cached per file version, so a long render costs the browser nothing.
- Editing-suite keys on the Stories page: Space play/pause, J back 5 s,
  K pause, L play (again for faster), Home/End. Ignored in fields and with
  modifiers; listed in an info button.
- Renders save a fingerprint per line, so lines edited, re-cast, re-timed or
  added since the render get a marker, and the timeline counts them.
- The line toolbar shows on hover or when focus enters it, not while typing,
  and sits inside the row. Rows skip layout off-screen again (column-level
  skipping laid out every toolbar: 224 ms vs 111 ms per key in 400 lines).

* feat(stories): pick any gallery voice from the Stories voice lists

The cast, line and inspector voice lists only offered saved voices, so a
gallery voice took a trip to the Gallery page. They now share one picker:
a search box over the default, your voices and the whole Voice Gallery.
Your voices filter as you type; the gallery is searched on the backend,
loads 60 at a time as the list scrolls, and long lists mount only the rows
in view. Picking a gallery voice saves it to your voices (reusing an
earlier copy) and assigns the saved voice. Arrow keys and Enter pick.

* feat(stories): rework the paste box into "Add lines from text"

The panel was titled after a button ("Auto-cast"), its placeholder promised
sentence splitting whatever the mode, and both actions hid behind a button,
a scissors icon and two info tips.

- Heading and subtitle say what it does; a collapsed panel shows when text
  is waiting.
- While empty it shows the three formats it recognises and an Open file
  button; text files can be dropped on the box.
- While typing it previews the speakers found (in their cast colours, or
  says everything goes to the narrator) and how many lines each action adds.
  The parse runs deferred, so long pastes do not stall typing.
- Auto-cast is the primary action (Ctrl/Cmd+Enter); Split into lines is a
  labelled button beside the split mode; a word count and Clear sit in the box.

* fix(stories): keep the speed help reachable while busy; NARRATOR lines never take a pronoun

- The busy state disabled the whole speed fieldset, which also took its help
  tip out of the tab order; the slider and reset are disabled one by one now.
- An explicit NARRATOR: line became the referent for a later "she said",
  casting that quote to the narrator; mergePronounCast already skipped it.

* fix(stories): address review findings on the timeline, line actions and voice picker

- Reaction-only lines ([laughter], [sigh]) took no time on the timeline, and a
  chapter of them dropped out of the chapter count, shifting every later clip.
  Estimates now come from the parser's spoken spans, reactions included.
- Changing a line's voice, its speaker's voice or the book voice left lines
  unmarked as changed. Render keys (now v2) include each line's resolved voice,
  so those lines are marked and the timeline stops mapping the old audio.
- Hovering a line put its action buttons over the first line of text. Rows now
  keep an end strip for a ⋯ button; the actions expand from it only on hover or
  focus of ⋯ or the actions themselves, or when ⋯ is pressed on touch screens.
- A gallery voice still saving when its picker closed could land later and
  rebuild the cast from an old copy, erasing newer edits. Closing the picker
  cancels it, and cast voice picks apply to the current cast.

* feat(sidebar): one line per setting in Stories, Audiobook and Batch dubbing

Title, voice, language and format (and Batch's target language, voice and
background switch) each sit on one row: muted icon and label on the left,
the control on the right, as Batch's engine row already did. The voice is a
compact button that opens the searchable voice list with the Voice Gallery;
Batch's presets appear there as their own group. Row labels are spans tied to
their fields, since the sidebar styles every label and legend as a heading.

* fix(stories): do not announce the speed help as unavailable while busy

aria-disabled on the speed group also marked its help button unavailable to
screen readers; the slider and reset carry their own disabled states.

* fix(stories): address timeline, voice picker and waveform review findings

- Time [slow]/[fast] spans at their own speed in line estimates.
- Only a render with a matching timing key maps onto the lines; resumed or
  keyless renders keep estimates instead of seeking into edited text.
- Group timeline clips in linear time; ignore transport keys another
  control already handled.
- The book voice picker offers no "engine default" row, which Generate
  would refuse.
- Voice picker: keep loaded gallery pages when a later page fails, show the
  gallery as loading until a new search settles so Enter can't pick a stale
  result, and refresh profiles when a cancelled pick may have saved.
- Line actions: the hidden toolbar's box no longer reveals it or catches
  clicks on the words.
- Waveform peaks rectify before the 1 kHz resample, so speech above 500 Hz
  is no longer drawn as silence.
- Localize the import examples and the clip length; reword the timeline
  estimate note; fix the Dutch "last render" wording.

* fix(stories): address the second round of timeline and picker review findings

- /audio-peaks needs the consumer tier: decoding a render is real work.
- The peak scan runs off the event loop.
- Timing keys include the output language, built by one timingContext()
  helper shared by the saved key and the live comparison.
- Literal bracketed text ([Appendix]) gets time; only reactions are not words.
- A result recovered only by file name keeps estimated clips.
- With estimated clips the lanes don't seek, the playhead hides and the
  clock shows the render's real length.
- Clips are reachable by keyboard (one tab stop, arrows/Home/End) and the
  lanes no longer rebuild every waveform on each playback update.
- The waveform cache keeps the last four renders.
- A clip click selects its line even while the text is locked.
- A second pointer lifting no longer ends a resize drag.
- The inspector summary lists unassigned lines when there is no Narrator.
- Speeds use the app language's decimal mark everywhere they are shown.
- The voice picker says when the gallery failed to load, with Retry.
- The page's basics panel and result views move to their own files, so
  the page stays under 500 lines.
This commit is contained in:
Palash Debnath authored and GitHub committed 2026-12-03 06:30:28 -08:00
1 parent 5deb3f6bcb
commit b73195bfc5
60 files changed
+4850 -540

No files matched your search

+41
View File
@@ -174,6 +174,47 @@ async def generated_ogg_opus(audio_id: str, request: Request):
_peaks_cache: "OrderedDict[tuple, dict]" = OrderedDict()
_PEAKS_CACHE_ENTRIES = 16
# Decoding a render is real work (an ffmpeg pass over the whole file), so the
# outline needs the same consumer tier that generates audio, not an open read.
@router.get(
"/audio-peaks/{name}",
dependencies=[Depends(reject_cross_site_get), Depends(require_consumer)],
)
async def audio_peaks(name: str, buckets: int = Query(2000, ge=1, le=20000)):
"""Waveform outline of a saved output (``buckets`` peaks, 0-100).
Lets the Stories timeline draw a long render's waveform without the
browser downloading and decoding the whole file. Cached per file
version, so redrawing at another zoom is instant."""
path = _safe_output_path(name)
if path is None or not os.path.isfile(path):
raise HTTPException(status_code=404, detail="Audio file not found")
stat = os.stat(path)
key = (path, stat.st_mtime_ns, stat.st_size, buckets)
cached = _peaks_cache.get(key)
if cached is not None:
_peaks_cache.move_to_end(key)
return cached
from services.audio_io import audio_peaks as read_peaks
try:
result = await read_peaks(path, buckets)
except asyncio.TimeoutError as exc:
raise HTTPException(
status_code=503, detail="Reading the waveform timed out; try again later"
) from exc
except RuntimeError as exc:
logger.warning("Waveform peaks failed: %s", log_safe(exc))
raise HTTPException(status_code=503, detail=str(exc)) from exc
_peaks_cache[key] = result
while len(_peaks_cache) > _PEAKS_CACHE_ENTRIES:
_peaks_cache.popitem(last=False)
return result
@router.get(
"/audio/{audio_id}.mp3",
dependencies=[Depends(reject_cross_site_get)],
+51
View File
@@ -341,6 +341,57 @@ async def encode_mp3(wav: bytes | str | os.PathLike[str]) -> bytes:
return await _encode_with_ffmpeg(wav, "MP3", [*MP3_CODEC_ARGS, "-f", "mp3"])
PEAKS_SAMPLE_RATE = 1000
async def audio_peaks(path: str | os.PathLike[str], buckets: int) -> dict:
"""Loudness outline of a saved render, for drawing its waveform.
ffmpeg decodes any format the app saves to a 1 kHz mono loudness
envelope (about 5 MB for an hour), so a long render costs neither the
browser's memory nor a full-rate decode. The signal is rectified before
that last resample: 1 kHz audio keeps nothing above 500 Hz, so resampling
the waveform itself would draw speech's higher frequencies as silence.
Rectifying at 8 kHz keeps the speech band at a fraction of a full-rate
pass. Returns the duration in seconds and ``buckets`` peaks scaled 0-100
to the loudest one.
"""
pcm = await _encode_with_ffmpeg(
path, "Waveform",
[
"-vn", "-ac", "1",
"-af", f"aresample=8000,aeval=abs(val(0)),aresample={PEAKS_SAMPLE_RATE}",
"-acodec", "pcm_s16le", "-f", "s16le",
],
)
import asyncio
# Scanning an hours-long envelope is pure Python: keep it off the event loop.
return await asyncio.to_thread(peaks_from_pcm, pcm, buckets)
def peaks_from_pcm(pcm: bytes, buckets: int) -> dict:
"""Split 16-bit little-endian mono PCM at PEAKS_SAMPLE_RATE into peaks."""
import array
import sys
samples = array.array("h")
samples.frombytes(pcm[: len(pcm) // 2 * 2])
if sys.byteorder == "big":
samples.byteswap()
total = len(samples)
count = max(1, min(int(buckets), total)) if total else 0
raw = []
for index in range(count):
chunk = samples[index * total // count:(index + 1) * total // count]
raw.append(max(-min(chunk), max(chunk)) if chunk else 0)
loudest = max(raw, default=0) or 1
return {
"duration": total / PEAKS_SAMPLE_RATE,
"peaks": [round(value * 100 / loudest) for value in raw],
}
async def _encode_with_ffmpeg(
wav: bytes | str | os.PathLike[str], label: str, output_args: list[str],
) -> bytes:
+1
View File
@@ -0,0 +1 @@
Stories has a timeline: one track per speaker with the render's waveform in each clip, a playhead that highlights the spoken line, click-to-jump clips, J/K/L and Space playback keys, and markers on lines changed since the last render; every voice picker in Stories searches your voices and the whole Voice Gallery (#4606)
+1
View File
@@ -0,0 +1 @@
The Stories paste box is now "Add lines from text": it previews the speakers it finds and how many lines each choice adds, opens or takes dropped text files, and casts with Ctrl+Enter; the Stories, Audiobook and Batch dubbing sidebars show each setting on one line, with a searchable voice picker that includes the Voice Gallery (#4606)
+1
View File
@@ -0,0 +1 @@
Stories stay fast to type in and scroll with long scripts; a right-hand inspector edits the selected line, and the editor uses the full window width (#4606)
@@ -14,7 +14,7 @@ import {
SquareIcon,
Trash2Icon,
Volume2Icon,
WandSparklesIcon,
FingerprintIcon,
} from 'lucide-react';
import { SecondarySidebar } from '@/components/workspace-sidebar';
import { WorkspaceHeader } from '@/components/app-shell/workspace-header';
@@ -43,6 +43,7 @@ import { usePendingKeys } from './use-pending-keys';
import { cachedTtsLanguagesSupported } from '@/lib/language-options';
import { useTranslationEngines } from '@/features/settings/translation-settings';
import { relaxWhenBackendBusy } from '@/lib/status-polling';
import { SettingRow, VoicePickerButton } from '@/features/longform/setting-row';
const languageOptions = TRANSLATION_TARGET_LABELS;
const exportKey = (job: BatchJob, lang: string) => `${job.id}:${lang}`;
@@ -301,19 +302,17 @@ export function BatchPage() {
)}
</section>
<section className="space-y-3 studio-panel p-3">
<h2 className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
<LanguagesIcon className="size-4" />
{t('batch.target_languages')}
</h2>
<EngineLanguagePicker
operation="batch"
options={languageOptions}
value={langs.at(-1) || 'Spanish'}
disabled={busy}
onValueChange={(value) =>
setLangs((current) => (current.includes(value) ? current : [...current, value]))
}
/>
<SettingRow icon={LanguagesIcon} label={t('batch.target_languages')}>
<EngineLanguagePicker
operation="batch"
options={languageOptions}
value={langs.at(-1) || 'Spanish'}
disabled={busy}
onValueChange={(value) =>
setLangs((current) => (current.includes(value) ? current : [...current, value]))
}
/>
</SettingRow>
<div className="flex flex-wrap gap-1">
{langs.map((lang) => (
<Button
@@ -345,61 +344,31 @@ export function BatchPage() {
)}
</section>
<section className="space-y-3 studio-panel p-3">
<details className="text-xs">
<summary className="cursor-pointer font-medium">{t('batch.voice_kicker')}</summary>
<div className="mt-2 flex flex-wrap gap-1">
<Button
size="xs"
variant={!voice ? 'secondary' : 'ghost'}
disabled={busy}
onClick={() => setVoice('')}
>
{t('batch.default_option')}
</Button>
{profiles.data?.map((profile) => (
<Button
key={profile.id}
size="xs"
variant={voice === profile.id ? 'secondary' : 'ghost'}
disabled={busy}
onClick={() => setVoice(profile.id)}
>
{profile.name}
</Button>
))}
</div>
<p className="mt-3 flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground">
<WandSparklesIcon className="size-3.5" />
{t('batch.presets')}
</p>
<div className="mt-1 flex flex-wrap gap-1">
{PRESETS.map((preset) => (
<Button
key={preset.id}
size="xs"
variant={voice === `preset:${preset.id}` ? 'secondary' : 'ghost'}
disabled={busy}
onClick={() => setVoice(`preset:${preset.id}`)}
>
{t(`clone.preset_${preset.id}`, {
defaultValue: preset.name,
})}
</Button>
))}
</div>
</details>
<div className="flex items-center justify-between gap-3 text-xs leading-5">
<span className="flex items-center gap-2">
<Volume2Icon className="size-4 shrink-0 text-muted-foreground" />
{t('batch.preserve_bg')}
</span>
<SettingRow icon={FingerprintIcon} label={t('batch.voice_kicker')}>
<VoicePickerButton
label={t('batch.voice_kicker')}
profiles={profiles.data ?? []}
value={voice || null}
disabled={busy}
defaultLabel={t('batch.default_option')}
extra={{
label: t('batch.presets'),
options: PRESETS.map((preset) => ({
id: `preset:${preset.id}`,
name: t(`clone.preset_${preset.id}`, { defaultValue: preset.name }),
})),
}}
onSelect={(id) => setVoice(id ?? '')}
/>
</SettingRow>
<SettingRow icon={Volume2Icon} label={t('batch.preserve_bg')} wide>
<Switch
aria-label={t('batch.preserve_bg')}
checked={preserve}
disabled={busy}
onCheckedChange={setPreserve}
/>
</div>
</SettingRow>
</section>
<EngineNotice operation="batch" />
<WatchFolder
@@ -0,0 +1,94 @@
import { useId, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { BookOpenTextIcon, FileAudioIcon, FingerprintIcon, LanguagesIcon } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { EngineLanguagePicker } from '@/features/clone/engine-language-picker';
import type { Draft, Mode } from './longform-session';
import { outputLanguageOptions } from './output-languages';
import { SettingRow, VoicePickerButton } from './setting-row';
import { StorySpeed } from './story-speed';
const FORMATS = ['m4b', 'mp3'] as const;
/**
* The sidebar's first panel: what the book is called, who reads it, how fast
* (Stories), in which language and file format, one setting per line.
*/
export function BookBasics({
mode,
draft,
profiles,
disabled,
onChange,
}: {
mode: Mode;
draft: Draft;
profiles: readonly { id: string; name: string }[];
disabled: boolean;
onChange: (patch: Partial<Draft>) => void;
}) {
const { t } = useTranslation();
const titleId = useId();
const languageOptions = useMemo(() => outputLanguageOptions(draft.language), [draft.language]);
return (
<div className="space-y-2 studio-panel p-3">
<SettingRow icon={BookOpenTextIcon} label={t('audiobook.meta_title')} labelId={titleId}>
<Input
aria-labelledby={titleId}
className="h-8"
value={draft.title}
disabled={disabled}
placeholder={t(mode === 'stories' ? 'stories.untitled' : 'audiobook.untitled')}
onChange={(e) => onChange({ title: e.target.value })}
/>
</SettingRow>
<SettingRow icon={FingerprintIcon} label={t('stories.voiceLabel')}>
<VoicePickerButton
label={t('stories.voiceLabel')}
profiles={profiles}
value={draft.voice}
disabled={disabled}
required
onSelect={(voice) => onChange({ voice })}
/>
</SettingRow>
{mode === 'stories' ? (
<StorySpeed draft={draft} disabled={disabled} onChange={onChange} />
) : null}
<SettingRow icon={LanguagesIcon} label={t('clone.language')}>
<EngineLanguagePicker
operation={mode === 'stories' ? 'longform' : 'audiobook'}
value={draft.language}
options={languageOptions}
disabled={disabled}
onValueChange={(language) => onChange({ language })}
/>
</SettingRow>
<SettingRow icon={FileAudioIcon} label={t('audiobook.format')}>
<ToggleGroup
aria-label={t('audiobook.format')}
value={[draft.format]}
disabled={disabled}
onValueChange={(values) => {
const format = FORMATS.find((candidate) => candidate === values[0]);
if (format) onChange({ format });
}}
spacing={0}
className="grid w-44 grid-cols-2 gap-0.5 rounded-lg bg-muted/40 p-0.5 ring-1 ring-inset ring-border/50"
>
{FORMATS.map((format) => (
<ToggleGroupItem
key={format}
value={format}
size="sm"
className="h-7 w-full rounded-md text-muted-foreground hover:bg-background/60 aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-sm"
>
{t('audiobook.format_' + format)}
</ToggleGroupItem>
))}
</ToggleGroup>
</SettingRow>
</div>
);
}
@@ -7,6 +7,6 @@ import source from './longform-page.tsx?raw';
// list. The column now grows but never shrinks below its content, and the pane
// scrolls instead.
it('lets the script column grow without shrinking below its content', () => {
expect(source).toContain('max-w-6xl flex-[1_0_auto] flex-col');
expect(source).not.toMatch(/max-w-6xl min-h-0 flex-1/);
expect(source).toContain('mx-auto flex w-full flex-[1_0_auto] flex-col');
expect(source).not.toMatch(/min-h-0 flex-1 flex-col gap-4 px-6/);
});
@@ -1,13 +1,5 @@
import { readTextFile } from '@shared/utils/readTextFile';
import { ProfileAvatar } from '@/components/profile-avatar';
import {
BookOpenTextIcon,
FileAudioIcon,
FingerprintIcon,
ImportIcon,
LanguagesIcon,
Trash2Icon,
} from 'lucide-react';
import { BookOpenTextIcon, ImportIcon, Trash2Icon } from 'lucide-react';
import { AudioLinesIcon } from 'lucide-react';
import { SecondarySidebar } from '@/components/workspace-sidebar';
import { WorkspaceHeader } from '@/components/app-shell/workspace-header';
@@ -17,7 +9,6 @@ import { cueSheetFor } from './cue-sheet';
import { saveLocalFile } from '@/lib/local-export';
import { StoryEditor } from './story-editor';
import { StoryCast } from './story-cast';
import { StorySpeed } from './story-speed';
import { clearedScriptPatch, scriptSize } from './story-clear';
import { ConfirmDialog } from '../clone/confirm-dialog';
import { AudiobookMarkupToolbar } from './audiobook-markup-toolbar';
@@ -35,6 +26,9 @@ import {
validateScript,
} from '@shared/utils/audiobookScript';
import { BookSettings } from './book-settings';
import { BookBasics } from './book-basics';
import { AudiobookResult, StoriesResultDock } from './longform-result';
import { useStoryTimeline } from './story-timeline';
import { IconAction, InfoTip } from './story-chips';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { duplicateWords } from './book-options';
@@ -43,13 +37,9 @@ import { useEngines } from '@/hooks/use-engines';
import { engineShortName, expressionCaps } from '@/lib/expression';
import { Link } from '@tanstack/react-router';
import { useTranslation } from 'react-i18next';
import { DownloadIcon, ListIcon, SparklesIcon } from 'lucide-react';
import { SparklesIcon } from 'lucide-react';
import { Button, buttonVariants } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { Input } from '@/components/ui/input';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { WaveformPlayer } from '@/components/waveform-player';
import { SyncedAudiobookPlayer } from './synced-audiobook-player';
import { GeneratePanel } from './generate-panel';
import { LongformResultRecovery } from './result-recovery';
import { generateBlocker } from './generate-blocker';
@@ -59,8 +49,6 @@ import { useProfiles } from '@/hooks/use-profiles';
import { apiJson, apiPath, describeError } from '@/lib/api/client';
import { RenderRecovery } from './render-recovery';
import { saveExport } from '@/lib/export-history';
import { EngineLanguagePicker } from '@/features/clone/engine-language-picker';
import { outputLanguageOptions } from './output-languages';
import {
editLongform,
dismissLongformError,
@@ -75,7 +63,6 @@ import {
} from './longform-session';
import { SAMPLE_AUDIOBOOK_SCRIPT } from '@shared/data/sampleAudiobook';
import { useTtsReadiness } from '@/hooks/use-tts-readiness';
const FORMATS = ['m4b', 'mp3'] as const;
export function LongformPage({ mode }: { mode: Mode }) {
const { t } = useTranslation();
const session = useLongformSession();
@@ -86,7 +73,10 @@ export function LongformPage({ mode }: { mode: Mode }) {
mode === 'audiobook' ? draft.script : draft.lines.map((line) => line.text).join('\n');
const names = useMemo(() => parseCastNames(text), [text]);
const stats = useMemo(() => scriptStats(text), [text]);
const languageOptions = useMemo(() => outputLanguageOptions(draft.language), [draft.language]);
// Stories lays lines out with their own speeds (and real durations once
// rendered); the runtime under the script matches the timeline's length.
const storyTiming = useStoryTimeline(draft);
const runtimeSec = mode === 'stories' ? storyTiming.total : stats.runtimeSec;
const { data: profiles = [] } = useProfiles();
const [importing, setImporting] = useState(false);
const [localError, setLocalError] = useState<string | null>(null);
@@ -265,85 +255,13 @@ export function LongformPage({ mode }: { mode: Mode }) {
onCollapsedChange={setSidebarCollapsed}
className="space-y-3"
>
<div className="space-y-4 studio-panel p-3">
<label className="block space-y-2 text-xs font-medium text-muted-foreground">
<span className="flex items-center gap-2">
<BookOpenTextIcon className="size-4" aria-hidden="true" />
{t('audiobook.meta_title')}
</span>
<Input
value={draft.title}
disabled={locked}
placeholder={t(mode === 'stories' ? 'stories.untitled' : 'audiobook.untitled')}
onChange={(e) => set({ title: e.target.value })}
/>
</label>
<div className="space-y-1">
<h2 className="mb-2 flex items-center gap-2 text-xs font-medium text-muted-foreground">
<FingerprintIcon className="size-4" aria-hidden="true" />
{t('stories.voiceLabel')}
</h2>
{!profiles.length && (
<p className="text-xs text-muted-foreground">{t('stories.noProfiles')}</p>
)}
{profiles.map((profile) => (
<Button
key={profile.id}
variant={draft.voice === profile.id ? 'secondary' : 'ghost'}
className="w-full justify-start truncate"
disabled={locked}
onClick={() => set({ voice: profile.id })}
>
<ProfileAvatar name={profile.name} className="size-6 shrink-0" />
<span className="truncate">{profile.name}</span>
</Button>
))}
</div>
{mode === 'stories' ? (
<StorySpeed draft={draft} disabled={locked} onChange={set} />
) : null}
<div className="space-y-2">
<h2 className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
<LanguagesIcon className="size-4" aria-hidden="true" />
{t('clone.language')}
</h2>
<EngineLanguagePicker
operation={ttsOperation}
value={draft.language}
options={languageOptions}
disabled={locked}
onValueChange={(language) => set({ language })}
/>
</div>
<div className="space-y-2">
<h2 className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
<FileAudioIcon className="size-4" aria-hidden="true" />
{t('audiobook.format')}
</h2>
<ToggleGroup
aria-label={t('audiobook.format')}
value={[draft.format]}
disabled={locked}
onValueChange={(values) => {
const format = FORMATS.find((candidate) => candidate === values[0]);
if (format) set({ format });
}}
spacing={0}
className="grid w-full grid-cols-2 gap-0.5 rounded-lg bg-muted/40 p-0.5 ring-1 ring-inset ring-border/50"
>
{FORMATS.map((format) => (
<ToggleGroupItem
key={format}
value={format}
size="sm"
className="h-7 w-full rounded-md text-muted-foreground hover:bg-background/60 aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-sm"
>
{t('audiobook.format_' + format)}
</ToggleGroupItem>
))}
</ToggleGroup>
</div>
</div>
<BookBasics
mode={mode}
draft={draft}
profiles={profiles}
disabled={locked}
onChange={set}
/>
{mode === 'stories' && (
<StoryCast draft={draft} profiles={profiles} disabled={locked} onChange={set} />
)}
@@ -381,7 +299,12 @@ export function LongformPage({ mode }: { mode: Mode }) {
{/* Grows to fill the pane but never shrinks below its content: the
editor keeps its height and the notes below it stay in normal flow,
so a short window scrolls the pane instead of stacking them. */}
<div className="mx-auto flex w-full max-w-6xl flex-[1_0_auto] flex-col gap-4 px-6 py-5">
<div
className={cn(
'mx-auto flex w-full flex-[1_0_auto] flex-col gap-4 px-6 py-5',
mode === 'stories' ? 'max-w-[112rem]' : 'max-w-6xl',
)}
>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="min-w-0 grow basis-64">
<h2 className="flex items-center gap-2 text-sm font-medium">
@@ -497,13 +420,14 @@ export function LongformPage({ mode }: { mode: Mode }) {
canSynthesize={ttsBlocker === null}
onChange={set}
onBusy={setImporting}
onImportFile={(file) => void importFile(file)}
/>
)}
<p className="text-xs text-muted-foreground">
{t('audiobook.stats', {
count: stats.chapters,
words: stats.words,
runtime: formatRuntimeClock(stats.runtimeSec),
runtime: formatRuntimeClock(runtimeSec),
})}
</p>
{!warningsDismissed && warnings.length > 0 && !session.active && (
@@ -531,63 +455,32 @@ export function LongformPage({ mode }: { mode: Mode }) {
</Link>
</div>
)}
{sidebarCollapsed && (
<div className="sticky bottom-0 z-10 -mx-3 mt-auto shrink-0 rounded-2xl border border-border/70 bg-background/75 p-3.5 shadow-lg backdrop-blur-lg">
{generatePanel}
</div>
)}
{draft.output && (
<section className="shrink-0 space-y-3 border-t border-border/50 pt-4">
<div className="flex items-center justify-between">
<div>
<h2 className="text-sm font-medium">{t('audiobook.last_completed_render')}</h2>
{mode === 'audiobook' && draft.outputCachedChapters > 0 && (
<p className="mt-0.5 text-xs text-muted-foreground">
{t('audiobook.cached_note', {
count: draft.outputCachedChapters,
})}
</p>
)}
{draft.outputFailedChapters > 0 && (
<p className="mt-0.5 text-xs text-muted-foreground">
{t('audiobook.failed_note', {
count: draft.outputFailedChapters,
})}
</p>
)}
</div>
<div className="flex items-center gap-1">
{downloadableCues !== null && (
<Button variant="ghost" size="sm" onClick={() => void saveCueSheet()}>
<ListIcon />
{t('audiobook.download_cues')}
</Button>
)}
<Button
variant="ghost"
size="sm"
disabled={exporting}
onClick={() => void download()}
>
<DownloadIcon />
{t('audiobook.download')}
</Button>
</div>
</div>
{mode === 'audiobook' ? (
<SyncedAudiobookPlayer
src={apiPath('/audio/' + encodeURIComponent(draft.output))}
script={draft.outputScript}
chapters={draft.outputChapters}
/>
) : (
<WaveformPlayer
showWaveform={false}
src={apiPath('/audio/' + encodeURIComponent(draft.output))}
source={'longform-' + mode}
{(sidebarCollapsed || mode === 'stories') && (
<div className="sticky bottom-0 z-10 -mx-3 mt-auto shrink-0 space-y-2">
{mode === 'stories' && (
<StoriesResultDock
draft={draft}
canSaveCues={downloadableCues !== null}
exporting={exporting}
onSaveCues={() => void saveCueSheet()}
onDownload={() => void download()}
/>
)}
</section>
{sidebarCollapsed && (
<div className="rounded-2xl border border-border/70 bg-background/75 p-3.5 shadow-lg backdrop-blur-lg">
{generatePanel}
</div>
)}
</div>
)}
{draft.output && mode === 'audiobook' && (
<AudiobookResult
draft={draft}
canSaveCues={downloadableCues !== null}
exporting={exporting}
onSaveCues={() => void saveCueSheet()}
onDownload={() => void download()}
/>
)}
</div>
</section>
@@ -0,0 +1,112 @@
import { useTranslation } from 'react-i18next';
import { DownloadIcon, ListIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { apiPath } from '@/lib/api/client';
import type { Draft } from './longform-session';
import { IconAction } from './story-chips';
import { StoryTimeline } from './story-timeline';
import { SyncedAudiobookPlayer } from './synced-audiobook-player';
interface ResultActions {
draft: Draft;
/** Whether the render has chapter cues to save as a cue sheet. */
canSaveCues: boolean;
exporting: boolean;
onSaveCues: () => void;
onDownload: () => void;
}
const audioSrc = (output: string) => apiPath('/audio/' + encodeURIComponent(output));
/** Stories' bottom dock: the last render's play bar and the timeline of the script. */
export function StoriesResultDock({
draft,
canSaveCues,
exporting,
onSaveCues,
onDownload,
}: ResultActions) {
const { t } = useTranslation();
return (
<StoryTimeline
draft={draft}
src={draft.output ? audioSrc(draft.output) : null}
status={
draft.output && (
<div className="flex items-baseline gap-2 px-1 pt-0.5 text-[11px] text-muted-foreground">
<h2 className="font-medium">{t('audiobook.last_completed_render')}</h2>
{draft.outputFailedChapters > 0 && (
<span>{t('audiobook.failed_note', { count: draft.outputFailedChapters })}</span>
)}
</div>
)
}
actions={
draft.output && (
<>
{canSaveCues && (
<IconAction
label={t('audiobook.download_cues')}
icon={ListIcon}
onClick={onSaveCues}
/>
)}
<IconAction
label={t('audiobook.download')}
icon={DownloadIcon}
disabled={exporting}
onClick={onDownload}
/>
</>
)
}
/>
);
}
/** The Audiobook page's last render: its notes, downloads and a chapter-synced player. */
export function AudiobookResult({
draft,
canSaveCues,
exporting,
onSaveCues,
onDownload,
}: ResultActions) {
const { t } = useTranslation();
return (
<section className="shrink-0 space-y-3 border-t border-border/50 pt-4">
<div className="flex items-center justify-between">
<div>
<h2 className="text-sm font-medium">{t('audiobook.last_completed_render')}</h2>
{draft.outputCachedChapters > 0 && (
<p className="mt-0.5 text-xs text-muted-foreground">
{t('audiobook.cached_note', { count: draft.outputCachedChapters })}
</p>
)}
{draft.outputFailedChapters > 0 && (
<p className="mt-0.5 text-xs text-muted-foreground">
{t('audiobook.failed_note', { count: draft.outputFailedChapters })}
</p>
)}
</div>
<div className="flex items-center gap-1">
{canSaveCues && (
<Button variant="ghost" size="sm" onClick={onSaveCues}>
<ListIcon />
{t('audiobook.download_cues')}
</Button>
)}
<Button variant="ghost" size="sm" disabled={exporting} onClick={onDownload}>
<DownloadIcon />
{t('audiobook.download')}
</Button>
</div>
</div>
<SyncedAudiobookPlayer
src={audioSrc(draft.output)}
script={draft.outputScript}
chapters={draft.outputChapters}
/>
</section>
);
}
@@ -25,6 +25,7 @@ import { beginAppActivity } from '@/lib/app-activity';
import { publishLongformActivity, publishLongformFailure } from '@/lib/longform-activity';
import { publicFailureFromEvent, type PublicFailure } from '@/lib/api/failure';
import { parseProgressEvent, type RenderProgressSnapshot } from './render-eta';
import { storyTimingKey, timingContext } from './story-timeline-model';
export type Mode = 'stories' | 'audiobook';
export interface Character {
id: string;
@@ -876,7 +877,13 @@ export async function renderLongform(mode: Mode, resumeId?: string) {
const result: CompletedResult = {
output: event.output,
outputOwner: owner,
outputScript: mode === 'audiobook' && !resumeId ? draft.script : '',
// Stories keep the timing key of the lines it was rendered from, so the
// timeline knows when edits have moved the script away from the audio.
outputScript: resumeId
? ''
: mode === 'audiobook'
? draft.script
: storyTimingKey(draft.lines, draft.globalSpeed, timingContext(draft)),
outputChapters: outputChapters.map((chapter) => ({ ...chapter })),
outputCachedChapters: Number(event.cached_chapters) || 0,
outputFailedChapters: failed,
@@ -931,8 +938,10 @@ export function dismissLongformError(): void {
function canRetryLongform(session: Session): boolean {
const failed = session.failedRender;
return Boolean(
!session.active && failed && failed.draft === session.drafts[failed.mode] &&
failed.connection === connectionRevision,
!session.active &&
failed &&
failed.draft === session.drafts[failed.mode] &&
failed.connection === connectionRevision,
);
}
@@ -0,0 +1,18 @@
import { render, screen } from '@testing-library/react';
import { expect, it } from 'vitest';
import i18n from '@/i18n';
import { LongformResultRecovery } from './result-recovery';
it('shows a failed saved-audio check to everyone, not only screen readers', () => {
render(
<LongformResultRecovery
state={{ status: 'legacy', recovering: false, recoveryFailed: true, availabilityOnly: false }}
disabled={false}
onRecover={() => {}}
/>,
);
const alert = screen.getByRole('alert');
expect(alert.textContent).toBe(i18n.t('audiobook.result_recovery_failed'));
expect(alert.className).not.toContain('sr-only');
screen.getByRole('button', { name: i18n.t('audiobook.result_check_audio') });
});
@@ -1,6 +1,7 @@
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import type { LongformResultState } from './longform-session';
import { InfoTip } from './story-chips';
/** A saved filename never authorizes a request to its previous connection. */
export function LongformResultRecovery({
@@ -23,19 +24,32 @@ export function LongformResultRecovery({
: null;
if (!message) return null;
return (
<section className="space-y-2 rounded-lg border border-border/60 bg-muted/30 p-3 text-xs">
<p role="status">{t(message)}</p>
{state.recoveryFailed && <p role="alert">{t('audiobook.result_recovery_failed')}</p>}
{state.status === 'legacy' && (
<Button
className="h-auto w-full whitespace-normal"
variant="outline"
size="sm"
disabled={disabled || state.recovering}
onClick={onRecover}
>
{t(state.recovering ? 'common.loading' : 'audiobook.result_check_audio')}
</Button>
<section className="flex flex-wrap items-center gap-1.5 rounded-lg border border-border/60 bg-muted/30 px-2 py-1.5 text-xs">
<InfoTip text={t(message)} />
{state.status === 'legacy' ? (
<>
<p role="status" className="sr-only">
{t(message)}
</p>
<Button
className="h-auto min-w-0 flex-1 justify-start whitespace-normal px-1.5 text-start"
variant="ghost"
size="xs"
disabled={disabled || state.recovering}
onClick={onRecover}
>
{t(state.recovering ? 'common.loading' : 'audiobook.result_check_audio')}
</Button>
</>
) : (
<p role="status" className="line-clamp-2 min-w-0 flex-1 text-muted-foreground">
{t(message)}
</p>
)}
{state.recoveryFailed && (
<p role="alert" className="basis-full text-destructive">
{t('audiobook.result_recovery_failed')}
</p>
)}
</section>
);
@@ -0,0 +1,82 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { fireEvent, render, screen } from '@testing-library/react';
import { FingerprintIcon } from 'lucide-react';
import { expect, it, vi } from 'vitest';
import { SettingRow, VoicePickerButton } from './setting-row';
import { voiceRows } from './voice-pick-list';
vi.mock('@/lib/api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/api/client')>()),
apiJson: vi.fn(() => new Promise(() => {})),
}));
const presets = { label: 'Presets', options: [{ id: 'preset:narrator', name: 'Narrator' }] };
it('puts the label and its control on one line, the label naming its field', () => {
render(
<SettingRow icon={FingerprintIcon} label="Title" labelId="t">
<input aria-labelledby="t" />
</SettingRow>,
);
const row = document.querySelector('[data-slot="setting-row"]')!;
expect(row.className.split(' ')).toContain('flex');
expect(screen.getByLabelText('Title').tagName).toBe('INPUT');
});
it('lists extra choices such as presets after the user’s voices, filtered by the search', () => {
const rows = (query: string) =>
voiceRows({
query,
defaultLabel: 'Default',
profiles: [{ id: 'p1', name: 'Ava' }],
gallery: [],
extra: presets,
headings: { yours: 'Yours', gallery: 'Gallery', loading: '…', empty: 'None' },
}).map((row) => row.key);
expect(rows('')).toEqual(['default', 'h:yours', 'p:p1', 'h:extra', 'x:preset:narrator']);
expect(rows('narr')).toEqual(['h:extra', 'x:preset:narrator']);
});
it('names the chosen voice, preset or default on its button and picks from the list', () => {
const onSelect = vi.fn();
const show = (value: string | null) =>
render(
<QueryClientProvider client={new QueryClient()}>
<VoicePickerButton
label="Voice"
profiles={[{ id: 'p1', name: 'Ava' }]}
value={value}
defaultLabel="Default"
extra={presets}
onSelect={onSelect}
/>
</QueryClientProvider>,
);
let view = show('preset:narrator');
screen.getByRole('button', { name: 'Voice: Narrator' });
view.unmount();
view = show(null);
screen.getByRole('button', { name: 'Voice: Default' });
view.unmount();
show('p1');
const button = screen.getByRole('button', { name: 'Voice: Ava' });
fireEvent.click(button);
fireEvent.click(screen.getByRole('option', { name: 'Narrator' }));
expect(onSelect).toHaveBeenCalledWith('preset:narrator');
});
it('offers no "no voice" choice where generation needs a real voice', () => {
render(
<QueryClientProvider client={new QueryClient()}>
<VoicePickerButton
label="Voice"
profiles={[{ id: 'p1', name: 'Ava' }]}
value={null}
required
onSelect={vi.fn()}
/>
</QueryClientProvider>,
);
fireEvent.click(screen.getByRole('button', { name: /^Voice: / }));
expect(screen.getAllByRole('option').map((option) => option.textContent)).toEqual(['Ava']);
});
@@ -0,0 +1,117 @@
import { ChevronDownIcon, type LucideIcon } from 'lucide-react';
import { useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { ProfileAvatar } from '@/components/profile-avatar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/popover';
import { cn } from '@/lib/utils';
import { VoicePickList, type VoiceGroup } from './voice-pick-list';
/**
* One sidebar setting on a single line: icon and label on the left, its
* control on the right (the Batch sidebar's layout). The label is a span (the
* sidebar styles every `label` as a heading); `labelId` lets a field name
* itself after it with `aria-labelledby`, otherwise give the control its own
* accessible name.
*/
export function SettingRow({
icon: Icon,
label,
labelId,
wide,
className,
children,
}: {
icon: LucideIcon;
label: string;
labelId?: string;
/** A long label that takes the room a small control (a switch) leaves. */
wide?: boolean;
className?: string;
children: ReactNode;
}) {
return (
<div
data-slot="setting-row"
className={cn('flex min-h-8 items-center gap-3 text-xs', className)}
>
<span
className={cn(
'flex items-center gap-2 font-medium text-muted-foreground',
wide ? 'min-w-0 flex-1' : 'min-w-24 shrink-0 whitespace-nowrap',
)}
>
<Icon className="size-4 shrink-0" aria-hidden="true" />
<span id={labelId} className={cn(wide && 'min-w-0')}>
{label}
</span>
</span>
<div className={cn('flex min-w-0 justify-end', wide ? 'shrink-0' : 'flex-1')}>{children}</div>
</div>
);
}
/**
* The book voice as a compact button that opens the searchable voice list
* (your voices and the Voice Gallery), for a one-line setting row.
*/
export function VoicePickerButton({
label,
profiles,
value,
disabled,
defaultLabel,
required = false,
extra,
onSelect,
}: {
label: string;
profiles: readonly { id: string; name: string }[];
value: string | null;
disabled?: boolean;
/** What no choice means here (defaults to the engine's own voice). */
defaultLabel?: string;
/** A voice must be chosen: no "no choice" row, which generation would refuse. */
required?: boolean;
extra?: VoiceGroup;
onSelect: (profileId: string | null) => void;
}) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const fallback = required
? t('cloneFlow.choose_voice')
: (defaultLabel ?? t('voiceSelector.engineDefault'));
const current = profiles.find((profile) => profile.id === value);
const name = value
? (current?.name ??
extra?.options.find((option) => option.id === value)?.name ??
t('modelSettings.unavailable'))
: fallback;
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
disabled={disabled}
aria-label={`${label}: ${name}`}
className="inline-flex h-8 min-w-0 max-w-full items-center gap-2 rounded-lg px-2 text-sm outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 data-popup-open:bg-muted"
>
{current && <ProfileAvatar name={current.name} className="size-5 shrink-0" />}
<span className={cn('truncate', !current && 'text-muted-foreground')}>{name}</span>
<ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
</PopoverTrigger>
<PopoverContent align="end" className="w-72 p-2">
<VoicePickList
label={label}
defaultLabel={required ? undefined : fallback}
profiles={profiles}
extra={extra}
value={value}
disabled={disabled}
autoFocus
onSelect={(profileId) => {
onSelect(profileId);
setOpen(false);
}}
/>
</PopoverContent>
</Popover>
);
}
@@ -1,4 +1,4 @@
import { fireEvent, render, screen, within } from '@testing-library/react';
import { fireEvent, render as renderUi, screen, within } from '@testing-library/react';
import { useState } from 'react';
import { expect, it, vi } from 'vitest';
import i18n from '@/i18n';
@@ -8,10 +8,25 @@ vi.mock('./story-preview', () => ({ previewStoryLine: vi.fn() }));
vi.mock('./story-stems', () => ({ StoryStems: () => null }));
vi.mock('@/components/pipeline-failure', () => ({ PipelineFailure: () => null }));
import { formatTimecode, lineStartTimes, speakerChangeFlags, StoryEditor } from './story-editor';
import { sameStoryBlock } from './story-block';
import { storyTimingKey, timingContext } from './story-timeline-model';
import { speakerChangeFlags, StoryEditor } from './story-editor';
import { castColor } from './cast-color';
import { blankLongformDraft, type Draft } from './longform-session';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactElement, ReactNode } from 'react';
// The voice list searches the gallery; keep it offline and pending here.
vi.mock('@/lib/api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/api/client')>()),
apiJson: vi.fn(() => new Promise(() => {})),
}));
function Queries({ children }: { children: ReactNode }) {
return <QueryClientProvider client={new QueryClient()}>{children}</QueryClientProvider>;
}
const render = (ui: ReactElement) => renderUi(ui, { wrapper: Queries });
const profiles = [
{ id: 'p1', name: 'Ava' },
{ id: 'p2', name: 'Ben' },
@@ -184,8 +199,32 @@ it('keeps line actions in a labelled toolbar that appears on hover and keyboard
const toolbars = screen.getAllByRole('toolbar', { name: i18n.t('stories.lineActions') });
expect(toolbars).toHaveLength(2);
const classes = toolbars[1].className.split(' ');
expect(classes).toContain('group-hover/block:opacity-100');
expect(classes).toContain('group-focus-within/block:opacity-100');
// Hidden and click-through until the pointer reaches ⋯ or keyboard focus
// enters: hovering or typing in the line never puts buttons over its words.
expect(classes).toEqual(
expect.arrayContaining([
'pointer-events-none',
'opacity-0',
'group-hover/actions:opacity-100',
'focus-within:opacity-100',
]),
);
expect(classes).not.toContain('group-hover/block:opacity-100');
// Nor does the hidden toolbar's box, through its container, catch the pointer.
const actions = toolbars[1].closest('[data-slot="line-actions"]')!;
expect(actions.className.split(' ')).toEqual(
expect.arrayContaining(['group/actions', 'pointer-events-none']),
);
expect(actions.className.split(' ')).not.toContain('gap-0.5');
expect(classes).not.toContain('group-focus-within/block:opacity-100');
// The row keeps an empty end strip for ⋯, wider than the text's own padding.
const row = toolbars[1].closest('[data-slot="story-block"]')!;
expect(row.className.split(' ')).toContain('pe-9');
const more = within(row as HTMLElement).getAllByRole('button', {
name: i18n.t('stories.lineActions'),
})[0];
fireEvent.click(more);
expect(toolbars[1].className.split(' ')).toContain('pointer-events-auto');
for (const key of ['preview', 'insertPause', 'moveUp', 'moveDown', 'removeLine'])
within(toolbars[1]).getByRole('button', { name: i18n.t(`stories.${key}`) });
expect(
@@ -198,23 +237,6 @@ it('keeps line actions in a labelled toolbar that appears on hover and keyboard
]);
});
it('estimates each line start from its words and speed, skipping chapter headings', () => {
const words = (n: number) => Array.from({ length: n }, () => 'word').join(' ');
const lines: Draft['lines'] = [
{ id: 'h', text: '# One', profileId: null },
{ id: 'a', text: words(150), profileId: null },
{ id: 'b', text: words(150), profileId: null, speed: 2 },
{ id: 'c', text: 'Last.', profileId: null },
];
const [h, a, b, c] = lineStartTimes(lines, 1);
expect([h, a]).toEqual([0, 0]);
expect(b).toBeGreaterThan(0);
// The same words at double speed take half as long.
expect(c - b).toBeCloseTo(b / 2);
expect(formatTimecode(65)).toBe('1:05');
expect(formatTimecode(3725)).toBe('1:02:05');
});
it('keeps the narrator neutral so colours mark the characters', () => {
const cast = [
{ id: 'narrator', name: 'Narrator', profileId: null },
@@ -260,6 +282,87 @@ it('offers to fold pronoun cast members left by older auto-casts into real speak
});
});
it('re-renders only the edited row, and an unrendered row still edits the current draft', () => {
const lines = [
{ id: 'a', text: 'First.', profileId: null },
{ id: 'b', text: 'Second.', profileId: null },
];
let draft = draftWith(lines);
const onChange = vi.fn((patch: Partial<Draft>) => {
draft = { ...draft, ...patch };
});
const view = render(
<StoryEditor draft={draft} profiles={profiles} disabled={false} onChange={onChange} />,
);
const second = () =>
screen.getAllByRole('textbox', { name: i18n.t('stories.linePlaceholder') })[1];
fireEvent.change(screen.getAllByRole('textbox', { name: i18n.t('stories.linePlaceholder') })[0], {
target: { value: 'First, edited.' },
});
view.rerender(
<StoryEditor draft={draft} profiles={profiles} disabled={false} onChange={onChange} />,
);
// Row b kept its handlers from the first render; they must not undo row a's edit.
fireEvent.change(second(), { target: { value: 'Second, edited.' } });
expect(onChange).toHaveBeenLastCalledWith({
lines: [
{ id: 'a', text: 'First, edited.', profileId: null },
{ id: 'b', text: 'Second, edited.', profileId: null },
],
});
});
it('shows the focused line in the inspector and edits it there', () => {
const draft = draftWith(
[
{ id: 'a', text: 'Hello there.', profileId: null, character: 'jan' },
{ id: 'b', text: 'Hi.', profileId: null },
],
[{ id: 'jan', name: 'Jan', profileId: null }],
);
const onChange = vi.fn();
render(<StoryEditor draft={draft} profiles={profiles} disabled={false} onChange={onChange} />);
const inspector = screen.getByRole('complementary', { name: i18n.t('stories.inspector') });
within(inspector).getByText(i18n.t('stories.inspectorEmpty'));
fireEvent.focus(screen.getAllByRole('textbox', { name: i18n.t('stories.linePlaceholder') })[1]);
within(inspector).getByText(i18n.t('stories.lineOf', { index: 2, count: 2 }));
const speakers = within(inspector).getByRole('group', { name: i18n.t('stories.speaker') });
fireEvent.click(within(speakers).getByRole('button', { name: 'Jan' }));
expect(onChange).toHaveBeenCalledWith({
lines: [draft.lines[0], { ...draft.lines[1], character: 'jan' }],
});
});
it('treats a row as unchanged unless its own data, the cast or book speed changes', () => {
const draft = draftWith([{ id: 'a', text: 'Hi.', profileId: null }]);
const props = {
line: draft.lines[0],
index: 0,
count: 1,
draft,
profiles,
disabled: false,
canMerge: false,
canPreview: true,
previewing: false,
previewUrl: null,
inputRef: () => {},
onUpdate: () => {},
onPreview: () => {},
onStopPreview: () => {},
onInsert: () => {},
onInlineVoice: () => {},
onMove: () => {},
onRemove: () => {},
onMerge: () => {},
};
const other = { ...draft, lines: [...draft.lines, { id: 'b', text: 'x', profileId: null }] };
expect(sameStoryBlock(props, { ...props, draft: other, onUpdate: () => {} })).toBe(true);
expect(sameStoryBlock(props, { ...props, line: { ...props.line, text: 'Hey.' } })).toBe(false);
expect(sameStoryBlock(props, { ...props, draft: { ...draft, globalSpeed: 1.2 } })).toBe(false);
expect(sameStoryBlock(props, { ...props, draft: { ...draft, cast: [] } })).toBe(false);
});
it('keeps the speed popup open while a first speed is set', () => {
function Harness() {
const [draft, setDraft] = useState(() =>
@@ -298,3 +401,36 @@ it('treats consecutive legacy lines without a speaker as one speaker', () => {
]),
).toEqual([true, false, false]);
});
it('keeps the unassigned choice in the inspector when the cast has a Narrator', () => {
const draft = draftWith(
[{ id: 'a', text: 'Hello.', profileId: null, character: 'narrator' }],
[{ id: 'narrator', name: 'Narrator', profileId: 'p1' }],
);
const onChange = vi.fn();
render(<StoryEditor draft={draft} profiles={profiles} disabled={false} onChange={onChange} />);
fireEvent.focus(screen.getByRole('textbox', { name: i18n.t('stories.linePlaceholder') }));
const inspector = screen.getByRole('complementary', { name: i18n.t('stories.inspector') });
const speakers = within(inspector).getByRole('group', { name: i18n.t('stories.speaker') });
fireEvent.click(within(speakers).getByRole('button', { name: i18n.t('stories.defaultVoice') }));
expect(onChange).toHaveBeenCalledWith({ lines: [{ ...draft.lines[0], character: undefined }] });
});
it('marks lines that sound different from the last render', () => {
const lines = [
{ id: 'a', text: 'Hello.', profileId: null },
{ id: 'b', text: 'Hi.', profileId: null },
];
const draft = {
...draftWith([lines[0], { ...lines[1], text: 'Hi there.' }]),
output: 'story.m4b',
outputScript: storyTimingKey(lines, 1, timingContext(draftWith(lines))),
};
const { container } = render(
<StoryEditor draft={draft} profiles={profiles} disabled={false} onChange={vi.fn()} />,
);
const marks = container.querySelectorAll('[data-slot="line-changed"]');
expect(marks).toHaveLength(1);
expect(marks[0].closest('[data-line-id]')?.getAttribute('data-line-id')).toBe('b');
expect(marks[0].getAttribute('aria-label')).toBe(i18n.t('stories.lineChanged'));
});
@@ -1,4 +1,4 @@
import { useState, type ReactNode } from 'react';
import { memo, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import {
AnnoyedIcon,
@@ -16,6 +16,7 @@ import {
UserIcon,
WindIcon,
ZapIcon,
EllipsisIcon,
} from 'lucide-react';
import { isChapterLine } from '@shared/utils/storyExport';
import { Button } from '@/components/ui/button';
@@ -24,6 +25,8 @@ import { cn } from '@/lib/utils';
import type { Draft } from './longform-session';
import { castColor } from './cast-color';
import { AutoSizeTextarea, ChipPopover, ChoiceList, IconAction } from './story-chips';
import { VoicePickList } from './voice-pick-list';
import { formatSpeed } from './story-timeline-model';
type Line = Draft['lines'][number];
type Profile = { id: string; name: string };
@@ -68,6 +71,8 @@ export function StoryBlock({
canPreview,
showSpeaker = true,
start,
active = false,
changed = false,
previewing,
previewUrl,
inputRef,
@@ -92,6 +97,10 @@ export function StoryBlock({
showSpeaker?: boolean;
/** Estimated start time, shown in the gutter like a timeline position. */
start?: string;
/** The line the render player is speaking now. */
active?: boolean;
/** The line sounds different from the last render (edited, re-cast or added since). */
changed?: boolean;
previewing: boolean;
previewUrl: string | null;
inputRef: (node: HTMLTextAreaElement | null) => void;
@@ -104,7 +113,7 @@ export function StoryBlock({
onRemove: () => void;
onMerge: () => void;
}) {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const heading = isChapterLine(line.text);
const character = draft.cast.find((c) => c.id === line.character);
const color = castColor(draft.cast, character?.id);
@@ -121,9 +130,11 @@ export function StoryBlock({
// moves the chip under the text; doing that while the popup is open would
// remount it mid-drag and close it, so the chip stays put until it closes.
const [tonePinned, setTonePinned] = useState<boolean | null>(null);
// Touch screens have no hover: the ⋯ button opens the actions instead.
const [actionsOpen, setActionsOpen] = useState(false);
const toneUnderText = tonePinned ?? ownSpeed;
const speed = line.speed ?? draft.globalSpeed;
const speedText = `${speed.toFixed(2)}×`;
const speedText = formatSpeed(speed, i18n.language);
const speakerChip = (
<ChipPopover
label={t('stories.speakerChip', { name: speakerName })}
@@ -165,11 +176,13 @@ export function StoryBlock({
content={(close) => (
<>
<PopoverHeading>{t('stories.lineVoice')}</PopoverHeading>
<ChoiceList
<VoicePickList
label={t('stories.lineVoice')}
options={[{ id: null, name: t('stories.defaultVoice') }, ...profiles]}
defaultLabel={t('stories.defaultVoice')}
profiles={profiles}
value={line.profileId}
disabled={disabled}
autoFocus
onSelect={(profileId) => {
onUpdate({ profileId });
close();
@@ -281,13 +294,16 @@ export function StoryBlock({
<div
data-slot="story-block"
data-kind={heading ? 'heading' : 'line'}
data-line-id={line.id}
data-active={active || undefined}
className={cn(
'group/block relative rounded-lg border border-transparent transition-colors focus-within:border-border/60 focus-within:bg-muted/15 hover:border-border/60 hover:bg-muted/15',
'group/block relative rounded-lg border border-transparent transition-colors [contain-intrinsic-size:auto_2.5rem] [content-visibility:auto] focus-within:border-border/60 focus-within:bg-muted/15 hover:border-border/60 hover:bg-muted/15',
heading
? 'px-3 py-1.5'
: 'grid grid-cols-1 gap-x-3 ps-1 pe-3 py-1 sm:grid-cols-[10rem_minmax(0,1fr)]',
? 'ps-3 pe-9 py-1.5'
: 'grid grid-cols-1 gap-x-3 ps-1 pe-9 py-1 sm:grid-cols-[10rem_minmax(0,1fr)]',
heading && index > 0 && 'mt-4',
!heading && showSpeaker && index > 0 && 'mt-1.5',
active && 'border-primary/40 bg-primary/8',
)}
>
{!heading && (
@@ -300,6 +316,15 @@ export function StoryBlock({
)}
{!heading && (
<div className="flex min-w-0 items-start gap-2 pt-px">
{changed && (
<span
role="img"
data-slot="line-changed"
aria-label={t('stories.lineChanged')}
title={t('stories.lineChanged')}
className="absolute start-2 top-[0.7rem] size-1.5 rounded-full bg-amber-500"
/>
)}
<span
data-slot="line-start"
title={t('stories.lineStart')}
@@ -345,55 +370,96 @@ export function StoryBlock({
</div>
)}
</div>
{/* The row keeps an empty strip at its end for the ⋯ button, so the
actions never sit over words being clicked or selected: they expand
leftwards only while the pointer or keyboard focus is on ⋯ or on the
actions themselves (or a popup of theirs is open). Inside the row,
which skips layout while off-screen and so clips anything outside it. */}
<div
role="toolbar"
aria-label={t('stories.lineActions')}
className="absolute -top-3 end-2 z-10 flex items-center gap-0.5 rounded-lg border border-border/60 bg-background/95 p-0.5 opacity-0 shadow-sm transition-opacity group-focus-within/block:opacity-100 group-hover/block:opacity-100 focus-within:opacity-100 [@media(hover:none)]:opacity-100"
data-slot="line-actions"
className="group/actions pointer-events-none absolute top-0.5 end-1 z-10 flex flex-row-reverse items-center"
onMouseLeave={() => setActionsOpen(false)}
>
{!heading && (
<>
{!line.profileId && voiceChip}
{!toneUnderText && toneChip}
<IconAction
label={t('stories.preview')}
icon={PlayIcon}
disabled={disabled || !canPreview}
onClick={onPreview}
/>
<IconAction
label={t('stories.insertPause')}
icon={PauseIcon}
disabled={disabled}
onClick={() => onInsert('[pause 0.5s]')}
/>
<IconAction
label={t('stories.mergeNext')}
hint={!canMerge ? t('stories.mergeNextHint') : undefined}
icon={MergeIcon}
disabled={disabled || !canMerge}
onClick={onMerge}
/>
</>
)}
{/* Only ⋯ and an open toolbar take the pointer: the hidden toolbar's
box must not reveal it, or catch clicks meant for the words. No gap
between them, so moving from ⋯ to the actions keeps them open. */}
<IconAction
label={t('stories.moveUp')}
icon={ArrowUpIcon}
disabled={disabled || index === 0}
onClick={() => onMove(-1)}
/>
<IconAction
label={t('stories.moveDown')}
icon={ArrowDownIcon}
disabled={disabled || index === count - 1}
onClick={() => onMove(1)}
/>
<IconAction
label={t('stories.removeLine')}
icon={TrashIcon}
disabled={disabled}
onClick={onRemove}
label={t('stories.lineActions')}
icon={EllipsisIcon}
className="pointer-events-auto opacity-0 transition-opacity group-hover/block:opacity-60 group-hover/actions:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-60"
onClick={() => setActionsOpen((open) => !open)}
/>
<div
role="toolbar"
aria-label={t('stories.lineActions')}
className={cn(
'pointer-events-none flex items-center gap-0.5 rounded-lg border border-border/60 bg-background/95 p-0.5 opacity-0 shadow-sm transition-opacity group-hover/actions:pointer-events-auto group-hover/actions:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100 has-data-popup-open:pointer-events-auto has-data-popup-open:opacity-100',
actionsOpen && 'pointer-events-auto opacity-100',
)}
>
{!heading && (
<>
{!line.profileId && voiceChip}
{!toneUnderText && toneChip}
<IconAction
label={t('stories.preview')}
icon={PlayIcon}
disabled={disabled || !canPreview}
onClick={onPreview}
/>
<IconAction
label={t('stories.insertPause')}
icon={PauseIcon}
disabled={disabled}
onClick={() => onInsert('[pause 0.5s]')}
/>
<IconAction
label={t('stories.mergeNext')}
hint={!canMerge ? t('stories.mergeNextHint') : undefined}
icon={MergeIcon}
disabled={disabled || !canMerge}
onClick={onMerge}
/>
</>
)}
<IconAction
label={t('stories.moveUp')}
icon={ArrowUpIcon}
disabled={disabled || index === 0}
onClick={() => onMove(-1)}
/>
<IconAction
label={t('stories.moveDown')}
icon={ArrowDownIcon}
disabled={disabled || index === count - 1}
onClick={() => onMove(1)}
/>
<IconAction
label={t('stories.removeLine')}
icon={TrashIcon}
disabled={disabled}
onClick={onRemove}
/>
</div>
</div>
</div>
);
}
type StoryBlockProps = Parameters<typeof StoryBlock>[0];
/**
* Whether a row would render the same: its data props match, and of the draft
* only the cast and book speed (all a row reads) are unchanged. Handlers are
* ignored; StoryEditor's read the current draft, so an older one is safe.
*/
export function sameStoryBlock(a: StoryBlockProps, b: StoryBlockProps) {
for (const key of Object.keys(b) as (keyof StoryBlockProps)[]) {
if (key === 'draft' || typeof b[key] === 'function') continue;
if (a[key] !== b[key]) return false;
}
return a.draft.cast === b.draft.cast && a.draft.globalSpeed === b.draft.globalSpeed;
}
/** A StoryBlock that re-renders only when what it shows changes. */
export const MemoStoryBlock = memo(StoryBlock, sameStoryBlock);
@@ -1,6 +1,8 @@
import { useLayoutEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { FingerprintIcon, PlusIcon, TrashIcon, UsersIcon } from 'lucide-react';
import { ChipPopover, ChoiceList } from './story-chips';
import { ChipPopover } from './story-chips';
import { VoicePickList } from './voice-pick-list';
import { SettingsSection } from './settings-section';
import { castColor } from './cast-color';
import { Button } from '@/components/ui/button';
@@ -16,6 +18,12 @@ interface Props {
export function StoryCast({ draft, profiles, disabled, onChange }: Props) {
const { t } = useTranslation();
// Voice picks can land a moment after they are made (a gallery voice is saved
// first), so they apply to the cast as it is then, not as it was.
const latest = useRef(draft);
useLayoutEffect(() => {
latest.current = draft;
});
return (
<SettingsSection
title={t('stories.cast')}
@@ -56,15 +64,18 @@ export function StoryCast({ draft, profiles, disabled, onChange }: Props) {
tone={character.profileId ? 'default' : 'muted'}
disabled={disabled}
className="h-8 max-w-32 px-2"
contentClassName="w-72"
content={(close) => (
<ChoiceList
<VoicePickList
label={t('stories.voiceChip', { name: character.name })}
options={[{ id: null, name: t('stories.defaultVoice') }, ...profiles]}
defaultLabel={t('stories.defaultVoice')}
profiles={profiles}
value={character.profileId}
disabled={disabled}
autoFocus
onSelect={(profileId) => {
onChange({
cast: draft.cast.map((c) =>
cast: latest.current.cast.map((c) =>
c.id === character.id ? { ...c, profileId } : c,
),
});
@@ -2,30 +2,37 @@ import { StoryStems } from './story-stems';
import { previewStoryLine } from './story-preview';
import { storyVoicesReady } from './story-inputs';
import { DEFAULT_SPLIT_MODE, splitStoryText, type SplitMode } from '@shared/utils/splitStoryText';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { buildAutoCast } from '@shared/utils/autoCast';
import { SAMPLE_STORY_CAST, SAMPLE_STORY_LINES, SAMPLE_STORY_NAME } from '@shared/data/sampleStory';
import { useTranslation } from 'react-i18next';
import {
BookmarkPlusIcon,
BookOpenTextIcon,
ChevronRightIcon,
PlusIcon,
ScissorsIcon,
SparklesIcon,
UsersIcon,
WandSparklesIcon,
} from 'lucide-react';
import { mergePronounCast, pronounCast } from './cast-cleanup';
import { IconAction, InfoTip } from './story-chips';
import { StoryBlock } from './story-block';
import { IconAction } from './story-chips';
import {
clipAt,
formatLineTime,
linesChangedSinceRender,
timingContext,
STORY_PLAYBACK,
} from './story-timeline-model';
import { trackOf, useStoryTimeline } from './story-timeline';
import { StoryInspector } from './story-inspector';
import { usePlaybackValue } from '@/lib/audio/playback-clock';
import { MemoStoryBlock } from './story-block';
import { Button } from '@/components/ui/button';
import { SplitPresetPicker } from './split-preset-picker';
import { StoryImport } from './story-import';
import { PipelineFailure } from '@/components/pipeline-failure';
import { describeError } from '@/lib/api/client';
import { reorder } from '@shared/utils/storyReorder';
import { isChapterLine } from '@shared/utils/storyExport';
import { scriptStats } from '@shared/utils/audiobookScript';
import { canMergeStoryLines, mergeStoryLineWithNext } from './story-merge';
import type { Draft } from './longform-session';
import { revokeObjectUrl } from '@/lib/audio/object-url';
@@ -36,6 +43,8 @@ interface Props {
canSynthesize?: boolean;
onChange: (patch: Partial<Draft>) => void;
onBusy?: (busy: boolean) => void;
/** Loads a text file into the paste box (the page owns file reading). */
onImportFile?: (file: File) => void;
}
function insertStoryToken(text: string, caret: number, token: string) {
@@ -76,33 +85,6 @@ export function speakerChangeFlags(lines: Draft['lines']) {
});
}
/**
* Estimated start time of every line in seconds, from its spoken words at the
* audiobook reading rate and its effective speed. Chapter headings take no
* time. It is the same estimate as the runtime under the script, laid out per
* line, so the gutter reads like a timeline before anything is rendered.
*/
export function lineStartTimes(lines: Draft['lines'], globalSpeed: number) {
let at = 0;
return lines.map((line) => {
const start = at;
if (!isChapterLine(line.text)) {
const speed = (line.speed && line.speed > 0 ? line.speed : globalSpeed) || 1;
at += scriptStats(line.text).runtimeSec / speed;
}
return start;
});
}
/** `M:SS`, or `H:MM:SS` from an hour on. */
export function formatTimecode(seconds: number) {
const total = Math.max(0, Math.round(seconds));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = String(total % 60).padStart(2, '0');
return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${s}` : `${m}:${s}`;
}
export function StoryEditor({
draft,
profiles,
@@ -110,10 +92,19 @@ export function StoryEditor({
canSynthesize = true,
onChange,
onBusy,
onImportFile,
}: Props) {
const { t } = useTranslation();
const controller = useRef<AbortController | null>(null);
const lineInputs = useRef(new Map<string, HTMLTextAreaElement>());
// Line rows skip re-rendering when their own props are unchanged (a
// keystroke in one line must not re-render 400 others), so their handlers
// can be from an older render: they read the draft from here, never from
// the render that created them.
const latest = useRef(draft);
useLayoutEffect(() => {
latest.current = draft;
});
const [preview, setPreview] = useState<{ id: string; url: string } | null>(null);
const [previewing, setPreviewing] = useState<string | null>(null);
const [previewError, setPreviewError] = useState<string | null>(null);
@@ -143,7 +134,7 @@ export function StoryEditor({
setPreviewError(null);
onBusy?.(true);
try {
const blob = await previewStoryLine(draft, line, current.signal, profiles);
const blob = await previewStoryLine(latest.current, line, current.signal, profiles);
if (!current.signal.aborted) setPreview({ id: line.id, url: URL.createObjectURL(blob) });
} catch (cause) {
if (!current.signal.aborted) setPreviewError(describeError(cause));
@@ -192,7 +183,7 @@ export function StoryEditor({
};
const update = (id: string, patch: Partial<Draft['lines'][number]>) =>
onChange({
lines: draft.lines.map((line) => (line.id === id ? { ...line, ...patch } : line)),
lines: latest.current.lines.map((line) => (line.id === id ? { ...line, ...patch } : line)),
});
const insertIntoLine = (line: Draft['lines'][number], token: string) => {
const input = lineInputs.current.get(line.id);
@@ -224,7 +215,30 @@ export function StoryEditor({
};
const speakerChanges = speakerChangeFlags(draft.lines);
const pronouns = pronounCast(draft.cast);
const starts = lineStartTimes(draft.lines, draft.globalSpeed);
const [selectedId, setSelectedId] = useState<string | null>(null);
const selected = draft.lines.find((line) => line.id === selectedId) ?? null;
const timeline = useStoryTimeline(draft);
const changedLines = useMemo(
() =>
draft.output
? linesChangedSinceRender(draft.lines, draft.globalSpeed, draft.outputScript, timingContext(draft))
: new Set<string>(),
[
draft.output,
draft.lines,
draft.globalSpeed,
draft.outputScript,
draft.cast,
draft.voice,
draft.language,
],
);
const activeId = usePlaybackValue(STORY_PLAYBACK, (clock) =>
// Only a measured timeline says which line the audio is on.
draft.output && timeline.measured && clock.time > 0
? (clipAt(timeline.clips, clock.time)?.id ?? null)
: null,
);
const add = (text = '') =>
onChange({
lines: [...draft.lines, { id: crypto.randomUUID(), text, profileId: null }],
@@ -252,69 +266,32 @@ export function StoryEditor({
{previewError && (
<PipelineFailure fallback={previewError} onDismiss={() => setPreviewError(null)} />
)}
<details
className="group studio-panel p-3"
<StoryImport
draft={draft}
profiles={profiles}
disabled={disabled}
open={inputOpen}
onToggle={(event) => setInputOpen(event.currentTarget.open)}
>
<summary className="flex cursor-pointer list-none items-center gap-2 text-sm font-medium">
<ChevronRightIcon className="size-4 text-muted-foreground transition-transform group-open:rotate-90" />
<WandSparklesIcon className="size-4 text-primary" aria-hidden="true" />
{t('stories.autocast')}
</summary>
<div className="mt-3 space-y-2">
<textarea
dir="auto"
aria-label={t('stories.autocast')}
placeholder={t('stories.splitPlaceholder')}
className="min-h-32 w-full rounded-lg border border-border/60 bg-background/40 p-3 text-sm outline-none focus-visible:ring-1 focus-visible:ring-ring"
value={script}
disabled={disabled}
onChange={(e) => setScript(e.target.value)}
/>
<div className="flex flex-wrap items-center gap-1">
<Button
size="sm"
variant="outline"
disabled={disabled || !script.trim()}
onClick={autoCast}
>
<WandSparklesIcon />
{t('stories.autocast')}
</Button>
<InfoTip text={t('stories.autocastHint')} />
<IconAction
size="icon-sm"
label={t('stories.splitIntoTracks')}
icon={ScissorsIcon}
disabled={disabled || !script.trim()}
onClick={() => {
const parts = splitStoryText(script, preset, charLimit);
onChange({
lines: [
...draft.lines,
...parts.map((text) => ({
id: crypto.randomUUID(),
text,
profileId: null,
})),
],
importText: '',
});
setNotice(t('stories.lines', { count: parts.length }));
}}
/>
<SplitPresetPicker
preset={preset}
onPreset={setPreset}
charLimit={charLimit}
onCharLimit={setCharLimit}
disabled={disabled}
/>
<InfoTip text={t('stories.splitModeHint')} />
</div>
</div>
</details>
onOpenChange={setInputOpen}
preset={preset}
onPreset={setPreset}
charLimit={charLimit}
onCharLimit={setCharLimit}
onScript={setScript}
onCast={autoCast}
onSplit={() => {
const parts = splitStoryText(script, preset, charLimit);
onChange({
lines: [
...draft.lines,
...parts.map((text) => ({ id: crypto.randomUUID(), text, profileId: null })),
],
importText: '',
});
setInputOpen(false);
setNotice(t('stories.lines', { count: parts.length }));
}}
onImportFile={onImportFile}
/>
{notice && (
<p role="status" className="-mt-2 px-1 text-xs text-muted-foreground">
{notice}
@@ -372,69 +349,116 @@ export function StoryEditor({
)}
{draft.lines.length > 0 && (
<div data-slot="story-script" className="space-y-px">
{draft.lines.map((line, index) => (
<StoryBlock
key={line.id}
line={line}
index={index}
count={draft.lines.length}
canMerge={canMergeStoryLines(line, draft.lines[index + 1]) && !previewing}
showSpeaker={speakerChanges[index]}
start={formatTimecode(starts[index])}
<div className="xl:grid xl:grid-cols-[minmax(0,1fr)_17rem] xl:items-start xl:gap-6">
<div className="min-w-0 space-y-4">
<div
data-slot="story-script"
className="space-y-px"
onFocus={(event) => {
const id = (event.target as HTMLElement)
.closest<HTMLElement>('[data-line-id]')
?.getAttribute('data-line-id');
if (id) setSelectedId(id);
}}
>
{draft.lines.map((line, index) => (
<MemoStoryBlock
key={line.id}
line={line}
index={index}
count={draft.lines.length}
canMerge={canMergeStoryLines(line, draft.lines[index + 1]) && !previewing}
showSpeaker={speakerChanges[index]}
start={formatLineTime(timeline.starts[index])}
active={activeId === line.id}
changed={changedLines.has(line.id)}
draft={draft}
profiles={profiles}
disabled={disabled}
canPreview={
canSynthesize && storyVoicesReady({ ...draft, lines: [line] }, profiles)
}
previewing={previewing === line.id}
previewUrl={preview?.id === line.id ? preview.url : null}
inputRef={(node) => {
if (node) lineInputs.current.set(line.id, node);
else lineInputs.current.delete(line.id);
}}
onUpdate={(patch) => update(line.id, patch)}
onPreview={() => void audition(line)}
onStopPreview={() => controller.current?.abort()}
onInsert={(token) => insertIntoLine(line, token)}
onInlineVoice={(profileId) => setInlineVoice(line, profileId)}
onMove={(direction) =>
onChange({
lines:
direction < 0
? reorder(
latest.current.lines,
line.id,
latest.current.lines[index - 1].id,
)
: reorder(
latest.current.lines,
latest.current.lines[index + 1].id,
line.id,
),
})
}
onRemove={() =>
onChange({ lines: latest.current.lines.filter((l) => l.id !== line.id) })
}
onMerge={() => {
if (disabled || controller.current) return;
const lines = mergeStoryLineWithNext(latest.current.lines, line.id);
if (lines) onChange({ lines });
}}
/>
))}
</div>
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => add()}>
<PlusIcon />
{t('stories.addLine')}
</Button>
<IconAction
size="icon-sm"
label={t('stories.addChapter')}
icon={BookmarkPlusIcon}
disabled={disabled}
onClick={() =>
add(
'# ' +
t('stories.chapterN', {
n: draft.lines.filter((line) => line.text.startsWith('# ')).length + 1,
}),
)
}
/>
</div>
</div>
<aside
aria-label={t('stories.inspector')}
className="sticky top-4 hidden max-h-[calc(100vh-7rem)] overflow-y-auto rounded-xl border border-border/60 bg-card/60 p-3 xl:block"
>
<StoryInspector
draft={draft}
profiles={profiles}
line={selected}
clips={timeline.clips}
disabled={disabled}
canPreview={canSynthesize && storyVoicesReady({ ...draft, lines: [line] }, profiles)}
previewing={previewing === line.id}
previewUrl={preview?.id === line.id ? preview.url : null}
inputRef={(node) => {
if (node) lineInputs.current.set(line.id, node);
else lineInputs.current.delete(line.id);
}}
onUpdate={(patch) => update(line.id, patch)}
onPreview={() => void audition(line)}
onStopPreview={() => controller.current?.abort()}
onInsert={(token) => insertIntoLine(line, token)}
onInlineVoice={(profileId) => setInlineVoice(line, profileId)}
onMove={(direction) =>
onChange({
lines:
direction < 0
? reorder(draft.lines, line.id, draft.lines[index - 1].id)
: reorder(draft.lines, draft.lines[index + 1].id, line.id),
})
canPreview={
Boolean(selected) &&
canSynthesize &&
storyVoicesReady({ ...draft, lines: selected ? [selected] : [] }, profiles)
}
onRemove={() => onChange({ lines: draft.lines.filter((l) => l.id !== line.id) })}
onMerge={() => {
if (disabled || controller.current) return;
const lines = mergeStoryLineWithNext(draft.lines, line.id);
if (lines) onChange({ lines });
}}
previewing={Boolean(selected) && previewing === selected?.id}
trackOf={(character) => trackOf(draft.cast, character)}
onUpdate={(patch) => selected && update(selected.id, patch)}
onPreview={() => selected && void audition(selected)}
onStopPreview={() => controller.current?.abort()}
/>
))}
</div>
)}
{draft.lines.length > 0 && (
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => add()}>
<PlusIcon />
{t('stories.addLine')}
</Button>
<IconAction
size="icon-sm"
label={t('stories.addChapter')}
icon={BookmarkPlusIcon}
disabled={disabled}
onClick={() =>
add(
'# ' +
t('stories.chapterN', {
n: draft.lines.filter((line) => line.text.startsWith('# ')).length + 1,
}),
)
}
/>
</aside>
</div>
)}
<StoryStems
@@ -0,0 +1,88 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import { formatExamples, scriptPreview, StoryImport } from './story-import';
import type { Draft } from './longform-session';
const SCRIPT = 'MARA: Hello.\nBEN: Hi there.\nMARA: Bye.';
function show(importText: string, extra: Partial<Parameters<typeof StoryImport>[0]> = {}) {
const props = {
draft: { importText, cast: [] } as unknown as Draft,
profiles: [],
disabled: false,
open: true,
onOpenChange: vi.fn(),
preset: 'paragraphs' as const,
onPreset: vi.fn(),
charLimit: 500,
onCharLimit: vi.fn(),
onScript: vi.fn(),
onCast: vi.fn(),
onSplit: vi.fn(),
onImportFile: vi.fn(),
...extra,
};
render(<StoryImport {...props} />);
return props;
}
it('previews the speakers and how many lines each action adds', () => {
const preview = scriptPreview(SCRIPT, [], [], 'sentences', 500)!;
expect(preview.speakers.map((s) => s.name.toUpperCase())).toEqual(['MARA', 'BEN']);
expect(preview.cast.tracks).toHaveLength(3);
expect(preview.narrated).toBe(false);
expect(scriptPreview('Once upon a time.', [], [], 'paragraphs', 500)!.narrated).toBe(true);
expect(scriptPreview(' ', [], [], 'paragraphs', 500)).toBeNull();
show(SCRIPT);
const found = document.querySelector('[data-slot="import-preview"]')!;
expect(found.textContent).toContain(i18n.t('stories.importSpeakers', { count: 2 }));
const cast = screen.getByRole('button', { name: new RegExp(i18n.t('stories.autocast')) });
expect(cast.textContent).toContain('3');
});
it('says what it does in its heading and teaches the formats while empty', () => {
show('');
expect(screen.getByText(i18n.t('stories.importTitle'))).toBeTruthy();
expect(screen.getByText('MARA: Hello.')).toBeTruthy();
for (const name of [i18n.t('stories.autocast'), i18n.t('stories.splitIntoTracks')])
expect(
(screen.getByRole('button', { name: new RegExp(name) }) as HTMLButtonElement).disabled,
).toBe(true);
});
it('casts on Ctrl+Enter and splits on demand', () => {
const props = show(SCRIPT);
const box = screen.getByRole('textbox', { name: i18n.t('stories.importTitle') });
fireEvent.keyDown(box, { key: 'Enter', ctrlKey: true });
expect(props.onCast).toHaveBeenCalledTimes(1);
fireEvent.keyDown(box, { key: 'Enter' });
expect(props.onCast).toHaveBeenCalledTimes(1);
fireEvent.click(
screen.getByRole('button', { name: new RegExp(i18n.t('stories.splitIntoTracks')) }),
);
expect(props.onSplit).toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: i18n.t('common.clear') }));
expect(props.onScript).toHaveBeenCalledWith('');
});
it('loads a dropped text file and ignores other files', () => {
const props = show('');
const box = screen.getByRole('textbox', { name: i18n.t('stories.importTitle') });
const drop = (name: string) =>
fireEvent.drop(box, { dataTransfer: { files: [new File(['x'], name)], types: ['Files'] } });
drop('photo.png');
expect(props.onImportFile).not.toHaveBeenCalled();
drop('chapter.txt');
expect(props.onImportFile).toHaveBeenCalledWith(expect.objectContaining({ name: 'chapter.txt' }));
});
it('shows the format examples in the reader’s language, prose attribution only in English', () => {
expect(formatExamples('Hello.', 'en-US')).toEqual([
'[Mara] Hello.',
'MARA: Hello.',
'“Hello,” Mara said.',
]);
expect(formatExamples('Hallo.', 'de')).toEqual(['[Mara] Hallo.', 'MARA: Hallo.']);
});
@@ -0,0 +1,302 @@
import { ChevronRightIcon, FileUpIcon, ListIcon, WandSparklesIcon, XIcon } from 'lucide-react';
import { useDeferredValue, useMemo, useState, type DragEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { buildAutoCast } from '@shared/utils/autoCast';
import { Button } from '@/components/ui/button';
import { Kbd } from '@/components/ui/kbd';
import { cn } from '@/lib/utils';
import { castColor } from './cast-color';
import { SplitPresetPicker } from './split-preset-picker';
import { splitStoryText, type SplitMode } from '@shared/utils/splitStoryText';
import type { Draft } from './longform-session';
/** Speaker chips shown before the rest collapse into "+N". */
const SHOWN_SPEAKERS = 6;
/** The script formats auto-cast understands, shown as examples. */
/**
* The script formats auto-cast reads, with a line in the reader's language.
* Speaker tags and screenplay names work in any language; prose attribution
* (`said Mara`) only knows English dialogue verbs, so it is shown in English.
*/
export function formatExamples(line: string, language: string) {
const examples = [`[Mara] ${line}`, `MARA: ${line}`];
if (language.startsWith('en')) examples.push('“Hello,” Mara said.');
return examples;
}
const MAC = typeof navigator !== 'undefined' && /Mac|iP(hone|ad)/.test(navigator.platform);
const TEXT_FILE = /\.(txt|md|srt|vtt|epub|pdf)$/i;
/** What pasting `script` would add, worked out as the user types. */
export function scriptPreview(
script: string,
cast: Draft['cast'],
profiles: readonly { id: string }[],
preset: SplitMode,
charLimit: number,
) {
if (!script.trim()) return null;
const cast_ = buildAutoCast(script, cast, [...profiles]);
return {
cast: cast_,
speakers: cast_.speakers.map((name) => {
const member = cast_.cast.find((c) => c.name.toLowerCase() === name.toLowerCase());
return { name, color: member ? castColor(cast_.cast, member.id) : undefined };
}),
narrated: cast_.speakers.length === 1 && cast_.speakers[0].toLowerCase() === 'narrator',
plainLines: splitStoryText(script, preset, charLimit).length,
words: script.trim().split(/\s+/).length,
};
}
/**
* Turns pasted or dropped text into story lines: either cast (each speaker
* found in the text gets a character and a voice) or plain lines split by
* sentence, paragraph or chapter. Shows what each would add before it runs.
*/
export function StoryImport({
draft,
profiles,
disabled,
open,
onOpenChange,
preset,
onPreset,
charLimit,
onCharLimit,
onScript,
onCast,
onSplit,
onImportFile,
}: {
draft: Draft;
profiles: readonly { id: string }[];
disabled: boolean;
open: boolean;
onOpenChange: (open: boolean) => void;
preset: SplitMode;
onPreset: (preset: SplitMode) => void;
charLimit: number;
onCharLimit: (limit: number) => void;
onScript: (text: string) => void;
onCast: () => void;
onSplit: () => void;
onImportFile?: (file: File) => void;
}) {
const { t, i18n } = useTranslation();
const script = draft.importText;
// Parsing a long paste on every keystroke would stall typing; the preview
// follows a frame behind instead.
const settled = useDeferredValue(script);
const preview = useMemo(
() => scriptPreview(settled, draft.cast, profiles, preset, charLimit),
[settled, draft.cast, profiles, preset, charLimit],
);
const [dragging, setDragging] = useState(false);
const empty = !script.trim();
const blocked = disabled || empty;
const fileFrom = (event: DragEvent) =>
[...event.dataTransfer.files].find((file) => TEXT_FILE.test(file.name));
const onDrop = (event: DragEvent) => {
setDragging(false);
const file = onImportFile && !disabled ? fileFrom(event) : undefined;
if (!file) return;
event.preventDefault();
onImportFile?.(file);
};
return (
<details
data-slot="story-import"
className="group studio-panel p-0"
open={open}
onToggle={(event) => onOpenChange(event.currentTarget.open)}
>
<summary className="flex cursor-pointer list-none items-center gap-3 rounded-[inherit] px-3 py-2.5 outline-none focus-visible:ring-2 focus-visible:ring-ring">
<ChevronRightIcon
aria-hidden="true"
className="size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-90"
/>
<span className="flex size-7 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
<WandSparklesIcon className="size-3.5" aria-hidden="true" />
</span>
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium">{t('stories.importTitle')}</span>
<span className="block truncate text-xs text-muted-foreground">
{t('stories.importSubtitle')}
</span>
</span>
{!open && !empty && (
<span className="shrink-0 rounded-full bg-secondary px-2 py-0.5 text-[11px] text-muted-foreground">
{t('stories.importPending')}
</span>
)}
</summary>
<div className="space-y-3 border-t border-border/50 p-3">
<div
className="relative"
onDragOver={(event) => {
if (!onImportFile || disabled || !event.dataTransfer.types.includes('Files')) return;
event.preventDefault();
setDragging(true);
}}
onDragLeave={() => setDragging(false)}
onDrop={onDrop}
>
<textarea
dir="auto"
aria-label={t('stories.importTitle')}
placeholder={t('stories.importPlaceholder')}
className="min-h-36 w-full resize-y rounded-lg border border-border/60 bg-background/40 p-3 pb-7 text-sm leading-relaxed outline-none transition-colors placeholder:text-muted-foreground/70 focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring"
value={script}
disabled={disabled}
onChange={(event) => onScript(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey) && !blocked) {
event.preventDefault();
onCast();
}
}}
/>
{!empty && (
<div className="pointer-events-none absolute inset-x-3 bottom-2 flex items-center justify-end gap-2 text-[11px] text-muted-foreground tabular-nums">
{preview && t('stories.importWords', { words: preview.words.toLocaleString() })}
<button
type="button"
className="pointer-events-auto inline-flex items-center gap-1 rounded px-1 hover:text-foreground disabled:opacity-50"
disabled={disabled}
onClick={() => onScript('')}
>
<XIcon className="size-3" aria-hidden="true" />
{t('common.clear')}
</button>
</div>
)}
{dragging && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/10 text-sm font-medium text-primary">
{t('stories.importDrop')}
</div>
)}
</div>
{empty ? (
<div className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
<span>{t('stories.importFormats')}</span>
{formatExamples(t('stories.importExampleLine'), i18n.language).map((example) => (
<code
key={example}
dir="ltr"
className="rounded-md border border-border/50 bg-background/40 px-1.5 py-0.5 font-mono text-[11px] text-foreground/80"
>
{example}
</code>
))}
{onImportFile && (
<label
className={cn(
'ms-auto inline-flex cursor-pointer items-center gap-1.5 rounded-md px-2 py-1 text-foreground/90 hover:bg-accent has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring',
disabled && 'pointer-events-none opacity-50',
)}
>
<FileUpIcon className="size-3.5" aria-hidden="true" />
{t('stories.importOpenFile')}
<input
type="file"
className="sr-only"
accept=".txt,.md,.srt,.vtt,.epub,.pdf"
disabled={disabled}
onChange={(event) => {
const file = event.target.files?.[0];
event.target.value = '';
if (file) onImportFile(file);
}}
/>
</label>
)}
</div>
) : (
preview && (
<div
data-slot="import-preview"
aria-live="polite"
className="flex flex-wrap items-center gap-1.5 text-xs"
>
<span className="text-muted-foreground">
{preview.narrated
? t('stories.importNarrated')
: t('stories.importSpeakers', { count: preview.speakers.length })}
</span>
{!preview.narrated &&
preview.speakers.slice(0, SHOWN_SPEAKERS).map((speaker) => (
<span
key={speaker.name}
dir="auto"
className="inline-flex items-center gap-1 rounded-full border border-border/50 px-2 py-0.5"
>
<span
aria-hidden="true"
className="size-1.5 rounded-full bg-muted-foreground/50"
style={speaker.color ? { backgroundColor: speaker.color } : undefined}
/>
{speaker.name}
</span>
))}
{!preview.narrated && preview.speakers.length > SHOWN_SPEAKERS && (
<span className="text-muted-foreground">
+{preview.speakers.length - SHOWN_SPEAKERS}
</span>
)}
</div>
)
)}
<div className="flex flex-wrap items-center gap-2 border-t border-border/40 pt-3">
<Button
size="sm"
disabled={blocked}
onClick={onCast}
aria-keyshortcuts={MAC ? 'Meta+Enter' : 'Control+Enter'}
>
<WandSparklesIcon />
{t('stories.autocast')}
{preview && (
<span
aria-hidden="true"
className="rounded bg-primary-foreground/15 px-1 text-[11px] tabular-nums"
>
{preview.cast.tracks.length.toLocaleString()}
</span>
)}
</Button>
<Kbd className="hidden sm:inline-flex" aria-hidden="true">
{MAC ? '⌘ ↵' : 'Ctrl ↵'}
</Kbd>
<span className="mx-1 hidden h-5 w-px bg-border/60 sm:block" aria-hidden="true" />
<Button size="sm" variant="outline" disabled={blocked} onClick={onSplit}>
<ListIcon />
{t('stories.splitIntoTracks')}
{preview && (
<span
aria-hidden="true"
className="rounded bg-secondary px-1 text-[11px] tabular-nums text-muted-foreground"
>
{preview.plainLines.toLocaleString()}
</span>
)}
</Button>
<SplitPresetPicker
preset={preset}
onPreset={onPreset}
charLimit={charLimit}
onCharLimit={onCharLimit}
disabled={disabled}
/>
</div>
<p className="text-[11px] leading-relaxed text-muted-foreground">
{t('stories.importActionsHint')}
</p>
</div>
</details>
);
}
@@ -0,0 +1,8 @@
import { expect, it } from 'vitest';
import { formatClipLength } from './story-inspector';
it('writes a clip length the way the app language does', () => {
expect(formatClipLength(1.5, 'en')).toBe('1.5s');
// German writes a decimal comma and its own unit.
expect(formatClipLength(1.5, 'de')).toMatch(/^1,5\D/);
});
@@ -0,0 +1,236 @@
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { PlayIcon, SquareIcon } from 'lucide-react';
import { isChapterLine } from '@shared/utils/storyExport';
import { castColor, isNarrator } from './cast-color';
import type { Draft } from './longform-session';
import { ChoiceList, IconAction } from './story-chips';
import { VoicePickList } from './voice-pick-list';
import { formatLineTime, formatSpeed, type TimelineClip } from './story-timeline-model';
/** A clip's length in seconds, as the app's language writes it (1.5 s, 1,5 s). */
export function formatClipLength(seconds: number, language: string) {
return new Intl.NumberFormat(language, {
style: 'unit',
unit: 'second',
unitDisplay: 'narrow',
minimumFractionDigits: 1,
maximumFractionDigits: 1,
}).format(seconds);
}
type Line = Draft['lines'][number];
type Profile = { id: string; name: string };
function Section({
title,
aside,
children,
}: {
title: string;
aside?: ReactNode;
children: ReactNode;
}) {
return (
<section className="space-y-1.5 border-t border-border/50 pt-3 first:border-t-0 first:pt-0">
<div className="flex items-center justify-between gap-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
<h3>{title}</h3>
{aside}
</div>
{children}
</section>
);
}
/** Track id → { lines, seconds } over the timeline (unassigned lines count as the narrator's). */
export function castBreakdown(clips: TimelineClip[], trackOf: (character?: string) => string) {
const totals = new Map<string, { lines: number; seconds: number }>();
for (const clip of clips) {
const id = trackOf(clip.character);
const row = totals.get(id) ?? { lines: 0, seconds: 0 };
row.lines += 1;
row.seconds += clip.end - clip.start;
totals.set(id, row);
}
return totals;
}
/**
* The editor's right-hand inspector, as in an editing suite: the selected
* line's speaker, voice, speed and timing, editable in place. With nothing
* selected it summarises who speaks how much.
*/
export function StoryInspector({
draft,
profiles,
line,
clips,
disabled,
canPreview,
previewing,
trackOf,
onUpdate,
onPreview,
onStopPreview,
}: {
draft: Draft;
profiles: Profile[];
line: Line | null;
clips: TimelineClip[];
disabled: boolean;
canPreview: boolean;
previewing: boolean;
trackOf: (character?: string) => string;
onUpdate: (patch: Partial<Line>) => void;
onPreview: () => void;
onStopPreview: () => void;
}) {
const { t, i18n } = useTranslation();
if (!line || isChapterLine(line.text)) {
const totals = castBreakdown(clips, trackOf);
// Lines with no speaker share the Narrator's track when the cast has one;
// otherwise they get their own row, as on the timeline.
const rows = [
...draft.cast
.filter((member) => totals.has(member.id))
.map((member) => ({
id: member.id,
name: member.name,
color: castColor(draft.cast, member.id),
})),
...(totals.has('')
? [{ id: '', name: t('stories.speakerNone'), color: undefined as string | undefined }]
: []),
];
return (
<div data-slot="story-inspector" className="space-y-3 text-xs">
<p className="text-muted-foreground">{t('stories.inspectorEmpty')}</p>
{rows.length > 0 && (
<Section title={t('stories.cast')}>
<ul className="space-y-1">
{rows.map((member) => {
const row = totals.get(member.id)!;
const color = member.color;
return (
<li key={member.id} className="flex items-center gap-2">
<span
aria-hidden="true"
className="size-2 shrink-0 rounded-full bg-muted-foreground/40"
style={color ? { backgroundColor: color } : undefined}
/>
<span className="min-w-0 flex-1 truncate">{member.name}</span>
<span className="tabular-nums text-muted-foreground">
{t('stories.lines', { count: row.lines })}
</span>
<span className="w-12 text-end font-mono tabular-nums text-muted-foreground">
{formatLineTime(row.seconds)}
</span>
</li>
);
})}
</ul>
</Section>
)}
</div>
);
}
const index = draft.lines.findIndex((l) => l.id === line.id);
const clip = clips.find((c) => c.id === line.id);
const character = draft.cast.find((c) => c.id === line.character);
const narrator = draft.cast.find(isNarrator);
const color = castColor(draft.cast, character?.id);
const ownSpeed = typeof line.speed === 'number' && line.speed > 0;
const speed = ownSpeed ? (line.speed as number) : draft.globalSpeed;
return (
<div data-slot="story-inspector" className="space-y-3 text-xs">
<div className="flex items-center gap-2">
<span
aria-hidden="true"
className="h-4 w-0.5 rounded-full bg-border"
style={color ? { backgroundColor: color } : undefined}
/>
<h3 className="min-w-0 flex-1 truncate text-sm font-medium">
{t('stories.lineOf', { index: index + 1, count: draft.lines.length })}
</h3>
<IconAction
label={t(previewing ? 'common.stop' : 'stories.preview')}
icon={previewing ? SquareIcon : PlayIcon}
disabled={!previewing && (disabled || !canPreview)}
onClick={previewing ? onStopPreview : onPreview}
/>
</div>
{clip && (
<dl className="grid grid-cols-2 gap-2 rounded-md bg-muted/30 px-2 py-1.5 font-mono tabular-nums">
<div>
<dt className="font-sans text-[10px] text-muted-foreground">
{t('stories.lineStart')}
</dt>
<dd>{formatLineTime(clip.start)}</dd>
</div>
<div>
<dt className="font-sans text-[10px] text-muted-foreground">
{t('stories.lineLength')}
</dt>
<dd>{formatClipLength(clip.end - clip.start, i18n.language)}</dd>
</div>
</dl>
)}
<Section title={t('stories.speaker')}>
<ChoiceList
label={t('stories.speaker')}
// Unassigned lines use the book voice, which may differ from a
// Narrator cast member's, so both stay choosable; with a Narrator in
// the cast the unassigned choice is named after its voice instead.
options={[
{ id: '', name: t(narrator ? 'stories.defaultVoice' : 'stories.speakerNone') },
...draft.cast,
]}
value={character ? character.id : ''}
disabled={disabled}
onSelect={(id) => onUpdate({ character: id || undefined })}
/>
</Section>
<Section title={t('stories.lineVoice')}>
<VoicePickList
label={t('stories.lineVoice')}
defaultLabel={t('stories.defaultVoice')}
profiles={profiles}
value={line.profileId}
disabled={disabled}
onSelect={(profileId) => onUpdate({ profileId })}
/>
</Section>
<Section
title={t('stories.speed')}
aside={
<span className="font-mono normal-case tabular-nums text-foreground/90">
{formatSpeed(speed, i18n.language)}
</span>
}
>
<input
className="w-full accent-primary"
aria-label={t('stories.speed')}
type="range"
min="0.5"
max="2"
step="0.05"
value={speed}
disabled={disabled}
onChange={(e) => onUpdate({ speed: Number(e.target.value) })}
/>
{ownSpeed && (
<button
type="button"
className="text-muted-foreground underline-offset-2 hover:text-foreground hover:underline disabled:opacity-50"
disabled={disabled}
onClick={() => onUpdate({ speed: null })}
>
{t('stories.reset')}
</button>
)}
</Section>
</div>
);
}
@@ -1,4 +1,4 @@
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { fireEvent, render as renderUi, screen, waitFor, within } from '@testing-library/react';
import { beforeEach, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
@@ -20,6 +20,19 @@ import {
type Line,
} from './longform-session';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactElement, ReactNode } from 'react';
// The voice list searches the gallery; keep it offline and pending here.
vi.mock('@/lib/api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/api/client')>()),
apiJson: vi.fn(() => new Promise(() => {})),
}));
function Queries({ children }: { children: ReactNode }) {
return <QueryClientProvider client={new QueryClient()}>{children}</QueryClientProvider>;
}
const render = (ui: ReactElement) => renderUi(ui, { wrapper: Queries });
const profiles = [
{ id: 'actor', name: 'Ava' },
{ id: 'guest', name: 'Ben' },
@@ -2,6 +2,7 @@ import { RotateCcwIcon, TimerIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { IconAction, InfoTip } from './story-chips';
import type { Draft } from './longform-session';
import { formatSpeed } from './story-timeline-model';
type SpeedLine = { speed?: number | null };
@@ -21,7 +22,7 @@ export function StorySpeed({
disabled: boolean;
onChange: (patch: Partial<Draft>) => void;
}) {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const overridden = linesWithOwnSpeed(draft.lines);
const clearLineSpeeds = () =>
onChange({ lines: draft.lines.map((l) => ({ ...l, speed: null })) });
@@ -33,10 +34,13 @@ export function StorySpeed({
<fieldset className="grid gap-1.5 border-0 p-0">
<div className="flex items-baseline gap-2 text-xs font-medium text-muted-foreground">
<TimerIcon className="size-4 self-center" aria-hidden="true" />
<legend className="float-left p-0">{t('stories.global_speed')}</legend>
{/* Muted like the other setting rows; the sidebar styles every legend
as a heading, so the legend itself is for screen readers. */}
<legend className="sr-only">{t('stories.global_speed')}</legend>
<span aria-hidden="true">{t('stories.global_speed')}</span>
<InfoTip text={t('stories.speedHint')} />
<output className="ml-auto font-mono tabular-nums text-foreground">
{`${draft.globalSpeed.toFixed(2)}×`}
{formatSpeed(draft.globalSpeed, i18n.language)}
</output>
</div>
<input
@@ -0,0 +1,299 @@
import { AUDIOBOOK_WPM } from '@shared/utils/audiobookScript';
import { parseChapterBody, pauseMilliseconds } from '@shared/utils/longformParser';
import { TAGS } from '@shared/utils/constants';
import { isChapterLine } from '@shared/utils/storyExport';
import type { AudiobookRenderChapter, Draft } from './longform-session';
type Line = Draft['lines'][number];
/** The playback source the Stories render player publishes its clock on. */
export const STORY_PLAYBACK = 'longform-stories';
export interface TimelineClip {
id: string;
character?: string;
start: number;
end: number;
}
export interface StoryTimeline {
clips: TimelineClip[];
/** Start of every line (headings included), indexed like `lines`. */
starts: number[];
total: number;
/** Positions come from a finished render's real durations, not only word estimates. */
measured: boolean;
}
/** Rough length of a voiced reaction such as `[laughter]` or `[sigh]`. */
export const REACTION_SECONDS = 0.8;
const REACTIONS = new Set(TAGS.map((tag) => tag.toLowerCase()));
const BRACKET = /\[[^\]]*\]/g;
/**
* Seconds of one line, from what the render will actually voice (the parser's
* spans): their words at the audiobook reading rate and effective speed, each
* reaction tag the engine voices (`[laughter]`), plus the silence of its
* `[pause …]` markers (which speed leaves alone, and which a render keeps even
* in a line with nothing to say).
*/
export function estimateLineSeconds(line: Line, globalSpeed: number) {
if (isChapterLine(line.text)) return 0;
const speed = (line.speed && line.speed > 0 ? line.speed : globalSpeed) || 1;
let spoken = 0;
for (const span of parseChapterBody(line.text)) {
let reactions = 0;
// The parser has already removed the markup that isn't spoken; a bracket
// left in the text is a voiced reaction or literal text (`[Appendix]`).
const spokenText = span.text.replace(BRACKET, (tag) => {
if (!REACTIONS.has(tag.toLowerCase())) return tag;
reactions++;
return ' ';
});
const words = spokenText.split(/\s+/).filter(Boolean).length;
// `[slow]`/`[fast]` set their span's own speed in place of the line's.
const spanSpeed = (span.speed && span.speed > 0 ? span.speed : speed) || 1;
spoken += ((words / AUDIOBOOK_WPM) * 60 + reactions * REACTION_SECONDS) / spanSpeed;
}
return spoken + pauseMilliseconds(line.text) / 1000;
}
/** What a render's sound depends on beyond each line's text. */
export interface VoiceContext {
cast: Draft['cast'];
/** The book voice, used by lines with no voice of their own or their speaker's. */
voice: string | null;
/** The language the render speaks in; changing it re-times every line. */
language?: string;
}
/**
* The context of a draft's render, from the same fields the render request
* sends. Every caller builds it here, so the saved key and the live comparison
* can never disagree about what counts.
*/
export function timingContext(
draft: Pick<Draft, 'cast' | 'voice' | 'language'>,
): VoiceContext {
return { cast: draft.cast, voice: draft.voice, language: draft.language };
}
/** The voice a line renders with, as the render resolves it. */
function lineVoice(line: Line, voices: VoiceContext | undefined) {
if (!voices) return '';
return (
line.profileId ||
voices.cast.find((member) => member.id === line.character)?.profileId ||
voices.voice ||
''
);
}
/** A short fingerprint of what a line renders as: its text, speaker, voice and speed. */
function lineKey(line: Line, voices?: VoiceContext) {
let hash = 0x811c9dc5;
for (const value of [
line.id,
line.text,
line.character ?? '',
String(line.speed ?? ''),
lineVoice(line, voices),
]) {
for (let i = 0; i < value.length; i++) hash = Math.imul(hash ^ value.charCodeAt(i), 0x01000193);
hash = Math.imul(hash ^ 0x1f, 0x01000193);
}
return (hash >>> 0).toString(36);
}
const KEY_PREFIX = 'story-timing:v3:';
/**
* A fingerprint of everything that sets the timing: book speed, then each
* line's key in order. Saved with a render, so the timeline only maps the
* render's real durations onto the script it was made from, and the editor
* can tell which lines changed since.
*/
export function storyTimingKey(lines: Line[], globalSpeed: number, voices?: VoiceContext) {
return (
KEY_PREFIX +
globalSpeed +
':' +
encodeURIComponent(voices?.language ?? '') +
':' +
lines.map((line) => lineKey(line, voices)).join(',')
);
}
/**
* Ids of lines that would sound different from the render saved with
* `renderKey`: edited, re-cast, re-timed or added since. Every line counts as
* changed after a book speed change. Empty when there is no key to compare
* (no render, or one saved before keys existed).
*/
export function linesChangedSinceRender(
lines: Line[],
globalSpeed: number,
renderKey: string,
voices?: VoiceContext,
) {
const changed = new Set<string>();
if (!renderKey.startsWith(KEY_PREFIX)) return changed;
const [speed, language, keys = ''] = renderKey.slice(KEY_PREFIX.length).split(':');
const rendered = new Set(keys ? keys.split(',') : []);
const sameWhole =
speed === String(globalSpeed) && language === encodeURIComponent(voices?.language ?? '');
for (const line of lines) {
if (isChapterLine(line.text)) continue;
if (!sameWhole || !rendered.has(lineKey(line, voices))) changed.add(line.id);
}
return changed;
}
function chapterSeconds(chapter: AudiobookRenderChapter) {
if (Number.isFinite(chapter.duration_ms) && Number(chapter.duration_ms) > 0)
return Number(chapter.duration_ms) / 1000;
if (Number.isFinite(chapter.duration_s) && Number(chapter.duration_s) > 0)
return Number(chapter.duration_s);
return 0;
}
/**
* Lay the script out in time. Every line gets an estimated length; when a
* render is available its real durations rescale the estimates so the clips
* and timecodes line up with the audio:
*
* - per chapter, when the render reports one duration per spoken chapter (a
* render splits at `# ` headings and skips chapters with nothing to say, as
* storyToSpans does);
* - otherwise across the whole story, when the audio's total length is known.
*
* Without a render the layout is the word-rate estimate.
*/
export function storyTimeline(
lines: Line[],
globalSpeed: number,
render?: {
chapters?: AudiobookRenderChapter[];
duration?: number;
/** Chapters the render skipped after failing. */
failed?: number;
/** storyTimingKey of the script the render was made from ('' when unknown). */
script?: string;
/** Who voices each line now, to compare with the render's key. */
voices?: VoiceContext;
},
): StoryTimeline {
const estimates = lines.map((line) => estimateLineSeconds(line, globalSpeed));
// Spoken chapters: runs of lines between headings that contain speech.
const groups: number[][] = [];
let current: number[] = [];
lines.forEach((line, index) => {
if (isChapterLine(line.text)) {
if (current.some((i) => estimates[i] > 0)) groups.push(current);
current = [];
} else current.push(index);
});
if (current.some((i) => estimates[i] > 0)) groups.push(current);
const scale = Array.from({ length: lines.length }, () => 1);
let measured = false;
// A render of an older version of the script can't place today's lines, and
// one with no saved key (resumed, or from before keys existed) can't prove
// it matches, so only a matching key lets real durations in.
const sameScript =
!!render?.script && render.script === storyTimingKey(lines, globalSpeed, render.voices);
const chapters = sameScript ? (render?.chapters ?? []) : [];
// A failed chapter is missing from the audio: its lines take no time.
const failed = chapters.map((chapter) => chapter.status === 'failed');
const rendered = chapters.map(chapterSeconds);
if (
rendered.length === groups.length &&
groups.length > 0 &&
rendered.every((s, g) => s > 0 || failed[g])
) {
groups.forEach((group, g) => {
const estimated = group.reduce((sum, i) => sum + estimates[i], 0);
for (const i of group) scale[i] = failed[g] ? 0 : estimated > 0 ? rendered[g] / estimated : 1;
});
measured = true;
} else if (sameScript && !render?.failed && render?.duration && render.duration > 0) {
const estimated = estimates.reduce((sum, s) => sum + s, 0);
if (estimated > 0) scale.fill(render.duration / estimated);
measured = estimated > 0;
}
const starts: number[] = [];
const clips: TimelineClip[] = [];
let at = 0;
lines.forEach((line, index) => {
starts.push(at);
const length = estimates[index] * scale[index];
if (length > 0)
clips.push({ id: line.id, character: line.character, start: at, end: at + length });
at += length;
});
return { clips, starts, total: at, measured };
}
/** A render's loudness outline from /audio-peaks: `peaks` (0-100) evenly spread over `duration`. */
export interface RenderPeaks {
duration: number;
peaks: number[];
}
/** Peaks per second requested for a render: enough detail at the deepest zoom. */
export function peakBuckets(seconds: number) {
return Math.max(200, Math.min(20000, Math.round(seconds * 20)));
}
/**
* The outline of `[start, end)` of the render in `bins` columns, each the
* loudest peak it covers, for drawing a clip's waveform.
*/
export function clipOutline(render: RenderPeaks, start: number, end: number, bins: number) {
const { peaks, duration } = render;
if (!peaks.length || duration <= 0 || end <= start || bins < 1) return [];
const perSecond = peaks.length / duration;
const from = Math.max(0, Math.floor(start * perSecond));
const to = Math.min(peaks.length, Math.max(from + 1, Math.ceil(end * perSecond)));
const count = Math.max(1, Math.min(bins, to - from));
return Array.from({ length: count }, (_, i) => {
let loudest = 0;
const a = from + Math.floor((i * (to - from)) / count);
const b = from + Math.floor(((i + 1) * (to - from)) / count);
for (let k = a; k < Math.max(b, a + 1); k++) loudest = Math.max(loudest, peaks[k] ?? 0);
return loudest;
});
}
/** The clip playing at `time`, or null between and after clips. */
export function clipAt(clips: TimelineClip[], time: number) {
let low = 0;
let high = clips.length - 1;
while (low <= high) {
const mid = (low + high) >> 1;
const clip = clips[mid];
if (time < clip.start) high = mid - 1;
else if (time >= clip.end) low = mid + 1;
else return clip;
}
return null;
}
/** `M:SS`, or `H:MM:SS` from an hour on. */
/** A speed such as 1.25×, written with the app language's decimal mark (1,25×). */
export function formatSpeed(speed: number, language: string) {
return (
new Intl.NumberFormat(language, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
speed,
) + '×'
);
}
export function formatLineTime(seconds: number) {
const total = Math.max(0, Math.round(seconds));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = String(total % 60).padStart(2, '0');
return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${s}` : `${m}:${s}`;
}
@@ -0,0 +1,27 @@
import { renderHook } from '@testing-library/react';
import { expect, it, vi } from 'vitest';
// A result found again only by its file name: playable, not proven to be that render.
vi.mock('./longform-session', async (importOriginal) => ({
...(await importOriginal<typeof import('./longform-session')>()),
getLongformResultState: () => ({
status: 'available',
recovering: false,
recoveryFailed: false,
availabilityOnly: true,
}),
}));
import { blankLongformDraft } from './longform-session';
import { useStoryTimeline } from './story-timeline';
import { storyTimingKey, timingContext } from './story-timeline-model';
it('keeps estimated clips for a result recovered only by its file name', () => {
const draft = blankLongformDraft();
draft.lines = [{ id: 'a', text: 'Hello there.', profileId: null }];
draft.output = 'story.m4b';
draft.outputScript = storyTimingKey(draft.lines, 1, timingContext(draft));
draft.outputChapters = [{ title: '', status: 'done', duration_s: 30 }];
const { result } = renderHook(() => useStoryTimeline(draft));
expect(result.current.measured).toBe(false);
});
@@ -0,0 +1,159 @@
import { act, fireEvent, render, renderHook, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
const api = vi.hoisted(() => ({
apiJson: vi.fn((..._args: unknown[]): Promise<unknown> => new Promise(() => {})),
}));
vi.mock('@/lib/api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/api/client')>()),
apiJson: api.apiJson,
}));
vi.mock('@/components/waveform-player', () => ({ WaveformPlayer: () => null }));
import {
getPlaybackSeek,
publishPlaybackClock,
resetPlaybackClock,
} from '@/lib/audio/playback-clock';
import { blankLongformDraft, type Draft } from './longform-session';
import {
cachedPeakCount,
focusStoryLine,
PEAKS_CACHE_LIMIT,
StoryTimeline,
trackOf,
useRenderPeaks,
} from './story-timeline';
import { StoryInspector } from './story-inspector';
import {
estimateLineSeconds,
formatSpeed,
linesChangedSinceRender,
STORY_PLAYBACK,
storyTimingKey,
timingContext,
} from './story-timeline-model';
const words = (n: number) => Array.from({ length: n }, () => 'word').join(' ');
const line = (id: string, text: string): Draft['lines'][number] => ({ id, text, profileId: null });
afterEach(() => {
resetPlaybackClock(STORY_PLAYBACK);
api.apiJson.mockReset();
api.apiJson.mockImplementation(() => new Promise(() => {}));
});
it('times literal bracketed text the render speaks', () => {
// The parser keeps `[Appendix]` as words; only reactions and markup are not words.
expect(estimateLineSeconds(line('a', '[Appendix]'), 1)).toBeGreaterThan(0);
});
it('marks every line changed when the output language changes', () => {
const draft = { ...blankLongformDraft(), lines: [line('a', 'Hello.'), line('b', 'Bye.')] };
const key = storyTimingKey(draft.lines, 1, timingContext(draft));
expect([...linesChangedSinceRender(draft.lines, 1, key, timingContext(draft))]).toEqual([]);
const french = { ...draft, language: 'French' };
expect([...linesChangedSinceRender(draft.lines, 1, key, timingContext(french))]).toEqual([
'a',
'b',
]);
});
it('writes speeds with the app language’s decimal mark', () => {
expect(formatSpeed(1.25, 'en')).toBe('1.25×');
expect(formatSpeed(1.25, 'de')).toBe('1,25×');
});
it('selects a line from the timeline even while its text is locked', () => {
document.body.innerHTML =
'<div data-line-id="a"><textarea disabled></textarea></div><div data-line-id="b"></div>';
const block = document.querySelector<HTMLElement>('[data-line-id="a"]')!;
block.scrollIntoView = vi.fn();
focusStoryLine('a');
expect(document.activeElement).toBe(block);
document.body.innerHTML = '';
});
it('keeps only the last few waveform outlines', async () => {
api.apiJson.mockImplementation(async () => ({ duration: 10, peaks: [1, 2, 3] }));
for (let i = 0; i < PEAKS_CACHE_LIMIT + 3; i++) {
const { result, unmount } = renderHook(() => useRenderPeaks(`story_${i}.m4b`, 10));
await waitFor(() => expect(result.current).not.toBeNull());
unmount();
}
expect(cachedPeakCount()).toBe(PEAKS_CACHE_LIMIT);
});
it('does not seek by position or show the estimate as the length when clips are estimates', () => {
const draft = blankLongformDraft();
draft.lines = [line('a', words(10)), line('b', words(10))];
draft.output = 'story.m4b';
draft.outputScript = ''; // No key: the render can't vouch for these positions.
const { container } = render(<StoryTimeline draft={draft} src="/audio/story.m4b" />);
act(() => publishPlaybackClock(STORY_PLAYBACK, 80, 95));
expect(container.querySelector('[data-slot="timeline-clock"]')?.textContent).toBe('1:20 / 1:35');
fireEvent.click(container.querySelector('[data-slot="timeline-track"]')!);
expect(getPlaybackSeek(STORY_PLAYBACK)).toBeFalsy();
expect(container.querySelector('[data-slot="timeline-playhead"]')).toBeNull();
});
it('moves between clips with the arrow keys, one of them in the Tab order', () => {
const draft = blankLongformDraft();
draft.lines = [line('a', words(10)), line('b', words(10)), line('c', words(10))];
const { container } = render(<StoryTimeline draft={draft} src={null} />);
const clips = () =>
Array.from(container.querySelectorAll<HTMLElement>('[data-slot="timeline-clip"]'));
expect(clips().map((clip) => clip.tabIndex)).toEqual([0, -1, -1]);
clips()[0].focus();
fireEvent.keyDown(clips()[0], { key: 'ArrowRight' });
expect(document.activeElement).toBe(clips()[1]);
expect(clips().map((clip) => clip.tabIndex)).toEqual([-1, 0, -1]);
fireEvent.keyDown(clips()[1], { key: 'End' });
expect(document.activeElement).toBe(clips()[2]);
});
it('ends a resize only when its own pointer lifts', () => {
const draft = blankLongformDraft();
draft.lines = [line('a', words(10))];
const { container } = render(<StoryTimeline draft={draft} src={null} />);
const handle = container.querySelector<HTMLElement>('[data-slot="timeline-resize"]')!;
const before = Number(handle.getAttribute('aria-valuenow'));
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientY: 500 });
// A second finger lifting must not stop the first one's drag.
fireEvent.pointerUp(handle, { pointerId: 2 });
fireEvent.pointerMove(handle, { pointerId: 1, clientY: 452 });
expect(Number(handle.getAttribute('aria-valuenow'))).toBe(before + 48);
fireEvent.pointerUp(handle, { pointerId: 1 });
fireEvent.pointerMove(handle, { pointerId: 1, clientY: 400 });
expect(Number(handle.getAttribute('aria-valuenow'))).toBe(before + 48);
localStorage.removeItem('voicestudio.stories.timelineHeight');
});
it('summarises unassigned lines when the cast has no Narrator', () => {
const draft = blankLongformDraft();
draft.cast = [{ id: 'mara', name: 'Mara', profileId: null }];
draft.lines = [{ ...line('a', words(10)), character: 'mara' }, line('b', words(10))];
const clips = [
{ id: 'a', character: 'mara', start: 0, end: 4 },
{ id: 'b', start: 4, end: 9 },
] as Parameters<typeof StoryInspector>[0]['clips'];
const { container } = render(
<StoryInspector
draft={draft}
profiles={[]}
line={null}
clips={clips}
disabled={false}
canPreview={false}
previewing={false}
trackOf={(character) => trackOf(draft.cast, character)}
onUpdate={vi.fn()}
onPreview={vi.fn()}
onStopPreview={vi.fn()}
/>,
);
const rows = Array.from(container.querySelectorAll('li')).map((row) => row.textContent);
expect(rows).toHaveLength(2);
expect(rows[1]).toContain(i18n.t('stories.speakerNone'));
});
@@ -0,0 +1,286 @@
import {
useLayoutEffect,
useMemo,
useRef,
useState,
type KeyboardEvent,
type MouseEvent,
} from 'react';
import {
clipOutline,
formatLineTime,
type RenderPeaks,
type TimelineClip,
} from './story-timeline-model';
/** Width of the speaker-name column, in pixels. */
export const TRACK_LABEL_WIDTH = 112;
/** Lane width before the scroller is measured (and in environments without layout). */
const FALLBACK_LANES_WIDTH = 800;
/** A clip narrower than this shows only its colour: a cut-off "L…" says nothing. */
export const MIN_LABELLED_CLIP = 44;
const RULER_STEPS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600];
/** A tick spacing that keeps a label every ~90 px. */
export function rulerStep(seconds: number, pixels: number) {
const target = (seconds / Math.max(pixels, 1)) * 90;
return RULER_STEPS.find((step) => step >= target) ?? 3600;
}
export interface TrackRow {
id: string;
name: string;
color?: string;
}
/**
* The scrolling body of the timeline: a ruler pinned to the top, speaker names
* pinned to the left, and lanes that scroll both ways under them. Everything is
* laid out in pixels from the measured width, so zooming widens the lanes and
* clips too narrow to read drop their label instead of showing "L…".
*/
export function TimelineTracks({
tracks,
clips,
total,
zoom,
height,
time,
canSeek,
rowOf,
textOf,
onSeek,
onClip,
peaks,
}: {
/** The render's loudness outline, drawn inside clips when they match the audio. */
peaks?: RenderPeaks | null;
tracks: TrackRow[];
clips: TimelineClip[];
total: number;
zoom: number;
height: number;
/** Playhead position in seconds, or null to hide it. */
time: number | null;
canSeek: boolean;
rowOf: (character?: string) => string;
textOf: (id: string) => string;
onSeek: (seconds: number) => void;
onClip: (clip: TimelineClip) => void;
}) {
const scroller = useRef<HTMLDivElement>(null);
const [viewport, setViewport] = useState(TRACK_LABEL_WIDTH + FALLBACK_LANES_WIDTH);
useLayoutEffect(() => {
const node = scroller.current;
if (!node) return;
const measure = () => node.clientWidth > 0 && setViewport(node.clientWidth);
measure();
if (typeof ResizeObserver === 'undefined') return;
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, []);
const lanes = Math.max(viewport - TRACK_LABEL_WIDTH, 120) * zoom;
const step = rulerStep(total, lanes);
const ticks = Array.from({ length: Math.floor(total / step) + 1 }, (_, i) => i * step);
const byTrack = useMemo(() => {
const rows = new Map<string, TimelineClip[]>();
for (const clip of clips) {
const row = rowOf(clip.character);
const list = rows.get(row);
if (list) list.push(clip);
else rows.set(row, [clip]);
}
return rows;
}, [clips, rowOf]);
// Keep the playhead in view while playing, like an editor's page-follow.
useLayoutEffect(() => {
const node = scroller.current;
if (!node || time === null || zoom === 1) return;
const x = (Math.min(time, total) / total) * lanes;
const left = node.scrollLeft;
const visible = node.clientWidth - TRACK_LABEL_WIDTH;
if (x < left || x > left + visible - 24) node.scrollLeft = Math.max(0, x - visible / 4);
}, [time, zoom, lanes, total]);
// The lanes below don't depend on the playhead, so they are built once per
// layout change instead of on every playback update; handlers read the
// latest callbacks through a ref.
const latest = useRef({ canSeek, onSeek, onClip, lanes, total });
useLayoutEffect(() => {
latest.current = { canSeek, onSeek, onClip, lanes, total };
});
// One clip is in the Tab order at a time; arrows move along the story.
const [active, setActive] = useState<string | null>(null);
const tabStop = clips.some((clip) => clip.id === active) ? active : (clips[0]?.id ?? null);
const order = useMemo(() => clips.map((clip) => clip.id), [clips]);
const lanesBody = useMemo(() => {
const px = (seconds: number) => (seconds / total) * lanes;
const seekFromPointer = (event: MouseEvent<HTMLElement>) => {
const now = latest.current;
if (!now.canSeek) return;
const box = event.currentTarget.getBoundingClientRect();
now.onSeek(((event.clientX - box.left) / now.lanes) * now.total);
};
const moveFocus = (event: KeyboardEvent<HTMLButtonElement>, id: string) => {
const index = order.indexOf(id);
const next =
event.key === 'ArrowRight' || event.key === 'ArrowDown'
? order[index + 1]
: event.key === 'ArrowLeft' || event.key === 'ArrowUp'
? order[index - 1]
: event.key === 'Home'
? order[0]
: event.key === 'End'
? order[order.length - 1]
: undefined;
if (!['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp', 'Home', 'End'].includes(event.key))
return;
event.preventDefault();
if (!next) return;
setActive(next);
scroller.current?.querySelector<HTMLElement>(`[data-clip-id="${CSS.escape(next)}"]`)?.focus();
};
return { px, seekFromPointer, moveFocus };
}, [lanes, total, order]);
const { px, seekFromPointer } = lanesBody;
const rows = useMemo(
() => (
<>
{tracks.map((track) => (
<div key={track.id} className="flex h-6 border-b border-border/20">
<div
className="sticky left-0 z-10 flex shrink-0 items-center gap-1.5 truncate border-e border-border/40 bg-card px-2 text-[11px] text-muted-foreground"
style={{ width: TRACK_LABEL_WIDTH }}
>
<span
aria-hidden="true"
className="size-2 shrink-0 rounded-full bg-muted-foreground/40"
style={track.color ? { backgroundColor: track.color } : undefined}
/>
<span dir="auto" className="truncate">
{track.name}
</span>
</div>
<div
data-slot="timeline-track"
className="relative"
style={{ width: lanes }}
onClick={seekFromPointer}
>
{(byTrack.get(track.id) ?? []).map((clip) => {
const text = textOf(clip.id);
const width = px(clip.end - clip.start);
return (
<button
key={clip.id}
type="button"
tabIndex={clip.id === tabStop ? 0 : -1}
data-slot="timeline-clip"
data-clip-id={clip.id}
aria-label={text.slice(0, 80)}
title={text.slice(0, 160)}
className="absolute inset-y-0.5 truncate rounded-[3px] border border-black/25 bg-muted-foreground/35 px-1 text-start text-[10px] leading-[18px] text-foreground/90 outline-none hover:brightness-125 focus-visible:ring-1 focus-visible:ring-ring"
style={{
left: px(clip.start),
width: Math.max(width, 2),
...(track.color
? { backgroundColor: `color-mix(in srgb, ${track.color} 45%, transparent)` }
: {}),
}}
onClick={(event) => {
event.stopPropagation();
setActive(clip.id);
latest.current.onClip(clip);
}}
onKeyDown={(event) => lanesBody.moveFocus(event, clip.id)}
>
{peaks && width >= 6 && (
<ClipWave
values={clipOutline(peaks, clip.start, clip.end, Math.floor(width / 2))}
/>
)}
{width >= MIN_LABELLED_CLIP ? <span className="relative">{text}</span> : null}
</button>
);
})}
</div>
</div>
))}
</>
),
[tracks, byTrack, lanes, peaks, textOf, tabStop, lanesBody],
);
return (
<div
ref={scroller}
// Time runs left to right in every language (as in editing suites), so
// positions, sticky columns and scrolling share one direction; names
// inside keep their own direction.
dir="ltr"
data-slot="timeline-scroller"
className="studio-scrollbar relative overflow-auto overscroll-contain"
style={{ maxHeight: height }}
>
<div className="relative" style={{ width: TRACK_LABEL_WIDTH + lanes }}>
<div className="sticky top-0 z-20 flex h-5 border-b border-border/40 bg-card">
<div
className="sticky left-0 z-10 shrink-0 border-e border-border/40 bg-card"
style={{ width: TRACK_LABEL_WIDTH }}
/>
<div
data-slot="timeline-ruler"
className={canSeek ? 'relative cursor-pointer' : 'relative'}
style={{ width: lanes }}
onClick={seekFromPointer}
>
{ticks.map((tick) => (
<span
key={tick}
className="absolute inset-y-0 border-s border-border/50 ps-1 font-mono text-[10px] leading-5 tabular-nums text-muted-foreground/70"
style={{ left: px(tick) }}
>
{formatLineTime(tick)}
</span>
))}
</div>
</div>
{rows}
{time !== null && (
<span
aria-hidden="true"
data-slot="timeline-playhead"
className="pointer-events-none absolute top-0 bottom-0 z-30 w-px bg-primary shadow-[0_0_0_1px_color-mix(in_srgb,var(--primary)_30%,transparent)]"
style={{ left: TRACK_LABEL_WIDTH + px(Math.min(time, total)) }}
/>
)}
</div>
</div>
);
}
/** A clip's slice of the render waveform, mirrored around the middle like an editor's clip. */
function ClipWave({ values }: { values: number[] }) {
if (!values.length) return null;
const d = values
.map((value, i) => {
const half = Math.max(1, value) / 2;
return `M${i + 0.5} ${50 - half}V${50 + half}`;
})
.join('');
return (
<svg
aria-hidden="true"
data-slot="clip-wave"
className="pointer-events-none absolute inset-0 size-full text-foreground/45"
viewBox={`0 0 ${values.length} 100`}
preserveAspectRatio="none"
>
<path d={d} stroke="currentColor" strokeWidth={1} vectorEffect="non-scaling-stroke" />
</svg>
);
}
@@ -0,0 +1,450 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import { parseChapterBody } from '@shared/utils/longformParser';
const media = vi.hoisted(() => ({
paused: true,
currentTime: 30,
duration: 120,
playbackRate: 1,
play: vi.fn(),
pause: vi.fn(),
}));
const api = vi.hoisted(() => ({
apiJson: vi.fn((..._args: unknown[]): Promise<unknown> => new Promise(() => {})),
}));
vi.mock('@/lib/api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/api/client')>()),
apiJson: api.apiJson,
}));
vi.mock('@/components/waveform-player', () => ({
WaveformPlayer: ({ playerRef }: { playerRef?: { current: unknown } }) => {
if (playerRef) playerRef.current = media;
return null;
},
}));
import {
getPlaybackSeek,
publishPlaybackClock,
resetPlaybackClock,
} from '@/lib/audio/playback-clock';
import { blankLongformDraft, type Draft } from './longform-session';
import { StoryTimeline, transportAction } from './story-timeline';
import { MIN_LABELLED_CLIP, rulerStep, TRACK_LABEL_WIDTH } from './story-timeline-tracks';
import {
clipAt,
formatLineTime,
STORY_PLAYBACK,
storyTimeline,
clipOutline,
estimateLineSeconds,
linesChangedSinceRender,
REACTION_SECONDS,
storyTimingKey,
timingContext,
} from './story-timeline-model';
const words = (n: number) => Array.from({ length: n }, () => 'word').join(' ');
afterEach(() => resetPlaybackClock(STORY_PLAYBACK));
it('estimates each line from its words and speed, skipping chapter headings', () => {
const lines: Draft['lines'] = [
{ id: 'h', text: '# One', profileId: null },
{ id: 'a', text: words(150), profileId: null },
{ id: 'b', text: words(150), profileId: null, speed: 2 },
{ id: 'c', text: 'Last.', profileId: null },
];
const { starts, clips, measured } = storyTimeline(lines, 1);
expect(measured).toBe(false);
expect(starts.slice(0, 2)).toEqual([0, 0]);
// The same words at double speed take half as long.
expect(starts[3] - starts[2]).toBeCloseTo(starts[2] / 2);
expect(clips.map((clip) => clip.id)).toEqual(['a', 'b', 'c']);
expect(formatLineTime(65)).toBe('1:05');
expect(formatLineTime(3725)).toBe('1:02:05');
});
it('lines clips up with a render per spoken chapter, skipping chapters with nothing to say', () => {
const lines: Draft['lines'] = [
{ id: 'h0', text: '# Empty', profileId: null },
{ id: 'h1', text: '# One', profileId: null },
{ id: 'a', text: words(10), profileId: null },
{ id: 'b', text: words(30), profileId: null },
{ id: 'h2', text: '# Two', profileId: null },
{ id: 'c', text: words(10), profileId: null },
];
const chapters = [
{ title: 'One', status: 'done', duration_s: 20 },
{ title: 'Two', status: 'done', duration_ms: 5000 },
];
const { clips, total, measured } = storyTimeline(lines, 1, {
chapters,
script: storyTimingKey(lines, 1),
});
expect(measured).toBe(true);
expect(total).toBeCloseTo(25);
// Chapter one's 20 s split by word count: 10 words then 30.
expect(clips[0]).toMatchObject({ id: 'a', start: 0 });
expect(clips[0].end).toBeCloseTo(5);
expect(clips[1].end).toBeCloseTo(20);
expect(clips[2].start).toBeCloseTo(20);
expect(clips[2].end).toBeCloseTo(25);
});
it('falls back to the audio length when chapter durations do not match the script', () => {
const lines: Draft['lines'] = [
{ id: 'a', text: words(10), profileId: null },
{ id: 'b', text: words(10), profileId: null },
];
const stale = storyTimeline(lines, 1, {
chapters: [
{ title: '1', status: 'done', duration_s: 3 },
{ title: '2', status: 'done', duration_s: 3 },
],
duration: 40,
script: storyTimingKey(lines, 1),
});
expect(stale.measured).toBe(true);
expect(stale.total).toBeCloseTo(40);
expect(clipAt(stale.clips, 25)?.id).toBe('b');
expect(clipAt(stale.clips, 41)).toBeNull();
});
it('spaces ruler labels about 90 px apart at any length and zoom', () => {
expect(rulerStep(30, 800)).toBe(5);
expect(rulerStep(600, 800)).toBe(120);
expect(rulerStep(600, 6400)).toBe(10);
expect(rulerStep(10 * 3600, 800)).toBe(3600);
});
it('draws one track per speaker, follows playback and seeks from a clip', () => {
const draft = blankLongformDraft();
draft.cast = [
{ id: 'narrator', name: 'Narrator', profileId: null },
{ id: 'mara', name: 'Mara', profileId: null },
];
draft.lines = [
{ id: 'a', text: words(10), profileId: null, character: 'narrator' },
{ id: 'b', text: words(10), profileId: null, character: 'mara' },
{ id: 'c', text: words(10), profileId: null },
];
draft.output = 'story.m4b';
draft.outputScript = storyTimingKey(draft.lines, 1, timingContext(draft));
draft.outputChapters = [{ title: '', status: 'done', duration_s: 30 }];
const { container } = render(<StoryTimeline draft={draft} src="/audio/story.m4b" />);
const tracks = container.querySelectorAll('[data-slot="timeline-track"]');
// The unassigned line shares the narrator's track instead of a second "Narrator" row.
expect(tracks).toHaveLength(2);
expect(screen.getAllByText('Narrator')).toHaveLength(1);
act(() => publishPlaybackClock(STORY_PLAYBACK, 15, 30));
const playhead = container.querySelector<HTMLElement>('[data-slot="timeline-playhead"]');
// Lanes default to 800 px beside the name column before layout is measured.
expect(playhead?.style.left).toBe(`${TRACK_LABEL_WIDTH + 400}px`);
expect(container.querySelector('[data-slot="timeline-clock"]')?.textContent).toBe('0:15 / 0:30');
const clips = container.querySelectorAll<HTMLElement>('[data-slot="timeline-clip"]');
// Clips are grouped by track: narrator (a, c), then Mara (b). Line c starts at 20 s.
fireEvent.click(clips[1]);
expect(getPlaybackSeek(STORY_PLAYBACK)?.time).toBeCloseTo(20);
});
it('says positions are estimates before anything is rendered and hides on request', () => {
const draft = blankLongformDraft();
draft.lines = [{ id: 'a', text: words(10), profileId: null }];
const { container } = render(<StoryTimeline draft={draft} src={null} />);
screen.getByRole('button', { name: i18n.t('stories.timelineEstimate') });
expect(container.querySelector('[data-slot="timeline-playhead"]')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: i18n.t('stories.hideTimeline') }));
expect(container.querySelector('[data-slot="timeline-track"]')).toBeNull();
screen.getByRole('button', { name: i18n.t('stories.showTimeline') });
});
it('drops the label of a clip too narrow to read instead of showing "L…"', () => {
const draft = blankLongformDraft();
draft.lines = [
{ id: 'long', text: words(200), profileId: null },
{ id: 'short', text: 'Hi.', profileId: null },
];
const { container } = render(<StoryTimeline draft={draft} src={null} />);
const [long, short] = Array.from(
container.querySelectorAll<HTMLElement>('[data-slot="timeline-clip"]'),
);
expect(parseFloat(short.style.width)).toBeLessThan(MIN_LABELLED_CLIP);
expect(short.textContent).toBe('');
expect(short.getAttribute('aria-label')).toBe('Hi.');
expect(long.textContent).not.toBe('');
});
it('resizes the track area from its handle and remembers the height', () => {
localStorage.removeItem('voicestudio.stories.timelineHeight');
const draft = blankLongformDraft();
draft.lines = [{ id: 'a', text: words(10), profileId: null }];
const { container, unmount } = render(<StoryTimeline draft={draft} src={null} />);
const handle = screen.getByRole('separator', { name: i18n.t('stories.resizeTimeline') });
const scroller = () =>
container.querySelector<HTMLElement>('[data-slot="timeline-scroller"]')!.style.maxHeight;
const before = Number(handle.getAttribute('aria-valuenow'));
fireEvent.keyDown(handle, { key: 'ArrowUp' });
expect(Number(handle.getAttribute('aria-valuenow'))).toBe(before + 24);
expect(scroller()).toBe(`${before + 24}px`);
unmount();
render(<StoryTimeline draft={draft} src={null} />);
expect(
screen
.getByRole('separator', { name: i18n.t('stories.resizeTimeline') })
.getAttribute('aria-valuenow'),
).toBe(String(before + 24));
localStorage.removeItem('voicestudio.stories.timelineHeight');
});
const line = (id: string, text: string): Draft['lines'][number] => ({ id, text, profileId: null });
it('gives pauses their silence, even in a chapter with nothing to say', () => {
const lines = [
line('h1', '# Intro'),
line('p', '[pause 10s]'),
line('h2', '# One'),
line('a', `${words(150)} [pause 2s]`),
];
const timeline = storyTimeline(lines, 1);
const speech = storyTimeline([line('x', words(150))], 1).total;
expect(timeline.clips.map((c) => [c.id, c.start, c.end])).toEqual([
['p', 0, 10],
['a', 10, 10 + speech + 2],
]);
// Both chapters are rendered, so per-chapter durations still line up.
const rendered = storyTimeline(lines, 1, {
chapters: [
{ title: 'Intro', status: 'done', duration_s: 10 },
{ title: 'One', status: 'done', duration_s: 31 },
],
script: storyTimingKey(lines, 1),
});
expect(rendered.measured).toBe(true);
expect(rendered.clips[1].start).toBe(10);
});
it('gives a failed chapter no time, since its audio is missing', () => {
const lines = [
line('h1', '# One'),
line('a', words(150)),
line('h2', '# Two'),
line('b', words(150)),
];
const timeline = storyTimeline(lines, 1, {
chapters: [
{ title: 'One', status: 'failed' },
{ title: 'Two', status: 'done', duration_s: 50 },
],
duration: 50,
failed: 1,
script: storyTimingKey(lines, 1),
});
expect(timeline.measured).toBe(true);
expect(timeline.clips.map((c) => [c.id, c.start, c.end])).toEqual([['b', 0, 50]]);
// Without per-chapter durations a partial render can't be spread over the script.
expect(
storyTimeline(lines, 1, { duration: 50, failed: 1, script: storyTimingKey(lines, 1) }).measured,
).toBe(false);
});
it('maps a render only onto the script it was made from', () => {
const lines = [line('a', words(150)), line('b', words(150))];
const render = { duration: 100, script: storyTimingKey(lines, 1) };
expect(storyTimeline(lines, 1, render).measured).toBe(true);
const reordered = [lines[1], lines[0]];
expect(storyTimeline(reordered, 1, render).measured).toBe(false);
expect(storyTimeline(lines, 1.2, render).measured).toBe(false);
// A render with no saved key (resumed, or saved before keys existed) can't
// prove it matches today's lines, so they keep their estimates.
expect(storyTimeline(lines, 1, { duration: 100, script: '' }).measured).toBe(false);
expect(storyTimeline(lines, 1, { duration: 100 }).measured).toBe(false);
});
it('lays the time grid out left to right in right-to-left languages', () => {
const draft = blankLongformDraft();
draft.lines = [line('a', words(10))];
const { container } = render(<StoryTimeline draft={draft} src={null} />);
expect(container.querySelector('[data-slot="timeline-scroller"]')?.getAttribute('dir')).toBe(
'ltr',
);
});
it('ends a resize drag when the pointer is cancelled', () => {
localStorage.removeItem('voicestudio.stories.timelineHeight');
const draft = blankLongformDraft();
draft.lines = [line('a', words(10))];
render(<StoryTimeline draft={draft} src={null} />);
const handle = screen.getByRole('separator', { name: i18n.t('stories.resizeTimeline') });
const height = () => Number(handle.getAttribute('aria-valuenow'));
const start = height();
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientY: 500 });
fireEvent.pointerMove(handle, { pointerId: 1, clientY: 450 });
expect(height()).toBe(start + 50);
fireEvent.pointerCancel(handle, { pointerId: 1 });
fireEvent.pointerMove(handle, { pointerId: 1, clientY: 300 });
expect(height()).toBe(start + 50);
localStorage.removeItem('voicestudio.stories.timelineHeight');
});
it('maps editing-suite keys, leaving fields, buttons and modified keys alone', () => {
const key = (k: string, target: Element = document.body, mods = {}) =>
transportAction({ key: k, target, altKey: false, ctrlKey: false, metaKey: false, ...mods });
expect([' ', 'k', 'J', 'l', 'Home', 'End', 'x'].map((k) => key(k))).toEqual([
'toggle',
'pause',
'back',
'forward',
'start',
'end',
null,
]);
expect(key('k', document.createElement('textarea'))).toBeNull();
expect(key(' ', document.createElement('button'))).toBeNull();
expect(key('j', document.body, { ctrlKey: true })).toBeNull();
});
it('drives the render from the keyboard', () => {
Object.assign(media, { paused: true, currentTime: 30, playbackRate: 1 });
media.play.mockImplementation(() => {
media.paused = false;
return Promise.resolve();
});
media.pause.mockImplementation(() => {
media.paused = true;
});
const draft = blankLongformDraft();
draft.lines = [{ id: 'a', text: words(10), profileId: null }];
render(<StoryTimeline draft={draft} src="/api/audio/story.m4b" />);
fireEvent.keyDown(document.body, { key: ' ' });
expect(media.play).toHaveBeenCalledOnce();
fireEvent.keyDown(document.body, { key: 'l' });
expect(media.playbackRate).toBe(1.5);
fireEvent.keyDown(document.body, { key: 'j' });
expect(media.currentTime).toBe(25);
fireEvent.keyDown(document.body, { key: 'k' });
expect(media.paused).toBe(true);
expect(media.playbackRate).toBe(1);
fireEvent.keyDown(document.body, { key: 'End' });
expect(media.currentTime).toBe(120);
// A key another control already used (a tab list's Home) leaves playback alone.
const tab = document.createElement('div');
document.body.append(tab);
tab.addEventListener('keydown', (event) => event.preventDefault());
fireEvent.keyDown(tab, { key: 'Home' });
expect(media.currentTime).toBe(120);
tab.remove();
});
it('names the lines that changed since the render', () => {
const lines = [line('h', '# One'), line('a', 'Hello.'), line('b', 'Hi.'), line('c', 'Bye.')];
const key = storyTimingKey(lines, 1);
expect([...linesChangedSinceRender(lines, 1, key)]).toEqual([]);
const edited = [
lines[0],
{ ...lines[1], text: 'Hello there.' },
{ ...lines[2], character: 'jan' },
{ ...lines[3], speed: 1.2 },
line('d', 'New.'),
];
expect([...linesChangedSinceRender(edited, 1, key)]).toEqual(['a', 'b', 'c', 'd']);
// A book speed change re-times every line; reordering alone changes none.
expect([...linesChangedSinceRender(lines, 1.1, key)]).toEqual(['a', 'b', 'c']);
expect([...linesChangedSinceRender([lines[2], lines[1]], 1, key)]).toEqual([]);
// No key (no render, or one saved before keys existed): nothing to compare.
expect(linesChangedSinceRender(edited, 1, '').size).toBe(0);
});
it('marks lines whose voice changed, directly, through their speaker or the book voice', () => {
const lines = [
{ ...line('a', 'Hello.'), character: 'mara' },
line('b', 'Hi.'),
{ ...line('c', 'Bye.'), profileId: 'p3' },
];
const cast = [{ id: 'mara', name: 'Mara', profileId: 'p1' }];
const voices = { cast, voice: 'book' };
const key = storyTimingKey(lines, 1, voices);
expect(linesChangedSinceRender(lines, 1, key, voices).size).toBe(0);
// The line's own voice.
const own = [lines[0], { ...lines[1], profileId: 'p9' }, lines[2]];
expect([...linesChangedSinceRender(own, 1, key, voices)]).toEqual(['b']);
// Its speaker's voice in the cast.
const recast = { cast: [{ ...cast[0], profileId: 'p2' }], voice: 'book' };
expect([...linesChangedSinceRender(lines, 1, key, recast)]).toEqual(['a']);
// The book voice, used by lines with neither.
expect([...linesChangedSinceRender(lines, 1, key, { cast, voice: 'other' })]).toEqual(['b']);
// The timeline stops mapping the old audio onto the re-voiced script too.
const timeline = storyTimeline(own, 1, {
chapters: [{ title: '', status: 'done', duration_s: 9 }],
script: key,
voices,
});
expect(timeline.measured).toBe(false);
});
it('times [slow] and [fast] spans at their own speed', () => {
const plain = estimateLineSeconds(line('a', words(10)), 1);
// A [fast] span replaces the line's speed for its words only.
const half = `${words(5)} [fast]${words(5)}[/fast]`;
const fast = parseChapterBody(half).find((span) => span.speed)?.speed ?? 1;
expect(estimateLineSeconds(line('b', half), 1)).toBeCloseTo(plain / 2 + plain / 2 / fast);
// At another book speed, only the untagged words follow it.
expect(estimateLineSeconds(line('c', half), 0.5)).toBeCloseTo(plain + plain / 2 / fast);
});
it('gives reaction-only lines the time the engine voices them in', () => {
expect(estimateLineSeconds(line('a', '[laughter]'), 1)).toBeCloseTo(REACTION_SECONDS);
expect(estimateLineSeconds(line('b', '[sigh] [laughter]'), 2)).toBeCloseTo(REACTION_SECONDS);
// Other markup is still not spoken.
expect(estimateLineSeconds(line('c', '[voice:p1]'), 1)).toBe(0);
const withWords = estimateLineSeconds(line('d', 'Well [laughter] fine.'), 1);
expect(withWords).toBeCloseTo(REACTION_SECONDS + (2 / 155) * 60);
// A chapter of reactions alone is still a spoken chapter, so later chapters
// stay aligned with the render's.
const lines = [
line('h1', '# One'),
line('r', '[laughter]'),
line('h2', '# Two'),
line('w', words(10)),
];
const timeline = storyTimeline(lines, 1, {
chapters: [
{ title: 'One', status: 'done', duration_s: 2 },
{ title: 'Two', status: 'done', duration_s: 8 },
],
script: storyTimingKey(lines, 1),
});
expect(timeline.measured).toBe(true);
expect(timeline.starts[3]).toBeCloseTo(2);
});
it('outlines a clip from the loudest peak in each column', () => {
const render = { duration: 4, peaks: [10, 80, 20, 40, 0, 0, 90, 5] };
expect(clipOutline(render, 0, 2, 2)).toEqual([80, 40]);
expect(clipOutline(render, 3, 4, 10)).toEqual([90, 5]);
expect(clipOutline(render, 2, 2, 4)).toEqual([]);
});
it('draws the render waveform in clips once their timing matches the audio', async () => {
api.apiJson.mockResolvedValue({ duration: 100, peaks: Array.from({ length: 2000 }, () => 50) });
const draft = blankLongformDraft();
draft.lines = [
{ id: 'a', text: words(150), profileId: null },
{ id: 'b', text: words(150), profileId: null },
];
draft.output = 'story_1.m4b';
draft.outputScript = storyTimingKey(draft.lines, 1, timingContext(draft));
draft.outputChapters = [{ title: 'Story', status: 'done', duration_s: 100 }];
const { container } = render(<StoryTimeline draft={draft} src="/api/audio/story_1.m4b" />);
await screen.findAllByRole('button', { name: /word/ });
await act(async () => {});
expect(api.apiJson).toHaveBeenCalledWith(
'/audio-peaks/story_1.m4b?buckets=2000',
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
expect(container.querySelectorAll('[data-slot="clip-wave"]')).toHaveLength(2);
});
@@ -0,0 +1,475 @@
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type KeyboardEvent,
type PointerEvent,
type ReactNode,
} from 'react';
import { useTranslation } from 'react-i18next';
import {
AudioWaveformIcon,
ChevronDownIcon,
ChevronUpIcon,
ZoomInIcon,
ZoomOutIcon,
} from 'lucide-react';
import { WaveformPlayer } from '@/components/waveform-player';
import { apiJson } from '@/lib/api/client';
import type { MediaPlayerInstance } from '@/components/media-player';
import { requestPlaybackSeek, usePlaybackValue } from '@/lib/audio/playback-clock';
import { castColor, isNarrator } from './cast-color';
import { IconAction, InfoTip } from './story-chips';
import { TimelineTracks } from './story-timeline-tracks';
import {
formatLineTime,
STORY_PLAYBACK,
storyTimeline,
type StoryTimeline as Timeline,
linesChangedSinceRender,
timingContext,
peakBuckets,
type RenderPeaks,
} from './story-timeline-model';
import { getLongformResultState, type Draft } from './longform-session';
const ZOOM_LEVELS = [1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32] as const;
const HEIGHT_KEY = 'voicestudio.stories.timelineHeight';
const MIN_HEIGHT = 72;
const MAX_HEIGHT = 480;
const DEFAULT_HEIGHT = 176;
/** The dock's saved track-area height, clamped to what fits. */
export function readHeight() {
try {
const saved = Number(localStorage.getItem(HEIGHT_KEY));
if (Number.isFinite(saved) && saved > 0)
return Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, saved));
} catch {
// Storage unavailable: use the default.
}
return DEFAULT_HEIGHT;
}
/** The script laid out in time, shared by the gutter timecodes and the timeline dock. */
export function useStoryTimeline(draft: Draft): Timeline {
const renderSeconds = usePlaybackValue(STORY_PLAYBACK, (clock) => clock.duration);
// A result recovered only by finding its file name can't vouch that the file
// holds that render's audio: it still plays, but clips keep their estimates.
const verified = !getLongformResultState('stories').availabilityOnly;
return useMemo(
() =>
storyTimeline(
draft.lines,
draft.globalSpeed,
draft.output && verified
? {
chapters: draft.outputChapters,
duration: renderSeconds,
failed: draft.outputFailedChapters,
script: draft.outputScript,
voices: timingContext(draft),
}
: undefined,
),
[
verified,
draft.lines,
draft.globalSpeed,
draft.output,
draft.outputChapters,
draft.outputFailedChapters,
draft.outputScript,
renderSeconds,
draft.cast,
draft.voice,
draft.language,
],
);
}
const peaksCache = new Map<string, RenderPeaks>();
/** Each render gets a new file name, so keep only the last few outlines. */
export const PEAKS_CACHE_LIMIT = 4;
function cachePeaks(key: string, peaks: RenderPeaks) {
peaksCache.delete(key);
peaksCache.set(key, peaks);
for (const old of peaksCache.keys()) {
if (peaksCache.size <= PEAKS_CACHE_LIMIT) break;
peaksCache.delete(old);
}
}
/** Test seam: how many outlines are held. */
export const cachedPeakCount = () => peaksCache.size;
/**
* The render's loudness outline from the backend (decoded there at a low
* rate, so a long render costs the browser nothing), or null while loading,
* on failure, or with no render. Cached per render and detail level.
*/
export function useRenderPeaks(output: string, seconds: number) {
const buckets = peakBuckets(seconds);
const key = output ? `${output}|${buckets}` : '';
const [loaded, setLoaded] = useState<{ key: string; peaks: RenderPeaks } | null>(null);
useEffect(() => {
if (!key || peaksCache.has(key)) return;
const controller = new AbortController();
apiJson<RenderPeaks>(`/audio-peaks/${encodeURIComponent(output)}?buckets=${buckets}`, {
signal: controller.signal,
})
.then((peaks) => {
if (!Array.isArray(peaks?.peaks) || !(peaks.duration > 0)) return;
cachePeaks(key, peaks);
setLoaded({ key, peaks });
})
// The waveform is decoration: without it the clips still work.
.catch(() => {});
return () => controller.abort();
}, [key, output, buckets]);
if (!key) return null;
return peaksCache.get(key) ?? (loaded?.key === key ? loaded.peaks : null);
}
export type TransportAction = 'toggle' | 'pause' | 'back' | 'forward' | 'start' | 'end';
/**
* The editing-suite key for a keydown, or null. Keys typed into a field, or
* with a modifier held, stay with the field and the app.
*/
export function transportAction(event: {
key: string;
target: EventTarget | null;
altKey: boolean;
ctrlKey: boolean;
metaKey: boolean;
}): TransportAction | null {
if (event.altKey || event.ctrlKey || event.metaKey) return null;
const target = event.target as HTMLElement | null;
if (target?.closest?.('input, textarea, select, [contenteditable=""], [contenteditable="true"]'))
return null;
// A focused button or link already acts on Space.
if (event.key === ' ' && target?.closest?.('button, a, [role="button"], [role="slider"]'))
return null;
switch (event.key.toLowerCase()) {
case ' ':
return 'toggle';
case 'k':
return 'pause';
case 'j':
return 'back';
case 'l':
return 'forward';
case 'home':
return 'start';
case 'end':
return 'end';
default:
return null;
}
}
/** Playback speeds L steps through while playing, as in editing suites. */
const SHUTTLE_RATES = [1, 1.5, 2] as const;
const JUMP_BACK_SECONDS = 5;
/**
* The track a line sits on. Lines with no (or a removed) speaker are read in
* the default voice, which the script labels Narrator, so they share the
* narrator's track when the cast has one.
*/
export function trackOf(cast: Draft['cast'], character?: string) {
if (character && cast.some((member) => member.id === character)) return character;
return cast.find(isNarrator)?.id ?? '';
}
/**
* Select a script line and bring it into view: the caret goes to its text, or,
* while editing is locked (a render running) and the text can't take focus,
* to the line itself, so the inspector still follows the selection.
*/
export function focusStoryLine(id: string) {
const block = document.querySelector<HTMLElement>(`[data-line-id="${CSS.escape(id)}"]`);
if (!block) return;
block.scrollIntoView({ block: 'center', behavior: 'smooth' });
const text = block.querySelector('textarea');
if (text && !text.disabled) {
text.focus({ preventScroll: true });
return;
}
if (!block.hasAttribute('tabindex')) block.tabIndex = -1;
block.focus({ preventScroll: true });
}
/**
* The editor's bottom dock, laid out like an editing suite: the render's play
* bar, then one track per speaker with each line as a clip. Clips sit where the
* line plays in the last render (or at estimated positions before one exists);
* the playhead follows playback, and clicking a clip selects its line and
* moves the playhead there.
*/
export function StoryTimeline({
draft,
src,
actions,
status,
}: {
draft: Draft;
/** The last render's audio URL, when there is one. */
src: string | null;
/** Render actions (download, cue sheet) shown in the header. */
actions?: ReactNode;
/** What the play bar is playing (the last completed render, partial-render notes). */
status?: ReactNode;
}) {
const { t } = useTranslation();
const timeline = useStoryTimeline(draft);
const changed = useMemo(
() =>
draft.output
? linesChangedSinceRender(draft.lines, draft.globalSpeed, draft.outputScript, timingContext(draft)).size
: 0,
[
draft.output,
draft.lines,
draft.globalSpeed,
draft.outputScript,
draft.cast,
draft.voice,
draft.language,
],
);
const time = usePlaybackValue(STORY_PLAYBACK, (clock) => clock.time);
const renderSeconds = usePlaybackValue(STORY_PLAYBACK, (clock) => clock.duration);
const [open, setOpen] = useState(true);
const [zoomIndex, setZoomIndex] = useState(0);
const zoom = ZOOM_LEVELS[zoomIndex];
const total = Math.max(timeline.total, 1);
const rowOf = useCallback((character?: string) => trackOf(draft.cast, character), [draft.cast]);
const tracks = useMemo(() => {
const used = new Set(timeline.clips.map((clip) => trackOf(draft.cast, clip.character)));
const rows = draft.cast
.filter((member) => used.has(member.id))
.map((member) => ({
id: member.id,
name: member.name,
color: castColor(draft.cast, member.id),
}));
if (used.has('')) rows.push({ id: '', name: t('stories.speakerNone'), color: undefined });
return rows;
}, [draft.cast, timeline.clips, t]);
const lineText = useMemo(
() => new Map(draft.lines.map((line) => [line.id, line.text])),
[draft.lines],
);
const textOf = useCallback((id: string) => lineText.get(id) ?? '', [lineText]);
// Editing-suite keys for the render: Space plays or pauses, J jumps back,
// K pauses, L plays (again for faster), Home/End go to either end.
const player = useRef<MediaPlayerInstance | null>(null);
useEffect(() => {
if (!src) return;
const onKey = (event: globalThis.KeyboardEvent) => {
// Another control (a tab list's Home/End) already used this key.
if (event.defaultPrevented) return;
const action = transportAction(event);
const media = player.current;
if (!action || !media) return;
event.preventDefault();
if (action === 'toggle') {
if (media.paused) void media.play().catch(() => {});
else void media.pause();
} else if (action === 'pause') {
void media.pause();
media.playbackRate = 1;
} else if (action === 'back') {
media.currentTime = Math.max(0, media.currentTime - JUMP_BACK_SECONDS);
} else if (action === 'forward') {
if (media.paused) {
media.playbackRate = 1;
void media.play().catch(() => {});
} else {
const next = SHUTTLE_RATES.find((rate) => rate > media.playbackRate);
media.playbackRate = next ?? SHUTTLE_RATES[SHUTTLE_RATES.length - 1];
}
} else if (action === 'start') {
media.currentTime = 0;
} else if (Number.isFinite(media.duration)) {
media.currentTime = media.duration;
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [src]);
const peaks = useRenderPeaks(timeline.measured ? draft.output : '', timeline.total);
const [height, setHeight] = useState(readHeight);
const resize = (next: number) => {
const clamped = Math.round(Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, next)));
setHeight(clamped);
try {
localStorage.setItem(HEIGHT_KEY, String(clamped));
} catch {
// Private mode or a full quota: the size still applies for this session.
}
};
// The drag in progress: pointer capture keeps moves on the handle, and
// release, cancel, lost capture or unmount all end it.
const endDrag = useRef<(() => void) | null>(null);
useEffect(() => () => endDrag.current?.(), []);
const startResize = (event: PointerEvent<HTMLElement>) => {
if (event.button !== 0) return;
event.preventDefault();
endDrag.current?.();
const handle = event.currentTarget;
const pointer = event.pointerId;
const origin = event.clientY;
const from = height;
const move = (e: globalThis.PointerEvent) => {
if (e.pointerId === pointer) resize(from + (origin - e.clientY));
};
// Only this drag's pointer ends it: a second finger or pen lifting off the
// handle must not stop the first one's resize.
const stop = (e?: Event) => {
if (e && 'pointerId' in e && (e as globalThis.PointerEvent).pointerId !== pointer) return;
handle.removeEventListener('pointermove', move);
for (const type of ['pointerup', 'pointercancel', 'lostpointercapture'] as const)
handle.removeEventListener(type, stop);
if (handle.hasPointerCapture?.(pointer)) handle.releasePointerCapture(pointer);
endDrag.current = null;
};
handle.setPointerCapture?.(pointer);
handle.addEventListener('pointermove', move);
for (const type of ['pointerup', 'pointercancel', 'lostpointercapture'] as const)
handle.addEventListener(type, stop);
endDrag.current = () => stop();
};
// Seeking by position needs clips that match the audio: with estimates, a
// point on the lanes is not that moment of the render.
const canSeek = Boolean(src) && timeline.measured;
const seek = (seconds: number) => {
if (canSeek) requestPlaybackSeek(STORY_PLAYBACK, Math.max(0, Math.min(seconds, total)));
};
const zoomBy = (delta: number) =>
setZoomIndex((index) => Math.max(0, Math.min(ZOOM_LEVELS.length - 1, index + delta)));
const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
if (event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLInputElement)
return;
if (event.key === '+' || event.key === '=') zoomBy(1);
else if (event.key === '-') zoomBy(-1);
else return;
event.preventDefault();
};
if (!timeline.clips.length && !src) return null;
return (
<section
data-slot="story-timeline"
aria-label={t('stories.timeline')}
onKeyDown={onKeyDown}
className="overflow-hidden rounded-xl border border-border/70 bg-card/95 shadow-lg backdrop-blur-lg"
>
<div className="flex h-9 items-center gap-1.5 border-b border-border/50 px-1.5">
<IconAction
label={t(open ? 'stories.hideTimeline' : 'stories.showTimeline')}
icon={open ? ChevronDownIcon : ChevronUpIcon}
onClick={() => setOpen((value) => !value)}
/>
<AudioWaveformIcon className="size-3.5 text-primary" aria-hidden="true" />
<span className="text-xs font-medium">{t('stories.timeline')}</span>
<span
data-slot="timeline-clock"
className="ms-1 font-mono text-[11px] tabular-nums text-muted-foreground"
>
{formatLineTime(src ? time : 0)} /{' '}
{formatLineTime(
src && !timeline.measured && renderSeconds > 0 ? renderSeconds : timeline.total,
)}
</span>
{!timeline.measured && <InfoTip text={t('stories.timelineEstimate')} />}
{src && <InfoTip text={t('stories.transportKeys')} />}
{changed > 0 && (
<span
data-slot="timeline-changed"
className="ms-1 flex items-center gap-1 text-[11px] text-amber-500"
>
<span aria-hidden="true" className="size-1.5 rounded-full bg-amber-500" />
{t('stories.changedSinceRender', { count: changed })}
</span>
)}
<span className="flex-1" />
{open && (
<>
<IconAction
label={t('trimmer.zoom_out')}
icon={ZoomOutIcon}
disabled={zoomIndex === 0}
onClick={() => zoomBy(-1)}
/>
<IconAction
label={t('trimmer.zoom_in')}
icon={ZoomInIcon}
disabled={zoomIndex === ZOOM_LEVELS.length - 1}
onClick={() => zoomBy(1)}
/>
</>
)}
{actions}
</div>
{src && (
<div className="border-b border-border/40 px-2 py-1">
{status}
<WaveformPlayer
showWaveform={false}
src={src}
source={STORY_PLAYBACK}
playerRef={player}
/>
</div>
)}
{open && timeline.clips.length > 0 && (
<>
<div
role="separator"
aria-orientation="horizontal"
aria-label={t('stories.resizeTimeline')}
aria-valuemin={MIN_HEIGHT}
aria-valuemax={MAX_HEIGHT}
aria-valuenow={height}
tabIndex={0}
data-slot="timeline-resize"
className="h-1.5 cursor-row-resize border-b border-border/40 bg-muted/30 outline-none hover:bg-primary/30 focus-visible:bg-primary/40"
onPointerDown={startResize}
onKeyDown={(event) => {
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
event.preventDefault();
resize(height + (event.key === 'ArrowUp' ? 24 : -24));
}}
/>
<TimelineTracks
tracks={tracks}
clips={timeline.clips}
total={total}
zoom={zoom}
height={height}
time={canSeek ? time : null}
canSeek={canSeek}
rowOf={rowOf}
textOf={textOf}
peaks={peaks}
onSeek={seek}
onClip={(clip) => {
// Estimated positions don't match the audio, so only select the line.
if (timeline.measured) seek(clip.start);
focusStoryLine(clip.id);
}}
/>
</>
)}
</section>
);
}
@@ -0,0 +1,240 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import { apiJson } from '@/lib/api/client';
import { VOICE_LIST_VIRTUAL_ABOVE, VoicePickList, voiceRows } from './voice-pick-list';
vi.mock('@/lib/api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/api/client')>()),
apiJson: vi.fn(),
}));
const page = (items: { id: string; name: string }[], total = items.length, offset = 0) => ({
total,
offset,
limit: 60,
items,
});
const headings = { yours: 'Yours', gallery: 'Gallery', loading: 'Loading', empty: 'None' };
const profiles = [
{ id: 'p1', name: 'Ava' },
{ id: 'p2', name: 'Ben' },
];
function show(props: Partial<Parameters<typeof VoicePickList>[0]> = {}) {
const onSelect = vi.fn();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<QueryClientProvider client={client}>
<VoicePickList
label="Voice"
defaultLabel="Default voice"
profiles={profiles}
value="p1"
onSelect={onSelect}
{...props}
/>
</QueryClientProvider>,
);
return { onSelect, client };
}
beforeEach(() => vi.mocked(apiJson).mockReset());
it('lists the default, the user’s voices, then the gallery, filtered by the search', () => {
const rows = (query: string) =>
voiceRows({
query,
defaultLabel: 'Default voice',
profiles,
gallery: [{ id: 'a1', name: 'Bard' }],
headings,
}).map((row) => (row.kind === 'voice' ? row.name : `[${row.label}]`));
expect(rows('')).toEqual(['Default voice', '[Yours]', 'Ava', 'Ben', '[Gallery]', 'Bard']);
expect(rows('be')).toEqual(['[Yours]', 'Ben', '[Gallery]', 'Bard']);
expect(
voiceRows({ query: 'zz', defaultLabel: 'D', profiles, gallery: [], headings }).map(
(row) => row.key,
),
).toEqual(['empty']);
expect(
voiceRows({ query: '', defaultLabel: 'D', profiles: [], gallery: null, headings }).map(
(row) => row.key,
),
).toEqual(['default', 'h:gallery', 'loading']);
});
it('adds a picked gallery voice to the user’s voices and selects the new profile', async () => {
vi.mocked(apiJson).mockImplementation(async (path = '') => {
if (path.startsWith('/archetypes?')) return page([{ id: 'old-sage', name: 'Old Sage' }]);
if (path.startsWith('/archetypes/old-sage/use')) return { profile_id: 'p9' };
return undefined;
});
const { onSelect } = show();
fireEvent.click(await screen.findByRole('option', { name: 'Old Sage' }));
await waitFor(() => expect(onSelect).toHaveBeenCalledWith('p9'));
expect(
vi
.mocked(apiJson)
.mock.calls.some(([path]) => path === '/archetypes/old-sage/use?name=Old+Sage'),
).toBe(true);
});
it('drops a gallery pick still saving when the picker closes', async () => {
let save!: (value: { profile_id: string }) => void;
vi.mocked(apiJson).mockImplementation(async (path = '') => {
if (path.startsWith('/archetypes?')) return page([{ id: 'old-sage', name: 'Old Sage' }]);
if (path.startsWith('/archetypes/old-sage/use'))
return new Promise((resolve) => {
save = resolve;
});
return undefined;
});
const onSelect = vi.fn();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const view = render(
<QueryClientProvider client={client}>
<VoicePickList
label="Voice"
defaultLabel="Default voice"
profiles={profiles}
value={null}
onSelect={onSelect}
/>
</QueryClientProvider>,
);
fireEvent.click(await screen.findByRole('option', { name: 'Old Sage' }));
await waitFor(() => expect(save).toBeTypeOf('function'));
const signal = vi
.mocked(apiJson)
.mock.calls.find(([path]) => path?.includes('/use'))?.[1]?.signal;
view.unmount();
expect(signal?.aborted).toBe(true);
save({ profile_id: 'p9' });
await new Promise((resolve) => setTimeout(resolve, 0));
expect(onSelect).not.toHaveBeenCalled();
});
it('picks the user’s own voices directly, and the default as null', async () => {
vi.mocked(apiJson).mockResolvedValue(page([]));
const { onSelect } = show();
expect(screen.getByRole('option', { name: 'Ava' }).getAttribute('aria-selected')).toBe('true');
fireEvent.click(screen.getByRole('option', { name: 'Ben' }));
fireEvent.click(screen.getByRole('option', { name: 'Default voice' }));
expect(onSelect.mock.calls).toEqual([['p2'], [null]]);
expect(vi.mocked(apiJson).mock.calls.every(([path]) => !path.includes('/use'))).toBe(true);
});
it('searches the gallery on the backend and picks with the keyboard', async () => {
vi.mocked(apiJson).mockImplementation(async (path = '') =>
new URLSearchParams(path.split('?')[1]).get('q') === 'sage'
? page([{ id: 'old-sage', name: 'Old Sage' }])
: page([]),
);
const { onSelect } = show();
const search = screen.getByRole('combobox', { name: i18n.t('common.search') });
fireEvent.change(search, { target: { value: 'sage' } });
await screen.findByRole('option', { name: 'Old Sage' });
expect(screen.queryByRole('option', { name: 'Ava' })).toBeNull();
vi.mocked(apiJson).mockResolvedValueOnce({ profile_id: 'p9' });
fireEvent.keyDown(search, { key: 'ArrowDown' });
fireEvent.keyDown(search, { key: 'Enter' });
await waitFor(() => expect(onSelect).toHaveBeenCalledWith('p9'));
});
it('keeps the user’s voices working when the gallery cannot load', async () => {
vi.mocked(apiJson).mockImplementation(async (path = '') => {
if (path.startsWith('/archetypes')) throw new Error('offline');
});
show();
await waitFor(() => expect(screen.queryByText(i18n.t('common.loading'))).toBeNull());
expect(screen.getByRole('option', { name: 'Ben' })).toBeTruthy();
expect(screen.queryByText(i18n.t('voiceSelector.gallery'))).toBeNull();
});
it('mounts only the rows in view once the list is long', async () => {
const many = Array.from({ length: 300 }, (_, i) => ({ id: `a${i}`, name: `Voice ${i}` }));
vi.mocked(apiJson).mockResolvedValue(page(many.slice(0, 60), 300));
show();
await waitFor(() => expect(screen.getByRole('listbox').getAttribute('aria-busy')).toBeNull());
// 60 gallery voices + the default, the user's two and two headings.
expect(65).toBeGreaterThan(VOICE_LIST_VIRTUAL_ABOVE);
expect(screen.queryAllByRole('option').length).toBeLessThan(60);
});
it('refreshes the user’s voices when a cancelled gallery pick may still have saved', async () => {
vi.mocked(apiJson).mockImplementation(async (path = '', init?: RequestInit) => {
if (path.startsWith('/archetypes?')) return page([{ id: 'old-sage', name: 'Old Sage' }]);
if (!path.includes('/use')) return undefined;
// Like the real client, an aborted request rejects.
return new Promise((_, reject) =>
init?.signal?.addEventListener('abort', () => reject(new DOMException('', 'AbortError'))),
);
});
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const invalidate = vi.spyOn(client, 'invalidateQueries');
const view = render(
<QueryClientProvider client={client}>
<VoicePickList label="Voice" profiles={profiles} value={null} onSelect={vi.fn()} />
</QueryClientProvider>,
);
fireEvent.click(await screen.findByRole('option', { name: 'Old Sage' }));
view.unmount();
await waitFor(() =>
expect(invalidate).toHaveBeenCalledWith({ queryKey: expect.arrayContaining(['profiles']) }),
);
});
it('never picks a gallery voice found for the previous search words', async () => {
vi.mocked(apiJson).mockImplementation(async (path = '') =>
new URLSearchParams(path.split('?')[1]).get('q') === 'sage'
? page([{ id: 'old-sage', name: 'Old Sage' }])
: page([]),
);
const { onSelect } = show();
const search = screen.getByRole('combobox', { name: i18n.t('common.search') });
fireEvent.change(search, { target: { value: 'sage' } });
await screen.findByRole('option', { name: 'Old Sage' });
// Retyped, and Enter before the new search has run.
fireEvent.change(search, { target: { value: 'bard' } });
expect(screen.queryByRole('option', { name: 'Old Sage' })).toBeNull();
fireEvent.keyDown(search, { key: 'ArrowDown' });
fireEvent.keyDown(search, { key: 'Enter' });
expect(onSelect).not.toHaveBeenCalled();
expect(vi.mocked(apiJson).mock.calls.every(([path]) => !path.includes('/use'))).toBe(true);
});
it('keeps loaded gallery voices when a later page fails', async () => {
const first = Array.from({ length: 5 }, (_, i) => ({ id: `a${i}`, name: `Voice ${i}` }));
vi.mocked(apiJson).mockImplementation(async (path = '') => {
if (!path.startsWith('/archetypes?')) return undefined;
if (new URLSearchParams(path.split('?')[1]).get('offset') === '0') return page(first, 300);
throw new Error('offline');
});
show();
await screen.findByRole('option', { name: 'Voice 4' });
fireEvent.scroll(screen.getByRole('listbox'));
await waitFor(() =>
expect(vi.mocked(apiJson).mock.calls.some(([path]) => path.includes('offset=5'))).toBe(true),
);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(screen.getByRole('option', { name: 'Voice 4' })).toBeTruthy();
});
it('says the gallery failed and retries on request, keeping the user’s voices', async () => {
let fail = true;
vi.mocked(apiJson).mockImplementation(async (path = '') => {
if (!path.startsWith('/archetypes?')) return undefined;
if (fail) throw new Error('offline');
return page([{ id: 'old-sage', name: 'Old Sage' }]);
});
show();
const retry = await screen.findByRole('button', { name: i18n.t('common.retry') });
screen.getByText(i18n.t('voiceSelector.galleryFailed'));
expect(screen.getByRole('option', { name: 'Ben' })).toBeTruthy();
fail = false;
fireEvent.click(retry);
await screen.findByRole('option', { name: 'Old Sage' });
expect(screen.queryByText(i18n.t('voiceSelector.galleryFailed'))).toBeNull();
});
@@ -0,0 +1,384 @@
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { useVirtualizer } from '@tanstack/react-virtual';
import { CheckIcon, LoaderIcon, SearchIcon } from 'lucide-react';
import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import type { ArchetypePage } from '@shared/api/archetypes-types';
import { apiJson } from '@/lib/api/client';
import { queryKeys } from '@/lib/query';
import { cn } from '@/lib/utils';
const GALLERY_PAGE = 60;
const ROW_HEIGHT = 28;
/** Lists up to this many rows render whole; longer ones mount only what shows. */
export const VOICE_LIST_VIRTUAL_ABOVE = 40;
const SEARCH_DELAY_MS = 150;
export interface VoiceGroup {
label: string;
options: readonly { id: string; name: string }[];
}
export type VoiceRow =
| { kind: 'heading'; key: string; label: string }
| { kind: 'status'; key: string; label: string }
| { kind: 'voice'; key: string; id: string | null; name: string; gallery: boolean };
/**
* The rows of the picker: the default, the user's voices matching `query`,
* then gallery voices (already filtered by the server). Pure, for tests.
*/
export function voiceRows({
query,
defaultLabel,
profiles,
gallery,
headings,
extra,
}: {
query: string;
/** What no choice means here; omitted where a voice must be chosen. */
defaultLabel?: string;
profiles: readonly { id: string; name: string }[];
/** More choices after the user's voices, under their own heading (e.g. presets). */
extra?: VoiceGroup;
gallery: readonly { id: string; name: string }[] | null;
headings: { yours: string; gallery: string; loading: string; empty: string };
}): VoiceRow[] {
const needle = query.trim().toLocaleLowerCase();
const matches = (name: string) => !needle || name.toLocaleLowerCase().includes(needle);
const rows: VoiceRow[] = [];
if (defaultLabel !== undefined && matches(defaultLabel))
rows.push({ kind: 'voice', key: 'default', id: null, name: defaultLabel, gallery: false });
const own = profiles.filter((profile) => matches(profile.name));
if (own.length) {
rows.push({ kind: 'heading', key: 'h:yours', label: headings.yours });
for (const profile of own)
rows.push({
kind: 'voice',
key: 'p:' + profile.id,
id: profile.id,
name: profile.name,
gallery: false,
});
}
const extras = extra?.options.filter((option) => matches(option.name)) ?? [];
if (extra && extras.length) {
rows.push({ kind: 'heading', key: 'h:extra', label: extra.label });
for (const option of extras)
rows.push({
kind: 'voice',
key: 'x:' + option.id,
id: option.id,
name: option.name,
gallery: false,
});
}
if (gallery === null) {
rows.push({ kind: 'heading', key: 'h:gallery', label: headings.gallery });
rows.push({ kind: 'status', key: 'loading', label: headings.loading });
} else if (gallery.length) {
rows.push({ kind: 'heading', key: 'h:gallery', label: headings.gallery });
for (const voice of gallery)
rows.push({
kind: 'voice',
key: 'g:' + voice.id,
id: voice.id,
name: voice.name,
gallery: true,
});
}
if (!rows.some((row) => row.kind !== 'heading'))
rows.push({ kind: 'status', key: 'empty', label: headings.empty });
return rows;
}
function useDebounced<T>(value: T, ms: number) {
const [settled, setSettled] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setSettled(value), ms);
return () => clearTimeout(timer);
}, [value, ms]);
return settled;
}
/**
* Searchable voice list for Stories: the default voice, the user's voices and
* the whole Voice Gallery. Typing filters the user's voices at once and
* searches the gallery on the backend; the gallery loads page by page as the
* list scrolls, and long lists mount only the rows in view. Picking a gallery
* voice adds it to the user's voices first, so callers only ever get a profile
* id (or null for the default).
*/
export function VoicePickList({
label,
profiles,
value,
defaultLabel,
disabled,
autoFocus,
extra,
onSelect,
}: {
extra?: VoiceGroup;
label: string;
profiles: readonly { id: string; name: string }[];
value: string | null;
defaultLabel?: string;
disabled?: boolean;
autoFocus?: boolean;
onSelect: (profileId: string | null) => void;
}) {
const { t } = useTranslation();
const client = useQueryClient();
const listId = useId();
const [query, setQuery] = useState('');
const galleryQuery = useDebounced(query.trim(), SEARCH_DELAY_MS);
const [adding, setAdding] = useState<string | null>(null);
const [active, setActive] = useState(-1);
const scroller = useRef<HTMLDivElement>(null);
// A gallery pick still saving when the list closes is dropped: by the time it
// finished, the story it was picked for may have moved on.
const pending = useRef<AbortController | null>(null);
useEffect(() => () => pending.current?.abort(), []);
const catalogue = useInfiniteQuery({
queryKey: ['voice-pick-gallery', galleryQuery],
initialPageParam: 0,
queryFn: ({ pageParam, signal }) =>
apiJson<ArchetypePage>(
'/archetypes?' +
new URLSearchParams({
q: galleryQuery,
offset: String(pageParam),
limit: String(GALLERY_PAGE),
}),
{ signal },
),
getNextPageParam: (last) =>
last.offset + last.items.length < last.total && last.items.length
? last.offset + last.items.length
: undefined,
staleTime: 300_000,
});
// Until the search settles the gallery shows as loading, so Enter can't pick
// a voice found for the previous words. Pages already loaded stay when a
// later page fails; a gallery that never loaded shows nothing rather than a
// spinner forever, since the user's own voices still work.
const settled = galleryQuery === query.trim();
const gallery = useMemo(
() =>
!settled
? null
: catalogue.data
? catalogue.data.pages.flatMap((page) => page.items)
: catalogue.isError
? []
: null,
[settled, catalogue.isError, catalogue.data],
);
const rows = useMemo(
() =>
voiceRows({
query,
defaultLabel,
profiles,
gallery,
extra,
headings: {
yours: t('voiceSelector.yourVoices'),
gallery: t('voiceSelector.gallery'),
loading: t('common.loading'),
empty: t('common.no_matches'),
},
}),
[query, defaultLabel, profiles, gallery, extra, t],
);
const choices = useMemo(
() => rows.flatMap((row, index) => (row.kind === 'voice' ? [index] : [])),
[rows],
);
const virtual = rows.length > VOICE_LIST_VIRTUAL_ABOVE;
const virtualizer = useVirtualizer({
count: virtual ? rows.length : 0,
getScrollElement: () => scroller.current,
estimateSize: () => ROW_HEIGHT,
overscan: 10,
});
const loadMore = () => {
const element = scroller.current;
if (!element || !catalogue.hasNextPage || catalogue.isFetchingNextPage) return;
if (element.scrollTop + element.clientHeight >= element.scrollHeight - ROW_HEIGHT * 12)
void catalogue.fetchNextPage();
};
const pick = async (row: Extract<VoiceRow, { kind: 'voice' }>) => {
if (disabled || adding) return;
if (!row.gallery || !row.id) {
onSelect(row.id);
return;
}
setAdding(row.id);
const current = new AbortController();
pending.current = current;
try {
const result = await apiJson<{ profile_id: string }>(
'/archetypes/' +
encodeURIComponent(row.id) +
'/use?' +
new URLSearchParams({ name: row.name }),
{ method: 'POST', signal: current.signal },
);
await client.invalidateQueries({ queryKey: queryKeys.profiles });
if (current.signal.aborted) return;
onSelect(result.profile_id);
} catch {
// A save cancelled on our side may still have finished on the server.
if (current.signal.aborted) void client.invalidateQueries({ queryKey: queryKeys.profiles });
else toast.error(t('voiceSelector.addVoiceFailed'));
} finally {
if (pending.current === current) pending.current = null;
if (!current.signal.aborted) setAdding(null);
}
};
const move = (step: number) => {
if (!choices.length) return;
const at = choices.indexOf(active);
const next = choices[Math.max(0, Math.min(choices.length - 1, at < 0 ? 0 : at + step))];
setActive(next);
if (virtual) virtualizer.scrollToIndex(next, { align: 'auto' });
else document.getElementById(`${listId}-${next}`)?.scrollIntoView?.({ block: 'nearest' });
};
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
move(event.key === 'ArrowDown' ? 1 : -1);
} else if (event.key === 'Enter') {
const row = rows[active] ?? rows[choices[0]];
if (row?.kind !== 'voice') return;
event.preventDefault();
void pick(row);
}
};
const renderRow = (row: VoiceRow, index: number) => {
if (row.kind !== 'voice')
return (
<div
role="presentation"
className={cn(
'flex h-7 items-center px-2 text-muted-foreground',
row.kind === 'heading' ? 'text-[10px] font-medium uppercase tracking-wide' : 'text-xs',
)}
>
{row.label}
</div>
);
const selected = row.gallery ? false : row.id === value;
return (
<div
id={`${listId}-${index}`}
role="option"
aria-selected={selected}
aria-disabled={disabled || undefined}
data-gallery={row.gallery || undefined}
className={cn(
'flex h-7 cursor-default items-center justify-between gap-2 rounded-md px-2 text-sm',
selected && 'bg-secondary',
index === active && 'bg-accent text-accent-foreground',
!disabled && 'hover:bg-accent hover:text-accent-foreground',
disabled && 'opacity-50',
)}
// Keep focus in the search box, so the keys keep working after a click.
onMouseDown={(event) => event.preventDefault()}
onClick={() => void pick(row)}
>
<span className="truncate">{row.name}</span>
{adding === row.id && row.gallery ? (
<LoaderIcon
className="size-3.5 shrink-0 animate-spin text-muted-foreground"
aria-label={t('voiceSelector.addingVoice')}
/>
) : (
selected && <CheckIcon className="size-3.5 shrink-0 text-primary" aria-hidden="true" />
)}
</div>
);
};
return (
<div className="space-y-1">
<div className="relative">
<SearchIcon
aria-hidden="true"
className="pointer-events-none absolute start-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"
/>
<input
type="search"
role="combobox"
aria-expanded="true"
aria-controls={listId}
aria-activedescendant={active >= 0 ? `${listId}-${active}` : undefined}
aria-label={t('common.search')}
placeholder={t('common.search')}
autoFocus={autoFocus}
disabled={disabled}
value={query}
onChange={(event) => {
setQuery(event.target.value);
setActive(-1);
scroller.current?.scrollTo?.({ top: 0 });
}}
onKeyDown={onKeyDown}
className="h-8 w-full rounded-md border border-input bg-transparent ps-7 pe-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
</div>
{catalogue.isError && !catalogue.data && (
<p
role="status"
data-slot="gallery-error"
className="m-0 flex items-center gap-2 px-1 text-xs text-muted-foreground"
>
<span className="min-w-0 flex-1">{t('voiceSelector.galleryFailed')}</span>
<button
type="button"
className="shrink-0 rounded px-1.5 py-0.5 text-foreground underline-offset-2 hover:underline focus-visible:ring-2 focus-visible:ring-ring outline-none"
onClick={() => void catalogue.refetch()}
>
{t('common.retry')}
</button>
</p>
)}
<div
ref={scroller}
id={listId}
role="listbox"
aria-label={label}
aria-busy={catalogue.isFetching || undefined}
onScroll={loadMore}
className="max-h-64 overflow-y-auto overscroll-contain"
>
{virtual ? (
<div className="relative" style={{ height: virtualizer.getTotalSize() }}>
{virtualizer.getVirtualItems().map((item) => (
<div
key={rows[item.index].key}
className="absolute inset-x-0"
style={{ top: item.start, height: item.size }}
>
{renderRow(rows[item.index], item.index)}
</div>
))}
</div>
) : (
rows.map((row, index) => <div key={row.key}>{renderRow(row, index)}</div>)
)}
</div>
</div>
);
}
+26 -3
View File
@@ -1836,7 +1836,18 @@
"pasteSplit": "لصق وتقسيم",
"import": "استيراد",
"autocast": "الإرسال التلقائي",
"autocastHint": "اكتشف من يتحدث وقم بتعيين الأصوات تلقائيًا",
"importTitle": "إضافة أسطر من نص",
"importSubtitle": "الصق نصًا أو أفلته: يصبح كل متحدث شخصية بصوت خاص",
"importPending": "نص في الانتظار",
"importPlaceholder": "الصق فصلًا أو مشهدًا أو سيناريو، أو أفلت ملفًا نصيًا هنا",
"importDrop": "أفلت لتحميل النص",
"importFormats": "يتعرّف على:",
"importExampleLine": "مرحبًا.",
"importOpenFile": "فتح ملف",
"importWords": "الكلمات: {{words}}",
"importSpeakers": "المتحدثون: {{count}}",
"importNarrated": "لم يُعثر على حوار: كل الأسطر للراوي",
"importActionsHint": "التوزيع التلقائي يجد المتحدثين ويمنح كلًا منهم صوتًا. التقسيم إلى أسطر يضيف النص كما هو لراوٍ واحد.",
"autocastEmpty": "لا يوجد شيء للإرسال التلقائي — قم بلصق قصة أو استيرادها أولاً.",
"importFailed": "لا يمكن قراءة هذا الملف.",
"addLine": "إضافة خط",
@@ -1859,7 +1870,6 @@
"noProjects": "لا توجد قصص محفوظة حتى الآن — احفظ للاحتفاظ بهذه القصة.",
"projectSaved": "تم حفظ القصة",
"generateAll": "إنشاء",
"splitPlaceholder": "لصق مقطع طويل. سنقوم بتقسيمها إلى أجزاء عند حدود الجملة.",
"maxChars": "الحد الأقصى لعدد الأحرف لكل مقطع",
"segmentsHint": "~{{count}} المقطع (المقاطع) عند {{max}} حرفًا",
"pasteAbove": "لصق النص أعلاه",
@@ -1867,7 +1877,6 @@
"splitIntoTracks": "تقسيم إلى خطوط",
"splitMode": "التقسيم حسب",
"split_sentences": "الجُمل",
"splitModeHint": "يُقرأ كل سطر كتسجيل مستقل. مع راوٍ واحد تبدو الفقرات أو الفصول أكثر سلاسة.",
"emptyText": "ابدأ قصتك بإضافة الحوار وخطوط السرد. قم بتعيين صوت لكل شخصية في فريق التمثيل.",
"addFirst": "أضف السطر الأول",
"linePlaceholder": "أدخل الحوار أو السرد... استخدم [pause 0.5s] لاستراحة صامتة",
@@ -1918,6 +1927,18 @@
"chapterHeading": "عنوان الفصل",
"lineActions": "إجراءات السطر",
"lineStart": "وقت البدء التقديري",
"timeline": "المخطط الزمني",
"timelineEstimate": "مواضع المقاطع تقديرية حتى يتم توليد الأسطر الحالية",
"showTimeline": "إظهار المخطط الزمني",
"hideTimeline": "إخفاء المخطط الزمني",
"resizeTimeline": "تغيير حجم المخطط الزمني",
"transportKeys": "المفاتيح: مسافة تشغيل/إيقاف مؤقت · J رجوع 5 ث · K إيقاف مؤقت · L تشغيل، ومرة أخرى أسرع · Home/End",
"lineChanged": "تغيّر منذ آخر توليد",
"changedSinceRender": "أسطر تغيّرت منذ آخر توليد: {{count}}",
"inspector": "المراقب",
"inspectorEmpty": "حدد سطرًا لتعديل متحدثه وصوته وسرعته.",
"lineOf": "السطر {{index}} من {{count}}",
"lineLength": "المدة",
"mergeNext": "دمج مع التالي",
"mergeNextHint": "ادمج الأسطر المتجاورة التي لها المتحدث نفسه وتجاوز الصوت وإعداد السرعة نفسيهما.",
"autocastDone_zero": "تم توزيع {{lines}} سطرًا دون أصوات",
@@ -3543,10 +3564,12 @@
"createVoice": "إنشاء صوت جديد",
"fromVideo": "من الفيديو",
"gallery": "المعرض",
"yourVoices": "أصواتك",
"clone": "الأصوات المستنسخة",
"presets": "الإعدادات المسبقة",
"missingVoice": "لم يتم العثور على الصوت (إعادة الاختيار)",
"addVoiceFailed": "تعذّرت إضافة هذا الصوت",
"galleryFailed": "تعذّر تحميل معرض الأصوات. أصواتك لا تزال متاحة.",
"openGallery": "افتح في معرض الصوت",
"addingVoice": "جارٍ إضافة الصوت…",
"engineDefault": "المحرك الافتراضي",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "Einfügen und teilen",
"import": "Importieren",
"autocast": "Automatische Besetzung",
"autocastHint": "Erkennen Sie, wer spricht, und weisen Sie Stimmen automatisch zu",
"importTitle": "Zeilen aus Text hinzufügen",
"importSubtitle": "Skript einfügen oder ablegen: Jede sprechende Person wird eine Figur mit Stimme",
"importPending": "Text wartet",
"importPlaceholder": "Kapitel, Szene oder Drehbuch einfügen oder Textdatei hier ablegen",
"importDrop": "Ablegen, um den Text zu laden",
"importFormats": "Erkennt:",
"importExampleLine": "Hallo.",
"importOpenFile": "Datei öffnen",
"importWords": "Wörter: {{words}}",
"importSpeakers": "Sprecher: {{count}}",
"importNarrated": "Kein Dialog gefunden: Alle Zeilen gehen an die Erzählstimme",
"importActionsHint": "Auto-Besetzung findet die Sprecher und gibt jedem eine Stimme. In Zeilen teilen übernimmt den Text unverändert für eine Erzählstimme.",
"autocastEmpty": "Nichts zum automatischen Casting – fügen Sie zuerst eine Story ein oder importieren Sie sie.",
"importFailed": "Diese Datei konnte nicht gelesen werden.",
"addLine": "Zeile hinzufügen",
@@ -1827,13 +1838,11 @@
"noProjects": "Noch keine gespeicherten Geschichten – Speichern Sie, um diese zu behalten.",
"projectSaved": "Geschichte gespeichert",
"generateAll": "Generieren",
"splitPlaceholder": "Fügen Sie eine lange Passage ein. Wir teilen es an den Satzgrenzen in Segmente auf.",
"maxChars": "Maximale Zeichen pro Segment",
"segmentsHint": "~{{count}} Segment(e) mit {{max}} Zeichen",
"pasteAbove": "Fügen Sie den Text oben ein",
"cancel": "Abbrechen",
"splitIntoTracks": "In Zeilen aufteilen",
"splitModeHint": "Jede Zeile wird als eigene Aufnahme gesprochen. Für einen einzelnen Sprecher klingen Absätze oder Kapitel flüssiger.",
"emptyText": "Beginnen Sie Ihre Geschichte, indem Sie Dialog- und Erzählzeilen hinzufügen. Weisen Sie jedem Charakter eine Stimme in der Besetzung zu.",
"addFirst": "Erste Zeile hinzufügen",
"linePlaceholder": "Geben Sie einen Dialog oder eine Erzählung ein ... verwenden Sie [pause 0.5s] für eine stille Pause",
@@ -1884,6 +1893,18 @@
"chapterHeading": "Kapiteltitel",
"lineActions": "Zeilenaktionen",
"lineStart": "Geschätzte Startzeit",
"timeline": "Zeitleiste",
"timelineEstimate": "Clip-Positionen sind Schätzungen, bis die aktuellen Zeilen erzeugt wurden",
"showTimeline": "Zeitleiste anzeigen",
"hideTimeline": "Zeitleiste ausblenden",
"resizeTimeline": "Zeitleistengröße ändern",
"transportKeys": "Tasten: Leertaste Wiedergabe/Pause · J 5 s zurück · K Pause · L Wiedergabe, erneut schneller · Pos1/Ende",
"lineChanged": "Seit der letzten Erzeugung geändert",
"changedSinceRender": "Seit der letzten Erzeugung geänderte Zeilen: {{count}}",
"inspector": "Inspektor",
"inspectorEmpty": "Wähle eine Zeile, um Sprecher, Stimme und Tempo zu bearbeiten.",
"lineOf": "Zeile {{index}} von {{count}}",
"lineLength": "Länge",
"mergeNext": "Mit dem nächsten zusammenführen",
"mergeNextHint": "Benachbarte Zeilen mit gleichem Sprecher, gleicher Stimmüberschreibung und gleicher Geschwindigkeit zusammenführen.",
"autocastDone_one": "{{lines}} Zeilen mit {{count}} Stimme besetzt",
@@ -3487,10 +3508,12 @@
"createVoice": "Erstellen Sie eine neue Stimme",
"fromVideo": "Aus Video",
"gallery": "Galerie",
"yourVoices": "Deine Stimmen",
"clone": "Geklonte Stimmen",
"presets": "Voreinstellungen",
"missingVoice": "Stimme nicht gefunden (erneut auswählen)",
"addVoiceFailed": "Diese Stimme konnte nicht hinzugefügt werden",
"galleryFailed": "Die Stimmengalerie konnte nicht geladen werden. Deine eigenen Stimmen funktionieren weiterhin.",
"openGallery": "In der Sprachgalerie öffnen",
"addingVoice": "Stimme wird hinzugefügt…",
"engineDefault": "Motorstandard",
+26 -3
View File
@@ -1989,7 +1989,18 @@
"pasteSplit": "Paste & Split",
"import": "Import",
"autocast": "Auto-cast",
"autocastHint": "Detect who's speaking — tagged ([Name]), screenplay (NAME:), or quoted prose — and assign voices automatically",
"importTitle": "Add lines from text",
"importSubtitle": "Paste or drop a script: each speaker becomes a character with a voice",
"importPending": "Text waiting",
"importPlaceholder": "Paste a chapter, scene or screenplay, or drop a text file here",
"importDrop": "Drop to load the text",
"importFormats": "Recognises:",
"importExampleLine": "Hello.",
"importOpenFile": "Open file",
"importWords": "Words: {{words}}",
"importSpeakers": "Speakers: {{count}}",
"importNarrated": "No dialogue found: every line goes to the narrator",
"importActionsHint": "Auto-cast finds the speakers and gives each a voice. Split into lines adds the text as it is, for a single narrator.",
"autocastEmpty": "Nothing to auto-cast — paste or import a story first.",
"importFailed": "Couldn't read that file.",
"addLine": "Add Line",
@@ -2012,7 +2023,6 @@
"noProjects": "No saved stories yet — Save to keep this one.",
"projectSaved": "Story saved",
"generateAll": "Generate",
"splitPlaceholder": "Paste a long passage. We'll split it into segments at sentence boundaries.",
"maxChars": "Max chars per segment",
"segmentsHint": "~{{count}} segment(s) at {{max}} chars",
"pasteAbove": "Paste text above",
@@ -2022,7 +2032,6 @@
"split_sentences": "Sentences",
"split_paragraphs": "Paragraphs",
"split_chapters": "Chapters",
"splitModeHint": "Each line is read as its own take. For a single narrator, Paragraphs or Chapters flow more naturally.",
"emptyText": "Start your story by adding dialogue and narration lines. Assign each character a voice in the Cast.",
"addFirst": "Add First Line",
"linePlaceholder": "Enter dialogue or narration… use [pause 0.5s] for a silent break",
@@ -2073,6 +2082,18 @@
"chapterHeading": "Chapter title",
"lineActions": "Line actions",
"lineStart": "Estimated start time",
"timeline": "Timeline",
"timelineEstimate": "Clip positions are estimates until the current lines are generated",
"showTimeline": "Show timeline",
"hideTimeline": "Hide timeline",
"resizeTimeline": "Resize timeline",
"transportKeys": "Keys: Space play/pause · J back 5 s · K pause · L play, again for faster · Home/End",
"lineChanged": "Changed since the last render",
"changedSinceRender": "Lines changed since the last render: {{count}}",
"inspector": "Inspector",
"inspectorEmpty": "Select a line to edit its speaker, voice and speed.",
"lineOf": "Line {{index}} of {{count}}",
"lineLength": "Length",
"mergeNext": "Merge with next",
"mergeNextHint": "Merge adjacent lines with the same speaker, voice override and speed setting.",
"autocastDone_one": "Auto-cast {{lines}} lines with {{count}} voice",
@@ -3487,10 +3508,12 @@
"createVoice": "Create a new voice",
"fromVideo": "From video",
"gallery": "Gallery",
"yourVoices": "Your voices",
"clone": "Cloned voices",
"presets": "Presets",
"missingVoice": "Voice not found (re-pick)",
"addVoiceFailed": "Couldn't add that voice — please try again.",
"galleryFailed": "Couldn’t load the Voice Gallery. Your own voices still work.",
"openGallery": "Open in Voice Gallery",
"addingVoice": "Adding voice…",
"engineDefault": "Engine default",
+26 -3
View File
@@ -1806,7 +1806,18 @@
"pasteSplit": "Pegar y dividir",
"import": "Importar",
"autocast": "emisión automática",
"autocastHint": "Detecta quién habla y asigna voces automáticamente",
"importTitle": "Añadir líneas desde texto",
"importSubtitle": "Pega o suelta un guion: cada hablante se convierte en un personaje con voz",
"importPending": "Texto pendiente",
"importPlaceholder": "Pega un capítulo, una escena o un guion, o suelta aquí un archivo de texto",
"importDrop": "Suelta para cargar el texto",
"importFormats": "Reconoce:",
"importExampleLine": "Hola.",
"importOpenFile": "Abrir archivo",
"importWords": "Palabras: {{words}}",
"importSpeakers": "Hablantes: {{count}}",
"importNarrated": "No se encontró diálogo: todas las líneas van al narrador",
"importActionsHint": "El reparto automático encuentra a los hablantes y da una voz a cada uno. Dividir en líneas añade el texto tal cual, para un solo narrador.",
"autocastEmpty": "No hay nada que transmitir automáticamente: pegue o importe una historia primero.",
"importFailed": "No se pudo leer ese archivo.",
"addLine": "Agregar línea",
@@ -1829,13 +1840,11 @@
"noProjects": "Aún no hay historias guardadas: guárdalas para conservar esta.",
"projectSaved": "Historia guardada",
"generateAll": "generar",
"splitPlaceholder": "Pegue un pasaje largo. Lo dividiremos en segmentos en los límites de la oración.",
"maxChars": "Número máximo de caracteres por segmento",
"segmentsHint": "~{{count}} segmento(s) en {{max}} caracteres",
"pasteAbove": "Pegar texto arriba",
"cancel": "Cancelar",
"splitIntoTracks": "Dividir en líneas",
"splitModeHint": "Cada línea se lee como una toma independiente. Con un solo narrador, Párrafos o Capítulos suenan más fluidos.",
"emptyText": "Comience su historia agregando diálogos y líneas de narración. Asigna a cada personaje una voz en el elenco.",
"addFirst": "Agregar primera línea",
"linePlaceholder": "Ingrese un diálogo o narración... use [pause 0.5s] para un descanso en silencio",
@@ -1886,6 +1895,18 @@
"chapterHeading": "Título del capítulo",
"lineActions": "Acciones de la línea",
"lineStart": "Hora de inicio estimada",
"timeline": "Línea de tiempo",
"timelineEstimate": "Las posiciones de los clips son estimadas hasta que se generen las líneas actuales",
"showTimeline": "Mostrar línea de tiempo",
"hideTimeline": "Ocultar línea de tiempo",
"resizeTimeline": "Cambiar tamaño de la línea de tiempo",
"transportKeys": "Teclas: Espacio reproducir/pausa · J atrás 5 s · K pausa · L reproducir, otra vez más rápido · Inicio/Fin",
"lineChanged": "Cambiada desde la última generación",
"changedSinceRender": "Líneas cambiadas desde la última generación: {{count}}",
"inspector": "Inspector",
"inspectorEmpty": "Selecciona una línea para editar su hablante, voz y velocidad.",
"lineOf": "Línea {{index}} de {{count}}",
"lineLength": "Duración",
"mergeNext": "Fusionarse con el siguiente",
"mergeNextHint": "Combina líneas contiguas con el mismo hablante, la misma voz alternativa y el mismo ajuste de velocidad.",
"autocastDone_one": "Se repartieron {{lines}} líneas con {{count}} voz",
@@ -3489,10 +3510,12 @@
"createVoice": "Crea una nueva voz",
"fromVideo": "Del vídeo",
"gallery": "Galería",
"yourVoices": "Tus voces",
"clone": "Voces clonadas",
"presets": "Preajustes",
"missingVoice": "Voz no encontrada (volver a elegir)",
"addVoiceFailed": "No se pudo añadir esa voz",
"galleryFailed": "No se pudo cargar la galería de voces. Tus propias voces siguen funcionando.",
"openGallery": "Abrir en la galería de voz",
"addingVoice": "Añadiendo voz…",
"engineDefault": "Valor predeterminado del motor",
+26 -3
View File
@@ -1806,7 +1806,18 @@
"pasteSplit": "Coller et diviser",
"import": "Importer",
"autocast": "Diffusion automatique",
"autocastHint": "Détectez qui parle et attribuez automatiquement des voix",
"importTitle": "Ajouter des lignes depuis un texte",
"importSubtitle": "Collez ou déposez un script : chaque locuteur devient un personnage avec une voix",
"importPending": "Texte en attente",
"importPlaceholder": "Collez un chapitre, une scène ou un scénario, ou déposez un fichier texte ici",
"importDrop": "Déposez pour charger le texte",
"importFormats": "Reconnaît :",
"importExampleLine": "Bonjour.",
"importOpenFile": "Ouvrir un fichier",
"importWords": "Mots : {{words}}",
"importSpeakers": "Locuteurs : {{count}}",
"importNarrated": "Aucun dialogue trouvé : toutes les lignes vont au narrateur",
"importActionsHint": "La distribution automatique trouve les locuteurs et donne une voix à chacun. Diviser en lignes ajoute le texte tel quel, pour un seul narrateur.",
"autocastEmpty": "Rien à diffuser automatiquement : collez ou importez d'abord une histoire.",
"importFailed": "Impossible de lire ce fichier.",
"addLine": "Ajouter une ligne",
@@ -1829,13 +1840,11 @@
"noProjects": "Aucune histoire enregistrée pour l’instant – Enregistrez pour conserver celle-ci.",
"projectSaved": "Histoire enregistrée",
"generateAll": "Générer",
"splitPlaceholder": "Collez un long passage. Nous le diviserons en segments aux limites des phrases.",
"maxChars": "Nombre maximum de caractères par segment",
"segmentsHint": "~{{count}} segment(s) à {{max}} caractères",
"pasteAbove": "Coller le texte ci-dessus",
"cancel": "Annuler",
"splitIntoTracks": "Divisé en lignes",
"splitModeHint": "Chaque ligne est lue comme une prise distincte. Avec un seul narrateur, Paragraphes ou Chapitres sonnent plus naturellement.",
"emptyText": "Commencez votre histoire en ajoutant des lignes de dialogue et de narration. Attribuez à chaque personnage une voix dans le casting.",
"addFirst": "Ajouter la première ligne",
"linePlaceholder": "Entrez un dialogue ou une narration… utilisez [pause 0.5s] pour une pause silencieuse",
@@ -1886,6 +1895,18 @@
"chapterHeading": "Titre du chapitre",
"lineActions": "Actions de la ligne",
"lineStart": "Heure de début estimée",
"timeline": "Chronologie",
"timelineEstimate": "Les positions des clips sont estimées jusqu’à la génération des lignes actuelles",
"showTimeline": "Afficher la chronologie",
"hideTimeline": "Masquer la chronologie",
"resizeTimeline": "Redimensionner la chronologie",
"transportKeys": "Touches : Espace lecture/pause · J recul 5 s · K pause · L lecture, encore pour accélérer · Début/Fin",
"lineChanged": "Modifiée depuis le dernier rendu",
"changedSinceRender": "Lignes modifiées depuis le dernier rendu : {{count}}",
"inspector": "Inspecteur",
"inspectorEmpty": "Sélectionnez une ligne pour modifier son locuteur, sa voix et sa vitesse.",
"lineOf": "Ligne {{index}} sur {{count}}",
"lineLength": "Durée",
"mergeNext": "Fusionner avec le suivant",
"mergeNextHint": "Fusionnez les lignes adjacentes ayant le même locuteur, la même voix personnalisée et le même réglage de vitesse.",
"autocastDone_one": "{{lines}} lignes distribuées à {{count}} voix",
@@ -3489,10 +3510,12 @@
"createVoice": "Créer une nouvelle voix",
"fromVideo": "À partir de la vidéo",
"gallery": "Galerie",
"yourVoices": "Vos voix",
"clone": "Voix clonées",
"presets": "Préréglages",
"missingVoice": "Voix introuvable (re-sélectionner)",
"addVoiceFailed": "Impossible d'ajouter cette voix",
"galleryFailed": "Impossible de charger la galerie de voix. Vos propres voix restent disponibles.",
"openGallery": "Ouvrir dans la galerie vocale",
"addingVoice": "Ajout de la voix…",
"engineDefault": "Moteur par défaut",
+26 -3
View File
@@ -1989,7 +1989,18 @@
"pasteSplit": "Pegar e dividir",
"import": "Importar",
"autocast": "Transmisión automática",
"autocastHint": "Detecta quen fala: etiquetado ([Nome]), guión (NOME:) ou prosa citada, e asigna voces automaticamente",
"importTitle": "Engadir liñas desde texto",
"importSubtitle": "Pega ou solta un guión: cada falante convértese nun personaxe con voz",
"importPending": "Texto pendente",
"importPlaceholder": "Pega un capítulo, unha escena ou un guión, ou solta aquí un ficheiro de texto",
"importDrop": "Solta para cargar o texto",
"importFormats": "Recoñece:",
"importExampleLine": "Ola.",
"importOpenFile": "Abrir ficheiro",
"importWords": "Palabras: {{words}}",
"importSpeakers": "Falantes: {{count}}",
"importNarrated": "Non se atopou diálogo: todas as liñas van ao narrador",
"importActionsHint": "O reparto automático atopa os falantes e dálle unha voz a cada un. Dividir en liñas engade o texto tal cal, para un só narrador.",
"autocastEmpty": "Non hai nada que emitir automaticamente: primeiro pega ou importa unha historia.",
"importFailed": "Non se puido ler ese ficheiro.",
"addLine": "Engadir liña",
@@ -2012,7 +2023,6 @@
"noProjects": "Aínda non hai historias gardadas — Garda para conservar esta.",
"projectSaved": "Historia gardada",
"generateAll": "Xerar",
"splitPlaceholder": "Pega un paso longo. Dividirémolo en segmentos nos límites das frases.",
"maxChars": "Máximo de caracteres por segmento",
"segmentsHint": "~{{count}} segmento(s) con {{max}} caracteres",
"pasteAbove": "Pega o texto arriba",
@@ -2022,7 +2032,6 @@
"split_sentences": "Oracións",
"split_paragraphs": "Parágrafos",
"split_chapters": "Capítulos",
"splitModeHint": "Cada liña lese como a súa propia toma. Para un só narrador, os parágrafos ou os capítulos flúen con máis naturalidade.",
"emptyText": "Comeza a túa historia engadindo diálogos e liñas narrativas. Asigna a cada personaxe unha voz no elenco.",
"addFirst": "Engadir primeira liña",
"linePlaceholder": "Introduce o diálogo ou a narración... usa [pause 0.5s] para unha pausa en silencio",
@@ -2073,6 +2082,18 @@
"chapterHeading": "Título do capítulo",
"lineActions": "Accións de liña",
"lineStart": "Hora de inicio estimada",
"timeline": "Liña de tempo",
"timelineEstimate": "As posicións dos clips son estimadas ata que se xeren as liñas actuais",
"showTimeline": "Amosar a liña de tempo",
"hideTimeline": "Ocultar a liña de tempo",
"resizeTimeline": "Cambiar o tamaño da liña de tempo",
"transportKeys": "Teclas: Espazo reproducir/pausa · J atrás 5 s · K pausa · L reproducir, outra vez máis rápido · Inicio/Fin",
"lineChanged": "Cambiada desde a última xeración",
"changedSinceRender": "Liñas cambiadas desde a última xeración: {{count}}",
"inspector": "Inspector",
"inspectorEmpty": "Selecciona unha liña para editar o seu falante, voz e velocidade.",
"lineOf": "Liña {{index}} de {{count}}",
"lineLength": "Duración",
"mergeNext": "Combina co seguinte",
"mergeNextHint": "Combina liñas contiguas co mesmo falante, a mesma voz substitutiva e o mesmo axuste de velocidade.",
"autocastDone_one": "Emite automaticamente {{lines}} liñas con {{count}} voz",
@@ -3487,10 +3508,12 @@
"createVoice": "Crea unha nova voz",
"fromVideo": "Do vídeo",
"gallery": "Galería",
"yourVoices": "As túas voces",
"clone": "Voces clonadas",
"presets": "Presets",
"missingVoice": "Non se atopou a voz (recolla)",
"addVoiceFailed": "Non se puido engadir esa voz. Téntao de novo.",
"galleryFailed": "Non se puido cargar a galería de voces. As túas propias voces seguen funcionando.",
"openGallery": "Abrir na Galería de voz",
"addingVoice": "Engadindo voz…",
"engineDefault": "Motor predeterminado",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "चिपकाएँ और विभाजित करें",
"import": "आयात करें",
"autocast": "स्वतः-कास्ट",
"autocastHint": "पता लगाएं कि कौन बोल रहा है और स्वचालित रूप से आवाजें निर्दिष्ट करें",
"importTitle": "टेक्स्ट से पंक्तियाँ जोड़ें",
"importSubtitle": "स्क्रिप्ट चिपकाएँ या छोड़ें: हर वक्ता एक आवाज़ वाला पात्र बनता है",
"importPending": "टेक्स्ट प्रतीक्षा में",
"importPlaceholder": "कोई अध्याय, दृश्य या पटकथा चिपकाएँ, या यहाँ टेक्स्ट फ़ाइल छोड़ें",
"importDrop": "टेक्स्ट लोड करने के लिए छोड़ें",
"importFormats": "पहचानता है:",
"importExampleLine": "नमस्ते।",
"importOpenFile": "फ़ाइल खोलें",
"importWords": "शब्द: {{words}}",
"importSpeakers": "वक्ता: {{count}}",
"importNarrated": "कोई संवाद नहीं मिला: सभी पंक्तियाँ कथावाचक को जाएँगी",
"importActionsHint": "ऑटो-कास्ट वक्ताओं को ढूँढकर हर एक को आवाज़ देता है। पंक्तियों में बाँटें टेक्स्ट को जस का तस एक कथावाचक के लिए जोड़ता है।",
"autocastEmpty": "ऑटो-कास्ट करने के लिए कुछ भी नहीं - पहले एक कहानी पेस्ट करें या आयात करें।",
"importFailed": "उस फ़ाइल को पढ़ा नहीं जा सका.",
"addLine": "पंक्ति जोड़ें",
@@ -1827,14 +1838,12 @@
"noProjects": "अभी तक कोई सहेजी गई कहानियाँ नहीं - इसे रखने के लिए सहेजें।",
"projectSaved": "कहानी सहेजी गई",
"generateAll": "उत्पन्न करें",
"splitPlaceholder": "एक लंबा मार्ग चिपकाएँ. हम इसे वाक्य सीमाओं पर खंडों में विभाजित करेंगे।",
"maxChars": "प्रति खंड अधिकतम वर्ण",
"segmentsHint": "~{{count}} खंड {{max}} वर्ण पर",
"pasteAbove": "ऊपर पाठ चिपकाएँ",
"cancel": "रद्द करें",
"splitIntoTracks": "पंक्तियों में विभाजित करें",
"splitMode": "विभाजन का आधार",
"splitModeHint": "हर पंक्ति अलग टेक की तरह पढ़ी जाती है। एक ही वाचक हो तो अनुच्छेद या अध्याय अधिक सहज लगते हैं।",
"emptyText": "संवाद और कथन पंक्तियाँ जोड़कर अपनी कहानी शुरू करें। कास्ट में प्रत्येक पात्र को एक आवाज दें।",
"addFirst": "प्रथम पंक्ति जोड़ें",
"linePlaceholder": "संवाद या कथन दर्ज करें... मौन विराम के लिए [pause 0.5s] का उपयोग करें",
@@ -1885,6 +1894,18 @@
"chapterHeading": "अध्याय शीर्षक",
"lineActions": "पंक्ति क्रियाएँ",
"lineStart": "अनुमानित प्रारंभ समय",
"timeline": "टाइमलाइन",
"timelineEstimate": "मौजूदा पंक्तियाँ जनरेट होने तक क्लिप की स्थितियाँ अनुमानित हैं",
"showTimeline": "टाइमलाइन दिखाएँ",
"hideTimeline": "टाइमलाइन छिपाएँ",
"resizeTimeline": "टाइमलाइन का आकार बदलें",
"transportKeys": "कुंजियाँ: Space चलाएँ/रोकें · J 5 से. पीछे · K रोकें · L चलाएँ, फिर से तेज़ · Home/End",
"lineChanged": "पिछले रेंडर के बाद बदली गई",
"changedSinceRender": "पिछले रेंडर के बाद बदली पंक्तियाँ: {{count}}",
"inspector": "निरीक्षक",
"inspectorEmpty": "वक्ता, आवाज़ और गति बदलने के लिए एक पंक्ति चुनें।",
"lineOf": "पंक्ति {{index}} / {{count}}",
"lineLength": "अवधि",
"mergeNext": "अगले के साथ विलय करें",
"mergeNextHint": "एक ही वक्ता, वॉइस ओवरराइड और गति सेटिंग वाली आस-पास की पंक्तियाँ जोड़ें।",
"autocastDone_one": "{{lines}} पंक्तियाँ {{count}} आवाज़ को सौंपी गईं",
@@ -3487,10 +3508,12 @@
"createVoice": "एक नई आवाज बनाएं",
"fromVideo": "वीडियो से",
"gallery": "गैलरी",
"yourVoices": "आपकी आवाज़ें",
"clone": "क्लोन की गई आवाजें",
"presets": "प्रीसेट",
"missingVoice": "आवाज़ नहीं मिली (फिर से चुनें)",
"addVoiceFailed": "वह आवाज़ नहीं जोड़ी जा सकी",
"galleryFailed": "वॉइस गैलरी लोड नहीं हो सकी। आपकी अपनी आवाज़ें अब भी काम करती हैं।",
"openGallery": "वॉइस गैलरी में खोलें",
"addingVoice": "आवाज़ जोड़ी जा रही है…",
"engineDefault": "इंजन डिफ़ॉल्ट",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "Tempel & Pisahkan",
"import": "Impor",
"autocast": "Transmisi otomatis",
"autocastHint": "Deteksi siapa yang berbicara dan tetapkan suara secara otomatis",
"importTitle": "Tambah baris dari teks",
"importSubtitle": "Tempel atau jatuhkan naskah: setiap pembicara menjadi karakter dengan suara",
"importPending": "Teks menunggu",
"importPlaceholder": "Tempel bab, adegan, atau skenario, atau jatuhkan file teks di sini",
"importDrop": "Jatuhkan untuk memuat teks",
"importFormats": "Mengenali:",
"importExampleLine": "Halo.",
"importOpenFile": "Buka file",
"importWords": "Kata: {{words}}",
"importSpeakers": "Pembicara: {{count}}",
"importNarrated": "Tidak ada dialog: semua baris untuk narator",
"importActionsHint": "Auto-cast menemukan pembicara dan memberi masing-masing suara. Pisah jadi baris menambahkan teks apa adanya, untuk satu narator.",
"autocastEmpty": "Tidak ada yang perlu ditransmisikan secara otomatis — tempel atau impor cerita terlebih dahulu.",
"importFailed": "Tidak dapat membaca file itu.",
"addLine": "Tambahkan Baris",
@@ -1827,14 +1838,12 @@
"noProjects": "Belum ada cerita yang disimpan — Simpan untuk menyimpan cerita ini.",
"projectSaved": "Cerita disimpan",
"generateAll": "Hasilkan",
"splitPlaceholder": "Tempel bagian yang panjang. Kami akan membaginya menjadi beberapa segmen pada batas kalimat.",
"maxChars": "Karakter maksimal per segmen",
"segmentsHint": "~{{count}} segmen pada {{max}} karakter",
"pasteAbove": "Tempel teks di atas",
"cancel": "Batalkan",
"splitIntoTracks": "Bagi menjadi beberapa baris",
"splitMode": "Pisahkan per",
"splitModeHint": "Setiap baris dibaca sebagai rekaman tersendiri. Untuk satu narator, Paragraf atau Bab terdengar lebih mengalir.",
"emptyText": "Mulailah cerita Anda dengan menambahkan dialog dan alur narasi. Tetapkan suara untuk setiap karakter dalam Pemeran.",
"addFirst": "Tambahkan Baris Pertama",
"linePlaceholder": "Masuk ke dialog atau narasi… gunakan [pause 0.5s] untuk jeda hening",
@@ -1885,6 +1894,18 @@
"chapterHeading": "Judul bab",
"lineActions": "Tindakan baris",
"lineStart": "Perkiraan waktu mulai",
"timeline": "Lini waktu",
"timelineEstimate": "Posisi klip masih perkiraan sampai baris saat ini dibuat",
"showTimeline": "Tampilkan lini waktu",
"hideTimeline": "Sembunyikan lini waktu",
"resizeTimeline": "Ubah ukuran lini waktu",
"transportKeys": "Tombol: Spasi putar/jeda · J mundur 5 dtk · K jeda · L putar, lagi untuk lebih cepat · Home/End",
"lineChanged": "Berubah sejak render terakhir",
"changedSinceRender": "Baris yang berubah sejak render terakhir: {{count}}",
"inspector": "Inspektur",
"inspectorEmpty": "Pilih baris untuk mengubah pembicara, suara, dan kecepatannya.",
"lineOf": "Baris {{index}} dari {{count}}",
"lineLength": "Durasi",
"mergeNext": "Gabungkan dengan berikutnya",
"mergeNextHint": "Gabungkan baris bersebelahan dengan pembicara, penggantian suara, dan pengaturan kecepatan yang sama.",
"autocastDone_one": "{{lines}} baris dibagikan ke {{count}} suara",
@@ -3487,10 +3508,12 @@
"createVoice": "Ciptakan suara baru",
"fromVideo": "Dari video",
"gallery": "Galeri",
"yourVoices": "Suara Anda",
"clone": "Suara kloning",
"presets": "Preset",
"missingVoice": "Suara tidak ditemukan (pilih ulang)",
"addVoiceFailed": "Tidak dapat menambahkan suara itu",
"galleryFailed": "Galeri Suara gagal dimuat. Suara milik Anda tetap bisa dipakai.",
"openGallery": "Buka di Galeri Suara",
"addingVoice": "Menambahkan suara…",
"engineDefault": "Default mesin",
+26 -3
View File
@@ -1806,7 +1806,18 @@
"pasteSplit": "Incolla e dividi",
"import": "Importa",
"autocast": "Trasmissione automatica",
"autocastHint": "Rileva chi sta parlando e assegna automaticamente le voci",
"importTitle": "Aggiungi righe da testo",
"importSubtitle": "Incolla o trascina un copione: ogni personaggio che parla riceve una voce",
"importPending": "Testo in attesa",
"importPlaceholder": "Incolla un capitolo, una scena o una sceneggiatura, oppure trascina qui un file di testo",
"importDrop": "Rilascia per caricare il testo",
"importFormats": "Riconosce:",
"importExampleLine": "Ciao.",
"importOpenFile": "Apri file",
"importWords": "Parole: {{words}}",
"importSpeakers": "Voci parlanti: {{count}}",
"importNarrated": "Nessun dialogo trovato: tutte le righe vanno al narratore",
"importActionsHint": "Il cast automatico trova chi parla e assegna una voce a ciascuno. Dividi in righe aggiunge il testo così com'è, per un solo narratore.",
"autocastEmpty": "Niente da trasmettere automaticamente: incolla o importa prima una storia.",
"importFailed": "Impossibile leggere quel file.",
"addLine": "Aggiungi linea",
@@ -1829,13 +1840,11 @@
"noProjects": "Nessuna storia ancora salvata: salva per mantenere questa.",
"projectSaved": "Storia salvata",
"generateAll": "Genera",
"splitPlaceholder": "Incolla un passaggio lungo. Lo divideremo in segmenti ai confini della frase.",
"maxChars": "Caratteri massimi per segmento",
"segmentsHint": "~{{count}} segmento/i in {{max}} caratteri",
"pasteAbove": "Incolla il testo sopra",
"cancel": "Annulla",
"splitIntoTracks": "Diviso in linee",
"splitModeHint": "Ogni riga viene letta come una ripresa a sé. Con un solo narratore, Paragrafi o Capitoli scorrono meglio.",
"emptyText": "Inizia la tua storia aggiungendo linee di dialogo e narrazione. Assegna a ogni personaggio una voce nel cast.",
"addFirst": "Aggiungi la prima riga",
"linePlaceholder": "Inserisci un dialogo o una narrazione... usa [pause 0.5s] per una pausa silenziosa",
@@ -1886,6 +1895,18 @@
"chapterHeading": "Titolo del capitolo",
"lineActions": "Azioni della riga",
"lineStart": "Ora di inizio stimata",
"timeline": "Timeline",
"timelineEstimate": "Le posizioni delle clip sono stimate finché le righe attuali non vengono generate",
"showTimeline": "Mostra timeline",
"hideTimeline": "Nascondi timeline",
"resizeTimeline": "Ridimensiona timeline",
"transportKeys": "Tasti: Spazio riproduci/pausa · J indietro 5 s · K pausa · L riproduci, di nuovo più veloce · Home/Fine",
"lineChanged": "Modificata dall'ultima generazione",
"changedSinceRender": "Righe modificate dall'ultima generazione: {{count}}",
"inspector": "Ispettore",
"inspectorEmpty": "Seleziona una riga per modificarne parlante, voce e velocità.",
"lineOf": "Riga {{index}} di {{count}}",
"lineLength": "Durata",
"mergeNext": "Unisci con il successivo",
"mergeNextHint": "Unisci righe adiacenti con lo stesso parlante, la stessa voce sostitutiva e la stessa impostazione di velocità.",
"autocastDone_one": "{{lines}} righe assegnate a {{count}} voce",
@@ -3489,10 +3510,12 @@
"createVoice": "Crea una nuova voce",
"fromVideo": "Dal video",
"gallery": "Galleria",
"yourVoices": "Le tue voci",
"clone": "Voci clonate",
"presets": "Preimpostazioni",
"missingVoice": "Voce non trovata (riseleziona)",
"addVoiceFailed": "Impossibile aggiungere quella voce",
"galleryFailed": "Impossibile caricare la galleria delle voci. Le tue voci funzionano comunque.",
"openGallery": "Apri nella Galleria vocale",
"addingVoice": "Aggiunta voce…",
"engineDefault": "Motore difettoso",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "貼り付けと分割",
"import": "インポート",
"autocast": "オートキャスト",
"autocastHint": "誰が話しているのかを検出し、自動的に音声を割り当てます",
"importTitle": "テキストから行を追加",
"importSubtitle": "台本を貼り付けるかドロップ: 話者ごとに声付きのキャラクターになります",
"importPending": "未処理のテキスト",
"importPlaceholder": "章・シーン・脚本を貼り付けるか、テキストファイルをここにドロップ",
"importDrop": "ドロップしてテキストを読み込む",
"importFormats": "対応形式:",
"importExampleLine": "こんにちは。",
"importOpenFile": "ファイルを開く",
"importWords": "単語数: {{words}}",
"importSpeakers": "話者: {{count}}",
"importNarrated": "会話が見つかりません: すべての行がナレーターになります",
"importActionsHint": "自動キャストは話者を見つけてそれぞれに声を割り当てます。行に分割はテキストをそのまま追加します (ナレーター1人向け)。",
"autocastEmpty": "自動キャストするものはありません。最初にストーリーを貼り付けるかインポートしてください。",
"importFailed": "そのファイルを読み取れませんでした。",
"addLine": "行を追加",
@@ -1827,14 +1838,12 @@
"noProjects": "保存されたストーリーはまだありません — このストーリーを保存するには保存してください。",
"projectSaved": "ストーリーが保存されました",
"generateAll": "生成する",
"splitPlaceholder": "長い文章を貼り付けます。文の境界でセグメントに分割します。",
"maxChars": "セグメントあたりの最大文字数",
"segmentsHint": "~{{count}} セグメント ({{max}} 文字)",
"pasteAbove": "上にテキストを貼り付けます",
"cancel": "キャンセル",
"splitIntoTracks": "行に分割",
"splitMode": "分割の単位",
"splitModeHint": "各行は個別のテイクとして読み上げられます。語り手が一人なら、段落や章のほうが自然につながります。",
"emptyText": "会話やナレーションを追加してストーリーを開始します。各キャラクターにキャストの声を割り当てます。",
"addFirst": "最初の行を追加",
"linePlaceholder": "ダイアログまたはナレーションを入力します...無音の休憩には [pause 0.5s] を使用してください",
@@ -1885,6 +1894,18 @@
"chapterHeading": "章タイトル",
"lineActions": "行の操作",
"lineStart": "推定開始時刻",
"timeline": "タイムライン",
"timelineEstimate": "現在の行を生成するまで、クリップの位置は推定値です",
"showTimeline": "タイムラインを表示",
"hideTimeline": "タイムラインを隠す",
"resizeTimeline": "タイムラインのサイズを変更",
"transportKeys": "キー: Space 再生/一時停止 · J 5秒戻る · K 一時停止 · L 再生、もう一度で速く · Home/End",
"lineChanged": "前回の生成以降に変更",
"changedSinceRender": "前回の生成以降に変更された行: {{count}}",
"inspector": "インスペクター",
"inspectorEmpty": "行を選択すると、話者・声・速度を編集できます。",
"lineOf": "{{count}} 行中 {{index}} 行目",
"lineLength": "長さ",
"mergeNext": "次と結合",
"mergeNextHint": "話者、音声の個別指定、速度設定が同じ隣接行を結合します。",
"autocastDone_one": "{{lines}} 行を {{count}} 個の音声に自動割り当てしました",
@@ -3487,10 +3508,12 @@
"createVoice": "新しい音声を作成する",
"fromVideo": "ビデオから",
"gallery": "ギャラリー",
"yourVoices": "あなたの音声",
"clone": "クローン音声",
"presets": "プリセット",
"missingVoice": "音声が見つかりません (再選択)",
"addVoiceFailed": "その音声を追加できませんでした",
"galleryFailed": "ボイスギャラリーを読み込めませんでした。自分のボイスは引き続き使えます。",
"openGallery": "ボイスギャラリーで開く",
"addingVoice": "音声を追加中…",
"engineDefault": "エンジンのデフォルト",
+26 -3
View File
@@ -1801,7 +1801,6 @@
"removeCharacter": "캐릭터 삭제",
"noProfiles": "아직 음성 프로필이 설치되지 않았습니다. 먼저 음성을 복제하거나 디자인하세요.",
"pasteSplit": "붙여넣기 및 분할",
"autocastHint": "말하는 사람을 감지하고 자동으로 음성 할당",
"importFailed": "해당 파일을 읽을 수 없습니다.",
"addLine": "라인 추가",
"addChapter": "장 추가",
@@ -1822,13 +1821,11 @@
"noProjects": "아직 저장된 스토리가 없습니다. 이 스토리를 유지하려면 저장하세요.",
"projectSaved": "스토리가 저장되었습니다",
"generateAll": "생성",
"splitPlaceholder": "긴 구절을 붙여넣으세요. 문장 경계에서 세그먼트로 분할하겠습니다.",
"maxChars": "세그먼트당 최대 문자 수",
"segmentsHint": "{{max}} 문자의 ~{{count}} 세그먼트",
"pasteAbove": "위에 텍스트 붙여넣기",
"cancel": "취소",
"splitMode": "나누는 기준",
"splitModeHint": "각 줄은 별도의 테이크로 읽힙니다. 화자가 한 명이라면 문단이나 장 단위가 더 자연스럽습니다.",
"emptyText": "대화와 내레이션 대사를 추가하여 스토리를 시작하세요. 캐스트에서 각 캐릭터에게 음성을 할당하세요.",
"addFirst": "첫 번째 줄 추가",
"linePlaceholder": "대화나 내레이션을 입력하세요. 조용히 휴식하려면 [pause 0.5s]를 사용하세요.",
@@ -1876,6 +1873,18 @@
"chapterHeading": "챕터 제목",
"lineActions": "줄 작업",
"lineStart": "예상 시작 시간",
"timeline": "타임라인",
"timelineEstimate": "현재 줄을 생성하기 전까지 클립 위치는 추정치입니다",
"showTimeline": "타임라인 표시",
"hideTimeline": "타임라인 숨기기",
"resizeTimeline": "타임라인 크기 조정",
"transportKeys": "키: Space 재생/일시정지 · J 5초 뒤로 · K 일시정지 · L 재생, 다시 누르면 빠르게 · Home/End",
"lineChanged": "마지막 생성 이후 변경됨",
"changedSinceRender": "마지막 생성 이후 변경된 줄: {{count}}",
"inspector": "검사기",
"inspectorEmpty": "줄을 선택하면 화자, 목소리, 속도를 편집할 수 있습니다.",
"lineOf": "{{count}}줄 중 {{index}}번째",
"lineLength": "길이",
"mergeNext": "다음과 병합",
"mergeNextHint": "화자, 개별 음성 지정, 속도 설정이 같은 인접한 줄을 합칩니다.",
"autocastDone_one": "{{lines}}줄을 음성 {{count}}개에 자동 배정했습니다",
@@ -1885,6 +1894,18 @@
"split_paragraphs": "문단",
"split_sentences": "문장",
"autocast": "자동 배역 지정",
"importTitle": "텍스트에서 줄 추가",
"importSubtitle": "대본을 붙여넣거나 끌어다 놓으세요: 화자마다 목소리가 있는 캐릭터가 됩니다",
"importPending": "대기 중인 텍스트",
"importPlaceholder": "챕터, 장면, 각본을 붙여넣거나 텍스트 파일을 여기에 놓으세요",
"importDrop": "놓아서 텍스트 불러오기",
"importFormats": "인식 형식:",
"importExampleLine": "안녕하세요.",
"importOpenFile": "파일 열기",
"importWords": "단어: {{words}}",
"importSpeakers": "화자: {{count}}",
"importNarrated": "대화를 찾지 못함: 모든 줄이 내레이터에게 갑니다",
"importActionsHint": "자동 캐스팅은 화자를 찾아 각자에게 목소리를 줍니다. 줄로 나누기는 텍스트를 그대로 추가합니다(내레이터 한 명용).",
"autocastEmpty": "자동으로 배역을 지정할 내용이 없습니다. 먼저 스토리를 붙여 넣거나 가져오세요.",
"characters": "{{count}}자",
"import": "가져오기",
@@ -3487,10 +3508,12 @@
"createVoice": "새 목소리 만들기",
"fromVideo": "비디오에서",
"gallery": "갤러리",
"yourVoices": "내 음성",
"clone": "복제된 목소리",
"presets": "사전 설정",
"missingVoice": "음성을 찾을 수 없음(다시 선택)",
"addVoiceFailed": "해당 음성을 추가할 수 없습니다",
"galleryFailed": "보이스 갤러리를 불러오지 못했습니다. 내 음성은 계속 사용할 수 있습니다.",
"openGallery": "음성 갤러리에서 열기",
"addingVoice": "음성 추가 중…",
"preview": "음성 미리보기",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "Plakken en splitsen",
"import": "Importeren",
"autocast": "Automatisch casten",
"autocastHint": "Detecteer wie er spreekt en wijs automatisch stemmen toe",
"importTitle": "Regels toevoegen uit tekst",
"importSubtitle": "Plak of sleep een script: elke spreker wordt een personage met een stem",
"importPending": "Tekst wacht",
"importPlaceholder": "Plak een hoofdstuk, scène of scenario, of sleep hier een tekstbestand heen",
"importDrop": "Loslaten om de tekst te laden",
"importFormats": "Herkent:",
"importExampleLine": "Hallo.",
"importOpenFile": "Bestand openen",
"importWords": "Woorden: {{words}}",
"importSpeakers": "Sprekers: {{count}}",
"importNarrated": "Geen dialoog gevonden: alle regels gaan naar de verteller",
"importActionsHint": "Auto-cast vindt de sprekers en geeft ieder een stem. Opsplitsen in regels voegt de tekst ongewijzigd toe, voor één verteller.",
"autocastEmpty": "Niets om automatisch te casten. Plak of importeer eerst een verhaal.",
"importFailed": "Kan dat bestand niet lezen.",
"addLine": "Lijn toevoegen",
@@ -1827,14 +1838,12 @@
"noProjects": "Nog geen opgeslagen verhalen: sla deze op om deze te behouden.",
"projectSaved": "Verhaal opgeslagen",
"generateAll": "Genereer",
"splitPlaceholder": "Plak een lange passage. We splitsen het in segmenten op de zinsgrenzen.",
"maxChars": "Maximaal aantal tekens per segment",
"segmentsHint": "~{{count}} segment(en) bij {{max}} tekens",
"pasteAbove": "Plak de tekst hierboven",
"cancel": "Annuleer",
"splitIntoTracks": "Opgesplitst in lijnen",
"split_paragraphs": "Alinea’s",
"splitModeHint": "Elke regel wordt als aparte opname voorgelezen. Met één verteller klinken Alinea’s of Hoofdstukken vloeiender.",
"emptyText": "Begin je verhaal door dialoog- en verhaallijnen toe te voegen. Geef elk personage een stem in de cast.",
"addFirst": "Eerste regel toevoegen",
"linePlaceholder": "Voer een dialoog of verhaal in... gebruik [pause 0.5s] voor een stille pauze",
@@ -1885,6 +1894,18 @@
"chapterHeading": "Hoofdstuktitel",
"lineActions": "Regelacties",
"lineStart": "Geschatte starttijd",
"timeline": "Tijdlijn",
"timelineEstimate": "Clipposities zijn schattingen totdat de huidige regels zijn gegenereerd",
"showTimeline": "Tijdlijn tonen",
"hideTimeline": "Tijdlijn verbergen",
"resizeTimeline": "Tijdlijn vergroten of verkleinen",
"transportKeys": "Toetsen: Spatie afspelen/pauze · J 5 s terug · K pauze · L afspelen, nogmaals sneller · Home/End",
"lineChanged": "Gewijzigd sinds de laatste generatie",
"changedSinceRender": "Regels gewijzigd sinds de laatste generatie: {{count}}",
"inspector": "Inspector",
"inspectorEmpty": "Selecteer een regel om spreker, stem en snelheid te bewerken.",
"lineOf": "Regel {{index}} van {{count}}",
"lineLength": "Lengte",
"mergeNext": "Samenvoegen met volgende",
"mergeNextHint": "Voeg aangrenzende regels samen met dezelfde spreker, stemoverschrijving en snelheidsinstelling.",
"autocastDone_one": "{{lines}} regels toegewezen aan {{count}} stem",
@@ -3487,10 +3508,12 @@
"createVoice": "Creëer een nieuwe stem",
"fromVideo": "Van video",
"gallery": "Galerij",
"yourVoices": "Jouw stemmen",
"clone": "Gekloonde stemmen",
"presets": "Voorinstellingen",
"missingVoice": "Stem niet gevonden (opnieuw kiezen)",
"addVoiceFailed": "Kon die stem niet toevoegen",
"galleryFailed": "De stemmengalerij kon niet worden geladen. Je eigen stemmen werken nog steeds.",
"openGallery": "Openen in Voice Gallery",
"addingVoice": "Stem toevoegen…",
"engineDefault": "Standaard motor",
+26 -3
View File
@@ -1820,7 +1820,18 @@
"pasteSplit": "Wklej i podziel",
"import": "Importuj",
"autocast": "Automatyczne przesyłanie",
"autocastHint": "Wykryj, kto mówi i automatycznie przypisuj głosy",
"importTitle": "Dodaj linie z tekstu",
"importSubtitle": "Wklej lub upuść scenariusz: każda postać mówiąca dostaje głos",
"importPending": "Tekst czeka",
"importPlaceholder": "Wklej rozdział, scenę lub scenariusz albo upuść tu plik tekstowy",
"importDrop": "Upuść, aby wczytać tekst",
"importFormats": "Rozpoznaje:",
"importExampleLine": "Cześć.",
"importOpenFile": "Otwórz plik",
"importWords": "Słowa: {{words}}",
"importSpeakers": "Mówiący: {{count}}",
"importNarrated": "Nie znaleziono dialogu: wszystkie linie trafią do narratora",
"importActionsHint": "Auto-obsada znajduje mówiących i daje każdemu głos. Podział na linie dodaje tekst bez zmian, dla jednego narratora.",
"autocastEmpty": "Nie ma nic do automatycznego przesyłania — najpierw wklej lub zaimportuj historię.",
"importFailed": "Nie udało się odczytać tego pliku.",
"addLine": "Dodaj linię",
@@ -1843,13 +1854,11 @@
"noProjects": "Nie ma jeszcze zapisanych historii — Zapisz, aby zachować tę.",
"projectSaved": "Historia zapisana",
"generateAll": "Wygeneruj",
"splitPlaceholder": "Wklej długi fragment. Podzielimy to na segmenty na granicach zdań.",
"maxChars": "Maksymalna liczba znaków na segment",
"segmentsHint": "~{{count}} segment(y) zawierający {{max}} znaków",
"pasteAbove": "Wklej tekst powyżej",
"cancel": "Anuluj",
"splitIntoTracks": "Podziel na linie",
"splitModeHint": "Każdy wiersz jest czytany jako osobne nagranie. Przy jednym narratorze Akapity lub Rozdziały brzmią płynniej.",
"emptyText": "Rozpocznij swoją historię od dodania dialogów i linii narracji. Przypisz każdej postaci głos w obsadzie.",
"addFirst": "Dodaj pierwszą linię",
"linePlaceholder": "Wprowadź dialog lub narrację… użyj [pause 0.5s], aby zrobić cichą przerwę",
@@ -1900,6 +1909,18 @@
"chapterHeading": "Tytuł rozdziału",
"lineActions": "Akcje linii",
"lineStart": "Szacowany czas rozpoczęcia",
"timeline": "Oś czasu",
"timelineEstimate": "Pozycje klipów są szacunkowe, dopóki bieżące linie nie zostaną wygenerowane",
"showTimeline": "Pokaż oś czasu",
"hideTimeline": "Ukryj oś czasu",
"resizeTimeline": "Zmień rozmiar osi czasu",
"transportKeys": "Klawisze: Spacja odtwórz/pauza · J 5 s wstecz · K pauza · L odtwórz, ponownie szybciej · Home/End",
"lineChanged": "Zmieniono od ostatniego renderu",
"changedSinceRender": "Linie zmienione od ostatniego renderu: {{count}}",
"inspector": "Inspektor",
"inspectorEmpty": "Wybierz linię, aby edytować mówcę, głos i tempo.",
"lineOf": "Linia {{index}} z {{count}}",
"lineLength": "Długość",
"mergeNext": "Połącz z następnym",
"mergeNextHint": "Połącz sąsiednie wiersze z tym samym mówcą, takim samym nadpisaniem głosu i ustawieniem szybkości.",
"autocastDone_one": "Przydzielono {{lines}} linii do {{count}} głosu",
@@ -3515,10 +3536,12 @@
"createVoice": "Utwórz nowy głos",
"fromVideo": "Z wideo",
"gallery": "Galeria",
"yourVoices": "Twoje głosy",
"clone": "Sklonowane głosy",
"presets": "Ustawienia wstępne",
"missingVoice": "Nie znaleziono głosu (wybierz ponownie)",
"addVoiceFailed": "Nie udało się dodać tego głosu",
"galleryFailed": "Nie udało się wczytać galerii głosów. Twoje własne głosy nadal działają.",
"openGallery": "Otwórz w Galerii Voice",
"addingVoice": "Dodawanie głosu…",
"engineDefault": "Domyślne ustawienie silnika",
+26 -3
View File
@@ -1806,7 +1806,18 @@
"pasteSplit": "Colar e dividir",
"import": "Importar",
"autocast": "Transmissão automática",
"autocastHint": "Detecte quem está falando e atribua vozes automaticamente",
"importTitle": "Adicionar linhas a partir de texto",
"importSubtitle": "Cole ou solte um roteiro: cada falante vira um personagem com voz",
"importPending": "Texto pendente",
"importPlaceholder": "Cole um capítulo, uma cena ou um roteiro, ou solte aqui um arquivo de texto",
"importDrop": "Solte para carregar o texto",
"importFormats": "Reconhece:",
"importExampleLine": "Olá.",
"importOpenFile": "Abrir arquivo",
"importWords": "Palavras: {{words}}",
"importSpeakers": "Falantes: {{count}}",
"importNarrated": "Nenhum diálogo encontrado: todas as linhas vão para o narrador",
"importActionsHint": "O elenco automático encontra os falantes e dá uma voz a cada um. Dividir em linhas adiciona o texto como está, para um único narrador.",
"autocastEmpty": "Nada para transmitir automaticamente – cole ou importe uma história primeiro.",
"importFailed": "Não foi possível ler esse arquivo.",
"addLine": "Adicionar linha",
@@ -1829,13 +1840,11 @@
"noProjects": "Nenhuma história salva ainda – Salve para manter esta.",
"projectSaved": "História salva",
"generateAll": "Gerar",
"splitPlaceholder": "Cole uma passagem longa. Vamos dividi-lo em segmentos nos limites das frases.",
"maxChars": "Máximo de caracteres por segmento",
"segmentsHint": "~{{count}} segmento(s) em {{max}} caracteres",
"pasteAbove": "Cole o texto acima",
"cancel": "Cancelar",
"splitIntoTracks": "Dividir em linhas",
"splitModeHint": "Cada linha é lida como uma gravação separada. Com um único narrador, Parágrafos ou Capítulos soam mais naturais.",
"emptyText": "Comece sua história adicionando linhas de diálogo e narração. Atribua a cada personagem uma voz no elenco.",
"addFirst": "Adicionar primeira linha",
"linePlaceholder": "Insira um diálogo ou narração... use [pause 0.5s] para uma pausa silenciosa",
@@ -1886,6 +1895,18 @@
"chapterHeading": "Título do capítulo",
"lineActions": "Ações da linha",
"lineStart": "Hora de início estimada",
"timeline": "Linha do tempo",
"timelineEstimate": "As posições dos clipes são estimadas até as falas atuais serem geradas",
"showTimeline": "Mostrar linha do tempo",
"hideTimeline": "Ocultar linha do tempo",
"resizeTimeline": "Redimensionar linha do tempo",
"transportKeys": "Teclas: Espaço reproduzir/pausar · J recuar 5 s · K pausar · L reproduzir, de novo mais rápido · Home/End",
"lineChanged": "Alterada desde a última geração",
"changedSinceRender": "Linhas alteradas desde a última geração: {{count}}",
"inspector": "Inspetor",
"inspectorEmpty": "Selecione uma linha para editar o orador, a voz e a velocidade.",
"lineOf": "Linha {{index}} de {{count}}",
"lineLength": "Duração",
"mergeNext": "Mesclar com o próximo",
"mergeNextHint": "Una linhas adjacentes com o mesmo falante, a mesma substituição de voz e a mesma configuração de velocidade.",
"autocastDone_one": "{{lines}} linhas distribuídas para {{count}} voz",
@@ -3489,10 +3510,12 @@
"createVoice": "Crie uma nova voz",
"fromVideo": "Do vídeo",
"gallery": "Galeria",
"yourVoices": "Suas vozes",
"clone": "Vozes clonadas",
"presets": "Predefinições",
"missingVoice": "Voz não encontrada (re-escolha)",
"addVoiceFailed": "Não foi possível adicionar essa voz",
"galleryFailed": "Não foi possível carregar a galeria de vozes. As suas próprias vozes continuam funcionando.",
"openGallery": "Abrir na Galeria de Voz",
"addingVoice": "Adicionando voz…",
"engineDefault": "Padrão do mecanismo",
+26 -3
View File
@@ -1820,7 +1820,18 @@
"pasteSplit": "Вставить и разделить",
"import": "Импорт",
"autocast": "Автотрансляция",
"autocastHint": "Определите, кто говорит, и автоматически назначайте голоса",
"importTitle": "Добавить строки из текста",
"importSubtitle": "Вставьте или перетащите сценарий: каждый говорящий станет персонажем с голосом",
"importPending": "Текст ожидает",
"importPlaceholder": "Вставьте главу, сцену или сценарий либо перетащите сюда текстовый файл",
"importDrop": "Отпустите, чтобы загрузить текст",
"importFormats": "Распознаёт:",
"importExampleLine": "Привет.",
"importOpenFile": "Открыть файл",
"importWords": "Слов: {{words}}",
"importSpeakers": "Говорящих: {{count}}",
"importNarrated": "Диалог не найден: все строки получит рассказчик",
"importActionsHint": "Автокастинг находит говорящих и даёт каждому голос. Разделение на строки добавляет текст как есть, для одного рассказчика.",
"autocastEmpty": "Ничего не нужно автоматически транслировать — сначала вставьте или импортируйте историю.",
"importFailed": "Не удалось прочитать этот файл.",
"addLine": "Добавить строку",
@@ -1843,7 +1854,6 @@
"noProjects": "Сохраненных историй пока нет. Сохраните, чтобы сохранить эту.",
"projectSaved": "История сохранена.",
"generateAll": "Генерировать",
"splitPlaceholder": "Вставьте длинный отрывок. Мы разделим его на сегменты по границам предложений.",
"maxChars": "Максимальное количество символов в сегменте",
"segmentsHint": "Сегмент(ы) ~{{count}} в {{max}} символов",
"pasteAbove": "Вставить текст выше",
@@ -1853,7 +1863,6 @@
"split_sentences": "Предложениям",
"split_paragraphs": "Абзацам",
"split_chapters": "Главам",
"splitModeHint": "Каждая строка озвучивается отдельным дублем. Для одного диктора абзацы или главы звучат плавнее.",
"emptyText": "Начните свою историю с добавления диалогов и повествовательных линий. Назначьте каждому персонажу голос в составе актерского состава.",
"addFirst": "Добавить первую строку",
"linePlaceholder": "Введите диалог или повествование… используйте [pause 0.5s] для тихой паузы.",
@@ -1904,6 +1913,18 @@
"chapterHeading": "Название главы",
"lineActions": "Действия со строкой",
"lineStart": "Расчётное время начала",
"timeline": "Таймлайн",
"timelineEstimate": "Позиции клипов приблизительны, пока текущие строки не будут сгенерированы",
"showTimeline": "Показать таймлайн",
"hideTimeline": "Скрыть таймлайн",
"resizeTimeline": "Изменить размер таймлайна",
"transportKeys": "Клавиши: Пробел воспроизведение/пауза · J назад на 5 с · K пауза · L воспроизведение, ещё раз быстрее · Home/End",
"lineChanged": "Изменено после последней генерации",
"changedSinceRender": "Строк изменено после последней генерации: {{count}}",
"inspector": "Инспектор",
"inspectorEmpty": "Выберите строку, чтобы изменить диктора, голос и скорость.",
"lineOf": "Строка {{index}} из {{count}}",
"lineLength": "Длительность",
"mergeNext": "Объединить со следующим",
"mergeNextHint": "Объедините соседние строки с одинаковым говорящим, переопределением голоса и настройкой скорости.",
"autocastDone_one": "{{lines}} строк распределено на {{count}} голос",
@@ -3515,10 +3536,12 @@
"createVoice": "Создать новый голос",
"fromVideo": "Из видео",
"gallery": "Галерея",
"yourVoices": "Ваши голоса",
"clone": "Клонированные голоса",
"presets": "Пресеты",
"missingVoice": "Голос не найден (выбрать повторно)",
"addVoiceFailed": "Не удалось добавить этот голос",
"galleryFailed": "Не удалось загрузить галерею голосов. Ваши собственные голоса по-прежнему работают.",
"openGallery": "Открыть в голосовой галерее",
"addingVoice": "Добавление голоса…",
"engineDefault": "Двигатель по умолчанию",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "Klistra in och dela",
"import": "Importera",
"autocast": "Autocast",
"autocastHint": "Upptäck vem som talar och tilldela röster automatiskt",
"importTitle": "Lägg till rader från text",
"importSubtitle": "Klistra in eller släpp ett manus: varje talare blir en karaktär med röst",
"importPending": "Text väntar",
"importPlaceholder": "Klistra in ett kapitel, en scen eller ett manus, eller släpp en textfil här",
"importDrop": "Släpp för att läsa in texten",
"importFormats": "Känner igen:",
"importExampleLine": "Hej.",
"importOpenFile": "Öppna fil",
"importWords": "Ord: {{words}}",
"importSpeakers": "Talare: {{count}}",
"importNarrated": "Ingen dialog hittades: alla rader går till berättaren",
"importActionsHint": "Autocasting hittar talarna och ger var och en en röst. Dela upp i rader lägger till texten som den är, för en berättare.",
"autocastEmpty": "Inget att autocasta – klistra in eller importera en berättelse först.",
"importFailed": "Kunde inte läsa den filen.",
"addLine": "Lägg till rad",
@@ -1827,13 +1838,11 @@
"noProjects": "Inga sparade berättelser ännu — Spara för att behålla den här.",
"projectSaved": "Berättelsen sparad",
"generateAll": "Generera",
"splitPlaceholder": "Klistra in en lång passage. Vi delar upp det i segment vid meningsgränser.",
"maxChars": "Max tecken per segment",
"segmentsHint": "~{{count}} segment(er) vid {{max}} tecken",
"pasteAbove": "Klistra in texten ovan",
"cancel": "Avbryt",
"splitIntoTracks": "Dela upp i rader",
"splitModeHint": "Varje rad läses som en egen inspelning. Med en enda berättare flyter Stycken eller Kapitel bättre.",
"emptyText": "Börja din berättelse genom att lägga till dialog- och berättarrader. Tilldela varje karaktär en röst i rollen.",
"addFirst": "Lägg till första raden",
"linePlaceholder": "Gå in i dialog eller berättarröst... använd [pause 0.5s] för en tyst paus",
@@ -1884,6 +1893,18 @@
"chapterHeading": "Kapiteltitel",
"lineActions": "Radåtgärder",
"lineStart": "Beräknad starttid",
"timeline": "Tidslinje",
"timelineEstimate": "Klippens positioner är uppskattningar tills de aktuella raderna har genererats",
"showTimeline": "Visa tidslinje",
"hideTimeline": "Dölj tidslinje",
"resizeTimeline": "Ändra tidslinjens storlek",
"transportKeys": "Tangenter: Mellanslag spela/paus · J 5 s bakåt · K paus · L spela, igen för snabbare · Home/End",
"lineChanged": "Ändrad sedan senaste renderingen",
"changedSinceRender": "Rader ändrade sedan senaste renderingen: {{count}}",
"inspector": "Granskare",
"inspectorEmpty": "Välj en rad för att ändra talare, röst och hastighet.",
"lineOf": "Rad {{index}} av {{count}}",
"lineLength": "Längd",
"mergeNext": "Slå samman med nästa",
"mergeNextHint": "Slå ihop intilliggande rader med samma talare, åsidosättning av röst och hastighetsinställning.",
"autocastDone_one": "{{lines}} rader tilldelade {{count}} röst",
@@ -3487,10 +3508,12 @@
"createVoice": "Skapa en ny röst",
"fromVideo": "Från video",
"gallery": "Galleri",
"yourVoices": "Dina röster",
"clone": "Klonade röster",
"presets": "Förinställningar",
"missingVoice": "Rösten hittades inte (välj om)",
"addVoiceFailed": "Kunde inte lägga till den rösten",
"galleryFailed": "Röstgalleriet kunde inte läsas in. Dina egna röster fungerar fortfarande.",
"openGallery": "Öppna i Voice Gallery",
"addingVoice": "Lägger till röst…",
"engineDefault": "Standard för motor",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "วางและแยก",
"import": "นำเข้า",
"autocast": "แคสต์อัตโนมัติ",
"autocastHint": "ตรวจจับว่าใครกำลังพูดและกำหนดเสียงโดยอัตโนมัติ",
"importTitle": "เพิ่มบรรทัดจากข้อความ",
"importSubtitle": "วางหรือลากสคริปต์มาวาง: ผู้พูดแต่ละคนจะเป็นตัวละครที่มีเสียง",
"importPending": "ข้อความรอดำเนินการ",
"importPlaceholder": "วางบท ฉาก หรือบทภาพยนตร์ หรือลากไฟล์ข้อความมาวางที่นี่",
"importDrop": "ปล่อยเพื่อโหลดข้อความ",
"importFormats": "รองรับ:",
"importExampleLine": "สวัสดี",
"importOpenFile": "เปิดไฟล์",
"importWords": "คำ: {{words}}",
"importSpeakers": "ผู้พูด: {{count}}",
"importNarrated": "ไม่พบบทสนทนา: ทุกบรรทัดเป็นของผู้บรรยาย",
"importActionsHint": "คัดเสียงอัตโนมัติจะหาผู้พูดและให้เสียงแต่ละคน แบ่งเป็นบรรทัดจะเพิ่มข้อความตามเดิม สำหรับผู้บรรยายคนเดียว",
"autocastEmpty": "ไม่มีสิ่งใดที่จะส่งอัตโนมัติ — วางหรือนำเข้าเรื่องราวก่อน",
"importFailed": "ไม่สามารถอ่านไฟล์นั้นได้",
"addLine": "แอดไลน์",
@@ -1827,14 +1838,12 @@
"noProjects": "ยังไม่มีเรื่องราวที่บันทึกไว้ — บันทึกเพื่อเก็บไว้",
"projectSaved": "บันทึกเรื่องราวแล้ว",
"generateAll": "สร้าง",
"splitPlaceholder": "แปะข้อความยาวๆ. เราจะแบ่งออกเป็นส่วนๆ ตามขอบเขตประโยค",
"maxChars": "ตัวอักษรสูงสุดต่อเซ็กเมนต์",
"segmentsHint": "~{{count}} เซ็กเมนต์ที่ {{max}} ตัวอักษร",
"pasteAbove": "วางข้อความด้านบน",
"cancel": "ยกเลิก",
"splitIntoTracks": "แยกเป็นเส้น",
"splitMode": "แยกตาม",
"splitModeHint": "แต่ละบรรทัดจะถูกอ่านเป็นเทคแยกกัน หากมีผู้บรรยายคนเดียว ย่อหน้าหรือบทจะฟังลื่นไหลกว่า",
"emptyText": "เริ่มต้นเรื่องราวของคุณด้วยการเพิ่มบทสนทนาและการบรรยาย กำหนดเสียงของตัวละครแต่ละตัวในนักแสดง",
"addFirst": "เพิ่มบรรทัดแรก",
"linePlaceholder": "เข้าสู่บทสนทนาหรือคำบรรยาย... ใช้ [pause 0.5s] เพื่อพักอย่างเงียบๆ",
@@ -1885,6 +1894,18 @@
"chapterHeading": "ชื่อบท",
"lineActions": "การทำงานของบรรทัด",
"lineStart": "เวลาเริ่มต้นโดยประมาณ",
"timeline": "ไทม์ไลน์",
"timelineEstimate": "ตำแหน่งคลิปเป็นค่าประมาณจนกว่าจะสร้างบรรทัดปัจจุบัน",
"showTimeline": "แสดงไทม์ไลน์",
"hideTimeline": "ซ่อนไทม์ไลน์",
"resizeTimeline": "ปรับขนาดไทม์ไลน์",
"transportKeys": "ปุ่ม: Space เล่น/หยุดชั่วคราว · J ย้อน 5 วิ · K หยุดชั่วคราว · L เล่น กดอีกเพื่อเร็วขึ้น · Home/End",
"lineChanged": "เปลี่ยนตั้งแต่การสร้างครั้งล่าสุด",
"changedSinceRender": "บรรทัดที่เปลี่ยนตั้งแต่การสร้างครั้งล่าสุด: {{count}}",
"inspector": "ตัวตรวจสอบ",
"inspectorEmpty": "เลือกบรรทัดเพื่อแก้ไขผู้พูด เสียง และความเร็ว",
"lineOf": "บรรทัด {{index}} จาก {{count}}",
"lineLength": "ความยาว",
"mergeNext": "รวมกับต่อไป",
"mergeNextHint": "รวมบรรทัดที่อยู่ติดกันซึ่งมีผู้พูด การกำหนดเสียงเฉพาะ และการตั้งค่าความเร็วเหมือนกัน",
"autocastDone_one": "แจกบท {{lines}} บรรทัดให้ {{count}} เสียงแล้ว",
@@ -3487,10 +3508,12 @@
"createVoice": "สร้างเสียงใหม่",
"fromVideo": "จากวิดีโอ",
"gallery": "แกลเลอรี",
"yourVoices": "เสียงของคุณ",
"clone": "เสียงโคลน",
"presets": "ค่าที่ตั้งล่วงหน้า",
"missingVoice": "ไม่พบเสียง (เลือกใหม่)",
"addVoiceFailed": "ไม่สามารถเพิ่มเสียงนั้นได้",
"galleryFailed": "โหลดแกลเลอรีเสียงไม่สำเร็จ เสียงของคุณเองยังใช้งานได้",
"openGallery": "เปิดในแกลเลอรีเสียง",
"addingVoice": "กำลังเพิ่มเสียง…",
"engineDefault": "ค่าเริ่มต้นของเครื่องยนต์",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "Yapıştır ve Böl",
"import": "İthalat",
"autocast": "Otomatik yayınlama",
"autocastHint": "Kimin konuştuğunu tespit edin ve sesleri otomatik olarak atayın",
"importTitle": "Metinden satır ekle",
"importSubtitle": "Bir senaryo yapıştırın veya bırakın: her konuşan, sesi olan bir karakter olur",
"importPending": "Bekleyen metin",
"importPlaceholder": "Bir bölüm, sahne veya senaryo yapıştırın ya da buraya bir metin dosyası bırakın",
"importDrop": "Metni yüklemek için bırakın",
"importFormats": "Tanır:",
"importExampleLine": "Merhaba.",
"importOpenFile": "Dosya aç",
"importWords": "Kelime: {{words}}",
"importSpeakers": "Konuşan: {{count}}",
"importNarrated": "Diyalog bulunamadı: tüm satırlar anlatıcıya gider",
"importActionsHint": "Otomatik oyuncu seçimi konuşanları bulur ve her birine bir ses verir. Satırlara böl, metni olduğu gibi tek anlatıcı için ekler.",
"autocastEmpty": "Otomatik olarak yayınlanacak bir şey yok; önce bir hikayeyi yapıştırın veya içe aktarın.",
"importFailed": "Bu dosya okunamadı.",
"addLine": "Satır Ekle",
@@ -1827,13 +1838,11 @@
"noProjects": "Henüz kayıtlı hikaye yok — Bunu saklamak için kaydedin.",
"projectSaved": "Hikaye kaydedildi",
"generateAll": "Oluştur",
"splitPlaceholder": "Uzun bir pasaj yapıştırın. Bunu cümle sınırlarında bölümlere ayıracağız.",
"maxChars": "Segment başına maksimum karakter",
"segmentsHint": "~{{count}} segment(ler) ve {{max}} karakter",
"pasteAbove": "Metni yukarıya yapıştır",
"cancel": "İptal",
"splitIntoTracks": "Çizgilere bölünmüş",
"splitModeHint": "Her satır ayrı bir kayıt olarak okunur. Tek anlatıcı için Paragraflar veya Bölümler daha akıcı olur.",
"emptyText": "Hikayenize diyalog ve anlatım satırları ekleyerek başlayın. Cast'ta her karaktere bir ses atayın.",
"addFirst": "İlk Satırı Ekle",
"linePlaceholder": "Diyaloğa veya anlatıma girin… sessiz bir ara için [pause 0.5s] kullanın",
@@ -1884,6 +1893,18 @@
"chapterHeading": "Bölüm başlığı",
"lineActions": "Satır işlemleri",
"lineStart": "Tahmini başlangıç zamanı",
"timeline": "Zaman çizelgesi",
"timelineEstimate": "Klip konumları, mevcut satırlar oluşturulana kadar tahminidir",
"showTimeline": "Zaman çizelgesini göster",
"hideTimeline": "Zaman çizelgesini gizle",
"resizeTimeline": "Zaman çizelgesini yeniden boyutlandır",
"transportKeys": "Tuşlar: Boşluk oynat/duraklat · J 5 sn geri · K duraklat · L oynat, tekrar daha hızlı · Home/End",
"lineChanged": "Son oluşturmadan beri değişti",
"changedSinceRender": "Son oluşturmadan beri değişen satırlar: {{count}}",
"inspector": "Denetçi",
"inspectorEmpty": "Konuşmacısını, sesini ve hızını düzenlemek için bir satır seçin.",
"lineOf": "Satır {{index}} / {{count}}",
"lineLength": "Süre",
"mergeNext": "Sonrakiyle birleştir",
"mergeNextHint": "Aynı konuşmacı, ses geçersiz kılma ve hız ayarına sahip bitişik satırları birleştirin.",
"autocastDone_one": "{{lines}} satır {{count}} sese dağıtıldı",
@@ -3487,10 +3508,12 @@
"createVoice": "Yeni bir ses oluştur",
"fromVideo": "Videodan",
"gallery": "Galeri",
"yourVoices": "Sesleriniz",
"clone": "Klonlanmış sesler",
"presets": "Ön ayarlar",
"missingVoice": "Ses bulunamadı (yeniden seç)",
"addVoiceFailed": "Bu ses eklenemedi",
"galleryFailed": "Ses Galerisi yüklenemedi. Kendi sesleriniz hâlâ çalışıyor.",
"openGallery": "Ses Galerisinde aç",
"addingVoice": "Ses ekleniyor…",
"engineDefault": "Motor varsayılanı",
+26 -3
View File
@@ -1820,7 +1820,18 @@
"pasteSplit": "Вставити та розділити",
"import": "Імпорт",
"autocast": "Автокаст",
"autocastHint": "Визначайте, хто говорить, і автоматично призначайте голоси",
"importTitle": "Додати рядки з тексту",
"importSubtitle": "Вставте або перетягніть сценарій: кожен мовець стане персонажем із голосом",
"importPending": "Текст очікує",
"importPlaceholder": "Вставте розділ, сцену чи сценарій або перетягніть сюди текстовий файл",
"importDrop": "Відпустіть, щоб завантажити текст",
"importFormats": "Розпізнає:",
"importExampleLine": "Привіт.",
"importOpenFile": "Відкрити файл",
"importWords": "Слів: {{words}}",
"importSpeakers": "Мовців: {{count}}",
"importNarrated": "Діалог не знайдено: усі рядки отримає оповідач",
"importActionsHint": "Автокастинг знаходить мовців і дає кожному голос. Поділ на рядки додає текст як є, для одного оповідача.",
"autocastEmpty": "Нічого для автоматичної трансляції — спочатку вставте або імпортуйте історію.",
"importFailed": "Не вдалося прочитати цей файл.",
"addLine": "Додати лінію",
@@ -1843,7 +1854,6 @@
"noProjects": "Ще немає збережених історій — збережіть, щоб зберегти цю.",
"projectSaved": "Історія збережена",
"generateAll": "Генерувати",
"splitPlaceholder": "Вклейте довгий уривок. Ми розділимо його на сегменти на межі речень.",
"maxChars": "Максимальна кількість символів на сегмент",
"segmentsHint": "~{{count}} сегмент(и) на {{max}} символів",
"pasteAbove": "Вставте текст вище",
@@ -1853,7 +1863,6 @@
"split_sentences": "Реченнями",
"split_paragraphs": "Абзацами",
"split_chapters": "Розділами",
"splitModeHint": "Кожен рядок озвучується окремим дублем. Для одного диктора абзаци або розділи звучать плавніше.",
"emptyText": "Почніть свою історію, додавши діалоги та розповідь. Призначте кожному персонажу голос у Cast.",
"addFirst": "Додайте перший рядок",
"linePlaceholder": "Почніть діалог або розповідь… використовуйте [pause 0.5s] для мовчазної перерви",
@@ -1904,6 +1913,18 @@
"chapterHeading": "Назва розділу",
"lineActions": "Дії з рядком",
"lineStart": "Орієнтовний час початку",
"timeline": "Таймлайн",
"timelineEstimate": "Позиції кліпів приблизні, доки поточні рядки не буде згенеровано",
"showTimeline": "Показати таймлайн",
"hideTimeline": "Сховати таймлайн",
"resizeTimeline": "Змінити розмір таймлайна",
"transportKeys": "Клавіші: Пробіл відтворення/пауза · J назад на 5 с · K пауза · L відтворення, ще раз швидше · Home/End",
"lineChanged": "Змінено після останньої генерації",
"changedSinceRender": "Рядків змінено після останньої генерації: {{count}}",
"inspector": "Інспектор",
"inspectorEmpty": "Виберіть рядок, щоб змінити диктора, голос і швидкість.",
"lineOf": "Рядок {{index}} з {{count}}",
"lineLength": "Тривалість",
"mergeNext": "Об'єднати з наступним",
"mergeNextHint": "Об’єднайте сусідні рядки з однаковим мовцем, перевизначенням голосу й налаштуванням швидкості.",
"autocastDone_one": "{{lines}} рядків розподілено на {{count}} голос",
@@ -3515,10 +3536,12 @@
"createVoice": "Створіть новий голос",
"fromVideo": "З відео",
"gallery": "Галерея",
"yourVoices": "Ваші голоси",
"clone": "Клоновані голоси",
"presets": "Предустановки",
"missingVoice": "Голос не знайдено (виберіть ще раз)",
"addVoiceFailed": "Не вдалося додати цей голос",
"galleryFailed": "Не вдалося завантажити галерею голосів. Ваші власні голоси й далі працюють.",
"openGallery": "Відкрити в голосовій галереї",
"addingVoice": "Додавання голосу…",
"engineDefault": "Двигун за замовчуванням",
+26 -3
View File
@@ -1804,7 +1804,18 @@
"pasteSplit": "Dán & Tách",
"import": "Nhập khẩu",
"autocast": "Tự động truyền",
"autocastHint": "Phát hiện ai đang nói và tự động gán giọng nói",
"importTitle": "Thêm dòng từ văn bản",
"importSubtitle": "Dán hoặc thả kịch bản: mỗi người nói trở thành một nhân vật có giọng",
"importPending": "Văn bản đang chờ",
"importPlaceholder": "Dán một chương, cảnh hoặc kịch bản, hoặc thả tệp văn bản vào đây",
"importDrop": "Thả để tải văn bản",
"importFormats": "Nhận dạng:",
"importExampleLine": "Xin chào.",
"importOpenFile": "Mở tệp",
"importWords": "Số từ: {{words}}",
"importSpeakers": "Người nói: {{count}}",
"importNarrated": "Không thấy hội thoại: mọi dòng thuộc về người kể",
"importActionsHint": "Tự phân vai tìm người nói và gán giọng cho từng người. Tách thành dòng thêm văn bản nguyên vẹn, cho một người kể.",
"autocastEmpty": "Không có gì để tự động truyền — trước tiên hãy dán hoặc nhập câu chuyện.",
"importFailed": "Không thể đọc tập tin đó.",
"addLine": "Thêm dòng",
@@ -1827,14 +1838,12 @@
"noProjects": "Chưa có câu chuyện nào được lưu - Lưu để giữ câu chuyện này.",
"projectSaved": "Đã lưu câu chuyện",
"generateAll": "Tạo",
"splitPlaceholder": "Dán một đoạn văn dài. Chúng ta sẽ chia nó thành các phân đoạn ở ranh giới câu.",
"maxChars": "Ký tự tối đa trên mỗi phân đoạn",
"segmentsHint": "~{{count}} phân đoạn ở {{max}} ký tự",
"pasteAbove": "Dán văn bản ở trên",
"cancel": "Hủy bỏ",
"splitIntoTracks": "Chia thành dòng",
"split_paragraphs": "Đoạn",
"splitModeHint": "Mỗi dòng được đọc thành một bản thu riêng. Với một người đọc, Đoạn hoặc Chương nghe mượt hơn.",
"emptyText": "Bắt đầu câu chuyện của bạn bằng cách thêm lời thoại và lời kể. Gán cho mỗi nhân vật một giọng nói trong Cast.",
"addFirst": "Thêm dòng đầu tiên",
"linePlaceholder": "Nhập đoạn hội thoại hoặc tường thuật… sử dụng [pause 0.5s] để nghỉ im lặng",
@@ -1885,6 +1894,18 @@
"chapterHeading": "Tiêu đề chương",
"lineActions": "Thao tác dòng",
"lineStart": "Thời điểm bắt đầu ước tính",
"timeline": "Dòng thời gian",
"timelineEstimate": "Vị trí clip là ước tính cho đến khi các dòng hiện tại được tạo",
"showTimeline": "Hiện dòng thời gian",
"hideTimeline": "Ẩn dòng thời gian",
"resizeTimeline": "Đổi kích thước dòng thời gian",
"transportKeys": "Phím: Space phát/tạm dừng · J lùi 5 giây · K tạm dừng · L phát, nhấn lại để nhanh hơn · Home/End",
"lineChanged": "Đã thay đổi kể từ lần tạo gần nhất",
"changedSinceRender": "Số dòng đã thay đổi kể từ lần tạo gần nhất: {{count}}",
"inspector": "Trình kiểm tra",
"inspectorEmpty": "Chọn một dòng để sửa người nói, giọng và tốc độ.",
"lineOf": "Dòng {{index}} / {{count}}",
"lineLength": "Độ dài",
"mergeNext": "Hợp nhất với tiếp theo",
"mergeNextHint": "Gộp các dòng liền kề có cùng người nói, lựa chọn giọng riêng và cài đặt tốc độ.",
"autocastDone_one": "Đã phân {{lines}} dòng cho {{count}} giọng",
@@ -3487,10 +3508,12 @@
"createVoice": "Tạo một giọng nói mới",
"fromVideo": "Từ video",
"gallery": "Thư viện",
"yourVoices": "Giọng của bạn",
"clone": "Giọng nói nhân bản",
"presets": "cài đặt trước",
"missingVoice": "Không tìm thấy giọng nói (chọn lại)",
"addVoiceFailed": "Không thể thêm giọng nói đó",
"galleryFailed": "Không tải được Thư viện giọng. Giọng của bạn vẫn dùng được.",
"openGallery": "Mở trong Thư viện giọng nói",
"addingVoice": "Đang thêm giọng nói…",
"engineDefault": "Mặc định công cụ",
@@ -1804,7 +1804,18 @@
"pasteSplit": "粘贴并拆分",
"import": "导入",
"autocast": "自动配音",
"autocastHint": "自动检测说话者并分配语音",
"importTitle": "从文本添加台词",
"importSubtitle": "粘贴或拖入剧本:每位说话人都会成为有声音的角色",
"importPending": "有待处理的文本",
"importPlaceholder": "粘贴章节、场景或剧本,或将文本文件拖到这里",
"importDrop": "松开以载入文本",
"importFormats": "可识别:",
"importExampleLine": "你好。",
"importOpenFile": "打开文件",
"importWords": "词数:{{words}}",
"importSpeakers": "说话人:{{count}}",
"importNarrated": "未找到对话:所有台词都交给旁白",
"importActionsHint": "自动分配会找出说话人并为每人分配声音。拆分为台词则按原样添加文本,适合单一旁白。",
"autocastEmpty": "没有可自动配音的内容 — 请先粘贴或导入故事。",
"importFailed": "无法读取该文件。",
"addLine": "添加台词",
@@ -1827,14 +1838,12 @@
"noProjects": "尚无已保存的故事 — 点击保存以留存当前故事。",
"projectSaved": "故事已保存",
"generateAll": "生成",
"splitPlaceholder": "粘贴一段长文本,我们会在句子边界处将其拆分为多段。",
"maxChars": "每段最大字符数",
"segmentsHint": "约 {{count}} 段,每段 {{max}} 字符",
"pasteAbove": "在上方粘贴文本",
"cancel": "取消",
"splitIntoTracks": "拆分为台词",
"splitMode": "拆分依据",
"splitModeHint": "每一行都会作为独立的一遍朗读。只有一位讲述者时,按段落或章节拆分听起来更自然。",
"emptyText": "添加对白和旁白台词,开始你的故事。在配音中为每个角色分配语音。",
"addFirst": "添加第一句",
"linePlaceholder": "输入对白或旁白……使用 [pause 0.5s] 插入静音停顿",
@@ -1884,6 +1893,18 @@
"chapterHeading": "章节标题",
"lineActions": "行操作",
"lineStart": "预计开始时间",
"timeline": "时间线",
"timelineEstimate": "在生成当前台词之前,片段位置为估计值",
"showTimeline": "显示时间线",
"hideTimeline": "隐藏时间线",
"resizeTimeline": "调整时间线大小",
"transportKeys": "快捷键:空格 播放/暂停 · J 后退 5 秒 · K 暂停 · L 播放,再按加速 · Home/End",
"lineChanged": "自上次生成后已更改",
"changedSinceRender": "自上次生成后更改的行:{{count}}",
"inspector": "检查器",
"inspectorEmpty": "选择一行以编辑其说话人、声音和语速。",
"lineOf": "第 {{index}} 行,共 {{count}} 行",
"lineLength": "时长",
"mergeNext": "与下一段合并",
"mergeNextHint": "合并说话人、单独指定的音色和速度设置相同的相邻行。",
"autocastDone_one": "已将 {{lines}} 行自动分配给 {{count}} 个声音",
@@ -3481,6 +3502,7 @@
"voiceSelector": {
"createVoice": "创建新声音",
"gallery": "音色库",
"yourVoices": "你的声音",
"clone": "克隆声音",
"presets": "预设",
"missingVoice": "找不到语音(重新选择)",
@@ -3488,6 +3510,7 @@
"engineDefault": "引擎默认",
"preview": "预览语音",
"addVoiceFailed": "无法添加该声音 — 请重试。",
"galleryFailed": "无法加载声音库。你自己的声音仍可使用。",
"designed": "设计声音",
"fromVideo": "来自视频",
"openGallery": "在声音库中打开"
@@ -1804,7 +1804,18 @@
"pasteSplit": "貼上和分割",
"import": "進口",
"autocast": "自動施法",
"autocastHint": "偵測誰在說話並自動分配聲音",
"importTitle": "從文字新增台詞",
"importSubtitle": "貼上或拖入劇本:每位說話者都會成為有聲音的角色",
"importPending": "有待處理的文字",
"importPlaceholder": "貼上章節、場景或劇本,或將文字檔拖到這裡",
"importDrop": "放開以載入文字",
"importFormats": "可辨識:",
"importExampleLine": "你好。",
"importOpenFile": "開啟檔案",
"importWords": "字數:{{words}}",
"importSpeakers": "說話者:{{count}}",
"importNarrated": "找不到對話:所有台詞都交給旁白",
"importActionsHint": "自動分配會找出說話者並為每人分配聲音。拆分為台詞則依原樣新增文字,適合單一旁白。",
"autocastEmpty": "無需自動投射 - 首先貼上或匯入故事。",
"importFailed": "無法讀取該檔案。",
"addLine": "新增線路",
@@ -1827,14 +1838,12 @@
"noProjects": "尚未儲存故事 — 儲存以保留此故事。",
"projectSaved": "故事已儲存",
"generateAll": "產生",
"splitPlaceholder": "貼一個很長的段落。我們將在句子邊界將其分成片段。",
"maxChars": "每段最大字元數",
"segmentsHint": "~{{count}} 段位於 {{max}} 字元處",
"pasteAbove": "將文字貼到上面",
"cancel": "取消",
"splitIntoTracks": "分成幾行",
"splitMode": "拆分依據",
"splitModeHint": "每一行都會當作獨立的一遍朗讀。只有一位敘述者時,依段落或章節拆分聽起來更自然。",
"emptyText": "透過加入對話和旁白來開始你的故事。為演員陣容中的每個角色分配一個聲音。",
"addFirst": "新增第一行",
"linePlaceholder": "輸入對話或旁白…使用 [pause 0.5s] 進行靜默休息",
@@ -1885,6 +1894,18 @@
"chapterHeading": "章節標題",
"lineActions": "行操作",
"lineStart": "預估開始時間",
"timeline": "時間軸",
"timelineEstimate": "在生成目前台詞之前,片段位置為估計值",
"showTimeline": "顯示時間軸",
"hideTimeline": "隱藏時間軸",
"resizeTimeline": "調整時間軸大小",
"transportKeys": "快速鍵:空白鍵 播放/暫停 · J 倒退 5 秒 · K 暫停 · L 播放,再按加速 · Home/End",
"lineChanged": "自上次生成後已變更",
"changedSinceRender": "自上次生成後變更的行:{{count}}",
"inspector": "檢查器",
"inspectorEmpty": "選取一行以編輯其說話者、聲音和語速。",
"lineOf": "第 {{index}} 行,共 {{count}} 行",
"lineLength": "長度",
"mergeNext": "與下一個合併",
"mergeNextHint": "合併說話者、個別指定的音色和速度設定相同的相鄰行。",
"autocastDone_one": "已將 {{lines}} 行自動分配給 {{count}} 個聲音",
@@ -3487,10 +3508,12 @@
"createVoice": "創造新聲音",
"fromVideo": "來自視頻",
"gallery": "圖庫",
"yourVoices": "你的聲音",
"clone": "複製聲音",
"presets": "預設",
"missingVoice": "找不到語音(重新選擇)",
"addVoiceFailed": "無法新增該聲音",
"galleryFailed": "無法載入聲音庫。你自己的聲音仍可使用。",
"openGallery": "在語音庫中打開",
"addingVoice": "正在新增聲音…",
"engineDefault": "引擎預設",
@@ -117,6 +117,11 @@ export function usePlaybackClock(source: string): PlaybackClock {
return useStore(clocks, (state) => state[source] || emptyClock);
}
/** One derived value from a source's clock; re-renders only when that value changes. */
export function usePlaybackValue<T>(source: string, select: (clock: PlaybackClock) => T): T {
return useStore(clocks, (state) => select(state[source] || emptyClock));
}
export function getPlaybackSeek(source: string): SeekRequest | undefined {
return clocks.state[source]?.seek;
}
+25
View File
@@ -0,0 +1,25 @@
export interface LongformSpan {
voice_id: string | null;
text: string;
pause_ms_after: number;
speed: number | null;
join?: 'paragraph' | 'continue';
emotion?: string;
}
export interface LongformChapter {
title: string;
spans: LongformSpan[];
}
export const PAUSE_DEFAULT_MS: number;
export const PAUSE_MAX_MS: number;
export const EMOTION_MAX_CHARS: number;
export function roundHalfToEven(x: number): number;
export function pauseMilliseconds(text: string): number;
export function parseChapterBody(
body: string,
options?: { defaultVoice?: string | null; defaultSpeed?: number | null },
): LongformSpan[];
export function parseScriptToSpans(
text: string,
options?: { defaultVoice?: string | null; defaultSpeed?: number | null },
): LongformChapter[];
@@ -50,6 +50,11 @@ function _pauseMs(num, unit) {
return Math.max(0, Math.min(msInt, PAUSE_MAX_MS));
}
/** Milliseconds of silence the `[pause …]` markers in `text` add, as rendered. */
export function pauseMilliseconds(text) {
return parsePauseMarkers(text).reduce((sum, [, ms]) => sum + ms, 0);
}
/** Mirror of text.py:parse_pause_markers → [[spanText, pauseMsAfter], …]. */
function parsePauseMarkers(text) {
if (!text || text.indexOf('[') === -1) return [[text, 0]];
+50
View File
@@ -10739,6 +10739,56 @@
"summary": "Use Archetype"
}
},
"/audio-peaks/{name}": {
"get": {
"description": "Waveform outline of a saved output (``buckets`` peaks, 0-100).\n\nLets the Stories timeline draw a long render's waveform without the\nbrowser downloading and decoding the whole file. Cached per file\nversion, so redrawing at another zoom is instant.",
"operationId": "audio_peaks_audio_peaks__name__get",
"parameters": [
{
"in": "path",
"name": "name",
"required": true,
"schema": {
"title": "Name",
"type": "string"
}
},
{
"in": "query",
"name": "buckets",
"required": false,
"schema": {
"default": 2000,
"maximum": 20000,
"minimum": 1,
"title": "Buckets",
"type": "integer"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Audio Peaks"
}
},
"/audio/{audio_id}.mp3": {
"get": {
"description": "Serve the same render as /audio/<id>.wav, encoded as MP3 for export.\n\nUnlike Ogg/Opus this is a one-shot download, so it is not cached.",
+108
View File
@@ -0,0 +1,108 @@
"""GET /audio-peaks/<name>: a saved output's waveform outline for the Stories timeline."""
import io
import math
import os
import struct
import wave
os.environ.setdefault("OMNIVOICE_MODEL", "test")
os.environ.setdefault("OMNIVOICE_DISABLE_FILE_LOG", "1")
import pytest
def _wav(seconds=2.0, rate=24000, first=None, second=220):
# Silence (or a ``first`` tone) for the first half, a ``second`` tone after.
frames = int(seconds * rate)
tone = lambda hz, i: int(16000 * math.sin(i * 2 * math.pi * hz / rate)) if hz else 0
samples = [tone(first if i < frames // 2 else second, i) for i in range(frames)]
buf = io.BytesIO()
with wave.open(buf, "wb") as out:
out.setnchannels(1)
out.setsampwidth(2)
out.setframerate(rate)
out.writeframes(struct.pack(f"<{len(samples)}h", *samples))
return buf.getvalue()
def _client(monkeypatch, outputs, consumer=True):
from api.dependencies import require_consumer
from api.routers import generation
from fastapi import FastAPI
from fastapi.testclient import TestClient
monkeypatch.setattr(generation, "OUTPUTS_DIR", str(outputs))
generation._peaks_cache.clear()
app = FastAPI()
app.include_router(generation.router)
if consumer:
app.dependency_overrides[require_consumer] = lambda: None
return TestClient(app)
def test_peaks_need_the_consumer_tier(monkeypatch, tmp_path):
# Decoding a render is real work, so an unauthorised caller can't start it.
(tmp_path / "story_ab12.wav").write_bytes(_wav())
client = _client(monkeypatch, tmp_path, consumer=False)
assert client.get("/audio-peaks/story_ab12.wav").status_code in (401, 403)
def test_peaks_from_pcm_scales_each_bucket_to_the_loudest():
from services.audio_io import PEAKS_SAMPLE_RATE, peaks_from_pcm
pcm = struct.pack("<6h", 0, 0, 100, -200, 1000, -32768)
result = peaks_from_pcm(pcm, 3)
assert result == {"duration": 6 / PEAKS_SAMPLE_RATE, "peaks": [0, 1, 100]}
assert peaks_from_pcm(b"", 10) == {"duration": 0, "peaks": []}
# More buckets than samples: one per sample.
assert len(peaks_from_pcm(pcm, 50)["peaks"]) == 6
def test_peaks_outline_a_saved_render(monkeypatch, tmp_path):
from services.ffmpeg_utils import find_ffmpeg
if not find_ffmpeg():
pytest.skip("ffmpeg is not installed")
(tmp_path / "story_ab12.wav").write_bytes(_wav())
client = _client(monkeypatch, tmp_path)
response = client.get("/audio-peaks/story_ab12.wav", params={"buckets": 20})
assert response.status_code == 200
body = response.json()
assert body["duration"] == pytest.approx(2.0, abs=0.05)
assert len(body["peaks"]) == 20
assert max(body["peaks"][:9]) <= 2 # silent half
assert min(body["peaks"][11:]) >= 50 # tone half
assert client.get("/audio-peaks/story_ab12.wav", params={"buckets": 20}).json() == body
def test_peaks_draw_high_frequencies_as_loud_as_low_ones(monkeypatch, tmp_path):
from services.ffmpeg_utils import find_ffmpeg
if not find_ffmpeg():
pytest.skip("ffmpeg is not installed")
# Equally loud halves: a low hum, then a 2 kHz tone that 1 kHz audio can't carry.
(tmp_path / "story_hf.wav").write_bytes(_wav(first=220, second=2000))
body = _client(monkeypatch, tmp_path).get(
"/audio-peaks/story_hf.wav", params={"buckets": 20},
).json()
assert min(body["peaks"][11:]) >= 30
def test_peaks_reject_missing_and_escaping_names(monkeypatch, tmp_path):
client = _client(monkeypatch, tmp_path)
assert client.get("/audio-peaks/missing.wav").status_code == 404
assert client.get("/audio-peaks/..%2Fsecret.wav").status_code == 404
assert client.get("/audio-peaks/a.wav", params={"buckets": 0}).status_code == 422
def test_peaks_decoder_failure_is_service_unavailable(monkeypatch, tmp_path):
from services import audio_io
async def fail(*_args, **_kwargs):
raise RuntimeError("Waveform encoding failed: bad input")
monkeypatch.setattr(audio_io, "_encode_with_ffmpeg", fail)
(tmp_path / "x.wav").write_bytes(_wav(0.1))
response = _client(monkeypatch, tmp_path).get("/audio-peaks/x.wav")
assert response.status_code == 503
assert "Waveform" in response.json()["detail"]