fix(webui): prevent left carousel remounting and scroll jump on file selection (#351)

This commit is contained in:
Yiling-J
2026-08-25 21:01:51 +08:00
committed by GitHub
parent 1d9268b224
commit 59e641ccb3
8 changed files with 452 additions and 193 deletions
@@ -0,0 +1,203 @@
// @vitest-environment happy-dom
import { cleanup, render } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { FileViewerLeftSidebar } from './file-viewer-left-sidebar'
import type { AssetInfo } from '@shumai/dtos'
// Mock react-intersection-observer
vi.mock('react-intersection-observer', () => ({
useInView: () => ({
ref: vi.fn(),
inView: false,
}),
}))
// Mock @tanstack/react-router Link
vi.mock('@tanstack/react-router', () => ({
Link: ({
children,
className,
to,
}: {
children: React.ReactNode
className?: string
to?: string
}) => (
<a href={to} className={className} data-testid="carousel-link">
{children}
</a>
),
}))
// Mock api client
vi.mock('@/ui/api/client', () => ({
client: {
api: {
folders: {
':folderId': {
search: {
$post: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: [], pageInfo: {} }),
}),
},
},
},
},
},
}))
describe('FileViewerLeftSidebar', () => {
const scrollIntoViewMock = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock
})
afterEach(() => {
cleanup()
})
const mockFiles: AssetInfo[] = [
{
id: 'file-1',
name: 'Image 1.png',
proxyType: 'image',
} as AssetInfo,
{
id: 'file-2',
name: 'Image 2.png',
proxyType: 'image',
} as AssetInfo,
{
id: 'file-3',
name: 'Image 3.png',
proxyType: 'image',
} as AssetInfo,
]
it('renders files list and highlights active asset', () => {
const { container } = render(
<FileViewerLeftSidebar
projectId="proj-1"
currentAssetId="file-2"
parentFolderId="folder-1"
initialFiles={mockFiles}
initialNextCursor={undefined}
/>,
)
const links = container.querySelectorAll('[data-testid="carousel-link"]')
expect(links.length).toBe(3)
// Active item (file-2) has w-[62px] h-[62px] opacity-100 class
expect(links[1].className).toContain('w-[62px]')
expect(links[1].className).toContain('opacity-100')
// Inactive items have w-[52px] h-[52px] opacity-60 class
expect(links[0].className).toContain('w-[52px]')
expect(links[0].className).toContain('opacity-60')
})
it('uses behavior auto and block center on initial mount', () => {
render(
<FileViewerLeftSidebar
projectId="proj-1"
currentAssetId="file-2"
parentFolderId="folder-1"
initialFiles={mockFiles}
initialNextCursor={undefined}
/>,
)
expect(scrollIntoViewMock).toHaveBeenCalledTimes(1)
expect(scrollIntoViewMock).toHaveBeenCalledWith({
block: 'center',
inline: 'center',
behavior: 'auto',
})
})
it('uses behavior smooth and block nearest on subsequent active item change', () => {
const { rerender } = render(
<FileViewerLeftSidebar
projectId="proj-1"
currentAssetId="file-1"
parentFolderId="folder-1"
initialFiles={mockFiles}
initialNextCursor={undefined}
/>,
)
expect(scrollIntoViewMock).toHaveBeenCalledTimes(1)
expect(scrollIntoViewMock).toHaveBeenCalledWith({
block: 'center',
inline: 'center',
behavior: 'auto',
})
scrollIntoViewMock.mockClear()
// Switch to file-3 while staying mounted
rerender(
<FileViewerLeftSidebar
projectId="proj-1"
currentAssetId="file-3"
parentFolderId="folder-1"
initialFiles={mockFiles}
initialNextCursor={undefined}
/>,
)
expect(scrollIntoViewMock).toHaveBeenCalledTimes(1)
expect(scrollIntoViewMock).toHaveBeenCalledWith({
block: 'nearest',
inline: 'nearest',
behavior: 'smooth',
})
})
it('resets initial mount centering when parent folder / initial files change', () => {
const { rerender } = render(
<FileViewerLeftSidebar
projectId="proj-1"
currentAssetId="file-1"
parentFolderId="folder-1"
initialFiles={mockFiles}
initialNextCursor={undefined}
/>,
)
expect(scrollIntoViewMock).toHaveBeenCalledWith({
block: 'center',
inline: 'center',
behavior: 'auto',
})
scrollIntoViewMock.mockClear()
const newFiles: AssetInfo[] = [
{
id: 'file-10',
name: 'Other 10.png',
proxyType: 'image',
} as AssetInfo,
]
rerender(
<FileViewerLeftSidebar
projectId="proj-1"
currentAssetId="file-10"
parentFolderId="folder-2"
initialFiles={newFiles}
initialNextCursor={undefined}
/>,
)
expect(scrollIntoViewMock).toHaveBeenCalledWith({
block: 'center',
inline: 'center',
behavior: 'auto',
})
})
})
@@ -50,7 +50,7 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
rootMargin: '200px',
})
const activeItemRef = useRef<HTMLDivElement>(null)
const hasScrolledRef = useRef(false)
const isInitialMountRef = useRef(true)
const [files, setFiles] = useState<AssetInfo[]>(initialFiles)
const [nextCursor, setNextCursor] = useState<string | undefined>(initialNextCursor)
@@ -62,7 +62,7 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
setFiles(initialFiles)
setNextCursor(initialNextCursor)
setHasMore(!!initialNextCursor)
hasScrolledRef.current = false
isInitialMountRef.current = true
}, [initialFiles, initialNextCursor])
// Fetch next page when scrolling near bottom
@@ -98,21 +98,24 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
fetchNextPage()
}, [inView, nextCursor, hasMore, isFetchingNext, parentFolderId])
// Reset scroll lock when current asset changes
useEffect(() => {
hasScrolledRef.current = false
}, [currentAssetId])
// Scroll the active item into view
useEffect(() => {
const activeFileInView = files.some((f) => f?.id === currentAssetId)
if (activeFileInView && activeItemRef.current && !hasScrolledRef.current) {
activeItemRef.current.scrollIntoView({
block: 'center',
inline: 'center',
behavior: 'smooth',
})
hasScrolledRef.current = true
if (activeFileInView && activeItemRef.current) {
if (isInitialMountRef.current) {
activeItemRef.current.scrollIntoView({
block: 'center',
inline: 'center',
behavior: 'auto',
})
isInitialMountRef.current = false
} else {
activeItemRef.current.scrollIntoView({
block: 'nearest',
inline: 'nearest',
behavior: 'smooth',
})
}
}
}, [files, currentAssetId])
@@ -0,0 +1,84 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render } from '@testing-library/react'
import React, { useEffect, useState } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { FileViewer } from './file-viewer'
import type { AssetInfo } from '@shumai/dtos'
// Mock registry so getViewerForFile returns a simple test viewer
vi.mock('./viewers/registry', () => ({
getViewerForFile: () => ({
id: 'test-viewer',
name: 'Test Viewer',
match: () => true,
viewer: React.forwardRef<unknown, { file: AssetInfo }>(({ file }) => (
<div data-testid={`viewer-${file.id}`}>{file.name}</div>
)),
}),
}))
describe('FileViewer', () => {
afterEach(() => {
cleanup()
})
it('renders children alongside viewer and preserves children state across file changes', () => {
let mountCount = 0
const StatefulChild = () => {
const [count, setCount] = useState(0)
useEffect(() => {
mountCount++
}, [])
return (
<div data-testid="sidebar-child">
<span data-testid="child-count">{count}</span>
<button data-testid="child-btn" onClick={() => setCount((c) => c + 1)}>
Increment
</button>
</div>
)
}
const fileA: AssetInfo = {
id: 'file-a',
name: 'File A.png',
proxyType: 'image',
} as AssetInfo
const fileB: AssetInfo = {
id: 'file-b',
name: 'File B.png',
proxyType: 'image',
} as AssetInfo
const { getByTestId, rerender } = render(
<FileViewer file={fileA}>
<StatefulChild />
</FileViewer>,
)
expect(getByTestId('viewer-file-a')).toBeDefined()
expect(getByTestId('child-count').textContent).toBe('0')
expect(mountCount).toBe(1)
// Increment count inside child
fireEvent.click(getByTestId('child-btn'))
expect(getByTestId('child-count').textContent).toBe('1')
// Rerender with new file (fileB)
rerender(
<FileViewer file={fileB}>
<StatefulChild />
</FileViewer>,
)
// Viewer component changed to file B
expect(getByTestId('viewer-file-b')).toBeDefined()
// Child component remained mounted without remounting or resetting state
expect(mountCount).toBe(1)
expect(getByTestId('child-count').textContent).toBe('1')
})
})
+16 -13
View File
@@ -22,19 +22,22 @@ export function FileViewer({
const ViewerComponent = viewerDef.viewer
return (
<ViewerComponent
key={file.id}
ref={mediaControllerRef}
file={file}
onPlay={onPlay}
onPause={onPause}
onTimeUpdate={onTimeUpdate}
annotations={annotations}
startTime={startTime}
shareId={shareId}
allowDownload={allowDownload}
>
<div className="flex flex-col-reverse md:flex-row flex-1 h-full min-h-0 relative">
{children}
</ViewerComponent>
<div className="flex-1 min-w-0 h-full flex flex-col">
<ViewerComponent
key={file.id}
ref={mediaControllerRef}
file={file}
onPlay={onPlay}
onPause={onPause}
onTimeUpdate={onTimeUpdate}
annotations={annotations}
startTime={startTime}
shareId={shareId}
allowDownload={allowDownload}
/>
</div>
</div>
)
}
@@ -4,7 +4,7 @@ import React, { useImperativeHandle } from 'react'
import { FileViewerProps, MediaController } from '../types'
export const DefaultViewer = React.forwardRef<MediaController, FileViewerProps>(
({ file, shareId, children, allowDownload = true }, ref) => {
({ file, shareId, allowDownload = true }, ref) => {
// Implement no-op media controller
useImperativeHandle(ref, () => ({
play: () => {},
@@ -39,11 +39,8 @@ export const DefaultViewer = React.forwardRef<MediaController, FileViewerProps>(
return (
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{children}
<div className="flex-1 flex items-center justify-center">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
<div className="flex-1 flex items-center justify-center">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
{allowDownload && (
@@ -10,7 +10,7 @@ import { centeredPan, fitScale, isZoomed, zoomAtPoint } from '../pan-zoom'
import { usePanZoomGestures } from '../use-pan-zoom'
export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
({ file, annotations, shareId, children, allowDownload }, ref) => {
({ file, annotations, shareId, allowDownload }, ref) => {
// Implement no-op media controller since images are static
useImperativeHandle(ref, () => ({
play: () => {},
@@ -173,34 +173,31 @@ export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
return (
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{children}
<div ref={containerRef} className="flex-1 relative overflow-hidden touch-none">
{bestUrl ? (
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={{
width: imgW,
height: imgH,
}}
imageUrl={bestUrl}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
onPan={isZoomed(zoom, baseScale) ? setPan : undefined}
className="absolute inset-0 z-0"
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
) : (
<div className="flex h-full w-full items-center justify-center">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
)}
</div>
<div ref={containerRef} className="flex-1 relative overflow-hidden touch-none">
{bestUrl ? (
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={{
width: imgW,
height: imgH,
}}
imageUrl={bestUrl}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
onPan={isZoomed(zoom, baseScale) ? setPan : undefined}
className="absolute inset-0 z-0"
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
) : (
<div className="flex h-full w-full items-center justify-center">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
)}
</div>
<ImageControlBar
zoom={zoom}
@@ -31,17 +31,7 @@ if (typeof window !== 'undefined' && pdfjsLib.GlobalWorkerOptions) {
export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
(
{
file,
annotations,
shareId,
children,
onPlay,
onPause,
onTimeUpdate,
startTime,
allowDownload,
},
{ file, annotations, shareId, onPlay, onPause, onTimeUpdate, startTime, allowDownload },
ref,
) => {
const {
@@ -392,56 +382,53 @@ export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
return (
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{children}
<div ref={containerRef} className="flex-1 relative overflow-hidden touch-none">
{loading ? (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 z-20">
<div className="w-8 h-8 border-4 border-white/30 border-t-white rounded-full animate-spin" />
</div>
) : error ? (
<div className="absolute inset-0 flex items-center justify-center text-gray-500 text-sm">
{error}
</div>
) : (
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={pageDimensions}
canvasElement={pageCanvas}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
className="absolute inset-0 z-0"
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
)}
{/* Invisible selectable text overlay, transformed to match the Konva
stage. It sits ON TOP of the page canvas so the native selection
highlight is visible; pointer events are enabled only when not
drawing, so drags reach the stage below in draw mode. */}
<div
ref={textLayerContainerRef}
className="pdf-text-layer"
onMouseDown={(e) => {
// The container is user-select:none, so Chromium no longer
// clears the selection when clicking empty space (only text
// spans move the caret). Restore the expected behavior: a
// press on the container/br (not a text span) deselects.
if (e.target instanceof HTMLElement && e.target.tagName !== 'SPAN') {
window.getSelection()?.removeAllRanges()
}
}}
style={{
transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
transformOrigin: '0 0',
pointerEvents: isDrawing ? 'none' : 'auto',
}}
<div ref={containerRef} className="flex-1 relative overflow-hidden touch-none">
{loading ? (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 z-20">
<div className="w-8 h-8 border-4 border-white/30 border-t-white rounded-full animate-spin" />
</div>
) : error ? (
<div className="absolute inset-0 flex items-center justify-center text-gray-500 text-sm">
{error}
</div>
) : (
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={pageDimensions}
canvasElement={pageCanvas}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
className="absolute inset-0 z-0"
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
</div>
)}
{/* Invisible selectable text overlay, transformed to match the Konva
stage. It sits ON TOP of the page canvas so the native selection
highlight is visible; pointer events are enabled only when not
drawing, so drags reach the stage below in draw mode. */}
<div
ref={textLayerContainerRef}
className="pdf-text-layer"
onMouseDown={(e) => {
// The container is user-select:none, so Chromium no longer
// clears the selection when clicking empty space (only text
// spans move the caret). Restore the expected behavior: a
// press on the container/br (not a text span) deselects.
if (e.target instanceof HTMLElement && e.target.tagName !== 'SPAN') {
window.getSelection()?.removeAllRanges()
}
}}
style={{
transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
transformOrigin: '0 0',
pointerEvents: isDrawing ? 'none' : 'auto',
}}
/>
</div>
<PdfControlBar
currentPage={currentPage}
@@ -15,17 +15,7 @@ import { usePanZoomGestures } from '../use-pan-zoom'
const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
(
{
file: data,
onPlay,
onPause,
onTimeUpdate,
annotations,
startTime,
shareId,
children,
allowDownload,
},
{ file: data, onPlay, onPause, onTimeUpdate, annotations, startTime, shareId, allowDownload },
ref,
) => {
const localPlayerRef = useRef<Player | null>(null)
@@ -632,69 +622,64 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{/* Render Carousel/Sidebar here if not fullscreen */}
{!state.isFullScreen && children}
{/* Video Area */}
<div
ref={containerRef}
className={cn(
'flex-1 bg-black cursor-pointer relative flex items-center justify-center overflow-hidden min-h-0 touch-none',
)}
onClick={togglePlay}
data-vjs-player
data-testid="video-area"
>
{/* Hidden VideoJS container */}
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
{/* Video Area */}
<div
ref={containerRef}
className={cn(
'flex-1 bg-black cursor-pointer relative flex items-center justify-center overflow-hidden min-h-0 touch-none',
)}
onClick={togglePlay}
data-vjs-player
data-testid="video-area"
>
{/* Hidden VideoJS container */}
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
{isAudio ? (
<div className="flex flex-col items-center justify-center text-muted-foreground w-full h-full pointer-events-none select-none">
<AudioLines
className={cn(
'w-16 h-16 text-foreground/75 transition-transform duration-500',
state.isPlaying ? 'animate-pulse scale-110 text-primary' : '',
)}
/>
</div>
) : (
/* Drawing Canvas (Visible) */
videoHtmlEl &&
containerSize.width > 0 && (
<DrawingCanvas
width={containerSize.width}
height={containerSize.height}
mediaDimensions={{
width: vidW,
height: vidH,
}}
videoElement={videoHtmlEl}
annotations={displayAnnotations}
scale={scale}
offset={pan}
className="absolute inset-0"
// Play/pause is handled by the video-area div's onClick; a
// Konva-level onClick would double-toggle once the overlay
// becomes interactive (zoomed).
// Drawing Props
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
)
)}
{isAudio ? (
<div className="flex flex-col items-center justify-center text-muted-foreground w-full h-full pointer-events-none select-none">
<AudioLines
className={cn(
'w-16 h-16 text-foreground/75 transition-transform duration-500',
state.isPlaying ? 'animate-pulse scale-110 text-primary' : '',
)}
/>
{/* Big Play Button Overlay (when paused) */}
{!state.isPlaying && !isDrawing && (
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30 animate-pulse">
<Play className="w-10 h-10 text-white ml-1 fill-white" />
</div>
) : (
/* Drawing Canvas (Visible) */
videoHtmlEl &&
containerSize.width > 0 && (
<DrawingCanvas
width={containerSize.width}
height={containerSize.height}
mediaDimensions={{
width: vidW,
height: vidH,
}}
videoElement={videoHtmlEl}
annotations={displayAnnotations}
scale={scale}
offset={pan}
className="absolute inset-0"
// Play/pause is handled by the video-area div's onClick; a
// Konva-level onClick would double-toggle once the overlay
// becomes interactive (zoomed).
// Drawing Props
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
)
)}
{/* Big Play Button Overlay (when paused) */}
{!state.isPlaying && !isDrawing && (
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30 animate-pulse">
<Play className="w-10 h-10 text-white ml-1 fill-white" />
</div>
</div>
)}
</div>
</div>
)}
</div>
<VideoControlBar