Files
shumai/packages/webui/components/viewers/video/progress-bar.tsx
T
90f076f3ba fix(webui): stop duplicate seeks on the video progress bar (#532)
* fix(webui): avoid duplicate seek on progress bar tap

A single tap/click fired onSeek twice: once on pointer-down and again
on pointer-up at the same position. The second seek restarted the
native seek right as data began arriving, which stalled playback for
several seconds on slow connections. Track pointer movement and only
re-seek on release after an actual drag.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(webui): suppress synthetic mouse seek after touch on progress bar

Mobile browsers dispatch synthetic mousedown/mouseup after touch
interactions. The mouse path re-queued a seek to the same position,
which restarted the native seek ~500ms later and stalled playback on
slow connections. Ignore mouse-down within 700ms of a touch end.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(webui): reset progress bar drag state on touchcancel

OS gestures (app switch, palm rejection, notification pull) cancel
touches without a touchend. The drag/hover state then stayed stuck
until the next interaction. Reset state without seeking.

Co-Authored-By: Claude <noreply@anthropic.com>

* perf(webui): load seek preview video metadata only

The hidden 180p preview video used preload="auto", downloading the
whole file alongside main playback. On constrained connections it
competed for bandwidth exactly when a seek needed data, lengthening
rebuffering. Metadata is enough until the user actually scrubs.

Co-Authored-By: Claude <noreply@anthropic.com>

* test(webui): cover progress bar seeking on click, tap and touch cancel

Check that a plain click or tap seeks once, a real drag seeks again on release, synthetic mouse events right after a touch are ignored, a cancelled touch resets without seeking, and the hidden preview video preloads metadata only.

Co-Authored-By: Claude <noreply@anthropic.com>

* docs(changelog): note the progress bar seek fixes

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: phj1081 <5908832+phj1081@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-27 10:12:53 +08:00

389 lines
13 KiB
TypeScript

import { cn } from '@/ui/lib/utils'
import type { MediaMetadata } from '@shumai/dtos'
import React, { useCallback, useEffect, useRef, useState } from 'react'
const formatTime = (seconds: number): string => {
if (isNaN(seconds)) return '00:00'
const date = new Date(seconds * 1000)
const hh = date.getUTCHours()
const mm = date.getUTCMinutes()
const ss = date.getUTCSeconds().toString().padStart(2, '0')
if (hh) {
return `${hh}:${mm.toString().padStart(2, '0')}:${ss}`
}
return `${mm}:${ss}`
}
interface ProgressBarProps {
totalFrames: number
currentFrame: number
fps: number
previewUrl?: string
onSeek: (frame: number) => void
buffered?: number
metadata?: MediaMetadata
}
const ProgressBar: React.FC<ProgressBarProps> = ({
totalFrames,
currentFrame,
fps,
previewUrl,
onSeek,
buffered = 0,
metadata,
}) => {
const containerRef = useRef<HTMLDivElement>(null)
const previewVideoRef = useRef<HTMLVideoElement>(null)
const [hoverPosition, setHoverPosition] = useState<number | null>(null) // 0 to 1
const [isHovering, setIsHovering] = useState(false)
const [isDragging, setIsDragging] = useState(false)
// Tracks whether the pointer actually moved during a drag. A plain tap/click
// already seeks on pointer-down; re-seeking to the same frame on release
// restarts the native seek and stalls playback on slow connections.
const didDragMoveRef = useRef(false)
const lastSeekPosRef = useRef<number | null>(null)
// After a touch interaction, mobile browsers fire synthetic mouse events
// (mousedown/mouseup) for the same tap. Suppress them so one tap does not
// trigger a second seek through the mouse path.
const lastTouchEndAtRef = useRef(0)
const onSeekRef = useRef(onSeek)
useEffect(() => {
onSeekRef.current = onSeek
}, [onSeek])
// Load the preview video in background
useEffect(() => {
if (previewVideoRef.current && previewUrl) {
previewVideoRef.current.load()
}
}, [previewUrl])
const getPercentageFromEvent = useCallback((clientX: number) => {
if (!containerRef.current) return 0
const rect = containerRef.current.getBoundingClientRect()
const x = Math.max(0, Math.min(clientX - rect.left, rect.width))
return x / rect.width
}, [])
const handleMouseMove = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (isDragging) return
if (!containerRef.current) return
const rect = containerRef.current.getBoundingClientRect()
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width))
const percentage = x / rect.width
setHoverPosition(percentage)
setIsHovering(true)
if (previewVideoRef.current && totalFrames) {
const targetFrame = percentage * totalFrames
const frameDuration = 1 / fps
const seekTime = targetFrame * frameDuration + frameDuration / 2
const vid = previewVideoRef.current
if (Number.isFinite(seekTime)) {
vid.currentTime = seekTime
}
}
},
[totalFrames, fps, isDragging],
)
const handleMouseLeave = () => {
if (!isDragging) {
setIsHovering(false)
setHoverPosition(null)
}
}
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
if (e.button !== 0) return
if (Date.now() - lastTouchEndAtRef.current < 700) return
e.preventDefault()
setIsDragging(true)
didDragMoveRef.current = false
lastSeekPosRef.current = e.clientX
const percentage = getPercentageFromEvent(e.clientX)
setHoverPosition(percentage)
setIsHovering(true)
onSeekRef.current(percentage * totalFrames)
}
const handleTouchStart = (e: React.TouchEvent<HTMLDivElement>) => {
setIsDragging(true)
didDragMoveRef.current = false
lastSeekPosRef.current = e.touches[0].clientX
const percentage = getPercentageFromEvent(e.touches[0].clientX)
setHoverPosition(percentage)
setIsHovering(true)
onSeekRef.current(percentage * totalFrames)
}
useEffect(() => {
if (!isDragging) return
const handleWindowMouseMove = (e: MouseEvent) => {
if (lastSeekPosRef.current !== null && Math.abs(e.clientX - lastSeekPosRef.current) >= 2) {
didDragMoveRef.current = true
lastSeekPosRef.current = e.clientX
} else if (!didDragMoveRef.current) {
return
}
const percentage = getPercentageFromEvent(e.clientX)
setHoverPosition(percentage)
setIsHovering(true)
if (previewVideoRef.current && totalFrames) {
const targetFrame = percentage * totalFrames
const frameDuration = 1 / fps
const seekTime = targetFrame * frameDuration + frameDuration / 2
const vid = previewVideoRef.current
if (Number.isFinite(seekTime)) {
vid.currentTime = seekTime
}
}
onSeekRef.current(percentage * totalFrames)
}
const handleWindowMouseUp = (e: MouseEvent) => {
setIsDragging(false)
let stillHovering = false
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect()
stillHovering =
e.clientX >= rect.left &&
e.clientX <= rect.right &&
e.clientY >= rect.top &&
e.clientY <= rect.bottom
}
if (!stillHovering) {
setIsHovering(false)
setHoverPosition(null)
}
// A plain click already seeked on mousedown; only seek again if the
// pointer actually moved (drag release position differs from start).
if (didDragMoveRef.current) {
const percentage = getPercentageFromEvent(e.clientX)
onSeekRef.current(percentage * totalFrames)
}
didDragMoveRef.current = false
lastSeekPosRef.current = null
}
const handleWindowTouchMove = (e: TouchEvent) => {
if (e.touches.length === 0) return
if (
lastSeekPosRef.current !== null &&
Math.abs(e.touches[0].clientX - lastSeekPosRef.current) >= 2
) {
didDragMoveRef.current = true
lastSeekPosRef.current = e.touches[0].clientX
} else if (!didDragMoveRef.current) {
return
}
const percentage = getPercentageFromEvent(e.touches[0].clientX)
setHoverPosition(percentage)
setIsHovering(true)
if (previewVideoRef.current && totalFrames) {
const targetFrame = percentage * totalFrames
const frameDuration = 1 / fps
const seekTime = targetFrame * frameDuration + frameDuration / 2
const vid = previewVideoRef.current
if (Number.isFinite(seekTime)) {
vid.currentTime = seekTime
}
}
onSeekRef.current(percentage * totalFrames)
}
const handleWindowTouchEnd = (e: TouchEvent) => {
setIsDragging(false)
lastTouchEndAtRef.current = Date.now()
const clientX = e.changedTouches.length > 0 ? e.changedTouches[0].clientX : null
const clientY = e.changedTouches.length > 0 ? e.changedTouches[0].clientY : null
let stillHovering = false
if (clientX !== null && clientY !== null && containerRef.current) {
const rect = containerRef.current.getBoundingClientRect()
stillHovering =
clientX >= rect.left &&
clientX <= rect.right &&
clientY >= rect.top &&
clientY <= rect.bottom
}
if (!stillHovering) {
setIsHovering(false)
setHoverPosition(null)
}
if (clientX !== null && didDragMoveRef.current) {
// A plain tap already seeked on touchstart; only seek again after a
// real drag so a single tap doesn't restart the seek and stall.
const percentage = getPercentageFromEvent(clientX)
onSeekRef.current(percentage * totalFrames)
}
didDragMoveRef.current = false
lastSeekPosRef.current = null
}
const handleWindowTouchCancel = () => {
// OS gestures (app switch, palm rejection, notification pull) cancel
// the touch. Reset drag state without seeking so the bar doesn't stay
// stuck in dragging/hover mode.
setIsDragging(false)
setIsHovering(false)
setHoverPosition(null)
didDragMoveRef.current = false
lastSeekPosRef.current = null
lastTouchEndAtRef.current = Date.now()
}
window.addEventListener('mousemove', handleWindowMouseMove)
window.addEventListener('mouseup', handleWindowMouseUp)
window.addEventListener('touchmove', handleWindowTouchMove, { passive: true })
window.addEventListener('touchend', handleWindowTouchEnd)
window.addEventListener('touchcancel', handleWindowTouchCancel)
return () => {
window.removeEventListener('mousemove', handleWindowMouseMove)
window.removeEventListener('mouseup', handleWindowMouseUp)
window.removeEventListener('touchmove', handleWindowTouchMove)
window.removeEventListener('touchend', handleWindowTouchEnd)
window.removeEventListener('touchcancel', handleWindowTouchCancel)
}
}, [isDragging, totalFrames, fps, getPercentageFromEvent])
const progressPercent =
isDragging && hoverPosition !== null
? hoverPosition * 100
: totalFrames > 0
? (currentFrame / totalFrames) * 100
: 0
const hoverPercent = hoverPosition !== null ? hoverPosition * 100 : 0
// Calculate preview tooltip position
const getTooltipStyle = () => {
if (hoverPosition === null) return {}
return {
left: `${hoverPercent}%`,
transform: `translateX(-${hoverPercent}%)`,
}
}
// Dynamic Size Calculation
const MAX_PREVIEW_SIZE = 180
let previewDimensions: React.CSSProperties = {
width: `${MAX_PREVIEW_SIZE}px`,
height: 'auto',
}
if (metadata && metadata.originalWidth && metadata.originalHeight) {
const { originalWidth, originalHeight } = metadata
if (originalWidth >= originalHeight) {
// Landscape or Square: Constrain width
const height = (MAX_PREVIEW_SIZE * originalHeight) / originalWidth
previewDimensions = {
width: `${MAX_PREVIEW_SIZE}px`,
height: `${height}px`,
}
} else {
// Portrait: Constrain height
const width = (MAX_PREVIEW_SIZE * originalWidth) / originalHeight
previewDimensions = {
width: `${width}px`,
height: `${MAX_PREVIEW_SIZE}px`,
}
}
}
return (
<div
ref={containerRef}
className="group relative h-1.5 w-full cursor-pointer touch-none rounded-full bg-muted transition-colors duration-200"
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
data-testid="seekbar"
>
{/* Hidden Preview Video Element */}
<video
ref={previewVideoRef}
src={previewUrl}
className="hidden"
preload="metadata"
muted
playsInline
/>
{/* Hover Preview Tooltip */}
{isHovering && totalFrames > 0 && (
<div
className="pointer-events-none absolute bottom-full z-50 mb-3 flex w-max flex-col"
style={getTooltipStyle()}
>
<div className="relative overflow-hidden rounded-lg border-2 border-border bg-popover shadow-2xl">
<video
src={previewUrl}
className="bg-black object-cover"
style={previewDimensions}
muted
ref={(el) => {
if (el && previewVideoRef.current) {
el.currentTime = previewVideoRef.current.currentTime
}
}}
/>
<div className="absolute bottom-0 w-full bg-popover/80 py-0.5 text-center text-xs font-medium text-popover-foreground">
{formatTime((hoverPosition! * totalFrames) / fps)}
</div>
</div>
</div>
)}
{/* Buffered Bar */}
<div
className="absolute top-0 left-0 h-full rounded-full bg-muted-foreground/30 transition-all duration-200"
style={{ width: `${buffered}%` }}
/>
{/* Hover Highlight Bar */}
{isHovering && (
<div
className="absolute top-0 left-0 h-full rounded-full bg-primary/30"
style={{ width: `${hoverPercent}%` }}
/>
)}
{/* Play Progress Bar */}
<div
className="relative absolute top-0 left-0 h-full rounded-full bg-primary"
style={{ width: `${progressPercent}%` }}
data-testid="seekbar-fill"
>
{/* Thumb (Playhead) - visible on group hover or active */}
<div
className={cn(
'absolute top-1/2 right-0 h-3.5 w-3.5 -translate-y-1/2 translate-x-1/2 rounded-full border border-border bg-primary shadow-md transition-transform duration-100',
isHovering || isDragging ? 'scale-100' : 'scale-0 group-hover:scale-100',
)}
/>
</div>
</div>
)
}
export default ProgressBar