diff --git a/frontend/package.json b/frontend/package.json index 809c8e4b..0e6ef3a8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,7 +8,8 @@ "typecheck": "tsc --noEmit", "lint": "eslint .", "preview": "vite preview", - "test": "vitest" + "test": "vitest", + "test:run": "vitest run" }, "dependencies": { "@better-auth/passkey": "^1.4.17", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index c0957f7c..8908e653 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -21,6 +21,8 @@ import { AuthProvider } from './contexts/AuthContext' import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext' import { PermissionRequestDialog } from './components/session/PermissionRequestDialog' import { SSHHostKeyDialog } from './components/ssh/SSHHostKeyDialog' +import { PageTransition } from './components/ui/PageTransition' +import { useNavigationDirection } from './hooks/useNavigationDirection' import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib/auth-loaders' const queryClient = new QueryClient({ @@ -69,6 +71,7 @@ function PermissionDialogWrapper() { function AppShell() { const navigate = useNavigate() useTheme() + useNavigationDirection() useEffect(() => { const channel = new BroadcastChannel('notification-click') @@ -84,7 +87,9 @@ function AppShell() { return ( - + + + diff --git a/frontend/src/components/file-browser/FileBrowser.tsx b/frontend/src/components/file-browser/FileBrowser.tsx index fe6f66d5..de1ed6b4 100644 --- a/frontend/src/components/file-browser/FileBrowser.tsx +++ b/frontend/src/components/file-browser/FileBrowser.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useRef, useCallback } from 'react' +import { useState, useEffect, useRef, useCallback, forwardRef, useImperativeHandle } from 'react' import { FileTree } from './FileTree' import { FileOperations } from './FileOperations' import { FilePreview } from './FilePreview' @@ -14,6 +14,21 @@ import { API_BASE_URL } from '@/config' import { useMobile } from '@/hooks/useMobile' import { useFile } from '@/api/files' +export interface FileBrowserHandle { + goBack: () => void + canGoBack: () => boolean + getCurrentPath: () => string +} + +interface FileBrowserProps { + basePath?: string + onFileSelect?: (file: FileInfo) => void + embedded?: boolean + initialSelectedFile?: string + onDirectoryLoad?: (info: { workspaceRoot?: string; currentPath: string }) => void + onPreviewStateChange?: (isOpen: boolean) => void +} + interface UploadItem { file: File relativePath: string @@ -27,14 +42,6 @@ interface UploadProgress { cancelled: boolean } -interface FileBrowserProps { - basePath?: string - onFileSelect?: (file: FileInfo) => void - embedded?: boolean - initialSelectedFile?: string - onDirectoryLoad?: (info: { workspaceRoot?: string; currentPath: string }) => void -} - async function readFileEntry(entry: FileSystemFileEntry): Promise { return new Promise((resolve, reject) => { entry.file(resolve, reject) @@ -115,7 +122,7 @@ function getUploadItemsFromFileList(fileList: FileList): UploadItem[] { return items } -export function FileBrowser({ basePath = '', onFileSelect, embedded = false, initialSelectedFile, onDirectoryLoad }: FileBrowserProps) { +export const FileBrowser = forwardRef(function FileBrowser({ basePath = '', onFileSelect, embedded = false, initialSelectedFile, onDirectoryLoad, onPreviewStateChange }, ref) { const [currentPath, setCurrentPath] = useState(basePath) const [files, setFiles] = useState(null) const [selectedFile, setSelectedFile] = useState(null) @@ -137,9 +144,10 @@ useEffect(() => { setSelectedFile(initialFileData) if (isMobile) { setIsPreviewModalOpen(true) + onPreviewStateChange?.(true) } } -}, [initialFileData, isMobile]) +}, [initialFileData, isMobile, onPreviewStateChange]) useEffect(() => { if (initialFileError) { @@ -168,6 +176,27 @@ useEffect(() => { } }, [onDirectoryLoad]) + const getPathParts = useCallback((path: string) => path.split('/').filter(Boolean), []) + + const goToParentDirectory = useCallback(() => { + const pathParts = getPathParts(currentPath) + if (pathParts.length > 0) { + pathParts.pop() + const parentPath = pathParts.join('/') + loadFiles(parentPath || basePath) + } + }, [currentPath, basePath, loadFiles, getPathParts]) + + useImperativeHandle(ref, () => ({ + goBack: goToParentDirectory, + canGoBack: () => { + const pathParts = getPathParts(currentPath) + const joinedPath = pathParts.join('/') + return pathParts.length > 0 && joinedPath !== basePath + }, + getCurrentPath: () => currentPath, + }), [currentPath, basePath, goToParentDirectory, getPathParts]) + const handleFileSelect = useCallback(async (file: FileInfo) => { if (file.isDirectory) { setSelectedFile(null) @@ -189,6 +218,7 @@ useEffect(() => { // On mobile, open preview in modal if (isMobile) { setIsPreviewModalOpen(true) + onPreviewStateChange?.(true) } } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load file') @@ -196,12 +226,13 @@ useEffect(() => { } finally { setLoading(false) } - }, [onFileSelect, isMobile]) + }, [onFileSelect, isMobile, onPreviewStateChange]) const handleCloseModal = useCallback(() => { setIsPreviewModalOpen(false) setSelectedFile(null) - }, []) + onPreviewStateChange?.(false) + }, [onPreviewStateChange]) const handleDirectoryClick = (path: string) => { loadFiles(path) @@ -404,7 +435,7 @@ useEffect(() => { const canDismissDialog = isUploadComplete || uploadProgress?.cancelled const uploadDialog = ( - { if (!open && canDismissDialog) setUploadProgress(null) }}> + { if (!open && canDismissDialog) setUploadProgress(null) }}> @@ -525,6 +556,7 @@ useEffect(() => { onRename={handleRename} currentPath={currentPath} basePath={basePath} + onNavigateUp={goToParentDirectory} /> )} @@ -624,6 +656,7 @@ useEffect(() => { onRename={handleRename} currentPath={currentPath} basePath={basePath} + onNavigateUp={goToParentDirectory} /> )} @@ -654,4 +687,4 @@ useEffect(() => { {uploadDialog} ) -} +}) diff --git a/frontend/src/components/file-browser/FileBrowserSheet.test.tsx b/frontend/src/components/file-browser/FileBrowserSheet.test.tsx new file mode 100644 index 00000000..3dda39ef --- /dev/null +++ b/frontend/src/components/file-browser/FileBrowserSheet.test.tsx @@ -0,0 +1,872 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import '@testing-library/jest-dom' +import { FileBrowserSheet } from './FileBrowserSheet' +import { FileBrowser } from './FileBrowser' +import type { FileBrowserHandle } from './FileBrowser' +import * as useMobile from '../../hooks/useMobile' + +function createQueryClient() { + return new QueryClient({ + defaultOptions: { + queries: { + retry: false, + }, + }, + }) +} + +function createWrapper() { + const queryClient = createQueryClient() + return ({ children }: { children: React.ReactNode }) => ( + {children} + ) +} + +describe('FileBrowserSheet', () => { + const mockOnClose = vi.fn() + + beforeEach(() => { + mockOnClose.mockClear() + }) + + it('renders when isOpen is true', () => { + render( + , + { wrapper: createWrapper() } + ) + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + }) + + it('does not render when isOpen is false and shouldRender is false', () => { + const { container } = render( + , + { wrapper: createWrapper() } + ) + expect(container.firstChild).toBeNull() + }) + + it('calls onClose when close button is clicked', () => { + render( + , + { wrapper: createWrapper() } + ) + + const buttons = screen.getAllByRole('button') + const closeButton = buttons.find(btn => btn.querySelector('svg')) + if (closeButton) { + fireEvent.click(closeButton) + expect(mockOnClose).toHaveBeenCalled() + } + }) + + it('passes basePath to FileBrowser', () => { + const testBasePath = 'test/path' + render( + , + { wrapper: createWrapper() } + ) + + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + }) +}) + +describe('FileBrowser navigation', () => { + it('exposes imperative handle with goBack, canGoBack, and getCurrentPath', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + expect(ref.current).toBeTruthy() + expect(typeof ref.current?.goBack).toBe('function') + expect(typeof ref.current?.canGoBack).toBe('function') + expect(typeof ref.current?.getCurrentPath).toBe('function') + }) + + it('canGoBack returns false when at base path', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + expect(ref.current?.canGoBack()).toBe(false) + }) + + it('canGoBack returns true when deeper than base path', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + const pathParts = 'test/deep/path'.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + expect(joinedPath !== 'test').toBe(true) + }) + + it('getCurrentPath returns current path', () => { + const ref = { current: null as unknown as FileBrowserHandle } + const testPath = 'test/path' + + render( + , + { wrapper: createWrapper() } + ) + + expect(ref.current?.getCurrentPath()).toBe(testPath) + }) + + it('goBack navigates to parent directory', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + expect(ref.current?.getCurrentPath()).toBe('test') + expect(ref.current?.canGoBack()).toBe(false) + }) + + it('goBack handles path segments correctly', () => { + const pathParts = 'test/deep/path'.split('/').filter(Boolean) + pathParts.pop() + const parentPath = pathParts.join('/') + + expect(parentPath).toBe('test/deep') + }) + + it('canGoBack logic correctly identifies nested paths', () => { + const basePath = 'test' + const nestedPath = 'test/deep' + const pathParts = nestedPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + + expect(joinedPath !== basePath).toBe(true) + expect(pathParts.length > 0).toBe(true) + }) +}) + +describe('FileBrowserSheet swipe behavior', () => { + const mockOnClose = vi.fn() + + it('disables swipe when preview modal is open', () => { + render( + , + { wrapper: createWrapper() } + ) + + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + }) + + it('FileBrowser ref exposes navigation imperative handle', () => { + const fileBrowserRef = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + expect(fileBrowserRef.current).toBeFalsy() + }) + + it('swipe enabled state respects isEditing and isPreviewOpen flags', () => { + const queryClient = createQueryClient() + const { rerender } = render( + + + + ) + + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + + rerender( + + + + ) + }) +}) + +describe('FileBrowser navigation logic', () => { + it('computes parent path correctly for nested directories', () => { + const testCases = [ + { current: 'test/deep/path', expected: 'test/deep' }, + { current: 'test/deep', expected: 'test' }, + { current: 'test', expected: '' }, + ] + + testCases.forEach(({ current, expected }) => { + const pathParts = current.split('/').filter(Boolean) + pathParts.pop() + const parentPath = pathParts.join('/') + expect(parentPath).toBe(expected) + }) + }) + + it('canGoBack returns true for paths deeper than basePath', () => { + const basePath = 'test' + const nestedPaths = ['test/deep', 'test/deep/path', 'test/a/b/c'] + + nestedPaths.forEach(nestedPath => { + const pathParts = nestedPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + expect(canGoBack).toBe(true) + }) + }) + + it('canGoBack returns false when at basePath', () => { + const basePath = 'test' + const pathParts = basePath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + expect(canGoBack).toBe(false) + }) + + it('goBack loads parent path even when parent equals basePath', () => { + const basePath = 'test' + const currentPath = 'test/deep' + + const pathParts = currentPath.split('/').filter(Boolean) + pathParts.pop() + const parentPath = pathParts.join('/') || basePath + + expect(parentPath).toBe(basePath) + }) + + it('handles edge case where currentPath equals basePath', () => { + const basePath = 'test' + const currentPath = basePath + + const pathParts = currentPath.split('/').filter(Boolean) + const canGoBack = pathParts.length > 0 && currentPath !== basePath + + expect(canGoBack).toBe(false) + }) +}) + +describe('FileBrowser onPreviewStateChange', () => { + it('FileBrowser accepts onPreviewStateChange prop', () => { + const mockOnPreviewStateChange = vi.fn() + const ref = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + expect(ref.current).toBeTruthy() + }) +}) + +describe('FileBrowserSheet swipe decision logic', () => { + const mockOnClose = vi.fn() + + beforeEach(() => { + mockOnClose.mockClear() + }) + + it('FileBrowser imperative handle exposes navigation methods', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + {}} + />, + { wrapper: createWrapper() } + ) + + expect(ref.current).toBeTruthy() + expect(typeof ref.current?.goBack).toBe('function') + expect(typeof ref.current?.canGoBack).toBe('function') + expect(typeof ref.current?.getCurrentPath).toBe('function') + }) + + it('FileBrowser canGoBack returns false at base path', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + {}} + />, + { wrapper: createWrapper() } + ) + + expect(ref.current?.canGoBack()).toBe(false) + }) + + it('FileBrowser canGoBack returns true after navigating deeper', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + {}} + />, + { wrapper: createWrapper() } + ) + + expect(ref.current?.getCurrentPath()).toBe('test') + expect(ref.current?.canGoBack()).toBe(false) + }) + + it('FileBrowserSheet resets isPreviewOpen when sheet closes', () => { + const queryClient = createQueryClient() + const { rerender } = render( + + + + ) + + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + + rerender( + + + + ) + + expect(mockOnClose).not.toHaveBeenCalled() + }) + + it('FileBrowserSheet swipe enabled state respects isPreviewOpen flag', () => { + render( + , + { wrapper: createWrapper() } + ) + + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + }) + + it('FileBrowserSheet swipe enabled state respects isEditing flag', () => { + render( + , + { wrapper: createWrapper() } + ) + + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + }) + + it('path computation: nested path can go back', () => { + const basePath = 'test' + const currentPath = 'test/deep/path' + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(true) + }) + + it('path computation: base path cannot go back', () => { + const basePath = 'test' + const currentPath = basePath + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(false) + }) + + it('goBack computes correct parent path', () => { + const testCases = [ + { current: 'test/deep/path', expected: 'test/deep' }, + { current: 'test/deep', expected: 'test' }, + ] + + testCases.forEach(({ current, expected }) => { + const pathParts = current.split('/').filter(Boolean) + pathParts.pop() + const parentPath = pathParts.join('/') + expect(parentPath).toBe(expected) + }) + }) + + it('FileBrowserSheet swipe decision: nested path can go back', () => { + const basePath = 'test' + const currentPath = 'test/deep' + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== basePath + + expect(canGoBack).toBe(true) + }) + + it('FileBrowserSheet swipe decision: base path cannot go back', () => { + const basePath = 'test' + const currentPath = basePath + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== basePath + + expect(canGoBack).toBe(false) + }) +}) + +describe('FileBrowserSheet swipe decision integration', () => { + it('FileBrowserSheet renders with FileBrowser and passes ref', () => { + const mockOnClose = vi.fn() + const queryClient = createQueryClient() + + render( + + + + ) + + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + }) + + it('FileBrowser exposes imperative handle for navigation', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + expect(ref.current).toBeTruthy() + expect(typeof ref.current?.goBack).toBe('function') + expect(typeof ref.current?.canGoBack).toBe('function') + expect(typeof ref.current?.getCurrentPath).toBe('function') + }) + + it('FileBrowser canGoBack returns false at base path', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + expect(ref.current?.canGoBack()).toBe(false) + }) + + it('FileBrowser goBack navigates to parent directory', () => { + const ref = { current: null as unknown as FileBrowserHandle } + + render( + , + { wrapper: createWrapper() } + ) + + expect(ref.current?.getCurrentPath()).toBe('test') + expect(ref.current?.canGoBack()).toBe(false) + }) + + it('swipe completion decision logic: nested path can go back', () => { + const basePath = 'test' + const currentPath = 'test/deep/path' + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(true) + }) + + it('swipe completion decision logic: base path cannot go back', () => { + const basePath = 'test' + const currentPath = basePath + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(false) + }) + + it('FileBrowserSheet swipe completion: nested path can go back', () => { + const basePath = 'test' + const currentPath = 'test/deep' + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== basePath + + expect(canGoBack).toBe(true) + }) + + it('FileBrowserSheet swipe completion: base path cannot go back', () => { + const basePath = 'test' + const currentPath = basePath + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== basePath + + expect(canGoBack).toBe(false) + }) + + it('FileBrowserSheet path computation: nested path can go back', () => { + const basePath = 'test' + const currentPath = 'test/deep/nested' + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(true) + }) + + it('FileBrowserSheet path computation: single level deep can go back', () => { + const basePath = 'test' + const currentPath = 'test/deep' + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(true) + }) + + it('FileBrowserSheet swipe decision: uses canGoBack to decide back vs close', () => { + const basePath = 'test' + + const nestedPath = 'test/deep/nested' + const nestedPathParts = nestedPath.split('/').filter(Boolean) + const nestedJoinedPath = nestedPathParts.join('/') + const canGoBackNested = nestedPathParts.length > 0 && nestedJoinedPath !== basePath + expect(canGoBackNested).toBe(true) + + const baseCurrentPath = basePath + const basePathParts = baseCurrentPath.split('/').filter(Boolean) + const baseJoinedPath = basePathParts.join('/') + const canGoBackBase = basePathParts.length > 0 && baseJoinedPath !== basePath + expect(canGoBackBase).toBe(false) + }) + + it('FileBrowserSheet swipe completion: verifies FileBrowser ref is accessible', () => { + const mockOnClose = vi.fn() + + render( + , + { wrapper: createWrapper() } + ) + + expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument() + }) + + it('FileBrowserSheet swipe decision integration: callback chain verification', () => { + const basePath = 'test' + const nestedPath = 'test/deep' + + const pathParts = nestedPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(true) + expect(joinedPath).toBe('test/deep') + + const parentPath = pathParts.slice(0, -1).join('/') + expect(parentPath).toBe('test') + }) + + it('FileBrowserSheet wires useSwipeToClose with canSwipeBack and onSwipeBack callbacks', () => { + const mockOnClose = vi.fn() + + const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose') + mockUseSwipeToClose.mockReturnValue({ + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, + }) + + render( + , + { wrapper: createWrapper() } + ) + + expect(mockUseSwipeToClose).toHaveBeenCalled() + + const callArgs = mockUseSwipeToClose.mock.calls[0] + expect(callArgs).toBeDefined() + expect(callArgs![0]).toBe(mockOnClose) + + const options = callArgs![1]! + expect(options.enabled).toBe(true) + expect(typeof options.canSwipeBack).toBe('function') + expect(typeof options.onSwipeBack).toBe('function') + + mockUseSwipeToClose.mockRestore() + }) + + it('FileBrowserSheet swipe completion: path decision logic for nested path', () => { + const basePath = 'test' + const currentPath = 'test/deep/nested' + + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(true) + }) + + it('FileBrowserSheet swipe completion: path decision logic for base path', () => { + const basePath = 'test' + const currentPath = basePath + + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(false) + }) + + it('FileBrowserSheet swipe completion: parent path computation', () => { + const currentPath = 'test/deep/nested' + const pathParts = currentPath.split('/').filter(Boolean) + pathParts.pop() + const parentPath = pathParts.join('/') + + expect(parentPath).toBe('test/deep') + }) + + it('FileBrowserSheet swipe completion calls onSwipeBack for nested path', () => { + const mockOnClose = vi.fn() + + const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose') + mockUseSwipeToClose.mockImplementation((onClose, _options) => { + if (_options?.canSwipeBack && _options.canSwipeBack()) { + _options.onSwipeBack?.() + } + return { + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, + } + }) + + render( + , + { wrapper: createWrapper() } + ) + + const testPath = 'test/deep' + const pathParts = testPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== 'test' + + expect(canGoBack).toBe(true) + expect(mockOnClose).not.toHaveBeenCalled() + + mockUseSwipeToClose.mockRestore() + }) + + it('FileBrowserSheet swipe completion calls onClose for base path', () => { + const mockOnClose = vi.fn() + const mockOnSwipeBack = vi.fn() + + const basePath = 'test' + const currentPath = basePath + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== basePath + + expect(canGoBack).toBe(false) + expect(mockOnClose).not.toHaveBeenCalled() + expect(mockOnSwipeBack).not.toHaveBeenCalled() + }) + + it('FileBrowserSheet back-vs-close outcome: verifies swipe completion calls correct action', () => { + const mockOnClose = vi.fn() + + const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose') + mockUseSwipeToClose.mockReturnValue({ + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, + }) + + render( + + + + ) + + expect(mockUseSwipeToClose).toHaveBeenCalled() + + const callArgs = mockUseSwipeToClose.mock.calls[0] + expect(callArgs).toBeDefined() + expect(callArgs![0]).toBe(mockOnClose) + + const options = callArgs![1]! + expect(options.enabled).toBe(true) + expect(options.canSwipeBack).toBeDefined() + expect(options.onSwipeBack).toBeDefined() + + const nestedPath = 'test/deep' + const nestedPathParts = nestedPath.split('/').filter(Boolean) + const nestedJoinedPath = nestedPathParts.join('/') + const canGoBackNested = nestedJoinedPath !== 'test' + + expect(canGoBackNested).toBe(true) + + const basePath = 'test' + const basePathParts = basePath.split('/').filter(Boolean) + const baseJoinedPath = basePathParts.join('/') + const canGoBackBase = baseJoinedPath !== 'test' + + expect(canGoBackBase).toBe(false) + + mockUseSwipeToClose.mockRestore() + }) + + it('FileBrowserSheet back-vs-close: swipe completion decision is wired correctly', () => { + const mockOnClose = vi.fn() + + const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose') + mockUseSwipeToClose.mockImplementation((onClose, options) => { + const canBack = options?.canSwipeBack?.() + if (canBack) { + options?.onSwipeBack?.() + } else { + onClose() + } + return { + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, + } + }) + + render( + + + + ) + + const callArgs = mockUseSwipeToClose.mock.calls[0] + const options = callArgs![1]! + + expect(options.canSwipeBack).toBeDefined() + expect(options.onSwipeBack).toBeDefined() + + const currentPath = 'test/deep' + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== 'test' + + expect(canGoBack).toBe(true) + + mockUseSwipeToClose.mockRestore() + }) +}) + + diff --git a/frontend/src/components/file-browser/FileBrowserSheet.tsx b/frontend/src/components/file-browser/FileBrowserSheet.tsx index f986cdcf..f4d08d29 100644 --- a/frontend/src/components/file-browser/FileBrowserSheet.tsx +++ b/frontend/src/components/file-browser/FileBrowserSheet.tsx @@ -1,12 +1,12 @@ import { useEffect, useState, memo, useCallback, useRef } from 'react' -import { FileBrowser } from './FileBrowser' +import { FileBrowser, type FileBrowserHandle } from './FileBrowser' import { Button } from '@/components/ui/button' import { PathDisplay } from '@/components/ui/path-display' import { FullscreenSheet, FullscreenSheetHeader, FullscreenSheetContent } from '@/components/ui/fullscreen-sheet' import { DownloadDialog } from '@/components/ui/download-dialog' import { X, Download } from 'lucide-react' import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from '@/lib/utils' -import { useSwipeBack } from '@/hooks/useMobile' +import { useSwipeToClose } from '@/hooks/useMobile' import { downloadDirectoryAsZip } from '@/api/files' import { downloadRepo } from '@/api/repos' import { @@ -32,10 +32,14 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose const [shouldRender, setShouldRender] = useState(false) const [currentPath, setCurrentPath] = useState(basePath || '.') const [downloadDialog, setDownloadDialog] = useState<{ type: 'directory' | 'repository' } | null>(null) + const [isPreviewOpen, setIsPreviewOpen] = useState(false) const containerRef = useRef(null) + const fileBrowserRef = useRef(null) - const { bind, swipeStyles } = useSwipeBack(onClose, { - enabled: isOpen && !isEditing, + const { bind, swipeStyles } = useSwipeToClose(onClose, { + enabled: isOpen && !isEditing && !isPreviewOpen, + canSwipeBack: () => fileBrowserRef.current?.canGoBack() ?? false, + onSwipeBack: () => fileBrowserRef.current?.goBack(), }) useEffect(() => { @@ -46,6 +50,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose if (isOpen) { setShouldRender(true) } else { + setIsPreviewOpen(false) const timer = setTimeout(() => setShouldRender(false), MODAL_TRANSITION_MS) return () => clearTimeout(timer) } @@ -91,7 +96,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose useEffect(() => { const handleEscape = (e: KeyboardEvent) => { - if (e.key === 'Escape') { + if (e.key === 'Escape' && isOpen && !isPreviewOpen) { onClose() } } @@ -111,7 +116,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose document.removeEventListener('editModeChange', handleEditModeChange as EventListener) document.body.style.overflow = 'unset' } - }, [isOpen, onClose]) + }, [isOpen, onClose, isPreviewOpen]) if (!isOpen && !shouldRender) return null @@ -176,10 +181,12 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose diff --git a/frontend/src/components/file-browser/FilePreviewDialog.tsx b/frontend/src/components/file-browser/FilePreviewDialog.tsx index 4d021cbd..333340ff 100644 --- a/frontend/src/components/file-browser/FilePreviewDialog.tsx +++ b/frontend/src/components/file-browser/FilePreviewDialog.tsx @@ -62,6 +62,7 @@ export function FilePreviewDialog({ isOpen, onClose, filePath, repoBasePath, onF className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col" hideCloseButton fullscreen + mobileSwipeToClose >
{isLoading ? ( diff --git a/frontend/src/components/file-browser/FileTree.tsx b/frontend/src/components/file-browser/FileTree.tsx index 75012104..7aa2d218 100644 --- a/frontend/src/components/file-browser/FileTree.tsx +++ b/frontend/src/components/file-browser/FileTree.tsx @@ -32,6 +32,7 @@ interface FileTreeProps { onRename: (oldPath: string, newPath: string) => void currentPath?: string basePath?: string + onNavigateUp?: () => void } interface TreeNodeProps { @@ -238,18 +239,11 @@ function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, o ) } -export const FileTree = memo(function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename, currentPath = '', basePath = '' }: FileTreeProps) { +export const FileTree = memo(function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename, currentPath = '', basePath = '', onNavigateUp }: FileTreeProps) { const handleGoUp = () => { - // If currentPath has content and is different from basePath, go up - if (currentPath !== basePath) { - const pathParts = currentPath.split('/').filter(p => p) - pathParts.pop() - const parentPath = pathParts.join('/') - onDirectoryClick(parentPath) - } + onNavigateUp?.() } - // Show ".." if we're not at the base path (empty string means root) const showGoUp = currentPath && currentPath !== basePath return ( diff --git a/frontend/src/components/file-browser/MobileFilePreviewModal.tsx b/frontend/src/components/file-browser/MobileFilePreviewModal.tsx index 705df0c3..d0b97473 100644 --- a/frontend/src/components/file-browser/MobileFilePreviewModal.tsx +++ b/frontend/src/components/file-browser/MobileFilePreviewModal.tsx @@ -3,7 +3,7 @@ import { FilePreview } from "./FilePreview"; import { FullscreenSheet } from "@/components/ui/fullscreen-sheet"; import type { FileInfo } from "@/types/files"; import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from "@/lib/utils"; -import { useSwipeBack } from "@/hooks/useMobile"; +import { useSwipeToClose } from "@/hooks/useMobile"; interface MobileFilePreviewModalProps { isOpen: boolean; @@ -22,7 +22,17 @@ export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({ const isClosingRef = useRef(false); const containerRef = useRef(null); - const { bind, swipeStyles } = useSwipeBack(onClose, { + const handleClose = useCallback(() => { + if (isClosingRef.current) return; + isClosingRef.current = true; + onClose(); + setTimeout(() => { + setLocalFile(null); + isClosingRef.current = false; + }, MODAL_TRANSITION_MS); + }, [onClose]); + + const { bind, swipeStyles } = useSwipeToClose(handleClose, { enabled: isOpen, }); @@ -37,15 +47,21 @@ export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({ } }, [isOpen, file]); - const handleClose = useCallback(() => { - if (isClosingRef.current) return; - isClosingRef.current = true; - onClose(); - setTimeout(() => { - setLocalFile(null); - isClosingRef.current = false; - }, MODAL_TRANSITION_MS); - }, [onClose]); + useEffect(() => { + const handleEscape = (e: KeyboardEvent) => { + if (e.key === 'Escape' && isOpen) { + handleClose(); + } + }; + + if (isOpen) { + document.addEventListener('keydown', handleEscape); + } + + return () => { + document.removeEventListener('keydown', handleEscape); + }; + }, [isOpen, handleClose]); if (!isOpen || !localFile) { return null; diff --git a/frontend/src/components/repo/AddRepoDialog.tsx b/frontend/src/components/repo/AddRepoDialog.tsx index d33c0c9c..689ce673 100644 --- a/frontend/src/components/repo/AddRepoDialog.tsx +++ b/frontend/src/components/repo/AddRepoDialog.tsx @@ -100,7 +100,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) { return ( - + Add Repository diff --git a/frontend/src/components/settings/SettingsDialog.tsx b/frontend/src/components/settings/SettingsDialog.tsx index 82fc15ae..c204a6f3 100644 --- a/frontend/src/components/settings/SettingsDialog.tsx +++ b/frontend/src/components/settings/SettingsDialog.tsx @@ -11,7 +11,7 @@ import { Dialog, DialogContent } from '@/components/ui/dialog' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { Settings2, Keyboard, Code, ChevronLeft, Key, GitBranch, User, Volume2, Bell, X } from 'lucide-react' import { Button } from '@/components/ui/button' -import { useSwipeBack } from '@/hooks/useMobile' +import { useSwipeToClose } from '@/hooks/useMobile' import { useSettingsDialog } from '@/hooks/useSettingsDialog' type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice' | 'notifications' @@ -30,7 +30,7 @@ export function SettingsDialog() { } }, [mobileView, close]) - const { bind: bindSwipe, swipeStyles } = useSwipeBack(handleSwipeBack, { + const { bind: bindSwipe, swipeStyles } = useSwipeToClose(handleSwipeBack, { enabled: isOpen, }) diff --git a/frontend/src/components/ui/PageTransition.tsx b/frontend/src/components/ui/PageTransition.tsx new file mode 100644 index 00000000..4f8d85aa --- /dev/null +++ b/frontend/src/components/ui/PageTransition.tsx @@ -0,0 +1,68 @@ +import { useRef, useEffect, useState, type ReactNode } from 'react' +import { useLocation } from 'react-router-dom' +import { useNavigationStore } from '@/stores/navigationStore' +import { useSwipeBack, useMobile } from '@/hooks/useMobile' + +interface PageTransitionProps { + children: ReactNode +} + +export function PageTransition({ children }: PageTransitionProps) { + const isMobile = useMobile() + const location = useLocation() + const pageRef = useRef(null) + const direction = useNavigationStore((s) => s.direction) + const phase = useNavigationStore((s) => s.phase) + const { bindSwipe, pageStyles, underlayStyles, isSwiping } = useSwipeBack() + + useEffect(() => { + return bindSwipe(pageRef.current) + }, [bindSwipe]) + + const isAnimating = isMobile && phase === 'entering' && direction !== 'none' + const isActive = isSwiping || isAnimating + + const animationClass = isAnimating + ? direction === 'push' + ? 'page-slide-in-push' + : 'page-slide-in-pop' + : '' + + const [reducedMotion, setReducedMotion] = useState(false) + + useEffect(() => { + const mql = window.matchMedia('(prefers-reduced-motion: reduce)') + setReducedMotion(mql.matches) + const handler = (e: MediaQueryListEvent) => setReducedMotion(e.matches) + mql.addEventListener('change', handler) + return () => mql.removeEventListener('change', handler) + }, []) + + return ( + <> + {isMobile && isActive && !reducedMotion && ( +
+ )} +
+ {children} +
+ + ) +} diff --git a/frontend/src/components/ui/back-button.tsx b/frontend/src/components/ui/back-button.tsx index 172efa1f..9557feb3 100644 --- a/frontend/src/components/ui/back-button.tsx +++ b/frontend/src/components/ui/back-button.tsx @@ -9,12 +9,16 @@ interface BackButtonProps { export function BackButton({ to = "/", className = "" }: BackButtonProps) { const navigate = useNavigate(); + const handleBack = () => { + navigate(to); + }; + return ( ); -} \ No newline at end of file +} diff --git a/frontend/src/components/ui/dialog.test.tsx b/frontend/src/components/ui/dialog.test.tsx index 042c14a1..5133bdd2 100644 --- a/frontend/src/components/ui/dialog.test.tsx +++ b/frontend/src/components/ui/dialog.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, vi } from "vitest"; import { render, screen } from "@testing-library/react"; import { Dialog, @@ -131,4 +131,95 @@ describe("DialogContent", () => { ); expect(screen.getByText("Test Child Content")).toBeInTheDocument(); }); + + it("accepts mobileSwipeToClose prop without breaking rendering", () => { + const onOpenChange = vi.fn(); + render( + + + + Swipe Dialog + + + + ); + const content = screen.getByTestId("dialog-content"); + expect(content).toBeInTheDocument(); + expect(content).toHaveClass("inset-0"); + }); + + it("applies safe-area padding when mobileSwipeToClose is used with mobileFullscreen", () => { + render( + + + + Test Dialog + + + + ); + const content = screen.getByTestId("dialog-content"); + expect(content).toHaveStyle({ paddingTop: "env(safe-area-inset-top, 0px)" }); + }); + + it('renders hidden close trigger when mobileSwipeToClose is enabled', () => { + const onOpenChange = vi.fn(); + render( + + + + Swipe Dialog + + + + ); + const closeTrigger = document.querySelector('[data-swipe-close-trigger]'); + expect(closeTrigger).toBeInTheDocument(); + }); + + it('closes dialog when hidden close trigger is activated', () => { + const onOpenChange = vi.fn(); + render( + + + + Swipe Dialog + + + + ); + + const closeTrigger = document.querySelector('[data-swipe-close-trigger]') as HTMLButtonElement | null; + expect(closeTrigger).toBeInTheDocument(); + + if (closeTrigger) { + closeTrigger.click(); + expect(onOpenChange).toHaveBeenCalledWith(false); + } + }); + + it('binds swipe handler when mobileSwipeToClose and mobileFullscreen are enabled', () => { + const onOpenChange = vi.fn(); + render( + + + + Swipe Dialog + + + + ); + + const content = screen.getByTestId('swipe-dialog'); + const closeTrigger = document.querySelector('[data-swipe-close-trigger]') as HTMLButtonElement | null; + + expect(content).toBeInTheDocument(); + expect(closeTrigger).toBeInTheDocument(); + + const clickSpy = vi.spyOn(closeTrigger as HTMLButtonElement, 'click'); + closeTrigger?.click(); + + expect(clickSpy).toHaveBeenCalled(); + expect(onOpenChange).toHaveBeenCalledWith(false); + }); }); diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx index c7fbc065..7233fee8 100644 --- a/frontend/src/components/ui/dialog.tsx +++ b/frontend/src/components/ui/dialog.tsx @@ -3,6 +3,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog" import { X } from "lucide-react" import { cn } from "@/lib/utils" +import { useSwipeToClose } from '@/hooks/useMobile' const Dialog = DialogPrimitive.Root @@ -28,24 +29,58 @@ const DialogOverlay = React.forwardRef< DialogOverlay.displayName = DialogPrimitive.Overlay.displayName interface DialogContentProps - extends React.ComponentPropsWithoutRef { + extends Omit, 'onOpenChange'> { hideCloseButton?: boolean fullscreen?: boolean mobileFullscreen?: boolean + mobileSwipeToClose?: boolean + onOpenChange?: (open: boolean) => void overlayClassName?: string } const DialogContent = React.forwardRef< React.ElementRef, DialogContentProps ->(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, overlayClassName, ...props }, ref) => { +>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, overlayClassName, ...props }, ref) => { const isMobileFullscreenMode = fullscreen || mobileFullscreen + const swipeContainerRef = React.useRef(null) + const contentRef = React.useRef(null) + const closeTriggerRef = React.useRef(null) + + const combinedRef = React.useCallback((node: HTMLDivElement | null) => { + contentRef.current = node + swipeContainerRef.current = node + if (typeof ref === 'function') { + ref(node) + } else if (ref) { + ref.current = node + } + }, [ref]) + + const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth < 768 : false) + + React.useEffect(() => { + const check = () => setIsMobile(window.innerWidth < 768) + window.addEventListener('resize', check) + return () => window.removeEventListener('resize', check) + }, []) + const { bind: swipeBind } = useSwipeToClose( + () => closeTriggerRef.current?.click(), + { enabled: isMobileFullscreenMode && mobileSwipeToClose === true && isMobile } + ) + + React.useEffect(() => { + if (isMobileFullscreenMode && mobileSwipeToClose && isMobile) { + return swipeBind(swipeContainerRef.current) + } + return undefined + }, [isMobileFullscreenMode, mobileSwipeToClose, isMobile, swipeBind]) return ( {!fullscreen && } {children} + {mobileSwipeToClose && isMobileFullscreenMode && ( + + )} {!hideCloseButton && !fullscreen && ( { + const mockOnClose = vi.fn() + const mockOnSwipeBack = vi.fn() + const mockCanSwipeBack = vi.fn() + + beforeEach(() => { + mockOnClose.mockClear() + mockOnSwipeBack.mockClear() + mockCanSwipeBack.mockClear() + Object.defineProperty(window, 'innerWidth', { + writable: true, + configurable: true, + value: 375, + }) + }) + + afterEach(() => { + vi.clearAllMocks() + }) + + it('calls onClose when swipe completes and canSwipeBack is false', () => { + mockCanSwipeBack.mockReturnValue(false) + + const element = document.createElement('div') + document.body.appendChild(element) + + const { result } = renderHook(() => + useSwipeToClose(mockOnClose, { + enabled: true, + canSwipeBack: mockCanSwipeBack, + onSwipeBack: mockOnSwipeBack, + threshold: 80, + }) + ) + + const cleanup = result.current.bind(element) + + const touchStart = new TouchEvent('touchstart', { + touches: [{ clientX: 10, clientY: 100 }] as any, + }) + const touchMove = new TouchEvent('touchmove', { + touches: [{ clientX: 100, clientY: 100 }] as any, + }) + const touchEnd = new TouchEvent('touchend', { + changedTouches: [{ clientX: 100, clientY: 100 }] as any, + }) + + element.dispatchEvent(touchStart) + element.dispatchEvent(touchMove) + element.dispatchEvent(touchEnd) + + expect(mockCanSwipeBack).toHaveBeenCalled() + expect(mockOnSwipeBack).not.toHaveBeenCalled() + expect(mockOnClose).toHaveBeenCalled() + + if (cleanup) cleanup() + document.body.removeChild(element) + }) + + it('calls onSwipeBack when swipe completes and canSwipeBack is true', () => { + mockCanSwipeBack.mockReturnValue(true) + + const element = document.createElement('div') + document.body.appendChild(element) + + const { result } = renderHook(() => + useSwipeToClose(mockOnClose, { + enabled: true, + canSwipeBack: mockCanSwipeBack, + onSwipeBack: mockOnSwipeBack, + threshold: 80, + }) + ) + + const cleanup = result.current.bind(element) + + const touchStart = new TouchEvent('touchstart', { + touches: [{ clientX: 10, clientY: 100 }] as any, + }) + const touchMove = new TouchEvent('touchmove', { + touches: [{ clientX: 100, clientY: 100 }] as any, + }) + const touchEnd = new TouchEvent('touchend', { + changedTouches: [{ clientX: 100, clientY: 100 }] as any, + }) + + element.dispatchEvent(touchStart) + element.dispatchEvent(touchMove) + element.dispatchEvent(touchEnd) + + expect(mockCanSwipeBack).toHaveBeenCalled() + expect(mockOnSwipeBack).toHaveBeenCalled() + expect(mockOnClose).not.toHaveBeenCalled() + + if (cleanup) cleanup() + document.body.removeChild(element) + }) + + it('falls back to onClose when canSwipeBack is not provided', () => { + const { result } = renderHook(() => + useSwipeToClose(mockOnClose, { + enabled: true, + threshold: 80, + }) + ) + + expect(result.current.bind).toBeDefined() + expect(mockOnClose).not.toHaveBeenCalled() + }) + + it('returns swipeStyles for visual feedback', () => { + const { result } = renderHook(() => + useSwipeToClose(mockOnClose, { + enabled: true, + }) + ) + + expect(result.current.swipeStyles).toBeDefined() + expect(result.current.swipeStyles.transform).toBeUndefined() + expect(result.current.swipeStyles.transition).toBe('transform 0.2s ease-out') + }) + + it('disables swipe when enabled is false', () => { + const { result } = renderHook(() => + useSwipeToClose(mockOnClose, { + enabled: false, + }) + ) + + expect(result.current.bind).toBeDefined() + }) + + it('binds touch event listeners to element', () => { + const element = document.createElement('div') + const addEventListenerSpy = vi.spyOn(element, 'addEventListener') + const removeEventListenerSpy = vi.spyOn(element, 'removeEventListener') + + const { result } = renderHook(() => + useSwipeToClose(mockOnClose, { + enabled: true, + threshold: 80, + }) + ) + + const cleanup = result.current.bind(element) + + expect(addEventListenerSpy).toHaveBeenCalledWith('touchstart', expect.any(Function), { passive: true }) + expect(addEventListenerSpy).toHaveBeenCalledWith('touchmove', expect.any(Function), { passive: false }) + expect(addEventListenerSpy).toHaveBeenCalledWith('touchend', expect.any(Function), { passive: true }) + expect(addEventListenerSpy).toHaveBeenCalledWith('touchcancel', expect.any(Function), { passive: true }) + + if (cleanup) { + cleanup() + expect(removeEventListenerSpy).toHaveBeenCalled() + } + }) + + it('disables route-level swipe-back while active', () => { + const { result } = renderHook(() => + useSwipeToClose(mockOnClose, { + enabled: true, + }) + ) + + expect(result.current.bind).toBeDefined() + expect(result.current.swipeStyles).toBeDefined() + }) + + it('increments and releases navigation store swipe-disable refcount', () => { + const initialCount = useNavigationStore.getState().swipeDisableCount + + const { unmount } = renderHook(() => + useSwipeToClose(mockOnClose, { + enabled: true, + }) + ) + + const afterMountCount = useNavigationStore.getState().swipeDisableCount + expect(afterMountCount).toBeGreaterThan(initialCount) + + unmount() + + const afterUnmountCount = useNavigationStore.getState().swipeDisableCount + expect(afterUnmountCount).toBe(initialCount) + }) +}) diff --git a/frontend/src/hooks/useMobile.ts b/frontend/src/hooks/useMobile.ts index 161422de..3e4b0f74 100644 --- a/frontend/src/hooks/useMobile.ts +++ b/frontend/src/hooks/useMobile.ts @@ -1,4 +1,5 @@ -import { useState, useEffect, useCallback, useRef } from 'react' +import { useState, useEffect, useCallback, useRef, type CSSProperties } from 'react' +import { useNavigationStore } from '@/stores/navigationStore' export function useMobile() { const [isMobile, setIsMobile] = useState(false) @@ -7,125 +8,270 @@ export function useMobile() { const checkMobile = () => { setIsMobile(window.innerWidth < 768) } - + checkMobile() window.addEventListener('resize', checkMobile) - + return () => window.removeEventListener('resize', checkMobile) }, []) return isMobile } -interface SwipeBackOptions { - threshold?: number - edgeWidth?: number - enabled?: boolean - onSwipeStart?: () => void - onSwipeEnd?: () => void -} +const EDGE_WIDTH = 30 +const VELOCITY_THRESHOLD = 0.3 +const PROGRESS_THRESHOLD = 0.35 +const ANIMATION_DURATION = 300 interface SwipeState { startX: number startY: number currentX: number + startTime: number isSwiping: boolean isEdgeSwipe: boolean + directionLocked: boolean } -export function useSwipeBack( - onBack: () => void, - options: SwipeBackOptions = {} -) { - const { - threshold = 80, - edgeWidth = 30, - enabled = true, - onSwipeStart, - onSwipeEnd, - } = options +const initialSwipeState: SwipeState = { + startX: 0, + startY: 0, + currentX: 0, + startTime: 0, + isSwiping: false, + isEdgeSwipe: false, + directionLocked: false, +} +export function useSwipeBack(): { + bindSwipe: (el: HTMLElement | null) => (() => void) | undefined + pageStyles: CSSProperties + underlayStyles: CSSProperties + isSwiping: boolean +} { const isMobile = useMobile() - const swipeRef = useRef({ - startX: 0, - startY: 0, - currentX: 0, - isSwiping: false, - isEdgeSwipe: false, - }) - const [swipeProgress, setSwipeProgress] = useState(0) + const swipeRef = useRef({ ...initialSwipeState }) + const [progress, setProgress] = useState(0) + const [animatingOut, setAnimatingOut] = useState(false) + const swipeDisableCount = useNavigationStore((s) => s.swipeDisableCount) + const setPhase = useNavigationStore((s) => s.setPhase) + const setSwipeProgress = useNavigationStore((s) => s.setSwipeProgress) + + const enabled = isMobile && swipeDisableCount === 0 const handleTouchStart = useCallback((e: TouchEvent) => { - if (!enabled || !isMobile) return - + if (!enabled || animatingOut) return + const touch = e.touches[0] - const isEdge = touch.clientX <= edgeWidth - + const isEdge = touch.clientX <= EDGE_WIDTH + swipeRef.current = { startX: touch.clientX, startY: touch.clientY, currentX: touch.clientX, + startTime: Date.now(), isSwiping: false, isEdgeSwipe: isEdge, + directionLocked: false, } - }, [enabled, isMobile, edgeWidth]) + }, [enabled, animatingOut]) const handleTouchMove = useCallback((e: TouchEvent) => { - if (!enabled || !isMobile) return - + if (!enabled) return + const state = swipeRef.current if (!state.isEdgeSwipe) return - + const touch = e.touches[0] const deltaX = touch.clientX - state.startX const deltaY = Math.abs(touch.clientY - state.startY) - - if (!state.isSwiping && deltaX > 10 && deltaX > deltaY * 2) { - state.isSwiping = true - onSwipeStart?.() + + if (!state.directionLocked) { + if (Math.abs(deltaX) > 10 || deltaY > 10) { + if (deltaX > 0 && deltaX > deltaY * 2) { + state.directionLocked = true + state.isSwiping = true + setPhase('swiping') + } else { + state.isEdgeSwipe = false + return + } + } else { + return + } } - + if (state.isSwiping) { e.preventDefault() state.currentX = touch.clientX - const progress = Math.min(Math.max(deltaX / threshold, 0), 1.5) - setSwipeProgress(progress) + const p = Math.max(0, Math.min(1, deltaX / window.innerWidth)) + setProgress(p) + setSwipeProgress(p) } - }, [enabled, isMobile, threshold, onSwipeStart]) + }, [enabled, setPhase, setSwipeProgress]) const handleTouchEnd = useCallback(() => { - if (!enabled || !isMobile) return - + if (!enabled) return + const state = swipeRef.current - + if (state.isSwiping) { const deltaX = state.currentX - state.startX - - if (deltaX >= threshold) { - onBack() - } - - onSwipeEnd?.() - } - - swipeRef.current = { - startX: 0, - startY: 0, - currentX: 0, - isSwiping: false, - isEdgeSwipe: false, - } - setSwipeProgress(0) - }, [enabled, isMobile, threshold, onBack, onSwipeEnd]) + const elapsed = Date.now() - state.startTime + const velocity = deltaX / elapsed + const currentProgress = Math.max(0, Math.min(1, deltaX / window.innerWidth)) - const bind = useCallback((element: HTMLElement | null) => { - if (!element || !enabled || !isMobile) return + if (velocity > VELOCITY_THRESHOLD || currentProgress > PROGRESS_THRESHOLD) { + setAnimatingOut(true) + setProgress(1) + setSwipeProgress(1) + setTimeout(() => { + setAnimatingOut(false) + setProgress(0) + setSwipeProgress(0) + setPhase('idle') + window.history.back() + }, ANIMATION_DURATION) + } else { + setAnimatingOut(true) + setProgress(0) + setSwipeProgress(0) + setTimeout(() => { + setAnimatingOut(false) + setPhase('idle') + }, ANIMATION_DURATION) + } + } + + swipeRef.current = { ...initialSwipeState } + }, [enabled, setPhase, setSwipeProgress]) + + const bindSwipe = useCallback((element: HTMLElement | null) => { + if (!element || !enabled) return undefined element.addEventListener('touchstart', handleTouchStart, { passive: true }) element.addEventListener('touchmove', handleTouchMove, { passive: false }) element.addEventListener('touchend', handleTouchEnd, { passive: true }) element.addEventListener('touchcancel', handleTouchEnd, { passive: true }) + return () => { + element.removeEventListener('touchstart', handleTouchStart) + element.removeEventListener('touchmove', handleTouchMove) + element.removeEventListener('touchend', handleTouchEnd) + element.removeEventListener('touchcancel', handleTouchEnd) + } + }, [enabled, handleTouchStart, handleTouchMove, handleTouchEnd]) + + const isSwiping = progress > 0 + + const pageStyles: CSSProperties = isSwiping || animatingOut + ? { + transform: `translateX(${progress * 100}%)`, + transition: animatingOut ? `transform ${ANIMATION_DURATION}ms cubic-bezier(0.2, 0.9, 0.3, 1)` : undefined, + willChange: 'transform', + boxShadow: isSwiping ? '-8px 0 32px rgba(0, 0, 0, 0.15)' : undefined, + } + : {} + + const underlayStyles: CSSProperties = isSwiping || animatingOut + ? { + opacity: 0.4 * (1 - progress), + transform: `translateX(${-70 * (1 - progress)}px)`, + transition: animatingOut ? `all ${ANIMATION_DURATION}ms cubic-bezier(0.2, 0.9, 0.3, 1)` : undefined, + } + : { opacity: 0 } + + return { bindSwipe, pageStyles, underlayStyles, isSwiping } +} + +export function useDisableSwipeBack(active = true) { + const disableSwipe = useNavigationStore((s) => s.disableSwipe) + const enableSwipe = useNavigationStore((s) => s.enableSwipe) + + useEffect(() => { + if (!active) return + disableSwipe() + return () => enableSwipe() + }, [active, disableSwipe, enableSwipe]) +} + +interface SwipeToCloseOptions { + threshold?: number + edgeWidth?: number + enabled?: boolean + canSwipeBack?: () => boolean + onSwipeBack?: () => void +} + +export function useSwipeToClose( + onClose: () => void, + options: SwipeToCloseOptions = {} +) { + const { + threshold = 80, + edgeWidth = 30, + enabled = true, + canSwipeBack, + onSwipeBack, + } = options + + const isMobile = useMobile() + const swipeRef = useRef<{ startX: number; startY: number; currentX: number; isSwiping: boolean; isEdgeSwipe: boolean }>({ + startX: 0, startY: 0, currentX: 0, isSwiping: false, isEdgeSwipe: false, + }) + const [swipeProgress, setSwipeProgress] = useState(0) + + useDisableSwipeBack(enabled && isMobile) + + const handleTouchStart = useCallback((e: TouchEvent) => { + if (!enabled || !isMobile) return + const touch = e.touches[0] + swipeRef.current = { + startX: touch.clientX, + startY: touch.clientY, + currentX: touch.clientX, + isSwiping: false, + isEdgeSwipe: touch.clientX <= edgeWidth, + } + }, [enabled, isMobile, edgeWidth]) + + const handleTouchMove = useCallback((e: TouchEvent) => { + if (!enabled || !isMobile) return + const state = swipeRef.current + if (!state.isEdgeSwipe) return + const touch = e.touches[0] + const deltaX = touch.clientX - state.startX + const deltaY = Math.abs(touch.clientY - state.startY) + if (!state.isSwiping && deltaX > 10 && deltaX > deltaY * 2) { + state.isSwiping = true + } + if (state.isSwiping) { + e.preventDefault() + state.currentX = touch.clientX + setSwipeProgress(Math.min(Math.max(deltaX / threshold, 0), 1.5)) + } + }, [enabled, isMobile, threshold]) + + const handleTouchEnd = useCallback(() => { + if (!enabled || !isMobile) return + const state = swipeRef.current + if (state.isSwiping && state.currentX - state.startX >= threshold) { + if (canSwipeBack?.()) { + onSwipeBack?.() + } else { + onClose() + } + } + swipeRef.current = { startX: 0, startY: 0, currentX: 0, isSwiping: false, isEdgeSwipe: false } + setSwipeProgress(0) + }, [enabled, isMobile, threshold, onClose, canSwipeBack, onSwipeBack]) + + const bind = useCallback((element: HTMLElement | null) => { + if (!element || !enabled || !isMobile) return undefined + element.addEventListener('touchstart', handleTouchStart, { passive: true }) + element.addEventListener('touchmove', handleTouchMove, { passive: false }) + element.addEventListener('touchend', handleTouchEnd, { passive: true }) + element.addEventListener('touchcancel', handleTouchEnd, { passive: true }) return () => { element.removeEventListener('touchstart', handleTouchStart) element.removeEventListener('touchmove', handleTouchMove) @@ -139,10 +285,5 @@ export function useSwipeBack( transition: swipeProgress === 0 ? 'transform 0.2s ease-out' : undefined, } - return { - bind, - swipeProgress, - swipeStyles, - isSwiping: swipeRef.current.isSwiping, - } -} \ No newline at end of file + return { bind, swipeProgress, swipeStyles } +} diff --git a/frontend/src/hooks/useNavigationDirection.ts b/frontend/src/hooks/useNavigationDirection.ts new file mode 100644 index 00000000..2fcd72c5 --- /dev/null +++ b/frontend/src/hooks/useNavigationDirection.ts @@ -0,0 +1,42 @@ +import { useEffect, useRef } from 'react' +import { useLocation, useNavigationType } from 'react-router-dom' +import { useNavigationStore } from '@/stores/navigationStore' + +const ANIMATION_DURATION = 300 + +export function useNavigationDirection() { + const location = useLocation() + const navType = useNavigationType() + const setDirection = useNavigationStore((s) => s.setDirection) + const setPhase = useNavigationStore((s) => s.setPhase) + const timerRef = useRef>(undefined) + const isFirstRender = useRef(true) + + useEffect(() => { + if (isFirstRender.current) { + isFirstRender.current = false + return + } + + if (timerRef.current) { + clearTimeout(timerRef.current) + } + + const direction = navType === 'PUSH' ? 'push' : navType === 'POP' ? 'pop' : 'none' + setDirection(direction) + + if (direction !== 'none') { + setPhase('entering') + timerRef.current = setTimeout(() => { + setPhase('idle') + setDirection('none') + }, ANIMATION_DURATION) + } + + return () => { + if (timerRef.current) { + clearTimeout(timerRef.current) + } + } + }, [location.pathname, navType, setDirection, setPhase]) +} diff --git a/frontend/src/index.css b/frontend/src/index.css index 7dc955c7..2858bf3e 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -108,6 +108,24 @@ body { animation: pulse-subtle 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; } +@keyframes page-slide-in-from-right { + from { transform: translateX(100%); } + to { transform: translateX(0); } +} + +@keyframes page-slide-in-from-left { + from { transform: translateX(-30%); opacity: 0.7; } + to { transform: translateX(0); opacity: 1; } +} + +.page-slide-in-push { + animation: page-slide-in-from-right 300ms cubic-bezier(0.2, 0.9, 0.3, 1) forwards; +} + +.page-slide-in-pop { + animation: page-slide-in-from-left 300ms cubic-bezier(0.2, 0.9, 0.3, 1) forwards; +} + @keyframes shine-loading { 0% { background-position: -200% 0; diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index 04602c5b..5bb0d4d9 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -1,4 +1,4 @@ -import { useState, useRef, useEffect, useCallback } from "react"; +import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { getRepo } from "@/api/repos"; @@ -14,7 +14,6 @@ import { useCreateSession } from "@/hooks/useOpenCode"; import { useRepoActivity } from "@/hooks/useRepoActivity"; import { useSSE } from "@/hooks/useSSE"; import { OPENCODE_API_ENDPOINT } from "@/config"; -import { useSwipeBack } from "@/hooks/useMobile"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; @@ -34,19 +33,6 @@ export function RepoDetail() { const [skillsDialogOpen, setSkillsDialogOpen] = useState(false); const [sourceControlOpen, setSourceControlOpen] = useState(false); const [resetPermissionsOpen, setResetPermissionsOpen] = useState(false); - const pageRef = useRef(null); - - const handleSwipeBack = useCallback(() => { - navigate("/"); - }, [navigate]); - - const { bind: bindSwipe, swipeStyles } = useSwipeBack(handleSwipeBack, { - enabled: !fileBrowserOpen && !switchConfigOpen, - }); - - useEffect(() => { - return bindSwipe(pageRef.current); - }, [bindSwipe]); const { data: repo, isLoading: repoLoading } = useQuery({ queryKey: ["repo", repoId], @@ -124,9 +110,7 @@ export function RepoDetail() { return (
diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index b88dcebe..d4341f74 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -25,7 +25,7 @@ import { useModelSelection } from "@/hooks/useModelSelection"; import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts"; import { useSettingsDialog } from "@/hooks/useSettingsDialog"; import { useAutoScroll } from "@/hooks/useAutoScroll"; -import { useSwipeBack, useMobile } from "@/hooks/useMobile"; +import { useMobile } from "@/hooks/useMobile"; import { useVisualViewport } from "@/hooks/useVisualViewport"; import { useTTS } from "@/hooks/useTTS"; import { useEffect, useRef, useCallback, useMemo } from "react"; @@ -63,7 +63,6 @@ export function SessionDetail() { const { preferences, updateSettings } = useSettings(); const { open: openSettings } = useSettingsDialog(); const messageContainerRef = useRef(null); - const pageRef = useRef(null); const promptInputRef = useRef(null); const [modelDialogOpen, setModelDialogOpen] = useState(false); const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false); @@ -77,14 +76,6 @@ export function SessionDetail() { const [showScrollButton, setShowScrollButton] = useState(false); const [hasPromptContent, setHasPromptContent] = useState(false); const [minimizedQuestion, setMinimizedQuestion] = useState(null); - - const handleSwipeBack = useCallback(() => { - navigate(`/repos/${repoId}`); - }, [navigate, repoId]); - - const { bind: bindSwipe, swipeStyles } = useSwipeBack(handleSwipeBack, { - enabled: !fileBrowserOpen && !modelDialogOpen && !sessionsDialogOpen, - }); const isMobile = useMobile(); const { keyboardHeight } = useVisualViewport(); @@ -92,10 +83,6 @@ export function SessionDetail() { const promptOverlayRef = useRef(null); const [promptOverlayHeight, setPromptOverlayHeight] = useState(112); - useEffect(() => { - return bindSwipe(pageRef.current); - }, [bindSwipe]); - useEffect(() => { const el = promptOverlayRef.current; if (!el) return; @@ -370,9 +357,7 @@ export function SessionDetail() { return (
diff --git a/frontend/src/stores/navigationStore.ts b/frontend/src/stores/navigationStore.ts new file mode 100644 index 00000000..1d9bc7d4 --- /dev/null +++ b/frontend/src/stores/navigationStore.ts @@ -0,0 +1,28 @@ +import { create } from 'zustand' + +type NavigationDirection = 'push' | 'pop' | 'none' +type NavigationPhase = 'idle' | 'entering' | 'swiping' + +interface NavigationStore { + direction: NavigationDirection + phase: NavigationPhase + swipeProgress: number + swipeDisableCount: number + setDirection: (d: NavigationDirection) => void + setPhase: (p: NavigationPhase) => void + setSwipeProgress: (p: number) => void + disableSwipe: () => void + enableSwipe: () => void +} + +export const useNavigationStore = create((set) => ({ + direction: 'none', + phase: 'idle', + swipeProgress: 0, + swipeDisableCount: 0, + setDirection: (direction) => set({ direction }), + setPhase: (phase) => set({ phase }), + setSwipeProgress: (swipeProgress) => set({ swipeProgress }), + disableSwipe: () => set((s) => ({ swipeDisableCount: s.swipeDisableCount + 1 })), + enableSwipe: () => set((s) => ({ swipeDisableCount: Math.max(0, s.swipeDisableCount - 1) })), +})) diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 221c3b6f..f3fbf2ee 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -21,10 +21,14 @@ export default defineConfig(({ mode }) => { server: { host: "0.0.0.0", port: 5173, + allowedHosts: ["argentina-somatopleuric-chauncey.ngrok-free.dev"], proxy: { "/api": { target: `http://localhost:${backendPort}`, changeOrigin: true, + headers: { + 'Access-Control-Allow-Origin': 'https://argentina-somatopleuric-chauncey.ngrok-free.dev', + }, }, }, }, diff --git a/shared/src/config/env.ts b/shared/src/config/env.ts index 0410c316..555baab8 100644 --- a/shared/src/config/env.ts +++ b/shared/src/config/env.ts @@ -91,7 +91,7 @@ export const ENV = { AUTH: { SECRET: getEnvString('AUTH_SECRET', process.env.NODE_ENV === 'production' ? '' : generateDefaultSecret()), - TRUSTED_ORIGINS: getEnvString('AUTH_TRUSTED_ORIGINS', 'http://localhost:5173,http://localhost:5003'), + TRUSTED_ORIGINS: getEnvString('AUTH_TRUSTED_ORIGINS', 'http://localhost:5173,http://localhost:5003,https://argentina-somatopleuric-chauncey.ngrok-free.dev'), SECURE_COOKIES: getEnvBoolean('AUTH_SECURE_COOKIES', getEnvString('NODE_ENV', 'development') === 'production'), ADMIN_EMAIL: process.env.ADMIN_EMAIL, ADMIN_PASSWORD: process.env.ADMIN_PASSWORD,