From 59e641ccb3fc02b1b438b88d698fe5b077088545 Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Tue, 25 Aug 2026 21:01:51 +0800 Subject: [PATCH] fix(webui): prevent left carousel remounting and scroll jump on file selection (#351) --- .../file-viewer-left-sidebar.test.tsx | 203 ++++++++++++++++++ .../components/file-viewer-left-sidebar.tsx | 31 +-- .../webui/components/file-viewer.test.tsx | 84 ++++++++ packages/webui/components/file-viewer.tsx | 29 +-- .../viewers/default/default-viewer.tsx | 9 +- .../components/viewers/image/image-viewer.tsx | 55 +++-- .../components/viewers/pdf/pdf-viewer.tsx | 107 ++++----- .../components/viewers/video/video-viewer.tsx | 127 +++++------ 8 files changed, 452 insertions(+), 193 deletions(-) create mode 100644 packages/webui/components/file-viewer-left-sidebar.test.tsx create mode 100644 packages/webui/components/file-viewer.test.tsx diff --git a/packages/webui/components/file-viewer-left-sidebar.test.tsx b/packages/webui/components/file-viewer-left-sidebar.test.tsx new file mode 100644 index 00000000..e8525137 --- /dev/null +++ b/packages/webui/components/file-viewer-left-sidebar.test.tsx @@ -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 + }) => ( + + {children} + + ), +})) + +// 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( + , + ) + + 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( + , + ) + + 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( + , + ) + + expect(scrollIntoViewMock).toHaveBeenCalledTimes(1) + expect(scrollIntoViewMock).toHaveBeenCalledWith({ + block: 'center', + inline: 'center', + behavior: 'auto', + }) + + scrollIntoViewMock.mockClear() + + // Switch to file-3 while staying mounted + rerender( + , + ) + + 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( + , + ) + + 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( + , + ) + + expect(scrollIntoViewMock).toHaveBeenCalledWith({ + block: 'center', + inline: 'center', + behavior: 'auto', + }) + }) +}) diff --git a/packages/webui/components/file-viewer-left-sidebar.tsx b/packages/webui/components/file-viewer-left-sidebar.tsx index cd1f5789..88a26bfb 100644 --- a/packages/webui/components/file-viewer-left-sidebar.tsx +++ b/packages/webui/components/file-viewer-left-sidebar.tsx @@ -50,7 +50,7 @@ export const FileViewerLeftSidebar: FC = ({ rootMargin: '200px', }) const activeItemRef = useRef(null) - const hasScrolledRef = useRef(false) + const isInitialMountRef = useRef(true) const [files, setFiles] = useState(initialFiles) const [nextCursor, setNextCursor] = useState(initialNextCursor) @@ -62,7 +62,7 @@ export const FileViewerLeftSidebar: FC = ({ 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 = ({ 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]) diff --git a/packages/webui/components/file-viewer.test.tsx b/packages/webui/components/file-viewer.test.tsx new file mode 100644 index 00000000..587cdadb --- /dev/null +++ b/packages/webui/components/file-viewer.test.tsx @@ -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(({ file }) => ( +
{file.name}
+ )), + }), +})) + +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 ( +
+ {count} + +
+ ) + } + + 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( + + + , + ) + + 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( + + + , + ) + + // 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') + }) +}) diff --git a/packages/webui/components/file-viewer.tsx b/packages/webui/components/file-viewer.tsx index 6ee7069e..2db7422d 100644 --- a/packages/webui/components/file-viewer.tsx +++ b/packages/webui/components/file-viewer.tsx @@ -22,19 +22,22 @@ export function FileViewer({ const ViewerComponent = viewerDef.viewer return ( - +
{children} - +
+ +
+
) } diff --git a/packages/webui/components/viewers/default/default-viewer.tsx b/packages/webui/components/viewers/default/default-viewer.tsx index f55ca920..a5c026bd 100644 --- a/packages/webui/components/viewers/default/default-viewer.tsx +++ b/packages/webui/components/viewers/default/default-viewer.tsx @@ -4,7 +4,7 @@ import React, { useImperativeHandle } from 'react' import { FileViewerProps, MediaController } from '../types' export const DefaultViewer = React.forwardRef( - ({ 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( return (
-
- {children} -
-

Preview unavailable

-
+
+

Preview unavailable

{allowDownload && ( diff --git a/packages/webui/components/viewers/image/image-viewer.tsx b/packages/webui/components/viewers/image/image-viewer.tsx index f19c3e3a..1c445116 100644 --- a/packages/webui/components/viewers/image/image-viewer.tsx +++ b/packages/webui/components/viewers/image/image-viewer.tsx @@ -10,7 +10,7 @@ import { centeredPan, fitScale, isZoomed, zoomAtPoint } from '../pan-zoom' import { usePanZoomGestures } from '../use-pan-zoom' export const ImageViewer = React.forwardRef( - ({ 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( return (
-
- {children} -
- {bestUrl ? ( - - ) : ( -
-

Preview unavailable

-
- )} -
+
+ {bestUrl ? ( + + ) : ( +
+

Preview unavailable

+
+ )}
( ( - { - 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( return (
-
- {children} -
- {loading ? ( -
-
-
- ) : error ? ( -
- {error} -
- ) : ( - - )} - {/* 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. */} -
{ - // 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', - }} +
+ {loading ? ( +
+
+
+ ) : error ? ( +
+ {error} +
+ ) : ( + -
+ )} + {/* 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. */} +
{ + // 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', + }} + />
( ( - { - file: data, - onPlay, - onPause, - onTimeUpdate, - annotations, - startTime, - shareId, - children, - allowDownload, - }, + { file: data, onPlay, onPause, onTimeUpdate, annotations, startTime, shareId, allowDownload }, ref, ) => { const localPlayerRef = useRef(null) @@ -632,69 +622,64 @@ const VideoViewer = React.forwardRef( onMouseMove={handleMouseMove} onMouseLeave={handleMouseLeave} > -
- {/* Render Carousel/Sidebar here if not fullscreen */} - {!state.isFullScreen && children} + {/* Video Area */} +
+ {/* Hidden VideoJS container */} +
- {/* Video Area */} -
- {/* Hidden VideoJS container */} -
+ {isAudio ? ( +
+ +
+ ) : ( + /* Drawing Canvas (Visible) */ + videoHtmlEl && + containerSize.width > 0 && ( + + ) + )} - {isAudio ? ( -
- + {/* Big Play Button Overlay (when paused) */} + {!state.isPlaying && !isDrawing && ( +
+
+
- ) : ( - /* Drawing Canvas (Visible) */ - videoHtmlEl && - containerSize.width > 0 && ( - - ) - )} - - {/* Big Play Button Overlay (when paused) */} - {!state.isPlaying && !isDrawing && ( -
-
- -
-
- )} -
+
+ )}