fix(video): animate transcript playback scrolling

This commit is contained in:
yiling
2026-12-03 18:44:17 +08:00
parent ce4ae6e33e
commit cdd45429c4
5 changed files with 183 additions and 36 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **sessions**: See total tokens and estimated cost in the session logs footer, with a breakdown of input, output, and cached tokens.
- **projects**: Middle-click or Command/Ctrl-click a project to open it in a new tab. Use **Open in new tab** in a file or folder's context menu to keep your current view open.
- **video**: Use **Generate Transcripts** in a video's context menu to save a transcript with the local embedding server. Choose a language or let the server detect it automatically. The dialog closes when the transcript is ready.
- **video**: Open saved transcripts from the video player, switch languages, search the text, and jump to the exact start of a segment by selecting it. Drag the divider to resize the transcript panel on desktop. As the video plays, the panel scrolls early to keep upcoming segments in view.
- **video**: Open saved transcripts from the video player, switch languages, search the text, and jump to the exact start of a segment by selecting it. Drag the divider to resize the transcript panel on desktop. As the video plays, the panel scrolls smoothly to keep upcoming segments in view.
### Fixed
+1 -1
View File
@@ -121,7 +121,7 @@ apps/web/e2e/
| Upload a txt file, wait for transcode, and create a comment with draw | `tests/file/txt-draw-comment.spec.ts` |
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` |
| Upload a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
| Read and search saved video transcripts, resize the desktop panel, jump to a segment, check early playback scrolling and resume sync, and verify mobile and version-stack behavior | `tests/file/view-transcript.spec.ts` |
| Read and search saved video transcripts, resize the desktop panel, jump to a segment, verify smooth playback following and interruption, and check mobile and version-stack behavior | `tests/file/view-transcript.spec.ts` |
| Upload an audio file, wait for transcode, and create a comment at a non-zero timestamp | `tests/file/audio-timestamp-comment.spec.ts` |
| Create internal and public comments, verify internal comments are hidden on public share links | `tests/file/internal-comment-and-edit.spec.ts` |
| Author edits comment text, switches to internal, removes timestamp, and updates attachments | `tests/file/internal-comment-and-edit.spec.ts` |
@@ -101,6 +101,14 @@ test('reads, searches and follows a saved transcript in the video player', async
})
if (!nearBottomId) throw new Error('Expected a visible segment in the bottom quarter')
const nearBottom = panel.locator(`[data-segment-id="${nearBottomId}"]`).getByRole('button')
await viewport.evaluate((element) => {
let scrollSteps = 0
const record = () => {
element.setAttribute('data-test-scroll-steps', String(++scrollSteps))
if (scrollSteps === 2) element.removeEventListener('scroll', record)
}
element.addEventListener('scroll', record)
})
await nearBottom.click()
await expect(nearBottom).toHaveAttribute('aria-current', 'true')
await expect
@@ -112,12 +120,29 @@ test('reads, searches and follows a saved transcript in the video player', async
}),
)
.toBeCloseTo(0.5, 1)
await expect(viewport).toHaveAttribute('data-test-scroll-steps', '2')
await expect(sync).toBeHidden()
await page.emulateMedia({ reducedMotion: 'reduce' })
await viewport.evaluate((element) => {
let previousTop = element.scrollTop
const record = () => {
const top = element.scrollTop
if (top < previousTop) {
element.setAttribute('data-test-first-reverse-scroll-top', String(top))
element.removeEventListener('scroll', record)
}
previousTop = top
}
element.addEventListener('scroll', record)
})
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0
})
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first).toBeInViewport()
await expect(viewport).toHaveAttribute('data-test-first-reverse-scroll-top', '0')
await page.emulateMedia({ reducedMotion: 'no-preference' })
await panel.getByRole('button', { name: 'Search transcript' }).click()
const search = panel.getByRole('searchbox', { name: 'Search transcript' })
@@ -155,6 +180,20 @@ test('reads, searches and follows a saved transcript in the video player', async
await expect(sync).toBeVisible()
await expect(last).not.toBeInViewport()
await expect(last).toHaveAttribute('aria-current', 'true')
await viewport.evaluate((element) => {
element.addEventListener(
'scroll',
() => {
element.dispatchEvent(new WheelEvent('wheel', { bubbles: true, deltaY: -120 }))
element.setAttribute('data-test-follow-interrupted', 'true')
},
{ once: true },
)
})
await sync.click()
await expect(viewport).toHaveAttribute('data-test-follow-interrupted', 'true')
await expect(sync).toBeVisible()
await expect(last).not.toBeInViewport()
await sync.click()
await expect(last).toBeInViewport()
await expect(sync).toBeHidden()
@@ -14,6 +14,7 @@ import { useQuery } from '@tanstack/react-query'
import { ChevronDown, ChevronUp, LocateFixed, Search, X } from 'lucide-react'
import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'
import { createTranscriptTimeline } from './transcript-timeline'
import { useTranscriptScroll } from './use-transcript-scroll'
interface TranscriptPanelProps {
id: string
@@ -148,8 +149,8 @@ export const TranscriptPanel = memo(function TranscriptPanel({
const [activeId, setActiveId] = useState<string>()
const toggleSearchRef = useRef<HTMLButtonElement>(null)
const closeRef = useRef<HTMLButtonElement>(null)
const viewportRef = useRef<HTMLDivElement>(null)
const scrollPosition = useRef(0)
const { viewportRef, setViewport, scrollTo, cancelScroll, onScroll, onWheel } =
useTranscriptScroll(() => setFollowing(false))
const transcript = useQuery({
queryKey: [...savedTranscriptLanguagesKey(assetId), language],
@@ -181,31 +182,6 @@ export const TranscriptPanel = memo(function TranscriptPanel({
})
}, [activeAt, mediaControllerRef])
function scrollTo(
target: HTMLElement | null | undefined,
{ bottomInset = 0, followPlayback = false } = {},
) {
const viewport = viewportRef.current
if (!viewport || !target) return
const item = target.getBoundingClientRect()
const { top, bottom } = viewport.getBoundingClientRect()
if (followPlayback) {
const height = bottom - top
const midpoint = item.top + item.height / 2
if (item.top < top || midpoint >= top + height * 0.75) {
viewport.scrollTop += item.top - top - Math.max(0, (height - item.height) / 2)
}
} else {
const visibleBottom = bottom - bottomInset
if (item.top < top || item.height > visibleBottom - top) {
viewport.scrollTop += item.top - top
} else if (item.bottom > visibleBottom) {
viewport.scrollTop += item.bottom - visibleBottom
}
}
scrollPosition.current = viewport.scrollTop
}
useLayoutEffect(() => {
if (following && activeId) {
scrollTo(viewportRef.current?.querySelector(`[data-segment-id="${CSS.escape(activeId)}"]`), {
@@ -259,6 +235,7 @@ export const TranscriptPanel = memo(function TranscriptPanel({
aria-label={m.language()}
value={language}
onChange={(event) => {
cancelScroll()
setPreferredLanguage(event.target.value)
setMatchIndex(0)
setFollowing(true)
@@ -370,15 +347,11 @@ export const TranscriptPanel = memo(function TranscriptPanel({
<ScrollArea
className="h-full [&>div>div]:block!"
viewportProps={{
ref: viewportRef,
ref: setViewport,
tabIndex: 0,
className: '[overflow-anchor:none]',
onScroll: (event) => {
const position = event.currentTarget.scrollTop
if (position === scrollPosition.current) return
scrollPosition.current = position
setFollowing(false)
},
onScroll,
onWheel,
}}
>
<ol className="space-y-0.5 px-2 pt-2 pb-14">
@@ -0,0 +1,135 @@
import { useCallback, useEffect, useRef, type UIEvent, type WheelEvent } from 'react'
const followDurationMs = 220
interface FollowAnimation {
viewport: HTMLDivElement
targetTop: number
frame: number
}
export function useTranscriptScroll(onManualScroll: () => void) {
const viewportRef = useRef<HTMLDivElement>(null)
const scrollPosition = useRef(0)
const animation = useRef<FollowAnimation | null>(null)
const cancelScroll = useCallback(() => {
if (animation.current) cancelAnimationFrame(animation.current.frame)
animation.current = null
}, [])
const setViewport = useCallback(
(viewport: HTMLDivElement | null) => {
if (viewportRef.current === viewport) return
cancelScroll()
viewportRef.current = viewport
scrollPosition.current = viewport?.scrollTop ?? 0
},
[cancelScroll],
)
useEffect(() => cancelScroll, [cancelScroll])
function setScrollTop(viewport: HTMLDivElement, top: number) {
viewport.scrollTop = top
scrollPosition.current = viewport.scrollTop
}
function detectManualScroll(viewport: HTMLDivElement) {
const top = viewport.scrollTop
if (top === scrollPosition.current) return false
// A height or width change may clamp the browser's last scroll position.
const clampedTop = Math.min(
scrollPosition.current,
viewport.scrollHeight - viewport.clientHeight,
)
scrollPosition.current = top
if (top === clampedTop) return false
cancelScroll()
onManualScroll()
return true
}
function animateFollow(viewport: HTMLDivElement, top: number) {
const targetTop = Math.max(0, Math.min(top, viewport.scrollHeight - viewport.clientHeight))
if (animation.current?.viewport === viewport) {
if (detectManualScroll(viewport) || animation.current?.targetTop === targetTop) return
}
cancelScroll()
const startTop = viewport.scrollTop
scrollPosition.current = startTop
if (startTop === targetTop) return
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
setScrollTop(viewport, targetTop)
return
}
const motion = { viewport, targetTop, frame: 0 }
let startedAt: number | undefined
const step = (time: number) => {
if (animation.current !== motion) return
if (viewportRef.current !== viewport) {
animation.current = null
return
}
if (detectManualScroll(viewport)) return
startedAt ??= time
const progress = Math.min(1, (time - startedAt) / followDurationMs)
const eased = 1 - (1 - progress) ** 3
setScrollTop(viewport, startTop + (targetTop - startTop) * eased)
if (progress === 1) animation.current = null
else motion.frame = requestAnimationFrame(step)
}
animation.current = motion
motion.frame = requestAnimationFrame(step)
}
function scrollTo(
target: HTMLElement | null | undefined,
{ bottomInset = 0, followPlayback = false } = {},
) {
if (!followPlayback) cancelScroll()
const viewport = viewportRef.current
if (!viewport || !target) return
const item = target.getBoundingClientRect()
const { top, bottom } = viewport.getBoundingClientRect()
if (followPlayback) {
const height = bottom - top
// Check where the segment will settle so nearby segments don't restart the motion.
const pendingTop =
animation.current?.viewport === viewport ? animation.current.targetTop : viewport.scrollTop
const relativeTop = item.top - top
const settledTop = relativeTop + viewport.scrollTop - pendingTop
if (settledTop < 0 || settledTop + item.height / 2 >= height * 0.75) {
const centerOffset = Math.max(0, (height - item.height) / 2)
animateFollow(viewport, viewport.scrollTop + relativeTop - centerOffset)
}
return
}
const visibleBottom = bottom - bottomInset
if (item.top < top || item.height > visibleBottom - top) {
setScrollTop(viewport, viewport.scrollTop + item.top - top)
} else if (item.bottom > visibleBottom) {
setScrollTop(viewport, viewport.scrollTop + item.bottom - visibleBottom)
}
}
function onScroll(event: UIEvent<HTMLDivElement>) {
detectManualScroll(event.currentTarget)
}
function onWheel(event: WheelEvent<HTMLDivElement>) {
if (event.deltaY !== 0 && !event.ctrlKey && animation.current) {
cancelScroll()
onManualScroll()
}
}
return { viewportRef, setViewport, scrollTo, cancelScroll, onScroll, onWheel }
}