Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/starpod/src/components/FullPlayButton.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useComputed } from '@preact/signals';
import { useLayoutEffect, useRef, useState } from 'preact/hooks';

import { startEngine } from './media/engine';
Expand Down Expand Up @@ -31,8 +32,9 @@ export default function FullPlayButton({ episode, look = 'row' }: Props) {
const button = useRef<HTMLButtonElement>(null);
const [resumeAt, setResumeAt] = useState(0);

const isCurrent =
Boolean(episode) && episode!.id === currentEpisode.value?.id;
const isCurrent = useComputed(
() => Boolean(episode) && episode!.id === currentEpisode.value?.id
).value;

// Read again when it stops being current: it has just been played.
useLayoutEffect(() => {
Expand Down
33 changes: 23 additions & 10 deletions packages/starpod/src/components/media/LiveScript.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks';
import { useComputed, useSignal } from '@preact/signals';
import { useLayoutEffect, useMemo, useRef } from 'preact/hooks';

import type { TranscriptCue } from '../../lib/cues';
import { formatClock } from '../../utils/playable';
Expand Down Expand Up @@ -103,29 +104,42 @@ function useFlip(
* lines already spoken shrink back into the page. Any line seeks.
*/
export default function LiveScript({ episode }: Props) {
const [cues, setCues] = useState<Array<TranscriptCue> | null>(null);
const loaded = useSignal<Array<TranscriptCue> | null>(null);

// Fetched as hydration completes, not after the next frame; again for a
// new episode, whose lines replace the last one's (a reply for the old one
// arriving late is dropped).
useLayoutEffect(() => {
if (!episode.slug) {
setCues([]);
loaded.value = [];
return;
}
let current = true;
setCues(null);
void loadCues(episode.slug).then((next) => current && setCues(next));
loaded.value = null;
void loadCues(episode.slug).then((next) => {
if (current) {
loaded.value = next;
}
});
return () => {
current = false;
};
}, [episode.slug]);

const list = useRef<HTMLOListElement>(null);
const isCurrent = currentEpisode.value?.id === episode.id;
const live = useMemo(
() => (cues?.length && isCurrent ? cueIndexAt(cues, currentTime.value + 0.25) : -1),
[cues, isCurrent, Math.floor(currentTime.value * 4)]
// Only the playing episode's stage reads the clock, and it re-renders only
// when the live line moves.
const live = useComputed(() => {
const lines = loaded.value;
if (!lines?.length || currentEpisode.value?.id !== episode.id) {
return -1;
}
return cueIndexAt(lines, currentTime.value + 0.25);
}).value;
const cues = loaded.value;
const speakers = useMemo(
() => new Set(cues?.map((cue) => cue.n).filter(Boolean)).size,
[cues]
);

// Idle (not this episode, or not started): the opening line already holds
Expand All @@ -145,7 +159,6 @@ export default function LiveScript({ episode }: Props) {
const start = idle ? 0 : Math.max(0, anchor - BEFORE);
const end = Math.min(cues.length, anchor + (idle ? 4 : AFTER + 1));
const visible = cues.slice(start, end);
const speakers = new Set(cues.map((cue) => cue.n).filter(Boolean)).size;

return (
<ol
Expand Down
3 changes: 2 additions & 1 deletion packages/starpod/src/components/media/Scrubber.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export default function Scrubber({ duration, episode, time }: Props) {
const [cues, setCues] = useState<Array<TranscriptCue> | null>(null);
const [preview, setPreview] = useState<{ at: number; x: number; top: number } | null>(null);
const dragging = useRef(false);
const [dock] = useState(() => document.querySelector('.dock') ?? document.body);

const slug = useRef(episode.slug);
slug.current = episode.slug;
Expand Down Expand Up @@ -139,7 +140,7 @@ export default function Scrubber({ duration, episode, time }: Props) {
</span>
)}
</div>,
document.querySelector('.dock') ?? document.body
dock
)}
</>
);
Expand Down
114 changes: 114 additions & 0 deletions tests/unit/LiveScript.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { act, render } from '@testing-library/preact';
import { options } from 'preact';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

const lines = [
{ s: 0, t: 'Line zero', n: 'Host' },
{ s: 10, t: 'Line one', n: 'Guest' },
{ s: 20, t: 'Line two', n: 'Host' },
{ s: 30, t: 'Line three', n: 'Guest' }
];

vi.mock('starpod/src/components/media/cue-cache', async (original) => ({
...(await original<typeof import('starpod/src/components/media/cue-cache')>()),
loadCues: vi.fn(() => Promise.resolve(lines))
}));

import LiveScript from 'starpod/src/components/media/LiveScript';
import { currentEpisode, currentTime } from 'starpod/src/components/state';

const episode = (slug: string) => ({
id: slug,
slug,
title: `Episode ${slug}`,
audio: { src: `${slug}.mp3`, type: 'audio/mpeg' },
episodeNumber: '1'
});

const liveLine = (container: Element) =>
container.querySelector('.script-line[data-d="0"] .script-text')?.textContent;

async function mount(slug: string) {
const view = render(<LiveScript episode={episode(slug)} />);
await act(async () => {});
return view;
}

/** Counts LiveScript renders through Preact's public diff hook. */
function countRenders() {
const before = options.diffed;
let count = 0;
options.diffed = (vnode) => {
if (vnode.type === LiveScript) {
count++;
}
before?.(vnode);
};
return {
get count() {
return count;
},
stop: () => {
options.diffed = before;
}
};
}

describe('LiveScript', () => {
beforeEach(() => {
currentEpisode.value = null;
currentTime.value = 0;
});
afterEach(() => {
currentEpisode.value = null;
});

it('follows the clock through the lines of the episode playing', async () => {
currentEpisode.value = episode('a');
const { container } = await mount('a');
expect(container.querySelector('.script')).toHaveAttribute('data-state', 'live');
expect(liveLine(container)).toBe('Line zero');

act(() => {
currentTime.value = 12;
});
expect(liveLine(container)).toBe('Line one');

// A line about to start is already live a moment early.
act(() => {
currentTime.value = 29.8;
});
expect(liveLine(container)).toBe('Line three');
});

it('holds its opening preview while another episode plays', async () => {
currentEpisode.value = episode('a');
const { container } = await mount('b');
const script = container.querySelector('.script')!;
expect(script).toHaveAttribute('data-state', 'preview');

act(() => {
currentTime.value = 25;
});
expect(script).toHaveAttribute('data-state', 'preview');
expect(liveLine(container)).toBe('Line zero');
});

it('renders only when the live line changes, and never for another episode’s clock', async () => {
currentEpisode.value = episode('a');
await mount('a');
await mount('b');
const renders = countRenders();
try {
for (let t = 0; t < 10; t += 0.25) {
act(() => {
currentTime.value = t;
});
}
// Crossing 9.75s (10s with the lookahead) moves the live line once.
expect(renders.count).toBe(1);
} finally {
renders.stop();
}
});
});
Loading