feat: add mobile swipe-back navigation and gestures

- Implement swipe-to-close for mobile modals and dialogs
- Add PageTransition component with push/pop animations
- Create navigation store for managing navigation state
- Add useNavigationDirection hook for animation direction
- Implement useSwipeToClose hook for swipe gestures
- Add prefers-reduced-motion accessibility support
- Create FileBrowserSheet component for mobile file browser
- Add comprehensive tests for swipe behavior and navigation
- Update FileBrowser, Dialog, and BackButton components
- Configure Vite for proper CSS handling
This commit is contained in:
Chris Scott committed 2026-04-15 12:44:33 -04:00
1 parent 46731210e8
commit 9d94c333b4
23 files changed
+1684 -161

No files matched your search

@@ -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<File> {
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<FileBrowserHandle, FileBrowserProps>(function FileBrowser({ basePath = '', onFileSelect, embedded = false, initialSelectedFile, onDirectoryLoad, onPreviewStateChange }, ref) {
const [currentPath, setCurrentPath] = useState(basePath)
const [files, setFiles] = useState<FileInfo | null>(null)
const [selectedFile, setSelectedFile] = useState<FileInfo | null>(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 = (
<Dialog open={!!uploadProgress} onOpenChange={(open) => { if (!open && canDismissDialog) setUploadProgress(null) }}>
<Dialog open={!!uploadProgress} onOpenChange={(open: boolean) => { if (!open && canDismissDialog) setUploadProgress(null) }}>
<DialogContent className="sm:max-w-md" hideCloseButton={!canDismissDialog}>
<DialogHeader>
<DialogTitle className="flex items-center justify-between">
@@ -525,6 +556,7 @@ useEffect(() => {
onRename={handleRename}
currentPath={currentPath}
basePath={basePath}
onNavigateUp={goToParentDirectory}
/>
)}
</div>
@@ -624,6 +656,7 @@ useEffect(() => {
onRename={handleRename}
currentPath={currentPath}
basePath={basePath}
onNavigateUp={goToParentDirectory}
/>
</div>
)}
@@ -654,4 +687,4 @@ useEffect(() => {
{uploadDialog}
</div>
)
}
})
@@ -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 }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
describe('FileBrowserSheet', () => {
const mockOnClose = vi.fn()
beforeEach(() => {
mockOnClose.mockClear()
})
it('renders when isOpen is true', () => {
render(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>,
{ wrapper: createWrapper() }
)
expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument()
})
it('does not render when isOpen is false and shouldRender is false', () => {
const { container } = render(
<FileBrowserSheet
isOpen={false}
onClose={mockOnClose}
/>,
{ wrapper: createWrapper() }
)
expect(container.firstChild).toBeNull()
})
it('calls onClose when close button is clicked', () => {
render(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
/>,
{ 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(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath={testBasePath}
/>,
{ 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(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
/>,
{ 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(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
/>,
{ 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(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
/>,
{ 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(
<FileBrowser
ref={ref as any}
basePath={testPath}
embedded={true}
/>,
{ wrapper: createWrapper() }
)
expect(ref.current?.getCurrentPath()).toBe(testPath)
})
it('goBack navigates to parent directory', () => {
const ref = { current: null as unknown as FileBrowserHandle }
render(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
/>,
{ 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(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>,
{ wrapper: createWrapper() }
)
expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument()
})
it('FileBrowser ref exposes navigation imperative handle', () => {
const fileBrowserRef = { current: null as unknown as FileBrowserHandle }
render(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test/path"
/>,
{ wrapper: createWrapper() }
)
expect(fileBrowserRef.current).toBeFalsy()
})
it('swipe enabled state respects isEditing and isPreviewOpen flags', () => {
const queryClient = createQueryClient()
const { rerender } = render(
<QueryClientProvider client={queryClient}>
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>
</QueryClientProvider>
)
expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument()
rerender(
<QueryClientProvider client={queryClient}>
<FileBrowserSheet
isOpen={false}
onClose={mockOnClose}
basePath="test"
/>
</QueryClientProvider>
)
})
})
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(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
onPreviewStateChange={mockOnPreviewStateChange}
/>,
{ 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(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
onPreviewStateChange={() => {}}
/>,
{ 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(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
onPreviewStateChange={() => {}}
/>,
{ 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(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
onPreviewStateChange={() => {}}
/>,
{ 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(
<QueryClientProvider client={queryClient}>
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>
</QueryClientProvider>
)
expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument()
rerender(
<QueryClientProvider client={queryClient}>
<FileBrowserSheet
isOpen={false}
onClose={mockOnClose}
basePath="test"
/>
</QueryClientProvider>
)
expect(mockOnClose).not.toHaveBeenCalled()
})
it('FileBrowserSheet swipe enabled state respects isPreviewOpen flag', () => {
render(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>,
{ wrapper: createWrapper() }
)
expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument()
})
it('FileBrowserSheet swipe enabled state respects isEditing flag', () => {
render(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>,
{ 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(
<QueryClientProvider client={queryClient}>
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>
</QueryClientProvider>
)
expect(screen.getByPlaceholderText(/search/i)).toBeInTheDocument()
})
it('FileBrowser exposes imperative handle for navigation', () => {
const ref = { current: null as unknown as FileBrowserHandle }
render(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
/>,
{ 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(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
/>,
{ wrapper: createWrapper() }
)
expect(ref.current?.canGoBack()).toBe(false)
})
it('FileBrowser goBack navigates to parent directory', () => {
const ref = { current: null as unknown as FileBrowserHandle }
render(
<FileBrowser
ref={ref as any}
basePath="test"
embedded={true}
/>,
{ 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(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test/deep"
/>,
{ 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(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test/deep"
/>,
{ 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(
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>,
{ 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(
<QueryClientProvider client={createQueryClient()}>
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test"
/>
</QueryClientProvider>
)
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(
<QueryClientProvider client={createQueryClient()}>
<FileBrowserSheet
isOpen={true}
onClose={mockOnClose}
basePath="test/deep"
/>
</QueryClientProvider>
)
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()
})
})
@@ -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<string>(basePath || '.')
const [downloadDialog, setDownloadDialog] = useState<{ type: 'directory' | 'repository' } | null>(null)
const [isPreviewOpen, setIsPreviewOpen] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const fileBrowserRef = useRef<FileBrowserHandle>(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
<FullscreenSheetContent>
<FileBrowser
ref={fileBrowserRef}
basePath={normalizedBasePath}
embedded={true}
initialSelectedFile={initialSelectedFile}
onDirectoryLoad={handleDirectoryLoad}
onPreviewStateChange={setIsPreviewOpen}
/>
</FullscreenSheetContent>
</FullscreenSheet>
@@ -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
>
<div className="flex-1 overflow-hidden min-h-0">
{isLoading ? (
@@ -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 (
@@ -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<HTMLDivElement>(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;
@@ -100,7 +100,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen className="content-start gap-0 sm:max-w-[500px] sm:max-h-[80vh] sm:h-auto sm:top-[50%] sm:translate-y-[-50%] bg-[#141414] border-[#2a2a2a]">
<DialogContent mobileFullscreen mobileSwipeToClose className="content-start gap-0 sm:max-w-[500px] sm:max-h-[80vh] sm:h-auto sm:top-[50%] sm:translate-y-[-50%] bg-[#141414] border-[#2a2a2a]">
<DialogHeader className="px-4 sm:px-6 pt-2 sm:pt-6 pb-2 sm:pb-3 h-fit">
<DialogTitle className="text-xl bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
Add Repository
@@ -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,
})
@@ -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<HTMLDivElement>(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 && (
<div
className="fixed inset-0 bg-black pointer-events-none"
style={{
zIndex: 40,
...underlayStyles,
}}
/>
)}
<div
key={location.pathname}
ref={pageRef}
className={reducedMotion ? '' : animationClass}
style={{
position: 'relative',
zIndex: isActive ? 50 : undefined,
minHeight: '100dvh',
...(isSwiping && !reducedMotion ? pageStyles : {}),
willChange: isActive ? 'transform' : undefined,
}}
>
{children}
</div>
</>
)
}
+6 -2
View File
@@ -9,12 +9,16 @@ interface BackButtonProps {
export function BackButton({ to = "/", className = "" }: BackButtonProps) {
const navigate = useNavigate();
const handleBack = () => {
navigate(to);
};
return (
<button
onClick={() => navigate(to)}
onClick={handleBack}
className={`text-zinc-400 hover:text-zinc-100 transition-all duration-200 hover:scale-105 text-sm md:text-md border border-zinc-700 rounded-md px-3 py-1.5 hover ${className}`}
>
<ArrowLeft className="w-4 h-4" />
</button>
);
}
}
+92 -1
View File
@@ -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(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose data-testid="dialog-content">
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</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(
<Dialog open>
<DialogContent mobileFullscreen mobileSwipeToClose data-testid="dialog-content">
<DialogHeader>
<DialogTitle>Test Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</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(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose>
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</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(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose>
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</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(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose data-testid="swipe-dialog">
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</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);
});
});
+42 -4
View File
@@ -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<typeof DialogPrimitive.Content> {
extends Omit<React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>, 'onOpenChange'> {
hideCloseButton?: boolean
fullscreen?: boolean
mobileFullscreen?: boolean
mobileSwipeToClose?: boolean
onOpenChange?: (open: boolean) => void
overlayClassName?: string
}
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
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<HTMLDivElement>(null)
const contentRef = React.useRef<HTMLDivElement>(null)
const closeTriggerRef = React.useRef<HTMLButtonElement>(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 (
<DialogPortal>
{!fullscreen && <DialogOverlay className={overlayClassName} />}
<DialogPrimitive.Content
ref={ref}
ref={combinedRef}
autoFocus={false}
aria-describedby={undefined}
className={cn(
@@ -53,7 +88,7 @@ const DialogContent = React.forwardRef<
fullscreen
? "inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none"
: mobileFullscreen
? "inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none sm:inset-auto sm:left-[50%] sm:bottom-auto sm:w-[90%] sm:max-w-lg sm:translate-x-[-50%] sm:translate-y-0 sm:p-6 sm:rounded-lg sm:top-[8%]"
? "inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none sm:inset-auto sm:left-[50%] sm:bottom-auto sm:w-[90%] sm:max-w-lg sm:translate-x-[-50%] sm:translate-y-0 sm:rounded-lg sm:top-[8%] sm:p-6"
: "left-[50%] top-[50%] w-[90%] max-w-lg translate-x-[-50%] translate-y-[-50%] p-6 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
@@ -63,6 +98,9 @@ const DialogContent = React.forwardRef<
{...props}
>
{children}
{mobileSwipeToClose && isMobileFullscreenMode && (
<DialogPrimitive.Close ref={closeTriggerRef} className="sr-only" data-swipe-close-trigger />
)}
{!hideCloseButton && !fullscreen && (
<DialogPrimitive.Close
className="absolute right-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"