Number 32: Transcript that follows the talk
Specification
- Catalogue
- No. 32 of 110
- Section
- Text and code
- Interaction
- Press, Text Animation
- Element
- Text, Media
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
The words fill in to full ink as they are spoken, any sentence jumps there, and reading ahead is never pulled back.
A listener can jump to the line they want, and a reader can scroll ahead: following stops until they press Back to now.
Spoken words in full ink, upcoming words muted, the current word underlined in the brand colour. Keeps the current line a third of the way down; any manual scroll stops following. Plays only when asked and stops at the end. This demo runs a simulated clock; a real build reads the audio element's time and real word timings.
The names, figures and pictures in the demo are sample content; a real build uses the client's own.
Code
React and plain CSS"use client";
import { useEffect, useId, useMemo, useRef, useState, type CSSProperties } from "react";
import { reducedNow } from "@/components/pieces/motion-helpers";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./synced-transcript.css";
const TALK = [
"Most people skip the warm-up because it feels like wasted time.",
"It is the opposite.",
"Five minutes of easy movement raises your temperature and wakes up the muscles you are about to use.",
"Start with the big joints: hips, shoulders, ankles.",
"Then do a lighter version of your first exercise.",
"If that first set still feels heavy, it was your warm-up, so add one more.",
"After a few sessions it becomes habit.",
];
const WORD_S = 0.3;
const PAUSE_S = 0.45;
type Word = { text: string; start: number; s: number };
function timings() {
const words: Word[] = [];
const starts: number[] = [];
let t = 0;
TALK.forEach((sentence, s) => {
starts.push(t);
for (const w of sentence.split(" ")) {
words.push({ text: w, start: t, s });
t += WORD_S;
}
t += PAUSE_S;
});
return { words, starts, total: t };
}
const clock = (t: number) => `${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, "0")}`;
function SyncedTranscriptDemo() {
const { words, starts, total } = useMemo(() => timings(), []);
const [t, setT] = useState(0);
const [playing, setPlaying] = useState(false);
const [follow, setFollow] = useState(true);
const box = useRef<HTMLDivElement>(null);
const ourScroll = useRef(false);
const uid = useId();
// A simulated clock; a real build reads the audio element's currentTime.
useEffect(() => {
if (!playing) return;
let raf = 0;
let last = performance.now();
const tick = (now: number) => {
const dt = (now - last) / 1000;
setT((x) => {
const n = x + dt;
if (n >= total) {
setPlaying(false);
return total;
}
return n;
});
last = now;
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [playing, total]);
let curWord = -1;
for (let i = 0; i < words.length && words[i]!.start <= t; i++) curWord = i;
const curSentence = curWord < 0 ? 0 : words[curWord]!.s;
// Keep the spoken line in view, unless the reader has scrolled away.
useEffect(() => {
const b = box.current;
if (!b || !follow || !playing) return;
const line = b.querySelector<HTMLElement>(`[data-s="${curSentence}"]`);
if (!line) return;
const top = line.offsetTop - b.clientHeight / 3;
if (Math.abs(b.scrollTop - top) < 4) return;
ourScroll.current = true;
b.scrollTo({ top, behavior: reducedNow() ? "auto" : "smooth" });
const done = window.setTimeout(() => (ourScroll.current = false), 900);
return () => window.clearTimeout(done);
}, [curSentence, follow, playing]);
const stopFollowing = () => {
if (!ourScroll.current) setFollow(false);
};
const seek = (to: number) => {
setT(Math.min(total, Math.max(0, to)));
setFollow(true);
};
return (
<div className="dm">
<div className="stx">
<div className="stx-bar">
<button
type="button"
className="stx-play"
aria-label={playing ? "Pause" : t >= total ? "Play again" : "Play"}
onClick={() => {
if (t >= total) setT(0);
setPlaying((p) => !p);
setFollow(true);
}}
>
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
<path d={playing ? "M7 5h3.5v14H7zM13.5 5H17v14h-3.5z" : "M8 5.5v13l10.5-6.5z"} fill="currentColor" />
</svg>
</button>
<input
className="stx-seek"
type="range"
min={0}
max={total}
step={0.1}
value={t}
aria-label="Position in the talk"
aria-valuetext={`${clock(t)} of ${clock(total)}`}
onChange={(e) => seek(Number(e.target.value))}
style={{ "--p": `${(t / total) * 100}%` } as CSSProperties}
/>
<span className="stx-time">
{clock(t)} / {clock(total)}
</span>
</div>
<div ref={box} className="stx-text" id={`${uid}-tx`} tabIndex={0} role="region" aria-label="Transcript" onWheel={stopFollowing} onTouchMove={stopFollowing} onScroll={stopFollowing}>
{TALK.map((sentence, s) => (
<p key={s} data-s={s}>
<button type="button" className="stx-line" onClick={() => seek((starts[s] ?? 0) + 0.01)} aria-label={`Play from: ${sentence}`}>
{words.map((w, i) =>
w.s === s ? (
<span key={i} aria-hidden="true" data-said={i < curWord || undefined} data-now={i === curWord || undefined}>
{w.text}{" "}
</span>
) : null,
)}
</button>
</p>
))}
</div>
{!follow && playing && (
<button type="button" className="dm-btn stx-now" onClick={() => setFollow(true)}>
Back to now
</button>
)}
</div>
</div>
);
}
// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
{ click: ".stx-play", wait: 5200 },
{ click: ".stx-play", wait: 600 },
];
export default function SyncedTranscriptEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Transcript that follows the talk" sample tour={TOUR}>
<SyncedTranscriptDemo />
</PieceStage>
);
}