feat(video): show saved transcripts in the player

This commit is contained in:
yiling
2026-12-03 11:19:22 +08:00
parent e806435e49
commit 3952928b88
26 changed files with 1103 additions and 33 deletions
+1
View File
@@ -11,6 +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.
- **video**: Open saved transcripts from the video player, switch languages, search the text, and jump to a timestamp by selecting a segment. Follow along as the video plays.
### Fixed
+1
View File
@@ -121,6 +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, jump to a segment, resume following playback, and verify desktop, 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` |
@@ -0,0 +1,213 @@
import { expect, test } from '../../fixtures'
test.use({ fileOptions: { mediaType: 'video' } })
test('reads, searches and follows a saved transcript in the video player', async ({
file,
prisma,
}) => {
const { page, projectId, fileId } = file
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'en',
model: 'whisper-tiny',
workflowTaskId: 'english-test',
segments: {
create: [
{ position: 0, startMs: 0, endMs: 180, text: 'Signal. signal.' },
...Array.from({ length: 28 }, (_, index) => ({
position: index + 1,
startMs: 300 + index * 12,
endMs: 312 + index * 12,
text: `Intervening segment ${index + 1}`,
})),
{ position: 29, startMs: 720, endMs: 980, text: 'Final signal.' },
],
},
},
})
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'zh',
model: 'whisper-tiny',
workflowTaskId: 'chinese-test',
segments: { create: { position: 0, startMs: 0, endMs: 700, text: '你好。' } },
},
})
await page.goto(`/projects/${projectId}/files/${fileId}`)
const toggle = page.getByRole('button', { name: 'Show transcript' })
const navigator = page.getByRole('link', { name: 'Preview', exact: true })
await expect(navigator).toBeVisible()
await toggle.click()
const panel = page.getByRole('complementary', { name: 'Transcript' })
const first = panel.getByRole('button', { name: /Signal\. signal\./ })
const last = panel.getByRole('button', { name: /Final signal\./ })
const video = page.locator('video').first()
const sync = panel.getByRole('button', { name: 'Sync to playback' })
await expect(navigator).toBeHidden()
await expect(toggle).toHaveAttribute('aria-expanded', 'true')
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first).toContainText('00:00.000 – 00:00.180')
await panel.getByRole('button', { name: 'Search transcript' }).click()
const search = panel.getByRole('searchbox', { name: 'Search transcript' })
await expect(search).toBeFocused()
await search.fill('SIGNAL.')
await expect(panel.getByText('1 / 3')).toBeVisible()
await panel.getByRole('button', { name: 'Next match' }).click()
await expect(panel.getByText('2 / 3')).toBeVisible()
await search.press('Enter')
await expect(panel.getByText('3 / 3')).toBeVisible()
await expect(last).toBeInViewport()
await expect(first).toHaveAttribute('aria-current', 'true')
await last.click()
await expect(last).toHaveAttribute('aria-current', 'true')
await expect
.poll(() => video.evaluate((element) => (element as HTMLVideoElement).currentTime))
.toBeCloseTo(0.72, 1)
await expect(video).toHaveJSProperty('paused', true)
await panel.getByRole('button', { name: 'Next match' }).click()
await expect(panel.getByText('1 / 3')).toBeVisible()
await panel.getByRole('button', { name: 'Previous match' }).click()
await expect(panel.getByText('3 / 3')).toBeVisible()
await search.fill('unmatched')
await expect(panel.getByText('0 / 0')).toBeVisible()
await search.press('Escape')
await expect(search).toBeHidden()
await sync.click()
await expect(sync).toBeHidden()
const viewport = panel.locator('[data-slot=scroll-area-viewport]')
await viewport.hover()
await page.mouse.wheel(0, -2500)
await expect(sync).toBeVisible()
await expect(last).not.toBeInViewport()
await expect(last).toHaveAttribute('aria-current', 'true')
await sync.click()
await expect(last).toBeInViewport()
await expect(sync).toBeHidden()
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0.22
})
await expect(panel.locator('[aria-current=true]')).toHaveCount(0)
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0
})
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first).toBeInViewport()
await video.evaluate(async (element) => {
const media = element as HTMLVideoElement
media.playbackRate = 0.5
await media.play()
})
await expect(last).toBeInViewport()
await expect(sync).toBeHidden()
await expect(video).toHaveJSProperty('ended', true)
await last.press('Enter')
await expect(last).toHaveAttribute('aria-current', 'true')
await expect(video).toHaveJSProperty('paused', true)
await panel.getByRole('combobox', { name: 'Language' }).selectOption('zh')
await expect(panel.getByText('你好。')).toBeVisible()
await expect(last).toHaveCount(0)
await panel.getByRole('button', { name: 'Close transcript' }).click()
await expect(panel).toBeHidden()
await expect(navigator).toBeVisible()
await expect(toggle).toBeFocused()
await page.setViewportSize({ width: 390, height: 844 })
const comments = page.getByTestId('mobile-bottom-sheet')
await expect(comments).toBeVisible()
await toggle.click()
await expect(panel).toBeVisible()
await expect(video).toBeVisible()
await expect(comments).toBeHidden()
await panel.getByRole('button', { name: 'Close transcript' }).click()
await expect(comments).toBeVisible()
})
test('uses the displayed video version and hides the toggle for versions without a transcript', async ({
file,
prisma,
}) => {
const { page, projectId, fileId, rootFolderId } = file
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
const latest = await prisma.asset.findUniqueOrThrow({ where: { id: fileId } })
if (!latest.media) throw new Error('Expected processed video media')
const stack = await prisma.asset.create({
data: {
projectId,
parentId: rootFolderId,
name: latest.name,
type: 'version_stack',
status: 'processed',
fileCount: 2,
},
})
await prisma.asset.update({
where: { id: fileId },
data: { parentId: stack.id, sortIndex: 'a0' },
})
const old = await prisma.asset.create({
data: {
projectId,
parentId: stack.id,
name: 'Earlier video.mp4',
type: 'file',
status: 'processed',
mediaType: latest.mediaType,
storageKeyId: latest.storageKeyId,
media: latest.media,
sizeByte: latest.sizeByte,
sortIndex: 'a1',
},
})
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'en',
model: 'whisper-tiny',
workflowTaskId: 'latest-version-test',
segments: {
create: { position: 0, startMs: 0, endMs: 950, text: 'Latest version text' },
},
},
})
const stackUrl = `/projects/${projectId}/files/${stack.id}`
await page.goto(stackUrl)
const toggle = page.getByRole('button', { name: 'Show transcript' })
await toggle.click()
const panel = page.getByRole('complementary', { name: 'Transcript' })
await expect(panel.getByText('Latest version text')).toBeVisible()
const [languages] = await Promise.all([
page.waitForResponse(`**/api/files/${old.id}/transcripts`),
page.goto(`${stackUrl}?version=${old.id}`),
])
expect(await languages.json()).toEqual({ languages: [] })
await expect(panel).toBeHidden()
await expect(toggle).toBeHidden()
})
+48
View File
@@ -23,6 +23,54 @@ describe('Transcript API', () => {
expect(await response.json()).toEqual(list)
})
it('returns saved languages and segments with asset read access', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const list = vi
.spyOn(transcriptService, 'listSavedLanguages')
.mockResolvedValue({ languages: ['en'] })
const saved = {
id: 'transcript-id',
language: 'en',
segments: [{ id: 'segment-id', startMs: 0, endMs: 1400, text: 'Hello' }],
}
const get = vi.spyOn(transcriptService, 'getSavedTranscript').mockResolvedValue(saved)
const languages = await app.request('/files/file-id/transcripts')
expect(languages.status).toBe(200)
expect(await languages.json()).toEqual({ languages: ['en'] })
expect(list).toHaveBeenCalledWith('file-id')
const transcript = await app.request('/files/file-id/transcripts/en')
expect(transcript.status).toBe(200)
expect(await transcript.json()).toEqual(saved)
expect(get).toHaveBeenCalledWith('file-id', 'en')
expect(permission).toHaveBeenCalledTimes(2)
for (const [request] of permission.mock.calls) {
expect(request).toMatchObject({
type: ResourceType.Asset,
permission: Permission.Read,
id: 'file-id',
})
}
})
it('validates the saved language path and authorizes before reading saved data', async () => {
const permission = vi
.spyOn(authzService, 'hasPermission')
.mockRejectedValue(new HTTPException(403))
const list = vi.spyOn(transcriptService, 'listSavedLanguages')
const get = vi.spyOn(transcriptService, 'getSavedTranscript')
expect((await app.request('/files/file-id/transcripts/auto')).status).toBe(400)
expect((await app.request('/files/file-id/transcripts')).status).toBe(403)
expect((await app.request('/files/file-id/transcripts/en')).status).toBe(403)
expect(list).not.toHaveBeenCalled()
expect(get).not.toHaveBeenCalled()
permission.mockResolvedValue(undefined)
get.mockRejectedValue(new HTTPException(404))
expect((await app.request('/files/file-id/transcripts/zh')).status).toBe(404)
})
it('requires asset edit permission and returns a queued Auto job', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const generate = vi
+26 -1
View File
@@ -2,11 +2,36 @@ import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import type { User } from '@shumai/db'
import { generateTranscriptRequestSchema } from '@shumai/dtos'
import { generateTranscriptRequestSchema, transcriptLanguageCodeSchema } from '@shumai/dtos'
import { Hono } from 'hono'
import { z } from 'zod'
const route = new Hono<{ Variables: { user: User } }>()
.get('/transcription/languages', async (c) => c.json(await transcriptService.listLanguages()))
.get('/files/:fileId/transcripts', async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
})
return c.json(await transcriptService.listSavedLanguages(assetId))
})
.get(
'/files/:fileId/transcripts/:language',
zValidator('param', z.object({ fileId: z.string(), language: transcriptLanguageCodeSchema })),
async (c) => {
const { fileId, language } = c.req.valid('param')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
})
return c.json(await transcriptService.getSavedTranscript(fileId, language))
},
)
.post(
'/files/:fileId/transcripts',
zValidator('json', generateTranscriptRequestSchema),
@@ -55,6 +55,65 @@ describe('TranscriptService', () => {
return result.taskId
}
it('lists only the asset’s saved languages and reads every segment in position order', async () => {
const otherAsset = await prisma.asset.create({
data: { name: 'Another video', type: 'file', status: 'processed', projectId },
})
const save = (id: string, language: string) =>
prisma.assetTranscript.create({
data: {
assetId: id,
language,
model,
workflowTaskId: 'test-task',
segments: {
create: [
{ position: 1, startMs: 2000, endMs: 3000, text: 'Second' },
{ position: 0, startMs: 125, endMs: 1425, text: 'First' },
],
},
},
include: { segments: true },
})
await expect(transcriptService.listSavedLanguages(assetId)).resolves.toEqual({ languages: [] })
const english = await save(assetId, 'en')
await save(assetId, 'zh')
await save(otherAsset.id, 'ko')
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
const savedLanguages = await transcriptService.listSavedLanguages(assetId)
expect(savedLanguages.languages.sort()).toEqual(['en', 'zh'])
const transcript = await transcriptService.getSavedTranscript(assetId, 'en')
expect(transcript).toEqual({
id: english.id,
language: 'en',
segments: [
{
id: english.segments.find(({ position }) => position === 0)?.id,
startMs: 125,
endMs: 1425,
text: 'First',
},
{
id: english.segments.find(({ position }) => position === 1)?.id,
startMs: 2000,
endMs: 3000,
text: 'Second',
},
],
})
await expect(transcriptService.getSavedTranscript(assetId, 'ko')).rejects.toMatchObject({
status: 404,
})
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
await expect(transcriptService.listSavedLanguages(assetId)).resolves.toEqual({ languages: [] })
await expect(transcriptService.getSavedTranscript(assetId, 'en')).rejects.toMatchObject({
status: 404,
})
expect(fetch).not.toHaveBeenCalled()
})
it('validates provider capability, language and asset eligibility before queuing', async () => {
await expect(transcriptService.listLanguages()).resolves.toMatchObject({ model })
await expect(transcriptService.generate(assetId, 'xx')).rejects.toMatchObject({ status: 400 })
@@ -9,6 +9,8 @@ import {
import {
transcriptionErrors,
type GenerateTranscriptResult,
type SavedTranscript,
type SavedTranscriptLanguages,
type TranscriptJobStatus,
} from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
@@ -31,6 +33,30 @@ export class TranscriptService {
}
}
async listSavedLanguages(assetId: string): Promise<SavedTranscriptLanguages> {
const transcripts = await prisma.assetTranscript.findMany({
where: { assetId, asset: { isDeleted: false } },
orderBy: { id: 'desc' },
select: { language: true },
})
return { languages: transcripts.map(({ language }) => language) }
}
async getSavedTranscript(assetId: string, language: string): Promise<SavedTranscript> {
const transcript = await prisma.assetTranscript.findUnique({
where: { assetIdLanguage: { assetId, language }, asset: { isDeleted: false } },
select: {
...transcriptSelection,
segments: {
orderBy: { position: 'asc' },
select: { id: true, startMs: true, endMs: true, text: true },
},
},
})
if (!transcript) throw new HTTPException(404, { message: 'Transcript not found' })
return transcript
}
async generate(assetId: string, language: string | null): Promise<GenerateTranscriptResult> {
this.requireEnabled()
const saved = await this.findSaved(prisma, assetId, language)
+15
View File
@@ -2,6 +2,21 @@ import { z } from 'zod'
export const transcriptLanguageCodeSchema = z.string().regex(/^[a-z]{2,3}$/)
export type SavedTranscriptLanguages = { languages: string[] }
export type TranscriptSegment = {
id: string
startMs: number
endMs: number
text: string
}
export type SavedTranscript = {
id: string
language: string
segments: TranscriptSegment[]
}
export const generateTranscriptRequestSchema = z.object({
language: transcriptLanguageCodeSchema.optional(),
})
@@ -1,9 +1,10 @@
import { useRef, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { TranscriptJobStatus } from '@shumai/dtos'
import { toast } from 'sonner'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { savedTranscriptLanguagesKey } from '@/ui/hooks/use-video-transcript'
import { Button } from '@/ui/components/ui/button'
import {
Combobox,
@@ -79,6 +80,12 @@ export function GenerateTranscriptsDialog({
refetchInterval: (query) => (isActive(query.state.data) ? 2_000 : false),
})
useEffect(() => {
if (job.data?.status === 'completed') {
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(assetId) })
}
}, [assetId, job.data, queryClient])
const generate = useMutation({
mutationFn: async () => {
const response = await client.api.files[':fileId'].transcripts.$post({
@@ -90,6 +97,9 @@ export function GenerateTranscriptsDialog({
},
onSuccess: (result) => {
if (result.kind === 'existing' || result.kind === 'no_speech') {
if (result.kind === 'existing') {
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(assetId) })
}
toast.info(
result.kind === 'existing' ? m.transcript_already_exists() : m.transcript_no_speech(),
)
@@ -18,6 +18,7 @@ export function FileViewer({
shareId,
allowDownload,
autoPlay,
transcriptToggle,
children,
}: OuterFileViewerProps) {
const viewerDef = getViewerForFile(file)
@@ -37,6 +38,7 @@ export function FileViewer({
shareId={shareId}
allowDownload={allowDownload}
autoPlay={autoPlay}
transcriptToggle={transcriptToggle}
>
{children}
</ViewerComponent>
@@ -56,6 +56,12 @@ vi.mock('@/ui/api/client', () => ({
},
files: {
':fileId': {
transcripts: {
$get: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ languages: [] }),
}),
},
comments: {
$get: vi.fn().mockResolvedValue({
ok: true,
@@ -21,6 +21,7 @@ import {
} from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { useVideoTranscript } from '@/ui/hooks/use-video-transcript'
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
import { m } from '@/ui/paraglide/messages.js'
import { useMemberStore } from '@/ui/stores/members'
@@ -32,6 +33,7 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'
import type { MediaController } from '../viewers/types'
import { MobileFileBottomSheet } from './mobile-file-bottom-sheet'
import { MobileFileHeader } from './mobile-file-header'
import { TranscriptPanel } from './transcript-panel'
export interface MobileFileDetailProps {
projectId: string
@@ -100,6 +102,7 @@ export function MobileFileDetail({
const { canEdit } = usePermissions(projectId)
const { members } = useMemberStore()
const mediaControllerRef = useRef<MediaController | null>(null)
const transcript = useVideoTranscript(!isPublic && file.id === activeFileId ? file : undefined)
const [sheetHeightPercent, setSheetHeightPercent] = useState(50)
const [annotations, setAnnotations] = useState<Annotation[]>([])
@@ -268,28 +271,39 @@ export function MobileFileDetail({
startTime={startTime}
shareId={shareId}
allowDownload={allowDownload}
transcriptToggle={transcript?.toggle}
/>
</div>
{/* Part 3: Freely Draggable Bottom Sheet */}
<MobileFileBottomSheet
teamId={teamId}
projectId={projectId}
file={file}
onSaveField={onSaveField}
members={members}
onCommentSelect={handleCommentSelect}
hideAnnotationControl={file.proxyType === 'audio'}
readOnly={isPublic || !canEdit}
publicFields={publicFields}
isPublic={isPublic}
shareId={shareId}
currentTime={currentTime}
onTyping={() => mediaControllerRef.current?.pause()}
selectedCommentId={selectedCommentId}
heightPercent={sheetHeightPercent}
onHeightPercentChange={setSheetHeightPercent}
/>
{transcript?.panel && (
<TranscriptPanel
key={transcript.panel.assetId}
{...transcript.panel}
mediaControllerRef={mediaControllerRef}
className="z-20 h-[46dvh] w-full rounded-t-2xl border-t border-border"
/>
)}
<div className={transcript?.panel ? 'hidden' : 'contents'}>
<MobileFileBottomSheet
teamId={teamId}
projectId={projectId}
file={file}
onSaveField={onSaveField}
members={members}
onCommentSelect={handleCommentSelect}
hideAnnotationControl={file.proxyType === 'audio'}
readOnly={isPublic || !canEdit}
publicFields={publicFields}
isPublic={isPublic}
shareId={shareId}
currentTime={currentTime}
onTyping={() => mediaControllerRef.current?.pause()}
selectedCommentId={selectedCommentId}
heightPercent={sheetHeightPercent}
onHeightPercentChange={setSheetHeightPercent}
/>
</div>
{/* Dialogs */}
{!isPublic && isLinkedTasksOpen && (
@@ -0,0 +1,411 @@
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { NativeSelect, NativeSelectOption } from '@/ui/components/ui/native-select'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import type { MediaController } from '@/ui/components/viewers/types'
import { formatTime } from '@/ui/components/viewers/video/utils'
import { savedTranscriptLanguagesKey } from '@/ui/hooks/use-video-transcript'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { getLocale } from '@/ui/paraglide/runtime.js'
import type { TranscriptSegment } from '@shumai/dtos'
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'
interface TranscriptPanelProps {
id: string
assetId: string
languages: string[]
mediaControllerRef: RefObject<MediaController | null>
onClose: () => void
className?: string
}
interface TextMatch {
index: number
start: number
end: number
}
const noSegments: TranscriptSegment[] = []
function findMatches(segments: TranscriptSegment[], search: string) {
const bySegment = new Map<string, TextMatch[]>()
let total = 0
const query = search.trim()
if (!query) return { bySegment, total }
const literal = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const expression = new RegExp(literal, 'giu')
for (const segment of segments) {
const matches = Array.from(segment.text.matchAll(expression), ({ index, 0: text }) => ({
index: total++,
start: index,
end: index + text.length,
}))
if (matches.length) bySegment.set(segment.id, matches)
}
return { bySegment, total }
}
function formatTranscriptTime(ms: number) {
return `${formatTime(ms / 1000)}.${String(ms % 1000).padStart(3, '0')}`
}
const SegmentRow = memo(function SegmentRow({
segment,
active,
matches,
selectedMatch,
mediaControllerRef,
}: {
segment: TranscriptSegment
active: boolean
matches?: TextMatch[]
selectedMatch?: number
mediaControllerRef: RefObject<MediaController | null>
}) {
let textOffset = 0
return (
<li data-segment-id={segment.id}>
<button
type="button"
aria-current={active ? 'true' : undefined}
className={cn(
'block w-full cursor-pointer select-text rounded-md px-3 py-2 text-start hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:outline-none',
active && 'bg-primary/10 font-medium text-foreground',
)}
onClick={(event) => {
const selection = window.getSelection()
if (
event.detail > 0 &&
selection?.anchorNode &&
!selection.isCollapsed &&
event.currentTarget.contains(selection.anchorNode)
) {
return
}
mediaControllerRef.current?.seekTo(segment.startMs / 1000)
}}
>
<span className="mb-1 block font-mono text-xs tabular-nums text-muted-foreground" dir="ltr">
{formatTranscriptTime(segment.startMs)} – {formatTranscriptTime(segment.endMs)}
</span>
<span
className="block text-sm leading-relaxed whitespace-pre-wrap wrap-anywhere"
dir="auto"
>
{matches?.map((match) => {
const preceding = segment.text.slice(textOffset, match.start)
textOffset = match.end
const selected = selectedMatch === match.index
return (
<span key={match.start}>
{preceding}
<mark
data-current-match={selected ? '' : undefined}
className={cn(
'rounded-sm bg-primary/15 text-foreground',
selected && 'bg-primary text-primary-foreground',
)}
>
{segment.text.slice(match.start, match.end)}
</mark>
</span>
)
})}
{segment.text.slice(textOffset)}
</span>
</button>
</li>
)
})
export const TranscriptPanel = memo(function TranscriptPanel({
id,
assetId,
languages,
mediaControllerRef,
onClose,
className,
}: TranscriptPanelProps) {
const locale = getLocale()
const options = useMemo(() => {
const names = new Intl.DisplayNames(locale, { type: 'language' })
return languages
.map((code) => ({ code, name: names.of(code) ?? code }))
.sort((a, b) => a.name.localeCompare(b.name, locale))
}, [languages, locale])
const [preferredLanguage, setPreferredLanguage] = useState<string>(locale)
const language = options.find(({ code }) => code === preferredLanguage)?.code ?? options[0].code
const [searchOpen, setSearchOpen] = useState(false)
const [search, setSearch] = useState('')
const [matchIndex, setMatchIndex] = useState(0)
const [following, setFollowing] = useState(true)
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 transcript = useQuery({
queryKey: [...savedTranscriptLanguagesKey(assetId), language],
queryFn: async ({ signal }) => {
const response = await client.api.files[':fileId'].transcripts[':language'].$get(
{ param: { fileId: assetId, language } },
{ init: { signal } },
)
if (!response.ok) throw new Error(m.transcript_load_failed())
return await response.json()
},
retry: false,
})
const segments = transcript.data?.segments ?? noSegments
const activeAt = useMemo(() => createTranscriptTimeline(segments), [segments])
const matches = useMemo(() => findMatches(segments, search), [segments, search])
const selectedMatch = matches.total ? matchIndex % matches.total : undefined
useEffect(() => closeRef.current?.focus({ preventScroll: true }), [])
useEffect(() => {
let active: string | undefined
setActiveId(undefined)
return mediaControllerRef.current?.subscribeToPlaybackTime?.((second) => {
const segmentId = activeAt(second * 1000)
if (segmentId === active) return
active = segmentId
setActiveId(segmentId)
})
}, [activeAt, mediaControllerRef])
function scrollTo(target: HTMLElement | null | undefined, bottomInset = 0) {
const viewport = viewportRef.current
if (!viewport || !target) return
const item = target.getBoundingClientRect()
const { top, bottom } = viewport.getBoundingClientRect()
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)}"]`))
}
}, [activeId, following])
useLayoutEffect(() => {
if (selectedMatch === undefined) return
setFollowing(false)
scrollTo(viewportRef.current?.querySelector('[data-current-match]'), 48)
}, [matches, selectedMatch])
function toggleSearch() {
if (searchOpen) {
setSearch('')
setMatchIndex(0)
toggleSearchRef.current?.focus({ preventScroll: true })
}
setSearchOpen(!searchOpen)
}
function moveMatch(step: number) {
if (selectedMatch === undefined) return
setFollowing(false)
setMatchIndex((selectedMatch + step + matches.total) % matches.total)
if (matches.total === 1) {
scrollTo(viewportRef.current?.querySelector('[data-current-match]'), 48)
}
}
return (
<aside
id={id}
aria-label={m.transcript_title()}
onKeyDown={(event) => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') event.stopPropagation()
}}
className={cn(
'flex min-h-0 shrink-0 flex-col overflow-hidden bg-background text-foreground',
className,
)}
>
<div className="shrink-0 space-y-2 border-b border-border p-2">
<div className="flex items-center justify-between gap-2">
<div className="min-w-0 [&>[data-slot=native-select-wrapper]]:max-w-full">
<NativeSelect
size="sm"
className="max-w-40 truncate"
aria-label={m.language()}
value={language}
onChange={(event) => {
setPreferredLanguage(event.target.value)
setMatchIndex(0)
setFollowing(true)
}}
>
{options.map(({ code, name }) => (
<NativeSelectOption key={code} value={code}>
{name}
</NativeSelectOption>
))}
</NativeSelect>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
ref={toggleSearchRef}
size="icon-sm"
variant="ghost"
aria-expanded={searchOpen}
aria-label={m.transcript_search()}
title={m.transcript_search()}
onClick={toggleSearch}
>
<Search />
</Button>
<Button
ref={closeRef}
size="icon-sm"
variant="ghost"
aria-label={m.transcript_close()}
title={m.transcript_close()}
onClick={onClose}
>
<X />
</Button>
</div>
</div>
{searchOpen && (
<div className="flex items-center gap-1">
<Input
autoFocus
type="search"
className="h-8 min-w-0 px-2"
aria-label={m.transcript_search()}
placeholder={m.transcript_search()}
value={search}
onChange={(event) => {
setSearch(event.target.value)
setMatchIndex(0)
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === 'Escape') {
event.preventDefault()
event.stopPropagation()
if (event.key === 'Escape') toggleSearch()
else moveMatch(event.shiftKey ? -1 : 1)
}
}}
/>
{search.trim() && (
<output className="shrink-0 px-1 text-xs tabular-nums text-muted-foreground">
{m.transcript_search_count({
current: selectedMatch === undefined ? 0 : selectedMatch + 1,
total: matches.total,
})}
</output>
)}
<Button
size="icon-sm"
variant="ghost"
className="shrink-0"
aria-label={m.transcript_previous_match()}
title={m.transcript_previous_match()}
disabled={!matches.total}
onClick={() => moveMatch(-1)}
>
<ChevronUp />
</Button>
<Button
size="icon-sm"
variant="ghost"
className="shrink-0"
aria-label={m.transcript_next_match()}
title={m.transcript_next_match()}
disabled={!matches.total}
onClick={() => moveMatch(1)}
>
<ChevronDown />
</Button>
</div>
)}
</div>
{transcript.isPending && (
<p role="status" className="p-3 text-sm text-muted-foreground">
{m.loading()}
</p>
)}
{transcript.isError && (
<div className="space-y-2 p-3">
<p role="alert" className="text-sm text-destructive">
{m.transcript_load_failed()}
</p>
<Button size="sm" variant="outline" onClick={() => void transcript.refetch()}>
{m.retry()}
</Button>
</div>
)}
{transcript.data && (
<div className="relative min-h-0 flex-1">
<ScrollArea
className="h-full [&>div>div]:block!"
viewportProps={{
ref: viewportRef,
tabIndex: 0,
className: '[overflow-anchor:none]',
onScroll: (event) => {
const position = event.currentTarget.scrollTop
if (position === scrollPosition.current) return
scrollPosition.current = position
setFollowing(false)
},
}}
>
<ol className="space-y-0.5 px-2 pt-2 pb-14">
{segments.map((segment) => {
const segmentMatches = matches.bySegment.get(segment.id)
return (
<SegmentRow
key={segment.id}
segment={segment}
active={segment.id === activeId}
matches={segmentMatches}
selectedMatch={
segmentMatches?.some(({ index }) => index === selectedMatch)
? selectedMatch
: undefined
}
mediaControllerRef={mediaControllerRef}
/>
)
})}
</ol>
</ScrollArea>
{!following && (
<div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center px-2">
<Button
size="sm"
variant="outline"
className="pointer-events-auto bg-background shadow-md"
onClick={() => {
viewportRef.current?.focus({ preventScroll: true })
setFollowing(true)
}}
>
<LocateFixed />
{m.transcript_sync_to_playback()}
</Button>
</div>
)}
</div>
)}
</aside>
)
})
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest'
import { createTranscriptTimeline } from './transcript-timeline'
describe('createTranscriptTimeline', () => {
it('uses inclusive starts and exclusive ends for adjacent segments and gaps', () => {
const at = createTranscriptTimeline([
{ id: 'later', startMs: 2000, endMs: 2500, text: '' },
{ id: 'first', startMs: 300, endMs: 1000, text: '' },
{ id: 'second', startMs: 1000, endMs: 1700, text: '' },
])
expect(at(0)).toBeUndefined()
expect(at(300)).toBe('first')
expect(at(1000)).toBe('second')
expect(at(1700)).toBeUndefined()
expect(at(2000)).toBe('later')
expect(at(2500)).toBeUndefined()
})
it('finds the latest active start when a shorter segment overlaps a longer one', () => {
const at = createTranscriptTimeline([
{ id: 'long', startMs: 0, endMs: 4000, text: '' },
{ id: 'short', startMs: 1050, endMs: 1120, text: '' },
])
expect(at(1049.5)).toBe('long')
expect(at(1050)).toBe('short')
expect(at(1120)).toBe('long')
expect(at(4000)).toBeUndefined()
expect(createTranscriptTimeline([])(0)).toBeUndefined()
})
})
@@ -0,0 +1,28 @@
import type { TranscriptSegment } from '@shumai/dtos'
export function createTranscriptTimeline(segments: TranscriptSegment[]) {
const ordered = [...segments].sort((a, b) => a.startMs - b.startMs)
let latestEndMs = 0
const timeline = ordered.map((segment) => {
latestEndMs = Math.max(latestEndMs, segment.endMs)
return { segment, latestEndMs }
})
return (timeMs: number): string | undefined => {
let first = 0
let last = timeline.length
while (first < last) {
const middle = Math.floor((first + last) / 2)
if (timeline[middle].segment.startMs <= timeMs) first = middle + 1
else last = middle
}
// Prefer the most recent start when segments overlap. The running maximum bounds
// the backward scan even in long gaps or after the last segment.
for (let index = first - 1; index >= 0; index--) {
const { segment, latestEndMs } = timeline[index]
if (latestEndMs <= timeMs) break
if (segment.endMs > timeMs) return segment.id
}
}
}
+9 -2
View File
@@ -6,8 +6,11 @@ import { cn } from '@/ui/lib/utils'
function ScrollArea({
className,
children,
viewportProps,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
viewportProps?: React.ComponentProps<typeof ScrollAreaPrimitive.Viewport>
}) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
@@ -15,8 +18,12 @@ function ScrollArea({
{...props}
>
<ScrollAreaPrimitive.Viewport
{...viewportProps}
data-slot="scroll-area-viewport"
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
className={cn(
'size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1',
viewportProps?.className,
)}
>
{children}
</ScrollAreaPrimitive.Viewport>
@@ -9,6 +9,14 @@ export interface MediaController {
seekTo: (second: number) => void
getCurrentTime?: () => number
getDuration?: () => number
subscribeToPlaybackTime?: (listener: (second: number) => void) => (() => void) | undefined
}
export interface TranscriptToggle {
panelId: string
open: boolean
buttonRef: React.RefObject<HTMLButtonElement | null>
onToggle: () => void
}
export interface FileViewerProps {
@@ -23,6 +31,7 @@ export interface FileViewerProps {
/** When false, the viewer hides its download affordances. Defaults to true. */
allowDownload?: boolean
autoPlay?: boolean
transcriptToggle?: TranscriptToggle
children?: React.ReactNode
}
@@ -25,6 +25,7 @@ import {
import ProgressBar from './progress-bar'
import { formatTime, formatTimecode } from './utils'
import type { ControlBarProps, DisplayTranscode } from './video-control-bar'
import { TranscriptToggleButton } from './transcript-toggle-button'
export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
state,
@@ -47,6 +48,7 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
onMouseEnter,
onMouseLeave,
isLoading: propIsLoading,
transcriptToggle,
}) => {
const isLoading = propIsLoading ?? state.isLoading ?? false
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
@@ -188,6 +190,9 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
{/* Right Side: Settings (Quality + Speed) & Fullscreen */}
<div className="flex items-center gap-1 shrink-0">
{transcriptToggle && !isAudio && !state.isFullScreen && (
<TranscriptToggleButton {...transcriptToggle} className="p-1" />
)}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button
@@ -0,0 +1,31 @@
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { ListVideo } from 'lucide-react'
import type { TranscriptToggle } from '../types'
export function TranscriptToggleButton({
panelId,
open,
buttonRef,
onToggle,
className,
}: TranscriptToggle & { className?: string }) {
return (
<button
ref={buttonRef}
type="button"
aria-label={m.transcript_view()}
aria-expanded={open}
aria-controls={open ? panelId : undefined}
title={m.transcript_view()}
className={cn(
'shrink-0 rounded transition-colors hover:text-primary focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
open && 'text-primary',
className,
)}
onClick={onToggle}
>
<ListVideo className="size-5" aria-hidden="true" />
</button>
)
}
@@ -30,6 +30,8 @@ import { Slider } from '../../ui/slider'
import ProgressBar, { type SeekbarScrubHandlers } from './progress-bar'
import { formatTime, formatTimecode } from './utils'
import { getVideoResolutionLabel } from '@/ui/lib/media'
import type { TranscriptToggle } from '../types'
import { TranscriptToggleButton } from './transcript-toggle-button'
export interface PlayerState {
isPlaying: boolean
@@ -96,6 +98,7 @@ export interface ControlBarProps {
/** When false, hides the download affordance. Defaults to true. */
allowDownload?: boolean
isLoading?: boolean
transcriptToggle?: TranscriptToggle
}
export const VideoControlBar: React.FC<ControlBarProps> = ({
@@ -125,6 +128,7 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
onMouseLeave,
allowDownload = true,
isLoading: propIsLoading,
transcriptToggle,
}) => {
const isLoading = propIsLoading ?? state.isLoading ?? false
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
@@ -423,6 +427,10 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
</DropdownMenu>
)}
{transcriptToggle && !isAudio && !state.isFullScreen && (
<TranscriptToggleButton {...transcriptToggle} />
)}
{/* Download */}
{allowDownload &&
(isAudio ? (
@@ -32,11 +32,14 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
children,
allowDownload,
autoPlay,
transcriptToggle,
},
ref,
) => {
const hlsRef = useRef<Hls | null>(null)
const videoRef = useRef<HTMLVideoElement | null>(null)
const refreshPlaybackTime = useRef<() => void>(undefined)
const scrubTime = useRef<number | null>(null)
const [activeAutoResolution, setActiveAutoResolution] = useState<string | undefined>(undefined)
const [isHlsManualSupported, setIsHlsManualSupported] = useState<boolean>(true)
const isHls = Boolean(data.media?.isHls && data.media.hls?.url)
@@ -139,6 +142,20 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
getDuration: () => {
return (videoRef.current ? videoRef.current.duration : 0) ?? 0
},
subscribeToPlaybackTime: (listener) => {
const video = videoRef.current
if (!video) return
const update = () => listener(scrubTime.current ?? video.currentTime)
const events = ['timeupdate', 'seeking', 'seeked', 'loadedmetadata', 'ended']
refreshPlaybackTime.current = update
for (const event of events) video.addEventListener(event, update)
update()
return () => {
if (refreshPlaybackTime.current === update) refreshPlaybackTime.current = undefined
for (const event of events) video.removeEventListener(event, update)
}
},
}))
const isOverControlsRef = useRef(false)
@@ -303,6 +320,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const displayFrame = scrubFrame ?? currentFrame
const isScrubbing = scrubFrame !== null
const currentTime = displayFrame / frameRate
scrubTime.current = isScrubbing ? currentTime : null
const duration = totalFrames / frameRate
const progress = duration > 0 ? (currentTime / duration) * 100 : 0
@@ -323,6 +341,10 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
}
}, [currentFrame, frameRate, onTimeUpdate])
useEffect(() => {
refreshPlaybackTime.current?.()
}, [currentFrame, scrubFrame, frameRate])
// Initialize player (Hls.js or native HTML5 video)
useEffect(() => {
const video = videoRef.current
@@ -1159,6 +1181,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload}
isLoading={isLoading}
transcriptToggle={transcriptToggle}
/>
) : (
<VideoControlBar
@@ -1187,6 +1210,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload}
isLoading={isLoading}
transcriptToggle={transcriptToggle}
/>
)}
</div>
@@ -0,0 +1,52 @@
import { client } from '@/ui/api/client'
import type { AssetInfo } from '@shumai/dtos'
import { skipToken, useQuery } from '@tanstack/react-query'
import { useCallback, useId, useRef, useState } from 'react'
export const savedTranscriptLanguagesKey = (assetId?: string) =>
['files', assetId, 'transcripts'] as const
export function useVideoTranscript(file?: Pick<AssetInfo, 'id' | 'proxyType' | 'versionStack'>) {
const assetId =
file?.proxyType === 'video'
? (file.versionStack?.versions.find(({ current }) => current)?.id ?? file.id)
: undefined
const panelId = useId()
const buttonRef = useRef<HTMLButtonElement>(null)
const [selection, setSelection] = useState({ assetId, open: false })
if (selection.assetId !== assetId) {
setSelection({ assetId, open: false })
}
const { data } = useQuery({
queryKey: savedTranscriptLanguagesKey(assetId),
queryFn: assetId
? async ({ signal }) => {
const response = await client.api.files[':fileId'].transcripts.$get(
{ param: { fileId: assetId } },
{ init: { signal } },
)
if (!response.ok) throw new Error('Could not fetch saved transcript languages')
return await response.json()
}
: skipToken,
})
const close = useCallback(() => {
setSelection({ assetId, open: false })
buttonRef.current?.focus({ preventScroll: true })
}, [assetId])
if (!assetId || !data?.languages.length) return undefined
const open = selection.assetId === assetId && selection.open
return {
panel: open ? { id: panelId, assetId, languages: data.languages, onClose: close } : undefined,
toggle: {
panelId,
open,
buttonRef,
onToggle: open ? close : () => setSelection({ assetId, open: true }),
},
}
}
+10 -1
View File
@@ -1824,5 +1824,14 @@
"transcript_already_exists": "A transcript already exists for this language.",
"transcript_languages_unavailable": "Could not load transcription languages.",
"transcript_no_languages_found": "No matching languages.",
"transcript_status_unavailable": "Could not check transcript status."
"transcript_status_unavailable": "Could not check transcript status.",
"transcript_title": "Transcript",
"transcript_view": "Show transcript",
"transcript_close": "Close transcript",
"transcript_search": "Search transcript",
"transcript_search_count": "{current} / {total}",
"transcript_previous_match": "Previous match",
"transcript_next_match": "Next match",
"transcript_sync_to_playback": "Sync to playback",
"transcript_load_failed": "Could not load this transcript."
}
+10 -1
View File
@@ -1754,5 +1754,14 @@
"transcript_already_exists": "이 언어의 전사가 이미 있습니다.",
"transcript_languages_unavailable": "전사 언어를 불러올 수 없습니다.",
"transcript_no_languages_found": "일치하는 언어가 없습니다.",
"transcript_status_unavailable": "전사 상태를 확인할 수 없습니다."
"transcript_status_unavailable": "전사 상태를 확인할 수 없습니다.",
"transcript_title": "전사",
"transcript_view": "전사 보기",
"transcript_close": "전사 닫기",
"transcript_search": "전사 검색",
"transcript_search_count": "{current} / {total}",
"transcript_previous_match": "이전 검색 결과",
"transcript_next_match": "다음 검색 결과",
"transcript_sync_to_playback": "재생 위치에 맞추기",
"transcript_load_failed": "이 전사를 불러올 수 없습니다."
}
+10 -1
View File
@@ -1824,5 +1824,14 @@
"transcript_already_exists": "此语言的转录已存在。",
"transcript_languages_unavailable": "无法加载转录语言。",
"transcript_no_languages_found": "没有匹配的语言。",
"transcript_status_unavailable": "无法获取转录状态。"
"transcript_status_unavailable": "无法获取转录状态。",
"transcript_title": "转录",
"transcript_view": "显示转录",
"transcript_close": "关闭转录",
"transcript_search": "搜索转录",
"transcript_search_count": "{current} / {total}",
"transcript_previous_match": "上一个结果",
"transcript_next_match": "下一个结果",
"transcript_sync_to_playback": "同步到播放位置",
"transcript_load_failed": "无法加载此转录。"
}
@@ -7,6 +7,7 @@ import { FileViewer } from '@/ui/components/file-viewer'
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
import { MobileFileDetail } from '@/ui/components/file-viewer/mobile-file-detail'
import { TranscriptPanel } from '@/ui/components/file-viewer/transcript-panel'
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { ShareLinkCreatedDialog } from '@/ui/components/share-link-created-dialog'
@@ -14,6 +15,7 @@ import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { useIsMobile } from '@/ui/hooks/use-mobile'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { useShareLinkActions } from '@/ui/hooks/use-share-link-actions'
import { useVideoTranscript } from '@/ui/hooks/use-video-transcript'
import { m } from '@/ui/paraglide/messages.js'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import { useChatbotStore } from '@/ui/stores/chatbot'
@@ -211,6 +213,9 @@ function FileViewPage() {
const isError = isStackError || (!!versionAssetId && isVersionError)
const isFetching = isStackFetching || (!!versionAssetId && isVersionFetching)
const fileData = versionData || stackData
const transcript = useVideoTranscript(
!isMobile && !isCompareMode && fileData?.id === activeFileId ? fileData : undefined,
)
const versionsDataList = versionAssetId ? versionsList : stackData?.versionStack?.versions
const parentFolderId = fileData?.ancestorFolders?.[0]?.id ?? projectInfo?.rootFolder ?? ''
@@ -851,15 +856,26 @@ function FileViewPage() {
onSeek={handleSeek}
annotations={annotations}
startTime={startTime}
transcriptToggle={transcript?.toggle}
>
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={parentFolderId}
initialFiles={carouselState.files}
initialNextCursor={carouselState.nextCursor}
isLoading={isCarouselLoading}
/>
{transcript?.panel && (
<TranscriptPanel
key={transcript.panel.assetId}
{...transcript.panel}
mediaControllerRef={mediaControllerRef}
className="w-[clamp(16rem,26vw,22rem)] max-w-[48%] border-r border-border"
/>
)}
<div className={transcript?.panel ? 'hidden' : 'contents'}>
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={parentFolderId}
initialFiles={carouselState.files}
initialNextCursor={carouselState.nextCursor}
isLoading={isCarouselLoading}
/>
</div>
</FileViewer>
)}
</div>