mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
fix(search): preview matched video chunks on hover (#540)
* fix(search): preview matched video chunks on hover * fix(search): show chunk covers before hover * fix(search): reuse sprites for whole-video matches
This commit is contained in:
@@ -308,7 +308,9 @@ export function FileCard({
|
||||
|
||||
// A preview (poster thumbnail and/or sprite) can be available before transcoding finishes,
|
||||
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
|
||||
const hasPreview = Boolean(displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl)
|
||||
const hasPreview = Boolean(
|
||||
item.matchedSprite || displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl,
|
||||
)
|
||||
const isFailed = displayItem.status === 'failed'
|
||||
const isLocalUploader = Boolean(fileUploadState)
|
||||
const isUploadFailed = fileUploadState?.status === 'failed'
|
||||
@@ -520,9 +522,10 @@ export function FileCard({
|
||||
<FilePreview
|
||||
item={displayItem}
|
||||
showDuration={!isProcessing && !isFailed}
|
||||
matchedSprite={item.matchedSprite}
|
||||
matchDuration={
|
||||
displayItem.startTime != null && displayItem.endTime != null
|
||||
? { startTime: displayItem.startTime, endTime: displayItem.endTime }
|
||||
item.startTime != null && item.endTime != null
|
||||
? { startTime: item.startTime, endTime: item.endTime }
|
||||
: null
|
||||
}
|
||||
/>
|
||||
@@ -569,8 +572,8 @@ export function FileCard({
|
||||
item={displayItem}
|
||||
showDuration
|
||||
matchDuration={
|
||||
displayItem.startTime != null && displayItem.endTime != null
|
||||
? { startTime: displayItem.startTime, endTime: displayItem.endTime }
|
||||
item.startTime != null && item.endTime != null
|
||||
? { startTime: item.startTime, endTime: item.endTime }
|
||||
: null
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { File, Folder, AudioLines } from 'lucide-react'
|
||||
import type { MatchedSprite } from '@shumai/dtos'
|
||||
import { SpriteScrubber } from '../sprite-scrubber'
|
||||
import { formatTime } from '../viewers/video/utils'
|
||||
|
||||
@@ -20,13 +21,19 @@ type FilePreviewItem = {
|
||||
interface FilePreviewProps {
|
||||
item: FilePreviewItem
|
||||
showDuration?: boolean
|
||||
matchedSprite?: MatchedSprite
|
||||
matchDuration?: {
|
||||
startTime?: number | null
|
||||
endTime?: number | null
|
||||
} | null
|
||||
}
|
||||
|
||||
export const FilePreview = ({ item, showDuration = false, matchDuration }: FilePreviewProps) => {
|
||||
export const FilePreview = ({
|
||||
item,
|
||||
showDuration = false,
|
||||
matchedSprite,
|
||||
matchDuration,
|
||||
}: FilePreviewProps) => {
|
||||
const proxyType = item.preview?.proxyType || item.proxyType
|
||||
const isVideo = proxyType === 'video'
|
||||
const isAudio = proxyType === 'audio'
|
||||
@@ -56,21 +63,27 @@ export const FilePreview = ({ item, showDuration = false, matchDuration }: FileP
|
||||
</span>
|
||||
) : null
|
||||
|
||||
const isMediaWithSprite =
|
||||
(isVideo || isPdf || is3D) &&
|
||||
item.preview?.spriteUrl &&
|
||||
item.preview.thumbnailUrl &&
|
||||
item.preview.originalWidth &&
|
||||
item.preview.originalHeight
|
||||
const chunkSprite = hasMatchedChunk ? matchedSprite : undefined
|
||||
const canShowFullSprite =
|
||||
hasMatchedChunk ||
|
||||
((isVideo || isPdf || is3D) &&
|
||||
item.preview?.thumbnailUrl &&
|
||||
item.preview.originalWidth &&
|
||||
item.preview.originalHeight)
|
||||
const fullSpriteUrl = canShowFullSprite ? item.preview?.spriteUrl : undefined
|
||||
const spriteUrl = chunkSprite?.url || fullSpriteUrl
|
||||
|
||||
if (isMediaWithSprite && item.preview) {
|
||||
if (spriteUrl) {
|
||||
return (
|
||||
<>
|
||||
<SpriteScrubber
|
||||
spriteUrl={item.preview.spriteUrl!}
|
||||
thumbnailUrl={item.preview.thumbnailUrl!}
|
||||
videoWidth={item.preview.originalWidth!}
|
||||
videoHeight={item.preview.originalHeight!}
|
||||
spriteUrl={spriteUrl}
|
||||
spriteLayout={chunkSprite}
|
||||
showFirstFrame={Boolean(chunkSprite)}
|
||||
fallbackSpriteUrl={chunkSprite && fullSpriteUrl ? fullSpriteUrl : undefined}
|
||||
thumbnailUrl={item.preview?.thumbnailUrl}
|
||||
videoWidth={item.preview?.originalWidth}
|
||||
videoHeight={item.preview?.originalHeight}
|
||||
reverse={is3D}
|
||||
/>
|
||||
{overlay}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import {
|
||||
mockIsIntersecting,
|
||||
resetIntersectionMocking,
|
||||
setupIntersectionMocking,
|
||||
} from 'react-intersection-observer/test-utils'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SpriteScrubber } from './sprite-scrubber'
|
||||
import { FilePreview } from './file-browser/file-preview'
|
||||
@@ -15,8 +20,116 @@ globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserv
|
||||
describe('SpriteScrubber', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
resetIntersectionMocking()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it.each(['chunk', 'full video', 'thumbnail'])('uses the %s preview on hover', (expected) => {
|
||||
setupIntersectionMocking(vi.fn)
|
||||
const chunkUrl = 'https://example.com/match.webp'
|
||||
const fullUrl = 'https://example.com/full.webp'
|
||||
const requests: string[] = []
|
||||
const image = {
|
||||
naturalWidth: 500,
|
||||
naturalHeight: 200,
|
||||
onload: null as (() => void) | null,
|
||||
onerror: null as (() => void) | null,
|
||||
set src(url: string) {
|
||||
requests.push(url)
|
||||
},
|
||||
}
|
||||
vi.stubGlobal(
|
||||
'Image',
|
||||
class {
|
||||
constructor() {
|
||||
return image
|
||||
}
|
||||
},
|
||||
)
|
||||
const { getByTestId, getByAltText, queryByAltText, container } = render(
|
||||
<FilePreview
|
||||
item={{
|
||||
preview: { proxyType: 'video', spriteUrl: fullUrl, thumbnailUrl: '/poster.webp' },
|
||||
}}
|
||||
matchDuration={{ startTime: 0, endTime: 7 }}
|
||||
matchedSprite={{ url: chunkUrl, columns: 5, rows: 2, frameCount: 7 }}
|
||||
/>,
|
||||
)
|
||||
const scrubber = getByTestId('sprite-scrubber')
|
||||
vi.spyOn(scrubber, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 100, 100))
|
||||
expect(requests).toEqual([])
|
||||
act(() => mockIsIntersecting(scrubber, true))
|
||||
expect(requests).toEqual([chunkUrl])
|
||||
|
||||
if (expected === 'chunk') {
|
||||
act(() => image.onload?.())
|
||||
expect(queryByAltText('Thumbnail')).toBeNull()
|
||||
expect(scrubber).toHaveProperty('dataset.frame', '0')
|
||||
} else {
|
||||
act(() => image.onerror?.())
|
||||
expect(requests).toEqual([chunkUrl])
|
||||
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||
}
|
||||
|
||||
fireEvent.mouseEnter(scrubber)
|
||||
fireEvent.mouseMove(scrubber, { clientX: 100 })
|
||||
expect(scrubber).toHaveProperty('dataset.frame', '6')
|
||||
|
||||
if (expected === 'chunk') {
|
||||
expect(requests).toEqual([chunkUrl])
|
||||
} else {
|
||||
expect(requests).toEqual([chunkUrl, fullUrl])
|
||||
}
|
||||
|
||||
if (expected === 'thumbnail') {
|
||||
act(() => image.onerror?.())
|
||||
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||
expect(container.querySelector('.animate-spin')).toBeNull()
|
||||
} else if (expected === 'full video') {
|
||||
act(() => image.onload?.())
|
||||
expect(getByAltText('Thumbnail').className).toContain('opacity-0')
|
||||
expect(scrubber).toHaveProperty('dataset.frame', '99')
|
||||
}
|
||||
|
||||
fireEvent.mouseLeave(scrubber)
|
||||
expect(scrubber).toHaveProperty('dataset.frame', '0')
|
||||
if (expected === 'chunk') {
|
||||
expect(queryByAltText('Thumbnail')).toBeNull()
|
||||
} else {
|
||||
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the regular cover and waits for hover when a match has no chunk sprite', () => {
|
||||
const load = vi.fn()
|
||||
vi.stubGlobal('Image', load)
|
||||
const { getByAltText } = render(
|
||||
<FilePreview
|
||||
item={{
|
||||
preview: { proxyType: 'video', spriteUrl: '/full.webp', thumbnailUrl: '/poster.webp' },
|
||||
}}
|
||||
matchDuration={{ startTime: 0, endTime: 10 }}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(getByAltText('Thumbnail').getAttribute('src')).toBe('/poster.webp')
|
||||
expect(load).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['video', undefined] as const)(
|
||||
'uses the full sprite for a legacy video match with proxy type %s and no poster or dimensions',
|
||||
(proxyType) => {
|
||||
const { getByTestId } = render(
|
||||
<FilePreview
|
||||
item={{ preview: { proxyType, spriteUrl: '/full.webp' } }}
|
||||
matchDuration={{ startTime: 0, endTime: 10 }}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(getByTestId('sprite-scrubber')).toBeTruthy()
|
||||
},
|
||||
)
|
||||
|
||||
it('scrubs forward by default when hovering from left to right', () => {
|
||||
const { getByTestId } = render(
|
||||
<SpriteScrubber
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import type { SpriteLayout } from '@shumai/dtos'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
|
||||
interface SpriteScrubberProps {
|
||||
/** The URL of the 10x10 sprite sheet */
|
||||
spriteUrl: string
|
||||
spriteLayout?: SpriteLayout
|
||||
/** Load the primary sprite when visible and show its first frame at rest. */
|
||||
showFirstFrame?: boolean
|
||||
/** A full-asset 10x10 sprite to try when the primary sprite fails. */
|
||||
fallbackSpriteUrl?: string
|
||||
/** The URL of the static thumbnail */
|
||||
thumbnailUrl: string
|
||||
thumbnailUrl?: string
|
||||
/** The width of the original video source */
|
||||
videoWidth: number
|
||||
videoWidth?: number
|
||||
/** The height of the original video source */
|
||||
videoHeight: number
|
||||
videoHeight?: number
|
||||
/** The fixed width of a single frame in the sprite sheet (default 480) */
|
||||
frameWidth?: number
|
||||
/** Optional custom class name for the container */
|
||||
@@ -22,33 +28,79 @@ interface Dimensions {
|
||||
height: number
|
||||
}
|
||||
|
||||
const GRID_COLS = 10
|
||||
const GRID_ROWS = 10
|
||||
const TOTAL_FRAMES = GRID_COLS * GRID_ROWS
|
||||
const FULL_SPRITE_LAYOUT: SpriteLayout = { columns: 10, rows: 10, frameCount: 100 }
|
||||
|
||||
interface SpriteImage extends Dimensions {
|
||||
url: string
|
||||
}
|
||||
|
||||
function useSpriteImage(url: string | undefined) {
|
||||
const [result, setResult] = useState<{ url: string; image: SpriteImage | null }>()
|
||||
|
||||
useEffect(() => {
|
||||
if (!url) return
|
||||
const img = new Image()
|
||||
img.onload = () =>
|
||||
setResult({ url, image: { url, width: img.naturalWidth, height: img.naturalHeight } })
|
||||
img.onerror = () => setResult({ url, image: null })
|
||||
img.src = url
|
||||
return () => {
|
||||
img.onload = null
|
||||
img.onerror = null
|
||||
}
|
||||
}, [url])
|
||||
|
||||
return result?.url === url ? result?.image : undefined
|
||||
}
|
||||
|
||||
export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
spriteUrl,
|
||||
spriteLayout = FULL_SPRITE_LAYOUT,
|
||||
showFirstFrame = false,
|
||||
fallbackSpriteUrl,
|
||||
thumbnailUrl,
|
||||
videoWidth,
|
||||
videoHeight,
|
||||
videoWidth = 1,
|
||||
videoHeight = 1,
|
||||
className = '',
|
||||
reverse = false,
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const { ref: observeVisibility, inView } = useInView({
|
||||
skip: !showFirstFrame,
|
||||
triggerOnce: true,
|
||||
fallbackInView: true,
|
||||
})
|
||||
const setContainerRef = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
containerRef.current = element
|
||||
observeVisibility(element)
|
||||
},
|
||||
[observeVisibility],
|
||||
)
|
||||
const [containerSize, setContainerSize] = useState<Dimensions>({
|
||||
width: 0,
|
||||
height: 0,
|
||||
})
|
||||
const [naturalSize, setNaturalSize] = useState<Dimensions>({
|
||||
width: 0,
|
||||
height: 0,
|
||||
})
|
||||
|
||||
const [isHovering, setIsHovering] = useState(false)
|
||||
const [spriteLoaded, setSpriteLoaded] = useState(false)
|
||||
const [loadingSprite, setLoadingSprite] = useState(false)
|
||||
const [currentFrame, setCurrentFrame] = useState(0)
|
||||
const [hasHovered, setHasHovered] = useState(false)
|
||||
const [cursorX, setCursorX] = useState(0)
|
||||
const [progress, setProgress] = useState<number>()
|
||||
|
||||
const loadPrimary = hasHovered || (showFirstFrame && inView)
|
||||
const primary = useSpriteImage(loadPrimary ? spriteUrl : undefined)
|
||||
const fallbackUrl =
|
||||
hasHovered && primary === null && fallbackSpriteUrl !== spriteUrl
|
||||
? fallbackSpriteUrl
|
||||
: undefined
|
||||
const fallback = useSpriteImage(fallbackUrl)
|
||||
const sprite = primary ?? fallback
|
||||
const spriteVisible = Boolean(sprite && (isHovering || (showFirstFrame && primary)))
|
||||
const spriteLoading =
|
||||
primary === undefined || (fallbackUrl !== undefined && fallback === undefined)
|
||||
const { columns, rows, frameCount } = fallback ? FULL_SPRITE_LAYOUT : spriteLayout
|
||||
const frame = Math.min(Math.floor((progress ?? 0) * frameCount), frameCount - 1)
|
||||
const cursorFrame = reverse && progress !== undefined ? frameCount - 1 - frame : frame
|
||||
const currentFrame = showFirstFrame && !isHovering ? 0 : cursorFrame
|
||||
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return
|
||||
@@ -66,26 +118,9 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const loadSprite = useCallback(() => {
|
||||
if (spriteLoaded || loadingSprite) return
|
||||
|
||||
setLoadingSprite(true)
|
||||
const img = new Image()
|
||||
img.src = spriteUrl
|
||||
img.onload = () => {
|
||||
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
||||
setSpriteLoaded(true)
|
||||
setLoadingSprite(false)
|
||||
}
|
||||
img.onerror = () => {
|
||||
console.error('Failed to load sprite image')
|
||||
setLoadingSprite(false)
|
||||
}
|
||||
}, [spriteUrl, spriteLoaded, loadingSprite])
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
setIsHovering(true)
|
||||
loadSprite()
|
||||
setHasHovered(true)
|
||||
}
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
@@ -100,22 +135,17 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
|
||||
const clampedX = Math.max(0, Math.min(x, rect.width))
|
||||
setCursorX(clampedX)
|
||||
|
||||
const percentage = clampedX / rect.width
|
||||
const rawFrame = Math.min(Math.floor(percentage * TOTAL_FRAMES), TOTAL_FRAMES - 1)
|
||||
const frameIndex = reverse ? TOTAL_FRAMES - 1 - rawFrame : rawFrame
|
||||
|
||||
setCurrentFrame(frameIndex)
|
||||
setProgress(rect.width > 0 ? clampedX / rect.width : 0)
|
||||
}
|
||||
|
||||
// Calculate styles for the inner sprite frame box
|
||||
const spriteStyle: React.CSSProperties = useMemo(() => {
|
||||
if (containerSize.width === 0 || containerSize.height === 0) return {}
|
||||
if (!sprite || containerSize.width === 0 || containerSize.height === 0) return {}
|
||||
|
||||
let sourceAspect = videoWidth / videoHeight
|
||||
if (naturalSize.width > 0 && naturalSize.height > 0) {
|
||||
const singleFrameNaturalW = naturalSize.width / GRID_COLS
|
||||
const singleFrameNaturalH = naturalSize.height / GRID_ROWS
|
||||
if (sprite.width > 0 && sprite.height > 0) {
|
||||
const singleFrameNaturalW = sprite.width / columns
|
||||
const singleFrameNaturalH = sprite.height / rows
|
||||
sourceAspect = singleFrameNaturalW / singleFrameNaturalH
|
||||
}
|
||||
|
||||
@@ -139,17 +169,17 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
// IMPORTANT: We calculate the sheet size based on the SNAPPED frame size.
|
||||
// This slightly stretches the sprite if needed but ensures that every frame
|
||||
// falls exactly on an integer pixel boundary, preventing "shaking" during playback.
|
||||
const bgWidth = finalW * GRID_COLS
|
||||
const bgHeight = finalH * GRID_ROWS
|
||||
const bgWidth = finalW * columns
|
||||
const bgHeight = finalH * rows
|
||||
|
||||
const colIndex = currentFrame % GRID_COLS
|
||||
const rowIndex = Math.floor(currentFrame / GRID_COLS)
|
||||
const colIndex = currentFrame % columns
|
||||
const rowIndex = Math.floor(currentFrame / columns)
|
||||
|
||||
const bgPosX = -(colIndex * finalW)
|
||||
const bgPosY = -(rowIndex * finalH)
|
||||
|
||||
return {
|
||||
backgroundImage: `url(${spriteUrl})`,
|
||||
backgroundImage: `url(${sprite.url})`,
|
||||
backgroundSize: `${bgWidth}px ${bgHeight}px`,
|
||||
backgroundPosition: `${bgPosX}px ${bgPosY}px`,
|
||||
backgroundRepeat: 'no-repeat',
|
||||
@@ -158,11 +188,11 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
// Optional: helps with crisp edges on some screens, though default is usually fine
|
||||
imageRendering: 'auto',
|
||||
}
|
||||
}, [containerSize, videoWidth, videoHeight, currentFrame, spriteUrl, naturalSize])
|
||||
}, [containerSize, videoWidth, videoHeight, currentFrame, sprite, columns, rows])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
ref={setContainerRef}
|
||||
data-testid="sprite-scrubber"
|
||||
data-frame={currentFrame}
|
||||
className={`relative w-full h-full overflow-hidden cursor-pointer group bg-black select-none ${className}`}
|
||||
@@ -170,32 +200,34 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onMouseMove={handleMouseMove}
|
||||
>
|
||||
<img
|
||||
src={thumbnailUrl}
|
||||
alt="Thumbnail"
|
||||
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
|
||||
isHovering && spriteLoaded ? 'opacity-0' : 'opacity-100'
|
||||
}`}
|
||||
draggable={false}
|
||||
/>
|
||||
{thumbnailUrl && (!showFirstFrame || primary === null) && (
|
||||
<img
|
||||
src={thumbnailUrl}
|
||||
alt="Thumbnail"
|
||||
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
|
||||
spriteVisible ? 'opacity-0' : 'opacity-100'
|
||||
}`}
|
||||
draggable={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isHovering && !spriteLoaded && (
|
||||
{isHovering && spriteLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10 pointer-events-none">
|
||||
<div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{spriteLoaded && (
|
||||
{sprite && (
|
||||
<div
|
||||
className={`absolute inset-0 flex items-center justify-center transition-opacity duration-75 ${
|
||||
isHovering ? 'opacity-100' : 'opacity-0'
|
||||
spriteVisible ? 'opacity-100' : 'opacity-0'
|
||||
}`}
|
||||
>
|
||||
<div style={spriteStyle} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isHovering && (
|
||||
{isHovering && (spriteLoading || sprite) && (
|
||||
<div
|
||||
className="absolute top-0 bottom-0 w-0.5 bg-red-500 shadow-[0_0_4px_rgba(255,0,0,0.8)] z-20 pointer-events-none"
|
||||
style={{ transform: `translateX(${cursorX}px)` }}
|
||||
|
||||
Reference in New Issue
Block a user