mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
refactor - Add tabs menu - fix swipe nav
This commit is contained in:
1 parent
29b9d028c7
commit
4a90dda1a0
70 files changed
+4028
-975
No files matched your search
@@ -17,6 +17,11 @@ LOG_LEVEL=info
|
||||
OPENCODE_SERVER_PORT=5551
|
||||
OPENCODE_HOST=127.0.0.1
|
||||
|
||||
# Optional - bearer password required to talk to the spawned OpenCode server.
|
||||
# When set, the backend spawns OpenCode with this password and attaches it to
|
||||
# every proxied request. Leave unset to disable OpenCode-level auth.
|
||||
# OPENCODE_SERVER_PASSWORD=
|
||||
|
||||
# Optional - import an existing standalone OpenCode install on first startup
|
||||
# Useful for Docker when your host OpenCode data is bind-mounted into the container
|
||||
# OPENCODE_IMPORT_CONFIG_PATH=/import/opencode-config/opencode.json
|
||||
|
||||
@@ -6,7 +6,7 @@ import { readFile, writeFile, mkdir } from 'fs/promises'
|
||||
import { storeMcpOAuthFlow, consumeMcpOAuthFlow, deleteMcpOAuthFlow, markMcpOAuthFlowCompleted, markMcpOAuthFlowFailed, getMcpOAuthFlowResult } from '../services/mcp-oauth-state'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { OPENCODE_SERVER_URL } from '../services/proxy'
|
||||
import { OPENCODE_SERVER_URL, withOpenCodeAuth } from '../services/proxy'
|
||||
|
||||
const StartSchema = z.object({
|
||||
serverName: z.string(),
|
||||
@@ -300,11 +300,13 @@ export function createMcpOauthProxyRoutes(requireAuth?: any) {
|
||||
}
|
||||
await fetch(reconnectUrl, {
|
||||
method: 'POST',
|
||||
headers: withOpenCodeAuth(),
|
||||
})
|
||||
if (flow.directory) {
|
||||
const globalReconnectUrl = `${OPENCODE_SERVER_URL}/mcp/${encodeURIComponent(flow.serverName)}/connect`
|
||||
await fetch(globalReconnectUrl, {
|
||||
method: 'POST',
|
||||
headers: withOpenCodeAuth(),
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { resolveProjectId } from '../services/project-id-resolver'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { getWorkspacePath, getConfigPath } from '@opencode-manager/shared/config/env'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { OPENCODE_SERVER_URL } from '../services/proxy'
|
||||
import { OPENCODE_SERVER_URL, withOpenCodeAuth } from '../services/proxy'
|
||||
import {
|
||||
CreateMemoryRequestSchema,
|
||||
UpdateMemoryRequestSchema,
|
||||
@@ -640,7 +640,7 @@ export function createMemoryRoutes(db: Database): Hono {
|
||||
try {
|
||||
const abortUrl = new URL(`${OPENCODE_SERVER_URL}/session/${state.sessionId}/abort`)
|
||||
abortUrl.searchParams.set('directory', repo.fullPath)
|
||||
await fetch(abortUrl.toString(), { method: 'POST' })
|
||||
await fetch(abortUrl.toString(), { method: 'POST', headers: withOpenCodeAuth() })
|
||||
} catch {
|
||||
// Session may already be idle
|
||||
}
|
||||
|
||||
@@ -24,6 +24,11 @@ import { patchOpenCodeConfig } from './proxy'
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
||||
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
|
||||
const OPENCODE_SERVER_PUBLIC_URL = ENV.OPENCODE.PUBLIC_URL
|
||||
const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD
|
||||
const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME
|
||||
const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD
|
||||
? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}`
|
||||
: ''
|
||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
|
||||
@@ -234,6 +239,13 @@ class OpenCodeServerManager {
|
||||
|
||||
let stderrOutput = ''
|
||||
|
||||
const cleanEnv = { ...process.env }
|
||||
delete cleanEnv.OPENCODE_SERVER_PASSWORD
|
||||
delete cleanEnv.OPENCODE_RUN_ID
|
||||
delete cleanEnv.OPENCODE_PROCESS_ROLE
|
||||
delete cleanEnv.OPENCODE_PID
|
||||
delete cleanEnv.OPENCODE
|
||||
|
||||
this.serverProcess = spawn(
|
||||
'opencode',
|
||||
['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', OPENCODE_SERVER_HOST],
|
||||
@@ -242,13 +254,19 @@ class OpenCodeServerManager {
|
||||
detached: !isDevelopment,
|
||||
stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
||||
env: {
|
||||
...process.env,
|
||||
...cleanEnv,
|
||||
...gitEnv,
|
||||
...gitIdentityEnv,
|
||||
GIT_SSH_COMMAND: gitSshCommand,
|
||||
XDG_DATA_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
|
||||
XDG_CONFIG_HOME: path.join(openCodeServerDirectory, '.config'),
|
||||
...(OPENCODE_SERVER_PUBLIC_URL ? { OPENCODE_PUBLIC_URL: OPENCODE_SERVER_PUBLIC_URL } : {}),
|
||||
...(OPENCODE_SERVER_PASSWORD
|
||||
? {
|
||||
OPENCODE_SERVER_PASSWORD,
|
||||
OPENCODE_SERVER_USERNAME,
|
||||
}
|
||||
: {}),
|
||||
OPENCODE_CONFIG: openCodeConfigPath,
|
||||
}
|
||||
}
|
||||
@@ -450,8 +468,13 @@ class OpenCodeServerManager {
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
if (OPENCODE_BASIC_AUTH) {
|
||||
headers.Authorization = OPENCODE_BASIC_AUTH
|
||||
}
|
||||
const response = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/doc`, {
|
||||
signal: AbortSignal.timeout(3000)
|
||||
signal: AbortSignal.timeout(3000),
|
||||
headers
|
||||
})
|
||||
return response.ok
|
||||
} catch {
|
||||
|
||||
@@ -3,12 +3,25 @@ import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
|
||||
export const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}`
|
||||
const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD
|
||||
const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME
|
||||
|
||||
const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD
|
||||
? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}`
|
||||
: ''
|
||||
|
||||
export function withOpenCodeAuth(headers: Record<string, string> = {}): Record<string, string> {
|
||||
if (OPENCODE_BASIC_AUTH) {
|
||||
return { ...headers, Authorization: OPENCODE_BASIC_AUTH }
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
export async function setOpenCodeAuth(providerId: string, apiKey: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ type: 'api', key: apiKey }),
|
||||
})
|
||||
|
||||
@@ -29,6 +42,7 @@ export async function deleteOpenCodeAuth(providerId: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
|
||||
method: 'DELETE',
|
||||
headers: withOpenCodeAuth(),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
@@ -196,7 +210,7 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): Prom
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/config`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(config),
|
||||
})
|
||||
|
||||
@@ -242,7 +256,7 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): Prom
|
||||
logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`)
|
||||
const retryResponse = await fetch(`${OPENCODE_SERVER_URL}/config`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(cleanedConfig),
|
||||
})
|
||||
|
||||
@@ -287,14 +301,14 @@ export async function proxyRequest(request: Request) {
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
request.headers.forEach((value, key) => {
|
||||
if (!['host', 'connection'].includes(key.toLowerCase())) {
|
||||
if (!['host', 'connection', 'authorization'].includes(key.toLowerCase())) {
|
||||
headers[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: request.method,
|
||||
headers,
|
||||
headers: withOpenCodeAuth(headers),
|
||||
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined,
|
||||
})
|
||||
|
||||
@@ -337,7 +351,7 @@ export async function proxyToOpenCodeWithDirectory(
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method,
|
||||
headers: headers || { 'Content-Type': 'application/json' },
|
||||
headers: withOpenCodeAuth(headers || { 'Content-Type': 'application/json' }),
|
||||
body,
|
||||
})
|
||||
|
||||
@@ -378,7 +392,7 @@ export async function proxyMcpAuthStart(
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
})
|
||||
|
||||
const responseBody = await response.text()
|
||||
@@ -409,7 +423,7 @@ export async function proxyMcpAuthAuthenticate(
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
})
|
||||
|
||||
const responseBody = await response.text()
|
||||
|
||||
@@ -254,6 +254,8 @@ describe('OpenCodeServerManager - reloadConfig', () => {
|
||||
const mockPatchResult = { success: true }
|
||||
vi.mocked(patchOpenCodeConfig).mockResolvedValue(mockPatchResult)
|
||||
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
|
||||
await opencodeServerManager.reloadConfig()
|
||||
@@ -263,5 +265,7 @@ describe('OpenCodeServerManager - reloadConfig', () => {
|
||||
'utf-8'
|
||||
)
|
||||
expect(patchOpenCodeConfig).toHaveBeenCalled()
|
||||
|
||||
fetchSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
+67
-8
@@ -1,7 +1,7 @@
|
||||
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { createBrowserRouter, RouterProvider, Outlet, useNavigate } from 'react-router-dom'
|
||||
import { useEffect } from 'react'
|
||||
import { createBrowserRouter, RouterProvider, Outlet, useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Toaster } from 'sonner'
|
||||
import { Repos } from './pages/Repos'
|
||||
import { RepoDetail } from './pages/RepoDetail'
|
||||
@@ -15,14 +15,16 @@ import { Setup } from './pages/Setup'
|
||||
import { SettingsDialog } from './components/settings/SettingsDialog'
|
||||
import { VersionNotifier } from './components/VersionNotifier'
|
||||
import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt'
|
||||
import { MobileTabBar } from '@/components/navigation/MobileTabBar'
|
||||
import { MobileSheetHost } from '@/components/navigation/MobileSheetHost'
|
||||
import { useTheme } from './hooks/useTheme'
|
||||
import { useSwipeBack } from './hooks/useMobile'
|
||||
import { TTSProvider } from './contexts/TTSContext'
|
||||
import { AuthProvider } from './contexts/AuthContext'
|
||||
import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext'
|
||||
import { SwipeNavigationProvider } from '@/contexts/SwipeNavigationContext'
|
||||
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({
|
||||
@@ -70,8 +72,61 @@ function PermissionDialogWrapper() {
|
||||
|
||||
function AppShell() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
useTheme()
|
||||
useNavigationDirection()
|
||||
|
||||
const getSwipeBackTarget = () => {
|
||||
const path = location.pathname
|
||||
if (path.match(/^\/repos\/[^/]+\/sessions\/[^/]+$/)) {
|
||||
const repoId = path.split('/')[2]
|
||||
return `/repos/${repoId}`
|
||||
}
|
||||
if (path.match(/^\/repos\/[^/]+$/)) {
|
||||
return '/'
|
||||
}
|
||||
if (path.match(/^\/repos\/[^/]+\/memories$/)) {
|
||||
const repoId = path.split('/')[2]
|
||||
return `/repos/${repoId}`
|
||||
}
|
||||
if (path.match(/^\/repos\/[^/]+\/schedules$/)) {
|
||||
const repoId = path.split('/')[2]
|
||||
return `/repos/${repoId}`
|
||||
}
|
||||
if (path === '/schedules') {
|
||||
return '/'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const canSwipeBack = () => {
|
||||
const path = location.pathname
|
||||
return !['/login', '/setup', '/register', '/'].includes(path) && getSwipeBackTarget() !== null
|
||||
}
|
||||
|
||||
const handleSwipeBack = () => {
|
||||
const target = getSwipeBackTarget()
|
||||
if (target) {
|
||||
navigate(target)
|
||||
}
|
||||
}
|
||||
|
||||
const { bind: bindRouteSwipe } = useSwipeBack(
|
||||
() => {},
|
||||
{
|
||||
enabled: true,
|
||||
suspendsRouteSwipe: false,
|
||||
canBack: canSwipeBack,
|
||||
onBack: handleSwipeBack,
|
||||
}
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const cleanup = bindRouteSwipe(rootRef.current)
|
||||
return () => {
|
||||
cleanup?.()
|
||||
}
|
||||
}, [bindRouteSwipe])
|
||||
|
||||
useEffect(() => {
|
||||
const channel = new BroadcastChannel('notification-click')
|
||||
@@ -87,9 +142,11 @@ function AppShell() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<EventProvider>
|
||||
<PageTransition>
|
||||
<div ref={rootRef} className="contents">
|
||||
<Outlet />
|
||||
</PageTransition>
|
||||
</div>
|
||||
<MobileTabBar />
|
||||
<MobileSheetHost />
|
||||
<PermissionDialogWrapper />
|
||||
<SSHHostKeyDialogWrapper />
|
||||
<SettingsDialog />
|
||||
@@ -164,7 +221,9 @@ function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TTSProvider>
|
||||
<RouterProvider router={router} />
|
||||
<SwipeNavigationProvider>
|
||||
<RouterProvider router={router} />
|
||||
</SwipeNavigationProvider>
|
||||
</TTSProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
@@ -662,11 +662,11 @@ describe('FileBrowserSheet swipe decision integration', () => {
|
||||
expect(parentPath).toBe('test')
|
||||
})
|
||||
|
||||
it('FileBrowserSheet wires useSwipeToClose with canSwipeBack and onSwipeBack callbacks', () => {
|
||||
it('FileBrowserSheet wires useSwipeBack with canBack and onBack callbacks', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
|
||||
const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose')
|
||||
mockUseSwipeToClose.mockReturnValue({
|
||||
const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack')
|
||||
mockUseSwipeBack.mockReturnValue({
|
||||
bind: vi.fn(),
|
||||
swipeProgress: 0,
|
||||
swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' },
|
||||
@@ -681,18 +681,18 @@ describe('FileBrowserSheet swipe decision integration', () => {
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
expect(mockUseSwipeToClose).toHaveBeenCalled()
|
||||
expect(mockUseSwipeBack).toHaveBeenCalled()
|
||||
|
||||
const callArgs = mockUseSwipeToClose.mock.calls[0]
|
||||
const callArgs = mockUseSwipeBack.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')
|
||||
expect(typeof options.canBack).toBe('function')
|
||||
expect(typeof options.onBack).toBe('function')
|
||||
|
||||
mockUseSwipeToClose.mockRestore()
|
||||
mockUseSwipeBack.mockRestore()
|
||||
})
|
||||
|
||||
it('FileBrowserSheet swipe completion: path decision logic for nested path', () => {
|
||||
@@ -726,13 +726,13 @@ describe('FileBrowserSheet swipe decision integration', () => {
|
||||
expect(parentPath).toBe('test/deep')
|
||||
})
|
||||
|
||||
it('FileBrowserSheet swipe completion calls onSwipeBack for nested path', () => {
|
||||
it('FileBrowserSheet swipe completion calls onBack for nested path', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
|
||||
const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose')
|
||||
mockUseSwipeToClose.mockImplementation((onClose, _options) => {
|
||||
if (_options?.canSwipeBack && _options.canSwipeBack()) {
|
||||
_options.onSwipeBack?.()
|
||||
const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack')
|
||||
mockUseSwipeBack.mockImplementation((onClose, _options) => {
|
||||
if (_options?.canBack && _options.canBack()) {
|
||||
_options.onBack?.()
|
||||
}
|
||||
return {
|
||||
bind: vi.fn(),
|
||||
@@ -758,29 +758,30 @@ describe('FileBrowserSheet swipe decision integration', () => {
|
||||
expect(canGoBack).toBe(true)
|
||||
expect(mockOnClose).not.toHaveBeenCalled()
|
||||
|
||||
mockUseSwipeToClose.mockRestore()
|
||||
mockUseSwipeBack.mockRestore()
|
||||
})
|
||||
|
||||
it('FileBrowserSheet swipe completion calls onClose for base path', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
const mockOnSwipeBack = vi.fn()
|
||||
const mockOnBack = 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()
|
||||
expect(mockOnBack).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({
|
||||
const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack')
|
||||
mockUseSwipeBack.mockReturnValue({
|
||||
bind: vi.fn(),
|
||||
swipeProgress: 0,
|
||||
swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' },
|
||||
@@ -796,16 +797,16 @@ describe('FileBrowserSheet swipe decision integration', () => {
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
expect(mockUseSwipeToClose).toHaveBeenCalled()
|
||||
expect(mockUseSwipeBack).toHaveBeenCalled()
|
||||
|
||||
const callArgs = mockUseSwipeToClose.mock.calls[0]
|
||||
const callArgs = mockUseSwipeBack.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()
|
||||
expect(options.canBack).toBeDefined()
|
||||
expect(options.onBack).toBeDefined()
|
||||
|
||||
const nestedPath = 'test/deep'
|
||||
const nestedPathParts = nestedPath.split('/').filter(Boolean)
|
||||
@@ -821,17 +822,17 @@ describe('FileBrowserSheet swipe decision integration', () => {
|
||||
|
||||
expect(canGoBackBase).toBe(false)
|
||||
|
||||
mockUseSwipeToClose.mockRestore()
|
||||
mockUseSwipeBack.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?.()
|
||||
const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack')
|
||||
mockUseSwipeBack.mockImplementation((onClose, options) => {
|
||||
const canBack = options?.canBack?.()
|
||||
if (canBack) {
|
||||
options?.onSwipeBack?.()
|
||||
options?.onBack?.()
|
||||
} else {
|
||||
onClose()
|
||||
}
|
||||
@@ -852,11 +853,11 @@ describe('FileBrowserSheet swipe decision integration', () => {
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
const callArgs = mockUseSwipeToClose.mock.calls[0]
|
||||
const callArgs = mockUseSwipeBack.mock.calls[0]
|
||||
const options = callArgs![1]!
|
||||
|
||||
expect(options.canSwipeBack).toBeDefined()
|
||||
expect(options.onSwipeBack).toBeDefined()
|
||||
expect(options.canBack).toBeDefined()
|
||||
expect(options.onBack).toBeDefined()
|
||||
|
||||
const currentPath = 'test/deep'
|
||||
const pathParts = currentPath.split('/').filter(Boolean)
|
||||
@@ -865,7 +866,229 @@ describe('FileBrowserSheet swipe decision integration', () => {
|
||||
|
||||
expect(canGoBack).toBe(true)
|
||||
|
||||
mockUseSwipeToClose.mockRestore()
|
||||
mockUseSwipeBack.mockRestore()
|
||||
})
|
||||
|
||||
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 useSwipeBack with canBack and onBack callbacks', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
|
||||
const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack')
|
||||
mockUseSwipeBack.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(mockUseSwipeBack).toHaveBeenCalled()
|
||||
|
||||
const callArgs = mockUseSwipeBack.mock.calls[0]
|
||||
expect(callArgs).toBeDefined()
|
||||
expect(callArgs![0]).toBe(mockOnClose)
|
||||
|
||||
const options = callArgs![1]!
|
||||
expect(options.enabled).toBe(true)
|
||||
expect(typeof options.canBack).toBe('function')
|
||||
expect(typeof options.onBack).toBe('function')
|
||||
|
||||
mockUseSwipeBack.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 onBack for nested path', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
|
||||
const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack')
|
||||
mockUseSwipeBack.mockImplementation((onClose, _options) => {
|
||||
if (_options?.canBack && _options.canBack()) {
|
||||
_options.onBack?.()
|
||||
}
|
||||
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()
|
||||
|
||||
mockUseSwipeBack.mockRestore()
|
||||
})
|
||||
|
||||
it('FileBrowserSheet swipe completion calls onClose for base path', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
const mockOnBack = 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(mockOnBack).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FileBrowserSheet back-vs-close outcome: verifies swipe completion calls correct action', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
|
||||
const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack')
|
||||
mockUseSwipeBack.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(mockUseSwipeBack).toHaveBeenCalled()
|
||||
|
||||
const callArgs = mockUseSwipeBack.mock.calls[0]
|
||||
expect(callArgs).toBeDefined()
|
||||
expect(callArgs![0]).toBe(mockOnClose)
|
||||
|
||||
const options = callArgs![1]!
|
||||
expect(options.enabled).toBe(true)
|
||||
expect(options.canBack).toBeDefined()
|
||||
expect(options.onBack).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)
|
||||
|
||||
mockUseSwipeBack.mockRestore()
|
||||
})
|
||||
|
||||
it('FileBrowserSheet back-vs-close: swipe completion decision is wired correctly', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
|
||||
const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack')
|
||||
mockUseSwipeBack.mockImplementation((onClose, options) => {
|
||||
const canBack = options?.canBack?.()
|
||||
if (canBack) {
|
||||
options?.onBack?.()
|
||||
} 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 = mockUseSwipeBack.mock.calls[0]
|
||||
const options = callArgs![1]!
|
||||
|
||||
expect(options.canBack).toBeDefined()
|
||||
expect(options.onBack).toBeDefined()
|
||||
|
||||
const currentPath = 'test/deep'
|
||||
const pathParts = currentPath.split('/').filter(Boolean)
|
||||
const joinedPath = pathParts.join('/')
|
||||
const canGoBack = joinedPath !== 'test'
|
||||
|
||||
expect(canGoBack).toBe(true)
|
||||
|
||||
mockUseSwipeBack.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { FullscreenSheet, FullscreenSheetHeader, FullscreenSheetContent } from '
|
||||
import { DownloadDialog } from '@/components/ui/download-dialog'
|
||||
import { X, Download } from 'lucide-react'
|
||||
import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { useSwipeToClose } from '@/hooks/useMobile'
|
||||
import { useSwipeBack } from '@/hooks/useMobile'
|
||||
import { downloadDirectoryAsZip } from '@/api/files'
|
||||
import { downloadRepo } from '@/api/repos'
|
||||
import {
|
||||
@@ -36,10 +36,10 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const fileBrowserRef = useRef<FileBrowserHandle>(null)
|
||||
|
||||
const { bind, swipeStyles } = useSwipeToClose(onClose, {
|
||||
const { bind, swipeStyles } = useSwipeBack(onClose, {
|
||||
enabled: isOpen && !isEditing && !isPreviewOpen,
|
||||
canSwipeBack: () => fileBrowserRef.current?.canGoBack() ?? false,
|
||||
onSwipeBack: () => fileBrowserRef.current?.goBack(),
|
||||
canBack: () => fileBrowserRef.current?.canGoBack() ?? false,
|
||||
onBack: () => fileBrowserRef.current?.goBack(),
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -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 { useSwipeToClose } from "@/hooks/useMobile";
|
||||
import { useSwipeBack } from "@/hooks/useMobile";
|
||||
|
||||
interface MobileFilePreviewModalProps {
|
||||
isOpen: boolean;
|
||||
@@ -32,7 +32,7 @@ export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({
|
||||
}, MODAL_TRANSITION_MS);
|
||||
}, [onClose]);
|
||||
|
||||
const { bind, swipeStyles } = useSwipeToClose(handleClose, {
|
||||
const { bind, swipeStyles } = useSwipeBack(handleClose, {
|
||||
enabled: isOpen,
|
||||
});
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@ export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps
|
||||
return
|
||||
}
|
||||
|
||||
setIsLongPressVisual(false)
|
||||
|
||||
if (isAnyPlaybackActive) {
|
||||
stop()
|
||||
return
|
||||
@@ -74,15 +76,11 @@ export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps
|
||||
|
||||
const showStop = isAnyPlaybackActive
|
||||
const pillTitle = showStop
|
||||
? 'Stop playback (hold to toggle auto-play)'
|
||||
? 'Stop playback'
|
||||
: hasContent
|
||||
? autoPlay
|
||||
? 'Play latest reply (auto-play enabled; hold to toggle auto-play)'
|
||||
: 'Play latest reply (hold to toggle auto-play)'
|
||||
: autoPlay
|
||||
? 'Auto-play enabled (hold to toggle auto-play)'
|
||||
: 'Hold to toggle auto-play'
|
||||
const pillAriaLabel = pillTitle
|
||||
? 'Play latest reply'
|
||||
: 'TTS controls'
|
||||
const pillAriaLabel = `${pillTitle}. ${autoPlay ? 'Auto-play enabled.' : 'Auto-play disabled.'} hold to toggle auto-play`
|
||||
const buttonToneClasses = showStop
|
||||
? 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-red-600 to-red-700 border border-red-500/60 shadow-red-500/30 ring-red-500/20 hover:ring-red-500/40 text-white'
|
||||
: autoPlay
|
||||
|
||||
@@ -979,7 +979,7 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod
|
||||
onPromptChange?.(prompt.trim().length > 0)
|
||||
}, [prompt, onPromptChange])
|
||||
|
||||
useEffect(() => {
|
||||
useEffect(() => {
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
vi.mock('@/hooks/useMobile')
|
||||
vi.mock('@/hooks/useMobileTabBar', () => ({
|
||||
useMobileTabBar: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
|
||||
FileBrowserSheet: ({ isOpen, basePath, repoName }: { isOpen: boolean; basePath: string; repoName: string }) =>
|
||||
isOpen ? <div data-testid="file-browser-sheet" data-base-path={basePath} data-repo-name={repoName}>FileBrowserSheet</div> : null,
|
||||
}))
|
||||
vi.mock('@/components/navigation/RepoQuickSwitchSheet', () => ({
|
||||
RepoQuickSwitchSheet: ({ isOpen }: { isOpen: boolean }) =>
|
||||
isOpen ? <div data-testid="repo-quick-switch-sheet">RepoQuickSwitchSheet</div> : null,
|
||||
}))
|
||||
vi.mock('@/components/navigation/NotificationsSheet', () => ({
|
||||
NotificationsSheet: ({ isOpen }: { isOpen: boolean }) =>
|
||||
isOpen ? <div data-testid="notifications-sheet">NotificationsSheet</div> : null,
|
||||
}))
|
||||
vi.mock('@/components/navigation/MoreDrawer', () => ({
|
||||
MoreDrawer: ({ isOpen }: { isOpen: boolean }) =>
|
||||
isOpen ? <div data-testid="more-drawer">MoreDrawer</div> : null,
|
||||
}))
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { MobileSheetHost } from './MobileSheetHost'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
|
||||
describe('MobileSheetHost', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(useMobileTabBar).mockReturnValue({
|
||||
openSheet: null,
|
||||
open: vi.fn(),
|
||||
close: vi.fn(),
|
||||
})
|
||||
})
|
||||
|
||||
it('renders nothing when useMobile returns false', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(false)
|
||||
const { container } = render(
|
||||
<MemoryRouter>
|
||||
<MobileSheetHost />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders nothing when no mobileTab param is present', () => {
|
||||
const { container } = render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileSheetHost />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders RepoQuickSwitchSheet when mobileTab=repos', () => {
|
||||
vi.mocked(useMobileTabBar).mockReturnValue({
|
||||
openSheet: 'repos',
|
||||
open: vi.fn(),
|
||||
close: vi.fn(),
|
||||
})
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?mobileTab=repos']}>
|
||||
<MobileSheetHost />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
expect(screen.getByTestId('repo-quick-switch-sheet')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders FileBrowserSheet with correct props when mobileTab=files', () => {
|
||||
vi.mocked(useMobileTabBar).mockReturnValue({
|
||||
openSheet: 'files',
|
||||
open: vi.fn(),
|
||||
close: vi.fn(),
|
||||
})
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?mobileTab=files']}>
|
||||
<MobileSheetHost />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
const sheet = screen.getByTestId('file-browser-sheet')
|
||||
expect(sheet).toBeInTheDocument()
|
||||
expect(sheet.getAttribute('data-base-path')).toBe('')
|
||||
expect(sheet.getAttribute('data-repo-name')).toBe('Workspace Root')
|
||||
})
|
||||
|
||||
it('renders NotificationsSheet when mobileTab=notifications', () => {
|
||||
vi.mocked(useMobileTabBar).mockReturnValue({
|
||||
openSheet: 'notifications',
|
||||
open: vi.fn(),
|
||||
close: vi.fn(),
|
||||
})
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?mobileTab=notifications']}>
|
||||
<MobileSheetHost />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
expect(screen.getByTestId('notifications-sheet')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders MoreDrawer when mobileTab=more', () => {
|
||||
vi.mocked(useMobileTabBar).mockReturnValue({
|
||||
openSheet: 'more',
|
||||
open: vi.fn(),
|
||||
close: vi.fn(),
|
||||
})
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?mobileTab=more']}>
|
||||
<MobileSheetHost />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
expect(screen.getByTestId('more-drawer')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('closes sheet when onClose is called', () => {
|
||||
const mockClose = vi.fn()
|
||||
vi.mocked(useMobileTabBar).mockReturnValue({
|
||||
openSheet: 'repos',
|
||||
open: vi.fn(),
|
||||
close: mockClose,
|
||||
})
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?mobileTab=repos']}>
|
||||
<MobileSheetHost />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
expect(screen.getByTestId('repo-quick-switch-sheet')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
|
||||
import { RepoQuickSwitchSheet } from '@/components/navigation/RepoQuickSwitchSheet'
|
||||
import { NotificationsSheet } from '@/components/navigation/NotificationsSheet'
|
||||
import { MoreDrawer } from '@/components/navigation/MoreDrawer'
|
||||
|
||||
export function MobileSheetHost() {
|
||||
const isMobile = useMobile()
|
||||
const { openSheet, close } = useMobileTabBar()
|
||||
|
||||
if (!isMobile) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
{openSheet === 'repos' && <RepoQuickSwitchSheet isOpen onClose={close} />}
|
||||
{openSheet === 'files' && (
|
||||
<FileBrowserSheet
|
||||
isOpen
|
||||
onClose={close}
|
||||
basePath=""
|
||||
repoName="Workspace Root"
|
||||
/>
|
||||
)}
|
||||
{openSheet === 'notifications' && <NotificationsSheet isOpen onClose={close} />}
|
||||
{openSheet === 'more' && <MoreDrawer isOpen onClose={close} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
vi.mock('@/hooks/useMobile')
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
usePendingAlerts: vi.fn(),
|
||||
}))
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MobileTabBar } from './MobileTabBar'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { usePendingAlerts } from '@/contexts/EventContext'
|
||||
|
||||
describe('MobileTabBar', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('renders nothing when useMobile returns false', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(false)
|
||||
const queryClient = new QueryClient()
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders nothing on unsupported paths', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/login']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders global tabs on repo detail (session list) path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/123']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders schedule tabs on /repos/:id/schedules path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/123/schedules']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText('Jobs')).toBeInTheDocument()
|
||||
expect(screen.getByText('Detail')).toBeInTheDocument()
|
||||
expect(screen.getByText('Runs')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Alerts')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders tab bar on root path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Files')).toBeInTheDocument()
|
||||
expect(screen.getByText('Alerts')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
expect(screen.getByText('More')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders tab bar on /schedules path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/schedules']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows badge when usePendingAlerts returns true', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const badge = document.querySelector('.bg-orange-500')
|
||||
expect(badge).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show badge when usePendingAlerts returns false', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(false)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const badge = document.querySelector('.bg-orange-500')
|
||||
expect(badge).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('Repos tab is active when pathname is / and no sheet is open', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const reposButton = screen.getByText('Repos').closest('button')
|
||||
expect(reposButton).toHaveClass('text-primary')
|
||||
expect(reposButton).toHaveClass('border-primary')
|
||||
})
|
||||
|
||||
it('Repos tab is active when openSheet is repos regardless of pathname', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/123?mobileTab=repos']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const reposButton = screen.getByText('Repos').closest('button')
|
||||
expect(reposButton).toHaveClass('text-primary')
|
||||
expect(reposButton).toHaveClass('border-primary')
|
||||
})
|
||||
|
||||
it('maintains stable callbacks when search changes but mobileTab does not', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
|
||||
const { rerender } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/?foo=1']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const firstReposButton = screen.getByText('Repos').closest('button')
|
||||
expect(firstReposButton).toBeInTheDocument()
|
||||
|
||||
rerender(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/?foo=2']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const secondReposButton = screen.getByText('Repos').closest('button')
|
||||
expect(secondReposButton).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render tab bar on SessionDetail path /repos/:id/sessions/:sid', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/1/sessions/abc']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders tab bar on Memories path /repos/:id/memories', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/1/memories']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Files')).toBeInTheDocument()
|
||||
expect(screen.getByText('Alerts')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
expect(screen.getByText('More')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
import { memo, useMemo } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { FolderGit2, FolderOpen, Bell, CalendarClock, Menu, Info, History } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useMobileTabBar, useScheduleTab, type ScheduleTabKey } from '@/hooks/useMobileTabBar'
|
||||
import { usePendingAlerts } from '@/contexts/EventContext'
|
||||
|
||||
interface TabDef {
|
||||
key: string
|
||||
label: string
|
||||
icon: React.ElementType
|
||||
onClick: () => void
|
||||
active: boolean
|
||||
badge?: boolean
|
||||
}
|
||||
|
||||
interface GlobalTabsArgs {
|
||||
pathname: string
|
||||
openSheet: ReturnType<typeof useMobileTabBar>['openSheet']
|
||||
open: ReturnType<typeof useMobileTabBar>['open']
|
||||
navigate: ReturnType<typeof useNavigate>
|
||||
hasPending: boolean
|
||||
isInsideRepo: boolean
|
||||
repoId: string | null
|
||||
}
|
||||
|
||||
function buildGlobalTabs({ pathname, openSheet, open, navigate, hasPending, isInsideRepo, repoId }: GlobalTabsArgs): TabDef[] {
|
||||
const handleFilesClick = () => {
|
||||
if (isInsideRepo && repoId) {
|
||||
const newParams = new URLSearchParams({ dialog: 'files' })
|
||||
navigate(`${pathname}?${newParams.toString()}`, { replace: true })
|
||||
} else {
|
||||
open('files')
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
key: 'repos',
|
||||
label: 'Repos',
|
||||
icon: FolderGit2,
|
||||
onClick: () => open('repos'),
|
||||
active: openSheet === 'repos' || (pathname === '/' && !openSheet),
|
||||
},
|
||||
{
|
||||
key: 'files',
|
||||
label: 'Files',
|
||||
icon: FolderOpen,
|
||||
onClick: handleFilesClick,
|
||||
active: openSheet === 'files',
|
||||
},
|
||||
{
|
||||
key: 'notifications',
|
||||
label: 'Alerts',
|
||||
icon: Bell,
|
||||
onClick: () => open('notifications'),
|
||||
badge: hasPending,
|
||||
active: openSheet === 'notifications',
|
||||
},
|
||||
{
|
||||
key: 'schedules',
|
||||
label: 'Schedules',
|
||||
icon: CalendarClock,
|
||||
onClick: () => navigate('/schedules'),
|
||||
active: pathname === '/schedules' && !openSheet,
|
||||
},
|
||||
{
|
||||
key: 'more',
|
||||
label: 'More',
|
||||
icon: Menu,
|
||||
onClick: () => open('more'),
|
||||
active: openSheet === 'more',
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function buildScheduleTabs(scheduleTab: ScheduleTabKey, setScheduleTab: (tab: ScheduleTabKey) => void): TabDef[] {
|
||||
return [
|
||||
{
|
||||
key: 'jobs',
|
||||
label: 'Jobs',
|
||||
icon: CalendarClock,
|
||||
onClick: () => setScheduleTab('jobs'),
|
||||
active: scheduleTab === 'jobs',
|
||||
},
|
||||
{
|
||||
key: 'detail',
|
||||
label: 'Detail',
|
||||
icon: Info,
|
||||
onClick: () => setScheduleTab('detail'),
|
||||
active: scheduleTab === 'detail',
|
||||
},
|
||||
{
|
||||
key: 'runs',
|
||||
label: 'Runs',
|
||||
icon: History,
|
||||
onClick: () => setScheduleTab('runs'),
|
||||
active: scheduleTab === 'runs',
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
interface TabBarRowProps {
|
||||
tabs: TabDef[]
|
||||
}
|
||||
|
||||
const TabBarRow = memo(function TabBarRow({ tabs }: TabBarRowProps) {
|
||||
return (
|
||||
<div className="fixed bottom-0 inset-x-0 z-40 flex border-t border-border bg-card/90 backdrop-blur-sm pb-safe">
|
||||
{tabs.map((tab) => {
|
||||
const Icon = tab.icon
|
||||
return (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
className={cn(
|
||||
'relative flex-1 flex flex-col items-center justify-center gap-1 px-2 py-2 text-xs font-medium border-b-2 transition-colors',
|
||||
tab.active
|
||||
? 'text-primary border-primary'
|
||||
: 'text-muted-foreground border-transparent hover:text-foreground',
|
||||
)}
|
||||
onClick={tab.onClick}
|
||||
>
|
||||
<div className="relative">
|
||||
<Icon className="w-5 h-5" />
|
||||
{tab.badge && (
|
||||
<span className="absolute -top-0.5 -right-1 w-2 h-2 rounded-full bg-orange-500 ring-2 ring-card animate-pulse" />
|
||||
)}
|
||||
</div>
|
||||
<span className="leading-none">{tab.label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export const MobileTabBar = memo(function MobileTabBar() {
|
||||
const { pathname } = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const { openSheet, open } = useMobileTabBar()
|
||||
const { scheduleTab, setScheduleTab } = useScheduleTab()
|
||||
const hasPending = usePendingAlerts()
|
||||
|
||||
const isOnRepoSchedules = /^\/repos\/\d+\/schedules$/.test(pathname)
|
||||
const isRepoMemories = /^\/repos\/\d+\/memories$/.test(pathname)
|
||||
const isMobile = useMobile()
|
||||
const isRoot = pathname === '/'
|
||||
const isGlobalSchedules = pathname === '/schedules'
|
||||
const isRepoDetail = /^\/repos\/\d+$/.test(pathname)
|
||||
const isInsideRepo = isRepoDetail || isOnRepoSchedules || isRepoMemories
|
||||
const isRepoSession = /^\/repos\/\d+\/sessions\/\w+/.test(pathname)
|
||||
const allow = isRoot || isGlobalSchedules || (isInsideRepo && !isRepoSession)
|
||||
|
||||
const repoIdMatch = pathname.match(/^\/repos\/(\d+)/)
|
||||
const repoId = repoIdMatch ? repoIdMatch[1] : null
|
||||
|
||||
const tabs = useMemo<TabDef[]>(
|
||||
() => (isOnRepoSchedules
|
||||
? buildScheduleTabs(scheduleTab, setScheduleTab)
|
||||
: buildGlobalTabs({
|
||||
pathname,
|
||||
openSheet,
|
||||
open,
|
||||
navigate,
|
||||
hasPending,
|
||||
isInsideRepo,
|
||||
repoId,
|
||||
})),
|
||||
[isOnRepoSchedules, scheduleTab, setScheduleTab, pathname, openSheet, open, navigate, hasPending, isInsideRepo, repoId],
|
||||
)
|
||||
|
||||
if (!isMobile) return null
|
||||
if (!allow) return null
|
||||
|
||||
return <TabBarRow tabs={tabs} />
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { MemoryRouter, useNavigate } from 'react-router-dom'
|
||||
import { MoreDrawer } from './MoreDrawer'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
|
||||
vi.mock('@/hooks/useAuth')
|
||||
vi.mock('@/hooks/useServerHealth')
|
||||
vi.mock('@/hooks/useMemoryPluginStatus', () => ({
|
||||
useMemoryPluginStatus: () => ({ memoryPluginEnabled: false }),
|
||||
}))
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom')
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
const mockAuth = (logout = vi.fn()) => {
|
||||
vi.mocked(useAuth).mockReturnValue({
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
config: null,
|
||||
signInWithEmail: vi.fn(),
|
||||
signInWithProvider: vi.fn(),
|
||||
signInWithPasskey: vi.fn(),
|
||||
signUpWithEmail: vi.fn(),
|
||||
addPasskey: vi.fn(),
|
||||
logout,
|
||||
refreshSession: vi.fn(),
|
||||
})
|
||||
}
|
||||
|
||||
const mockServerHealth = (health?: Partial<ReturnType<typeof useServerHealth>['data']>) => {
|
||||
const baseHealth = {
|
||||
status: 'healthy' as const,
|
||||
timestamp: new Date().toISOString(),
|
||||
database: 'connected' as const,
|
||||
opencode: 'healthy' as const,
|
||||
opencodePort: 5551,
|
||||
opencodeVersion: null,
|
||||
opencodeMinVersion: '1.0.0',
|
||||
opencodeManagerVersion: null,
|
||||
error: undefined,
|
||||
}
|
||||
|
||||
vi.mocked(useServerHealth).mockReturnValue({
|
||||
data: {
|
||||
...baseHealth,
|
||||
...health,
|
||||
},
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
|
||||
})
|
||||
}
|
||||
|
||||
describe('MoreDrawer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(useNavigate).mockReturnValue(vi.fn())
|
||||
})
|
||||
|
||||
it('renders Settings and Logout menu items', () => {
|
||||
mockAuth()
|
||||
mockServerHealth()
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<MoreDrawer isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
expect(screen.getByText('OpenCode')).toBeInTheDocument()
|
||||
expect(screen.getByText('Settings')).toBeInTheDocument()
|
||||
expect(screen.getByText('Logout')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render theme controls', () => {
|
||||
mockAuth()
|
||||
mockServerHealth()
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<MoreDrawer isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
expect(screen.queryByText('Theme')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Light')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Dark')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('System')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('navigates to settings URL when Settings is clicked', () => {
|
||||
const navigateMock = vi.fn()
|
||||
vi.mocked(useNavigate).mockReturnValue(navigateMock)
|
||||
mockAuth()
|
||||
mockServerHealth()
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<MoreDrawer isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
fireEvent.click(screen.getByText('Settings'))
|
||||
expect(navigateMock).toHaveBeenCalledWith(
|
||||
{ search: 'settings=open&tab=account' },
|
||||
{ replace: true },
|
||||
)
|
||||
})
|
||||
|
||||
it('calls logout when Logout is clicked', () => {
|
||||
const logoutMock = vi.fn().mockResolvedValue(undefined)
|
||||
mockAuth(logoutMock)
|
||||
mockServerHealth()
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<MoreDrawer isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
fireEvent.click(screen.getByText('Logout'))
|
||||
expect(logoutMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('displays OpenCode and Manager versions when available', () => {
|
||||
mockAuth()
|
||||
mockServerHealth({ opencodeVersion: '1.4.11', opencodeManagerVersion: '0.9.16' })
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<MoreDrawer isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
expect(screen.getByText('OpenCode v1.4.11')).toBeInTheDocument()
|
||||
expect(screen.getByText('Manager v0.9.16')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows unhealthy server status when server is unhealthy', () => {
|
||||
mockAuth()
|
||||
mockServerHealth({ opencode: 'unhealthy' as const, opencodeVersion: '1.4.11' })
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<MoreDrawer isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
expect(screen.getByText('OpenCode v1.4.11')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows fallback text when version is not available', () => {
|
||||
mockAuth()
|
||||
mockServerHealth({ opencodeVersion: null, opencodeManagerVersion: null })
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<MoreDrawer isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
expect(screen.getByText('OpenCode')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useMemoryPluginStatus } from '@/hooks/useMemoryPluginStatus'
|
||||
import { SideDrawer, SideDrawerHeader, SideDrawerContent } from '@/components/ui/side-drawer'
|
||||
import { buildMoreItems } from './moreDrawerItems'
|
||||
|
||||
interface MoreDrawerProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { logout } = useAuth()
|
||||
const { data: health } = useServerHealth()
|
||||
const { memoryPluginEnabled } = useMemoryPluginStatus()
|
||||
|
||||
const handleSettingsClick = () => {
|
||||
const newParams = new URLSearchParams(location.search)
|
||||
newParams.delete('mobileTab')
|
||||
newParams.set('settings', 'open')
|
||||
newParams.set('tab', 'account')
|
||||
navigate({ search: newParams.toString() }, { replace: true })
|
||||
}
|
||||
|
||||
const handleLogoutClick = async () => {
|
||||
try {
|
||||
await logout()
|
||||
} finally {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
const handleItemClick = (item: ReturnType<typeof buildMoreItems>[0]) => {
|
||||
if (item.to) {
|
||||
navigate(item.to)
|
||||
} else if (item.dialog) {
|
||||
const newParams = new URLSearchParams(location.search)
|
||||
newParams.set('dialog', item.dialog)
|
||||
newParams.delete('mobileTab')
|
||||
navigate({ search: newParams.toString() }, { replace: true })
|
||||
}
|
||||
}
|
||||
|
||||
const items = buildMoreItems(location.pathname, { memoryPluginEnabled })
|
||||
|
||||
const opencodeVersion = health?.opencodeVersion
|
||||
const managerVersion = health?.opencodeManagerVersion
|
||||
|
||||
return (
|
||||
<SideDrawer isOpen={isOpen} onClose={onClose} side="right" ariaLabel="More">
|
||||
<SideDrawerHeader
|
||||
title={opencodeVersion ? `OpenCode v${opencodeVersion}` : 'OpenCode'}
|
||||
onClose={onClose}
|
||||
meta={
|
||||
managerVersion ? (
|
||||
<div className="text-xs text-muted-foreground">Manager v{managerVersion}</div>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
<SideDrawerContent className="flex flex-col gap-1">
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.key}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (item.key === 'settings') {
|
||||
handleSettingsClick()
|
||||
} else if (item.key === 'logout') {
|
||||
handleLogoutClick()
|
||||
} else {
|
||||
handleItemClick(item)
|
||||
}
|
||||
}}
|
||||
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
|
||||
>
|
||||
<item.icon className="w-5 h-5 text-muted-foreground" />
|
||||
<span className="font-medium text-foreground">{item.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</SideDrawerContent>
|
||||
</SideDrawer>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { NotificationsSheet } from './NotificationsSheet'
|
||||
import { usePermissions, useQuestions } from '@/contexts/EventContext'
|
||||
|
||||
vi.mock('@/contexts/EventContext')
|
||||
|
||||
describe('NotificationsSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders empty state when both counts are 0', () => {
|
||||
vi.mocked(usePermissions).mockReturnValue({
|
||||
pendingCount: 0,
|
||||
setShowDialog: vi.fn(),
|
||||
navigateToCurrent: vi.fn(),
|
||||
current: null,
|
||||
respond: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
vi.mocked(useQuestions).mockReturnValue({
|
||||
pendingCount: 0,
|
||||
navigateToCurrent: vi.fn(),
|
||||
current: null,
|
||||
reply: vi.fn(),
|
||||
reject: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<NotificationsSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
expect(screen.getAllByText("You're all caught up").length).toBe(2)
|
||||
})
|
||||
|
||||
it('renders permission section with pending count', () => {
|
||||
vi.mocked(usePermissions).mockReturnValue({
|
||||
pendingCount: 2,
|
||||
setShowDialog: vi.fn(),
|
||||
navigateToCurrent: vi.fn(),
|
||||
current: {
|
||||
id: 'perm-1',
|
||||
sessionID: 'session-1',
|
||||
permission: 'write',
|
||||
patterns: ['/test/pattern'],
|
||||
metadata: {},
|
||||
always: [],
|
||||
tool: {
|
||||
messageID: 'msg-1',
|
||||
callID: 'call-1',
|
||||
},
|
||||
},
|
||||
respond: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
vi.mocked(useQuestions).mockReturnValue({
|
||||
pendingCount: 0,
|
||||
navigateToCurrent: vi.fn(),
|
||||
current: null,
|
||||
reply: vi.fn(),
|
||||
reject: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<NotificationsSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
expect(screen.getByText('Pending permissions')).toBeInTheDocument()
|
||||
expect(screen.getByText('+1 more')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders question section with pending count', () => {
|
||||
vi.mocked(usePermissions).mockReturnValue({
|
||||
pendingCount: 0,
|
||||
setShowDialog: vi.fn(),
|
||||
navigateToCurrent: vi.fn(),
|
||||
current: null,
|
||||
respond: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
vi.mocked(useQuestions).mockReturnValue({
|
||||
pendingCount: 1,
|
||||
navigateToCurrent: vi.fn(),
|
||||
current: {
|
||||
id: 'q-1',
|
||||
sessionID: 'session-1',
|
||||
questions: [{
|
||||
question: 'Test question',
|
||||
options: [],
|
||||
}],
|
||||
metadata: {},
|
||||
tool: {
|
||||
messageID: 'msg-1',
|
||||
callID: 'call-1',
|
||||
},
|
||||
},
|
||||
reply: vi.fn(),
|
||||
reject: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<NotificationsSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
expect(screen.getByText('Pending questions')).toBeInTheDocument()
|
||||
expect(screen.getByText('Test question')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls setShowDialog and onClose when permission is clicked', () => {
|
||||
const setShowDialogMock = vi.fn()
|
||||
const navigateToPermissionMock = vi.fn()
|
||||
const handleClose = vi.fn()
|
||||
vi.mocked(usePermissions).mockReturnValue({
|
||||
pendingCount: 1,
|
||||
setShowDialog: setShowDialogMock,
|
||||
navigateToCurrent: navigateToPermissionMock,
|
||||
current: {
|
||||
id: 'perm-1',
|
||||
sessionID: 'session-1',
|
||||
permission: 'write',
|
||||
patterns: ['/test/pattern'],
|
||||
metadata: {},
|
||||
always: [],
|
||||
tool: {
|
||||
messageID: 'msg-1',
|
||||
callID: 'call-1',
|
||||
},
|
||||
},
|
||||
respond: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
vi.mocked(useQuestions).mockReturnValue({
|
||||
pendingCount: 0,
|
||||
navigateToCurrent: vi.fn(),
|
||||
current: null,
|
||||
reply: vi.fn(),
|
||||
reject: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
render(
|
||||
<NotificationsSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
fireEvent.click(screen.getByText('/test/pattern'))
|
||||
expect(navigateToPermissionMock).toHaveBeenCalled()
|
||||
expect(setShowDialogMock).toHaveBeenCalled()
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls navigateToCurrent and onClose when question is clicked', () => {
|
||||
const navigateToQuestionMock = vi.fn()
|
||||
const handleClose = vi.fn()
|
||||
vi.mocked(usePermissions).mockReturnValue({
|
||||
pendingCount: 0,
|
||||
setShowDialog: vi.fn(),
|
||||
navigateToCurrent: vi.fn(),
|
||||
current: null,
|
||||
respond: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
vi.mocked(useQuestions).mockReturnValue({
|
||||
pendingCount: 1,
|
||||
navigateToCurrent: navigateToQuestionMock,
|
||||
current: {
|
||||
id: 'q-1',
|
||||
sessionID: 'session-1',
|
||||
questions: [{
|
||||
question: 'Test question',
|
||||
options: [],
|
||||
}],
|
||||
metadata: {},
|
||||
tool: {
|
||||
messageID: 'msg-1',
|
||||
callID: 'call-1',
|
||||
},
|
||||
},
|
||||
reply: vi.fn(),
|
||||
reject: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
getForCallID: vi.fn(),
|
||||
hasForSession: vi.fn(),
|
||||
})
|
||||
render(
|
||||
<NotificationsSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter> },
|
||||
)
|
||||
fireEvent.click(screen.getByText('Test question'))
|
||||
expect(navigateToQuestionMock).toHaveBeenCalled()
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
|
||||
import { usePermissions, useQuestions } from '@/contexts/EventContext'
|
||||
import { Bell, HelpCircle } from 'lucide-react'
|
||||
|
||||
interface NotificationsSheetProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function NotificationsSheet({ isOpen, onClose }: NotificationsSheetProps) {
|
||||
const {
|
||||
current: currentPermission,
|
||||
pendingCount: permissionCount,
|
||||
setShowDialog,
|
||||
navigateToCurrent: navigateToPermission,
|
||||
} = usePermissions()
|
||||
const {
|
||||
current: currentQuestion,
|
||||
pendingCount: questionCount,
|
||||
navigateToCurrent: navigateToQuestion,
|
||||
} = useQuestions()
|
||||
|
||||
const handlePermissionClick = () => {
|
||||
navigateToPermission()
|
||||
setShowDialog(true)
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleQuestionClick = () => {
|
||||
navigateToQuestion()
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<BottomSheet isOpen={isOpen} onClose={onClose} ariaLabel="Notifications">
|
||||
<BottomSheetHeader title="Notifications" />
|
||||
<BottomSheetContent className="flex flex-col gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Bell className="w-5 h-5 text-orange-500" />
|
||||
<h3 className="font-semibold text-foreground">Pending permissions</h3>
|
||||
</div>
|
||||
{permissionCount === 0 ? (
|
||||
<div className="text-muted-foreground text-sm py-4">
|
||||
You're all caught up
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{currentPermission && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePermissionClick}
|
||||
className="flex flex-col items-start gap-1 p-3 rounded-lg border border-border hover:bg-accent transition-colors text-left w-full"
|
||||
>
|
||||
<span className="font-medium text-foreground capitalize">
|
||||
{currentPermission.permission.replace(/_/g, ' ')}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground truncate w-full">
|
||||
{currentPermission.patterns?.[0] || 'View details'}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
{permissionCount > 1 && (
|
||||
<div className="text-xs text-muted-foreground px-3">
|
||||
+{permissionCount - 1} more
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<HelpCircle className="w-5 h-5 text-blue-500" />
|
||||
<h3 className="font-semibold text-foreground">Pending questions</h3>
|
||||
</div>
|
||||
{questionCount === 0 ? (
|
||||
<div className="text-muted-foreground text-sm py-4">
|
||||
You're all caught up
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{currentQuestion && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleQuestionClick}
|
||||
className="flex flex-col items-start gap-1 p-3 rounded-lg border border-border hover:bg-accent transition-colors text-left w-full"
|
||||
>
|
||||
<span className="font-medium text-foreground">
|
||||
{currentQuestion.questions?.[0]?.question || 'Question'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground truncate w-full">
|
||||
Tap to view
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
{questionCount > 1 && (
|
||||
<div className="text-xs text-muted-foreground px-3">
|
||||
+{questionCount - 1} more
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</BottomSheetContent>
|
||||
</BottomSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
|
||||
import { listRepos } from '@/api/repos'
|
||||
|
||||
vi.mock('@/api/repos')
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('RepoQuickSwitchSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders with loading state', async () => {
|
||||
vi.mocked(listRepos).mockImplementation(() => new Promise(() => {}))
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<RepoQuickSwitchSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText('Search projects...')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('renders empty state when no repos', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([])
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<RepoQuickSwitchSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('No repos found')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('renders repo list and filters on search', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo1.git',
|
||||
localPath: '/path/to/repo1',
|
||||
sourcePath: null,
|
||||
currentBranch: 'main',
|
||||
isLocal: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
repoUrl: 'https://github.com/test/repo2.git',
|
||||
localPath: '/path/to/repo2',
|
||||
sourcePath: null,
|
||||
currentBranch: 'develop',
|
||||
isLocal: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<RepoQuickSwitchSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('repo1')).toBeInTheDocument()
|
||||
expect(screen.getByText('repo2')).toBeInTheDocument()
|
||||
})
|
||||
const input = screen.getByPlaceholderText('Search projects...')
|
||||
fireEvent.change(input, { target: { value: 'repo1' } })
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('repo1')).toBeInTheDocument()
|
||||
expect(screen.queryByText('repo2')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('navigates on repo click without calling onClose', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo1.git',
|
||||
localPath: '/path/to/repo1',
|
||||
sourcePath: null,
|
||||
currentBranch: 'main',
|
||||
isLocal: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<RepoQuickSwitchSheet isOpen onClose={handleClose} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('repo1')).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.click(screen.getByText('repo1'))
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
|
||||
import { cn, getRepoDisplayName } from '@/lib/utils'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import { FolderGit2, Check } from 'lucide-react'
|
||||
|
||||
interface RepoQuickSwitchSheetProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetProps) {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
const activeRepoId = useMemo(() => {
|
||||
const match = location.pathname.match(/^\/repos\/(\d+)/)
|
||||
return match ? Number(match[1]) : null
|
||||
}, [location.pathname])
|
||||
|
||||
const { data: repos, isLoading } = useQuery({
|
||||
queryKey: ['repos'],
|
||||
queryFn: listRepos,
|
||||
enabled: isOpen,
|
||||
})
|
||||
|
||||
const filteredRepos = useMemo(() => {
|
||||
if (!repos) return []
|
||||
const sorted = [...repos].sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0))
|
||||
if (!searchQuery.trim()) return sorted
|
||||
const query = searchQuery.toLowerCase()
|
||||
return sorted.filter((repo) =>
|
||||
getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath).toLowerCase().includes(query)
|
||||
)
|
||||
}, [repos, searchQuery])
|
||||
|
||||
const handleClick = (id: number) => {
|
||||
if (id === activeRepoId) {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
navigate(`/repos/${id}`, { replace: true })
|
||||
}
|
||||
|
||||
return (
|
||||
<BottomSheet isOpen={isOpen} onClose={onClose} heightClass="h-[70dvh]" ariaLabel="Switch repo">
|
||||
<BottomSheetHeader>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search projects..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
autoFocus
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
</BottomSheetHeader>
|
||||
<BottomSheetContent className="flex flex-col gap-2 overflow-y-auto pt-2">
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<div key={i} className="h-14 rounded-lg bg-muted animate-pulse" />
|
||||
))}
|
||||
</div>
|
||||
) : filteredRepos.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
|
||||
<FolderGit2 className="h-12 w-12 mb-3 opacity-50" />
|
||||
<p className="text-sm">No repos found</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{filteredRepos.map((repo) => {
|
||||
const isActive = repo.id === activeRepoId
|
||||
return (
|
||||
<button
|
||||
key={repo.id}
|
||||
type="button"
|
||||
onClick={() => handleClick(repo.id)}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
className={cn(
|
||||
'group flex items-center gap-3 p-3 rounded-lg border transition-all text-left w-full',
|
||||
isActive
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-accent hover:bg-accent/50',
|
||||
)}
|
||||
>
|
||||
<div className="flex-shrink-0">
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-center w-8 h-8 rounded-md',
|
||||
isActive ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary',
|
||||
)}
|
||||
>
|
||||
<FolderGit2 className="h-4 w-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 font-medium text-sm text-foreground truncate">
|
||||
{getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}
|
||||
</div>
|
||||
{isActive && <Check className="h-4 w-4 text-primary flex-shrink-0" />}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</BottomSheetContent>
|
||||
</BottomSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { MoreVertical } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
|
||||
export function SessionMoreButton() {
|
||||
const { open } = useMobileTabBar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => open('more')}
|
||||
className="md:hidden h-10 w-10 p-0 text-foreground border-border hover:bg-accent"
|
||||
aria-label="More"
|
||||
>
|
||||
<MoreVertical className="w-5 h-5" />
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildMoreItems } from './moreDrawerItems'
|
||||
|
||||
describe('buildMoreItems', () => {
|
||||
it('returns only Settings + Logout for root path', () => {
|
||||
const items = buildMoreItems('/')
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[0].key).toBe('settings')
|
||||
expect(items[1].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns repo-specific items with memory when plugin enabled for /repos/:id', () => {
|
||||
const items = buildMoreItems('/repos/42', { memoryPluginEnabled: true })
|
||||
expect(items).toHaveLength(9)
|
||||
expect(items[0].key).toBe('files')
|
||||
expect(items[0].dialog).toBe('files')
|
||||
expect(items[1].key).toBe('memory')
|
||||
expect(items[1].to).toBe('/repos/42/memories')
|
||||
expect(items[2].key).toBe('mcp')
|
||||
expect(items[2].dialog).toBe('mcp')
|
||||
expect(items[3].key).toBe('skills')
|
||||
expect(items[3].dialog).toBe('skills')
|
||||
expect(items[4].key).toBe('reset-permissions')
|
||||
expect(items[4].dialog).toBe('resetPermissions')
|
||||
expect(items[4].danger).toBe(true)
|
||||
expect(items[5].key).toBe('schedules')
|
||||
expect(items[5].to).toBe('/repos/42/schedules')
|
||||
expect(items[6].key).toBe('source-control')
|
||||
expect(items[6].dialog).toBe('sourceControl')
|
||||
expect(items[7].key).toBe('settings')
|
||||
expect(items[8].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('omits memory item for /repos/:id when plugin disabled', () => {
|
||||
const items = buildMoreItems('/repos/42')
|
||||
expect(items).toHaveLength(8)
|
||||
expect(items.some((item) => item.key === 'memory')).toBe(false)
|
||||
expect(items[0].key).toBe('files')
|
||||
expect(items[1].key).toBe('mcp')
|
||||
})
|
||||
|
||||
it('returns session-specific items with memory when plugin enabled for /repos/:id/sessions/:sid', () => {
|
||||
const items = buildMoreItems('/repos/42/sessions/abc', { memoryPluginEnabled: true })
|
||||
expect(items).toHaveLength(9)
|
||||
expect(items[0].key).toBe('files')
|
||||
expect(items[1].key).toBe('memory')
|
||||
expect(items[2].key).toBe('mcp')
|
||||
expect(items[3].key).toBe('skills')
|
||||
expect(items[4].key).toBe('lsp')
|
||||
expect(items[4].dialog).toBe('lsp')
|
||||
expect(items[5].key).toBe('reset-permissions')
|
||||
expect(items[6].key).toBe('source-control')
|
||||
expect(items[7].key).toBe('settings')
|
||||
expect(items[8].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('omits memory item for /repos/:id/sessions/:sid when plugin disabled', () => {
|
||||
const items = buildMoreItems('/repos/42/sessions/abc')
|
||||
expect(items).toHaveLength(8)
|
||||
expect(items.some((item) => item.key === 'memory')).toBe(false)
|
||||
expect(items[0].key).toBe('files')
|
||||
expect(items[1].key).toBe('mcp')
|
||||
})
|
||||
|
||||
it('returns only Settings + Logout for /repos/:id/memories', () => {
|
||||
const items = buildMoreItems('/repos/42/memories')
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[0].key).toBe('settings')
|
||||
expect(items[1].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns only Settings + Logout for /schedules', () => {
|
||||
const items = buildMoreItems('/schedules')
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[0].key).toBe('settings')
|
||||
expect(items[1].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns only Settings + Logout for /repos/:id/schedules', () => {
|
||||
const items = buildMoreItems('/repos/42/schedules')
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[0].key).toBe('settings')
|
||||
expect(items[1].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns only Settings + Logout for unknown paths', () => {
|
||||
const items = buildMoreItems('/unknown/path')
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[0].key).toBe('settings')
|
||||
expect(items[1].key).toBe('logout')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { FolderOpen, Brain, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, Code2, Settings, LogOut } from 'lucide-react'
|
||||
|
||||
export interface MoreDrawerItem {
|
||||
key: string
|
||||
label: string
|
||||
icon: LucideIcon
|
||||
to?: string
|
||||
dialog?: string
|
||||
danger?: boolean
|
||||
}
|
||||
|
||||
export interface BuildMoreItemsOptions {
|
||||
memoryPluginEnabled?: boolean
|
||||
}
|
||||
|
||||
export function buildMoreItems(pathname: string, options: BuildMoreItemsOptions = {}): MoreDrawerItem[] {
|
||||
const { memoryPluginEnabled = false } = options
|
||||
const baseItems: MoreDrawerItem[] = [
|
||||
{ key: 'settings', label: 'Settings', icon: Settings },
|
||||
{ key: 'logout', label: 'Logout', icon: LogOut },
|
||||
]
|
||||
|
||||
// Root path - no route-specific items
|
||||
if (pathname === '/') {
|
||||
return baseItems
|
||||
}
|
||||
|
||||
// RepoDetail: /repos/:id
|
||||
const repoDetailMatch = /^\/repos\/(\d+)$/.exec(pathname)
|
||||
if (repoDetailMatch) {
|
||||
const id = repoDetailMatch[1]
|
||||
return [
|
||||
{ key: 'files', label: 'Files', icon: FolderOpen, dialog: 'files' },
|
||||
...(memoryPluginEnabled
|
||||
? [{ key: 'memory', label: 'Memory', icon: Brain, to: `/repos/${id}/memories` }]
|
||||
: []),
|
||||
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
|
||||
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
|
||||
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
|
||||
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/schedules` },
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
...baseItems,
|
||||
]
|
||||
}
|
||||
|
||||
// SessionDetail: /repos/:id/sessions/:sid
|
||||
const sessionDetailMatch = /^\/repos\/(\d+)\/sessions\/[^/]+$/.exec(pathname)
|
||||
if (sessionDetailMatch) {
|
||||
const id = sessionDetailMatch[1]
|
||||
return [
|
||||
{ key: 'files', label: 'Files', icon: FolderOpen, dialog: 'files' },
|
||||
...(memoryPluginEnabled
|
||||
? [{ key: 'memory', label: 'Memory', icon: Brain, to: `/repos/${id}/memories` }]
|
||||
: []),
|
||||
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
|
||||
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
|
||||
{ key: 'lsp', label: 'LSP', icon: Code2, dialog: 'lsp' },
|
||||
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
...baseItems,
|
||||
]
|
||||
}
|
||||
|
||||
// Memories: /repos/:id/memories - no extra items
|
||||
if (/^\/repos\/\d+\/memories$/.test(pathname)) {
|
||||
return baseItems
|
||||
}
|
||||
|
||||
// Schedules routes - no extra items
|
||||
if (pathname === '/schedules' || /^\/repos\/\d+\/schedules$/.test(pathname)) {
|
||||
return baseItems
|
||||
}
|
||||
|
||||
// Unknown path - return base items only
|
||||
return baseItems
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { RepoCard } from './RepoCard'
|
||||
|
||||
const mockNavigate = vi.fn()
|
||||
@@ -15,7 +16,7 @@ vi.mock('react-router-dom', async () => {
|
||||
const defaultProps = {
|
||||
repo: {
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
repoUrl: 'https://github.com/test/test-repo',
|
||||
localPath: 'repos/test-repo',
|
||||
fullPath: '/Users/test/repos/test-repo',
|
||||
branch: 'main',
|
||||
@@ -31,7 +32,14 @@ const defaultProps = {
|
||||
}
|
||||
|
||||
const renderWithRouter = (ui: React.ReactElement) => {
|
||||
return render(<BrowserRouter>{ui}</BrowserRouter>)
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>{ui}</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('RepoCard', () => {
|
||||
@@ -50,8 +58,10 @@ describe('RepoCard', () => {
|
||||
expect(mockNavigate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should not show checkbox when manageMode is false', () => {
|
||||
renderWithRouter(<RepoCard {...defaultProps} manageMode={false} />)
|
||||
it('should not show checkbox when onSelect is not provided', () => {
|
||||
const { onSelect, ...propsWithoutSelect } = defaultProps
|
||||
void onSelect
|
||||
renderWithRouter(<RepoCard {...propsWithoutSelect} />)
|
||||
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -88,9 +98,9 @@ describe('RepoCard', () => {
|
||||
hasChanges: true,
|
||||
},
|
||||
}
|
||||
renderWithRouter(<RepoCard {...props} />)
|
||||
const { container } = renderWithRouter(<RepoCard {...props} />)
|
||||
|
||||
const indicator = screen.getByTestId('dirty-indicator') || screen.container.querySelector('.bg-orange-500')
|
||||
const indicator = container.querySelector('.bg-orange-500')
|
||||
expect(indicator).toBeTruthy()
|
||||
})
|
||||
|
||||
@@ -107,8 +117,8 @@ describe('RepoCard', () => {
|
||||
}
|
||||
renderWithRouter(<RepoCard {...props} />)
|
||||
|
||||
expect(screen.getByText('↑2')).toBeInTheDocument()
|
||||
expect(screen.getByText('↓1')).toBeInTheDocument()
|
||||
expect(screen.getByText(/↑2/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/↓1/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display activity label when provided', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { Search, SlidersHorizontal, Trash2 } from 'lucide-react'
|
||||
import { Search, SlidersHorizontal, Trash2, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
@@ -99,11 +99,11 @@ export function RepoListControls({
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onClearSelection}
|
||||
className="shrink-0 h-9 text-xs ml-auto"
|
||||
size="sm"
|
||||
className="shrink-0 size-9 ml-auto text-destructive hover:text-destructive"
|
||||
>
|
||||
Cancel
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -149,22 +149,22 @@ describe('repo-list-state', () => {
|
||||
|
||||
it('should filter by display name', () => {
|
||||
const repos = [
|
||||
createMockRepo({ id: 1, localPath: 'repos/test-repo' }),
|
||||
createMockRepo({ id: 2, localPath: 'repos/other-repo' }),
|
||||
createMockRepo({ id: 1, repoUrl: 'https://github.com/org/test-repo', localPath: 'repos/test-repo' }),
|
||||
createMockRepo({ id: 2, repoUrl: 'https://github.com/org/other-repo', localPath: 'repos/other-repo' }),
|
||||
]
|
||||
const viewModels = repos.map(r => ({ ...r, attentionState: getAttentionState(r), activityTimestamp: getActivityTimestamp(r) }))
|
||||
const result = filterReposBySearch(viewModels, 'test')
|
||||
const result = filterReposBySearch(viewModels, 'test-repo')
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].id).toBe(1)
|
||||
})
|
||||
|
||||
it('should filter case-insensitively', () => {
|
||||
const repos = [
|
||||
createMockRepo({ id: 1, localPath: 'repos/test-repo' }),
|
||||
createMockRepo({ id: 2, localPath: 'repos/other-repo' }),
|
||||
createMockRepo({ id: 1, repoUrl: 'https://github.com/org/test-repo', localPath: 'repos/test-repo' }),
|
||||
createMockRepo({ id: 2, repoUrl: 'https://github.com/org/other-repo', localPath: 'repos/other-repo' }),
|
||||
]
|
||||
const viewModels = repos.map(r => ({ ...r, attentionState: getAttentionState(r), activityTimestamp: getActivityTimestamp(r) }))
|
||||
const result = filterReposBySearch(viewModels, 'TEST')
|
||||
const result = filterReposBySearch(viewModels, 'TEST-REPO')
|
||||
expect(result).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -253,9 +253,9 @@ describe('repo-list-state', () => {
|
||||
|
||||
it('should sort alphabetically by name', () => {
|
||||
const repos = [
|
||||
createViewModel(1, { localPath: 'repos/zebra' }),
|
||||
createViewModel(2, { localPath: 'repos/alpha' }),
|
||||
createViewModel(3, { localPath: 'repos/middle' }),
|
||||
createViewModel(1, { repoUrl: 'https://github.com/org/zebra', localPath: 'repos/zebra' }),
|
||||
createViewModel(2, { repoUrl: 'https://github.com/org/alpha', localPath: 'repos/alpha' }),
|
||||
createViewModel(3, { repoUrl: 'https://github.com/org/middle', localPath: 'repos/middle' }),
|
||||
]
|
||||
const result = sortRepos(repos, 'name')
|
||||
expect(result[0].id).toBe(2)
|
||||
@@ -315,15 +315,17 @@ describe('repo-list-state', () => {
|
||||
|
||||
it('should return attention section for attention filter', () => {
|
||||
const now = Date.now()
|
||||
const repos = [
|
||||
createViewModel(1, {
|
||||
const repos: RepoViewModel[] = [
|
||||
{
|
||||
...createMockRepo({ id: 1 }),
|
||||
activityTimestamp: now,
|
||||
attentionState: { hasChanges: true, ahead: 0, behind: 0, isCloneStatusReady: true }
|
||||
}),
|
||||
createViewModel(2, {
|
||||
},
|
||||
{
|
||||
...createMockRepo({ id: 2 }),
|
||||
activityTimestamp: now,
|
||||
attentionState: { hasChanges: false, ahead: 0, behind: 0, isCloneStatusReady: true }
|
||||
}),
|
||||
},
|
||||
]
|
||||
const result = groupReposIntoSections(repos, 'attention', 'recent')
|
||||
expect(result).toHaveLength(1)
|
||||
|
||||
@@ -73,7 +73,7 @@ export function RunHistoryCards({
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-h-0 flex-1 h-full">
|
||||
<div className="min-h-0 flex-1 overflow-y-auto pt-4 pb-6 px-2 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<div className="min-h-0 flex-1 overflow-y-auto pt-4 px-2 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{runs.map((run, index) => {
|
||||
const isExpanded = expandedRunId === run.id
|
||||
const displayRun = isExpanded && runDetail ? runDetail : run
|
||||
|
||||
@@ -15,41 +15,41 @@ export function ScheduleTabMenu({ activeTab, onTabChange, className }: ScheduleT
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex-1 flex flex-col items-center gap-0.5 pt-2.5 pb-2 pb-safe text-xs font-medium transition-colors',
|
||||
'flex-1 flex flex-col items-center gap-1 px-2 py-2 text-xs font-medium border-b-2 transition-colors',
|
||||
activeTab === 'jobs'
|
||||
? 'bg-primary/10 text-primary'
|
||||
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
|
||||
? 'text-primary border-primary'
|
||||
: 'text-muted-foreground border-transparent hover:text-foreground',
|
||||
)}
|
||||
onClick={() => onTabChange('jobs')}
|
||||
>
|
||||
<CalendarClock className="h-4 w-4" />
|
||||
<CalendarClock className="h-5 w-5" />
|
||||
<span>Jobs</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex-1 flex flex-col items-center gap-0.5 pt-2.5 pb-2 pb-safe text-xs font-medium transition-colors',
|
||||
'flex-1 flex flex-col items-center gap-1 px-2 py-2 text-xs font-medium border-b-2 transition-colors',
|
||||
activeTab === 'detail'
|
||||
? 'bg-primary/10 text-primary'
|
||||
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
|
||||
? 'text-primary border-primary'
|
||||
: 'text-muted-foreground border-transparent hover:text-foreground',
|
||||
)}
|
||||
onClick={() => onTabChange('detail')}
|
||||
>
|
||||
<Info className="h-4 w-4" />
|
||||
<Info className="h-5 w-5" />
|
||||
<span>Detail</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex-1 flex flex-col items-center gap-0.5 pt-1.5 py-2 pb-safe text-xs font-medium transition-colors',
|
||||
'flex-1 flex flex-col items-center gap-1 px-2 py-2 text-xs font-medium border-b-2 transition-colors',
|
||||
activeTab === 'runs'
|
||||
? 'bg-primary/10 text-primary'
|
||||
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
|
||||
? 'text-primary border-primary'
|
||||
: 'text-muted-foreground border-transparent hover:text-foreground',
|
||||
)}
|
||||
onClick={() => onTabChange('runs')}
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
<span>Run History</span>
|
||||
<History className="h-5 w-5" />
|
||||
<span>Runs</span>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -70,7 +70,11 @@ export const SessionCard = ({
|
||||
} hover:shadow-lg`}
|
||||
onClick={() => {
|
||||
if (!isOpen) {
|
||||
onSelect(session.id);
|
||||
if (manageMode) {
|
||||
onToggleSelection(!isSelected);
|
||||
} else {
|
||||
onSelect(session.id);
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { useSessions, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { ListToolbar } from "@/components/ui/list-toolbar";
|
||||
import { DeleteSessionDialog } from "./DeleteSessionDialog";
|
||||
import { SessionCard } from "./SessionCard";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Search, Trash2, Pencil, X } from "lucide-react";
|
||||
|
||||
interface SessionListProps {
|
||||
opcodeUrl: string;
|
||||
@@ -24,13 +26,9 @@ export const SessionList = ({
|
||||
onSelectSession(newSession.id);
|
||||
});
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [sessionToDelete, setSessionToDelete] = useState<
|
||||
string | string[] | null
|
||||
>(null);
|
||||
const [sessionToDelete, setSessionToDelete] = useState<string | string[] | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(
|
||||
new Set(),
|
||||
);
|
||||
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(new Set());
|
||||
const [manageMode, setManageMode] = useState(false);
|
||||
|
||||
const filteredSessions = useMemo(() => {
|
||||
@@ -53,14 +51,12 @@ export const SessionList = ({
|
||||
}, [sessions, searchQuery, directory]);
|
||||
|
||||
const todaySessions = useMemo(() => {
|
||||
if (!filteredSessions) return [];
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
return filteredSessions.filter((session) => new Date(session.time.updated) >= today);
|
||||
}, [filteredSessions]);
|
||||
|
||||
const olderSessions = useMemo(() => {
|
||||
if (!filteredSessions) return [];
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
return filteredSessions.filter((session) => new Date(session.time.updated) < today);
|
||||
@@ -88,10 +84,7 @@ export const SessionList = ({
|
||||
);
|
||||
}
|
||||
|
||||
const handleDelete = (
|
||||
sessionId: string,
|
||||
e: React.MouseEvent<HTMLButtonElement>,
|
||||
) => {
|
||||
const handleDelete = (sessionId: string, e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
setSessionToDelete(sessionId);
|
||||
setDeleteDialogOpen(true);
|
||||
@@ -103,6 +96,7 @@ export const SessionList = ({
|
||||
setDeleteDialogOpen(false);
|
||||
setSessionToDelete(null);
|
||||
setSelectedSessions(new Set());
|
||||
setManageMode(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -110,6 +104,7 @@ export const SessionList = ({
|
||||
setDeleteDialogOpen(false);
|
||||
setSessionToDelete(null);
|
||||
setSelectedSessions(new Set());
|
||||
setManageMode(false);
|
||||
};
|
||||
|
||||
const toggleSessionSelection = (sessionId: string, selected: boolean) => {
|
||||
@@ -122,29 +117,15 @@ export const SessionList = ({
|
||||
setSelectedSessions(newSelected);
|
||||
};
|
||||
|
||||
const toggleManageMode = () => {
|
||||
setManageMode((prev) => {
|
||||
if (!prev) {
|
||||
return true;
|
||||
} else {
|
||||
setSelectedSessions(new Set());
|
||||
return false;
|
||||
}
|
||||
});
|
||||
};
|
||||
const allVisibleSelected =
|
||||
filteredSessions.length > 0 &&
|
||||
filteredSessions.every((s) => selectedSessions.has(s.id));
|
||||
|
||||
const toggleSelectAll = () => {
|
||||
if (!filteredSessions || filteredSessions.length === 0) return;
|
||||
|
||||
const allFilteredSelected = filteredSessions.every((session) =>
|
||||
selectedSessions.has(session.id),
|
||||
);
|
||||
|
||||
if (allFilteredSelected) {
|
||||
if (allVisibleSelected) {
|
||||
setSelectedSessions(new Set());
|
||||
} else {
|
||||
const filteredIds = filteredSessions.map((s) => s.id);
|
||||
setSelectedSessions(new Set(filteredIds));
|
||||
setSelectedSessions(new Set(filteredSessions.map((s) => s.id)));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -155,30 +136,60 @@ export const SessionList = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAll = () => {
|
||||
if (!filteredSessions || filteredSessions.length === 0) return;
|
||||
setSessionToDelete(filteredSessions.map((s) => s.id));
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
<ListToolbar
|
||||
searchQuery={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
selectedCount={selectedSessions.size}
|
||||
totalCount={filteredSessions.length}
|
||||
allSelected={
|
||||
filteredSessions.length > 0 &&
|
||||
filteredSessions.every((session) => selectedSessions.has(session.id))
|
||||
}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
onDelete={handleBulkDelete}
|
||||
onDeleteAll={handleDeleteAll}
|
||||
manageMode={manageMode}
|
||||
onToggleManageMode={toggleManageMode}
|
||||
/>
|
||||
{manageMode ? (
|
||||
<div className="flex items-center gap-2 bg-accent/50 rounded-md p-2">
|
||||
<span className="text-sm font-medium text-foreground shrink-0">
|
||||
{selectedSessions.size} selected
|
||||
</span>
|
||||
<Button variant="ghost" onClick={toggleSelectAll} className="shrink-0 h-9 text-xs" size="sm">
|
||||
{allVisibleSelected ? "Unselect All" : "Select All"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleBulkDelete}
|
||||
disabled={selectedSessions.size === 0}
|
||||
className="shrink-0 h-9 text-xs text-destructive hover:text-destructive"
|
||||
size="sm"
|
||||
>
|
||||
<Trash2 className="w-3 h-3 mr-1" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => { setSelectedSessions(new Set()); setManageMode(false); }}
|
||||
className="shrink-0 size-9 ml-auto text-destructive hover:text-destructive"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search sessions..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="shrink-0 size-9"
|
||||
onClick={() => {
|
||||
setManageMode(true);
|
||||
}}
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
@@ -202,9 +213,7 @@ export const SessionList = ({
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => {
|
||||
toggleSessionSelection(session.id, selected);
|
||||
}}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session.id, selected)}
|
||||
onDelete={(e) => handleDelete(session.id, e)}
|
||||
/>
|
||||
))}
|
||||
@@ -222,9 +231,7 @@ export const SessionList = ({
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => {
|
||||
toggleSessionSelection(session.id, selected);
|
||||
}}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session.id, selected)}
|
||||
onDelete={(e) => handleDelete(session.id, e)}
|
||||
/>
|
||||
))}
|
||||
@@ -239,9 +246,7 @@ export const SessionList = ({
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={cancelDelete}
|
||||
isDeleting={deleteSession.isPending}
|
||||
sessionCount={
|
||||
Array.isArray(sessionToDelete) ? sessionToDelete.length : 1
|
||||
}
|
||||
sessionCount={Array.isArray(sessionToDelete) ? sessionToDelete.length : 1}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -16,7 +16,6 @@ import { McpManager } from './McpManager'
|
||||
import { SkillsEditor } from './SkillsEditor'
|
||||
import { OpenCodeModelsEditor, type ConfigProvider } from './OpenCodeModelsEditor'
|
||||
import { VersionSelectDialog } from './VersionSelectDialog'
|
||||
import { MemoryPluginConfig } from './MemoryPluginConfig'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
@@ -599,28 +598,7 @@ export function OpenCodeConfigManager() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<MemoryPluginConfig
|
||||
memoryPluginEnabled={((configs.find(c => c.isDefault)?.content?.plugin as string[] | undefined) ?? []).includes('@opencode-manager/memory')}
|
||||
onToggle={async (enabled) => {
|
||||
const defaultConfig = configs.find(c => c.isDefault)
|
||||
if (!defaultConfig) return
|
||||
|
||||
const currentPlugins = (defaultConfig.content?.plugin as string[] | undefined) ?? []
|
||||
const memoryPlugin = '@opencode-manager/memory'
|
||||
const newPlugins = enabled
|
||||
? currentPlugins.includes(memoryPlugin)
|
||||
? currentPlugins
|
||||
: [...currentPlugins, memoryPlugin]
|
||||
: currentPlugins.filter(p => p !== memoryPlugin)
|
||||
|
||||
await updateConfigContent(defaultConfig.name, {
|
||||
...defaultConfig.content,
|
||||
plugin: newPlugins.length > 0 ? newPlugins : undefined
|
||||
}, true)
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ['memory-plugin-status'] })
|
||||
}}
|
||||
/>
|
||||
|
||||
|
||||
<CreateConfigDialog
|
||||
isOpen={isCreateDialogOpen}
|
||||
|
||||
@@ -24,6 +24,17 @@ const mockProviders: Record<string, ConfigProvider> = {
|
||||
},
|
||||
}
|
||||
|
||||
const findTrashButton = (): HTMLButtonElement | null => {
|
||||
const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>('button'))
|
||||
for (const btn of buttons) {
|
||||
const svg = btn.querySelector('svg')
|
||||
if (svg && svg.getAttribute('class')?.includes('trash')) {
|
||||
return btn
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
describe('OpenCodeModelsEditor', () => {
|
||||
describe('rendering', () => {
|
||||
it('should render empty state when no providers configured', () => {
|
||||
@@ -68,15 +79,7 @@ describe('OpenCodeModelsEditor', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<OpenCodeModelsEditor providers={mockProviders} onChange={onChange} />)
|
||||
|
||||
const deleteButtons = document.querySelectorAll('button')
|
||||
let deleteButton: HTMLButtonElement | null = null
|
||||
deleteButtons.forEach(btn => {
|
||||
const svg = btn.querySelector('svg')
|
||||
if (svg && svg.className.baseVal.includes('Trash2')) {
|
||||
deleteButton = btn as HTMLButtonElement
|
||||
}
|
||||
})
|
||||
|
||||
const deleteButton = findTrashButton()
|
||||
expect(deleteButton).not.toBeNull()
|
||||
if (deleteButton) {
|
||||
fireEvent.click(deleteButton)
|
||||
@@ -107,15 +110,7 @@ describe('OpenCodeModelsEditor', () => {
|
||||
|
||||
render(<OpenCodeModelsEditor providers={providersWithExtras} onChange={onChange} />)
|
||||
|
||||
const deleteButtons = document.querySelectorAll('button')
|
||||
let deleteButton: HTMLButtonElement | null = null
|
||||
deleteButtons.forEach(btn => {
|
||||
const svg = btn.querySelector('svg')
|
||||
if (svg && svg.className.baseVal.includes('Trash2')) {
|
||||
deleteButton = btn as HTMLButtonElement
|
||||
}
|
||||
})
|
||||
|
||||
const deleteButton = findTrashButton()
|
||||
if (deleteButton) {
|
||||
fireEvent.click(deleteButton)
|
||||
}
|
||||
@@ -155,15 +150,13 @@ describe('OpenCodeModelDialog', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('should require display name when submitting empty form', async () => {
|
||||
it('should disable create button when required fields are empty', async () => {
|
||||
const { OpenCodeModelDialog } = await import('./OpenCodeModelDialog')
|
||||
render(<OpenCodeModelDialog {...defaultProps} />)
|
||||
|
||||
const createButton = screen.getByRole('button', { name: /create/i })
|
||||
fireEvent.click(createButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/display name is required/i)).toBeInTheDocument()
|
||||
const createButton = screen.getByRole('button', { name: /create/i })
|
||||
expect(createButton).toBeDisabled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -172,15 +165,12 @@ describe('OpenCodeModelDialog', () => {
|
||||
render(<OpenCodeModelDialog {...defaultProps} />)
|
||||
|
||||
const modelIdInput = document.querySelector('input[name="modelId"]') as HTMLInputElement
|
||||
if (modelIdInput) {
|
||||
fireEvent.change(modelIdInput, { target: { value: 'invalid model id!' } })
|
||||
const createButton = screen.getByRole('button', { name: /create/i })
|
||||
fireEvent.click(createButton)
|
||||
expect(modelIdInput).not.toBeNull()
|
||||
fireEvent.change(modelIdInput, { target: { value: 'invalid model id!' } })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/alphanumeric/i)).toBeInTheDocument()
|
||||
})
|
||||
}
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/must use only letters, numbers/i)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -191,15 +181,18 @@ describe('OpenCodeModelDialog', () => {
|
||||
render(<OpenCodeModelDialog {...defaultProps} onSubmit={onSubmit} />)
|
||||
|
||||
const modelIdInput = document.querySelector('input[name="modelId"]') as HTMLInputElement
|
||||
const nameInput = document.querySelector('input[name="name"]') as HTMLInputElement
|
||||
const displayNameInput = document.querySelector('input[name="displayName"]') as HTMLInputElement
|
||||
|
||||
if (modelIdInput && nameInput) {
|
||||
fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } })
|
||||
fireEvent.change(nameInput, { target: { value: 'GPT-5' } })
|
||||
}
|
||||
expect(modelIdInput).not.toBeNull()
|
||||
expect(displayNameInput).not.toBeNull()
|
||||
fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } })
|
||||
fireEvent.change(displayNameInput, { target: { value: 'GPT-5' } })
|
||||
|
||||
const createButton = screen.getByRole('button', { name: /create/i })
|
||||
fireEvent.click(createButton)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: /create/i })).not.toBeDisabled()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /create/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledWith(
|
||||
@@ -218,19 +211,25 @@ describe('OpenCodeModelDialog', () => {
|
||||
render(<OpenCodeModelDialog {...defaultProps} onSubmit={onSubmit} />)
|
||||
|
||||
const modelIdInput = document.querySelector('input[name="modelId"]') as HTMLInputElement
|
||||
const nameInput = document.querySelector('input[name="name"]') as HTMLInputElement
|
||||
const displayNameInput = document.querySelector('input[name="displayName"]') as HTMLInputElement
|
||||
const contextLimitInput = document.querySelector('input[name="contextLimit"]') as HTMLInputElement
|
||||
const outputLimitInput = document.querySelector('input[name="outputLimit"]') as HTMLInputElement
|
||||
|
||||
if (modelIdInput && nameInput && contextLimitInput && outputLimitInput) {
|
||||
fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } })
|
||||
fireEvent.change(nameInput, { target: { value: 'GPT-5' } })
|
||||
fireEvent.change(contextLimitInput, { target: { value: '256000' } })
|
||||
fireEvent.change(outputLimitInput, { target: { value: '8192' } })
|
||||
}
|
||||
expect(modelIdInput).not.toBeNull()
|
||||
expect(displayNameInput).not.toBeNull()
|
||||
expect(contextLimitInput).not.toBeNull()
|
||||
expect(outputLimitInput).not.toBeNull()
|
||||
|
||||
const createButton = screen.getByRole('button', { name: /create/i })
|
||||
fireEvent.click(createButton)
|
||||
fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } })
|
||||
fireEvent.change(displayNameInput, { target: { value: 'GPT-5' } })
|
||||
fireEvent.change(contextLimitInput, { target: { value: '256000' } })
|
||||
fireEvent.change(outputLimitInput, { target: { value: '8192' } })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: /create/i })).not.toBeDisabled()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /create/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledWith(
|
||||
@@ -300,6 +299,7 @@ describe('OpenCodeModelDialog', () => {
|
||||
providerId: 'openai',
|
||||
modelId: 'gpt-4o',
|
||||
model: {
|
||||
id: 'gpt-4o',
|
||||
name: 'GPT-4o',
|
||||
limit: { context: 128000, output: 4096 },
|
||||
reasoning: true,
|
||||
@@ -321,6 +321,10 @@ describe('OpenCodeModelDialog', () => {
|
||||
target: { value: 'my-friendly-model' },
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: /update/i })).not.toBeDisabled()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /update/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useRef, useEffect, useCallback } from 'react'
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { GeneralSettings } from '@/components/settings/GeneralSettings'
|
||||
import { GitSettings } from '@/components/settings/GitSettings'
|
||||
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
||||
@@ -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 { useSwipeToClose } from '@/hooks/useMobile'
|
||||
import { useSwipeBack } from '@/hooks/useMobile'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
|
||||
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice' | 'notifications'
|
||||
@@ -21,17 +21,10 @@ export function SettingsDialog() {
|
||||
const [mobileView, setMobileView] = useState<SettingsView>('menu')
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const handleSwipeBack = useCallback(() => {
|
||||
if (mobileView === 'menu') {
|
||||
setMobileView('menu')
|
||||
close()
|
||||
} else {
|
||||
setMobileView('menu')
|
||||
}
|
||||
}, [mobileView, close])
|
||||
|
||||
const { bind: bindSwipe, swipeStyles } = useSwipeToClose(handleSwipeBack, {
|
||||
const { bind: bindSwipe, swipeStyles } = useSwipeBack(close, {
|
||||
enabled: isOpen,
|
||||
canBack: () => mobileView !== 'menu',
|
||||
onBack: () => setMobileView('menu'),
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from './bottom-sheet'
|
||||
import { useSwipeDismiss } from '@/hooks/useMobile'
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useSwipeDismiss: vi.fn(() => ({
|
||||
bind: vi.fn(),
|
||||
swipeProgress: 0,
|
||||
swipeStyles: {},
|
||||
})),
|
||||
}))
|
||||
|
||||
describe('BottomSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders when isOpen is true', () => {
|
||||
render(
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
expect(screen.getByText('Test content')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render when isOpen is false', async () => {
|
||||
const { container } = render(
|
||||
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(container.querySelector('[role="dialog"]')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('calls onClose when backdrop is clicked', () => {
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<BottomSheet isOpen onClose={handleClose} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
const backdrop = document.querySelector('.bg-black\\/40')
|
||||
if (backdrop) {
|
||||
fireEvent.click(backdrop)
|
||||
}
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls onClose when Escape key is pressed', () => {
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<BottomSheet isOpen onClose={handleClose} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('applies pb-safe class', () => {
|
||||
render(
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('pb-safe')
|
||||
})
|
||||
|
||||
it('applies custom heightClass', () => {
|
||||
render(
|
||||
<BottomSheet isOpen onClose={() => {}} heightClass="h-[50dvh]" ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('h-[50dvh]')
|
||||
})
|
||||
|
||||
it('passes correct options to useSwipeDismiss', () => {
|
||||
const mockBind = vi.fn()
|
||||
vi.mocked(useSwipeDismiss).mockReturnValue({
|
||||
bind: mockBind,
|
||||
swipeProgress: 0,
|
||||
swipeStyles: {},
|
||||
})
|
||||
|
||||
render(
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
|
||||
expect(useSwipeDismiss).toHaveBeenCalledWith(expect.any(Function), {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
})
|
||||
|
||||
it('binds gesture to the panel element with aria-modal', () => {
|
||||
const mockBind = vi.fn()
|
||||
vi.mocked(useSwipeDismiss).mockReturnValue({
|
||||
bind: mockBind,
|
||||
swipeProgress: 0,
|
||||
swipeStyles: {},
|
||||
})
|
||||
|
||||
render(
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
|
||||
const panelElement = document.querySelector('[aria-modal="true"]')
|
||||
expect(panelElement).toBeInTheDocument()
|
||||
|
||||
expect(mockBind).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BottomSheetHeader', () => {
|
||||
it('renders with title', () => {
|
||||
render(
|
||||
<BottomSheetHeader title="Test Title">
|
||||
<div>Header content</div>
|
||||
</BottomSheetHeader>,
|
||||
)
|
||||
expect(screen.getByText('Test Title')).toBeInTheDocument()
|
||||
expect(screen.getByText('Header content')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders without title', () => {
|
||||
render(
|
||||
<BottomSheetHeader>
|
||||
<div>Header content only</div>
|
||||
</BottomSheetHeader>,
|
||||
)
|
||||
expect(screen.getByText('Header content only')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BottomSheetContent', () => {
|
||||
it('renders children with default padding', () => {
|
||||
render(
|
||||
<BottomSheetContent>
|
||||
<div>Content</div>
|
||||
</BottomSheetContent>,
|
||||
)
|
||||
expect(screen.getByText('Content')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(
|
||||
<BottomSheetContent className="custom-class">
|
||||
<div>Content</div>
|
||||
</BottomSheetContent>,
|
||||
)
|
||||
const content = screen.getByText('Content').parentElement
|
||||
expect(content).toHaveClass('custom-class')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { useSwipeDismiss } from '@/hooks/useMobile'
|
||||
|
||||
export interface BottomSheetProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
heightClass?: string
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
ariaLabel?: string
|
||||
}
|
||||
|
||||
export function BottomSheet({
|
||||
isOpen,
|
||||
onClose,
|
||||
heightClass = 'h-[70dvh]',
|
||||
className,
|
||||
children,
|
||||
ariaLabel,
|
||||
}: BottomSheetProps) {
|
||||
const [shouldRender, setShouldRender] = useState(false)
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const { bind, swipeStyles } = useSwipeDismiss(onClose, {
|
||||
enabled: isOpen,
|
||||
threshold: 80,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
return bind(panelRef.current)
|
||||
}, [bind])
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setShouldRender(true)
|
||||
} else {
|
||||
const timer = setTimeout(() => setShouldRender(false), MODAL_TRANSITION_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && isOpen) {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('keydown', handleEscape)
|
||||
document.body.style.overflow = 'hidden'
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleEscape)
|
||||
document.body.style.overflow = 'unset'
|
||||
}
|
||||
}, [isOpen, onClose])
|
||||
|
||||
if (!isOpen && !shouldRender) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50"
|
||||
style={{
|
||||
opacity: isOpen ? 1 : 0,
|
||||
pointerEvents: isOpen ? 'auto' : 'none',
|
||||
transition: `opacity ${MODAL_TRANSITION_MS}ms ease-out`,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div
|
||||
ref={panelRef}
|
||||
className={cn(
|
||||
'fixed inset-x-0 bottom-0 flex flex-col bg-background rounded-t-2xl border-t border-border',
|
||||
heightClass,
|
||||
className,
|
||||
)}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={ariaLabel}
|
||||
style={swipeStyles}
|
||||
>
|
||||
<div className="w-full flex justify-center pt-3 pb-2">
|
||||
<div className="w-9 h-1 rounded-full bg-muted-foreground/30" />
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface BottomSheetHeaderProps {
|
||||
title?: string
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
export function BottomSheetHeader({ title, children }: BottomSheetHeaderProps) {
|
||||
return (
|
||||
<div className="flex-shrink-0 border-b border-border bg-background px-4 py-3">
|
||||
{title && (
|
||||
<h2 className="text-lg font-semibold text-foreground">{title}</h2>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface BottomSheetContentProps {
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export function BottomSheetContent({ className, children }: BottomSheetContentProps) {
|
||||
return (
|
||||
<div className={cn('flex-1 overflow-auto min-h-0 px-4 pt-3 pb-safe', className)}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,7 +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'
|
||||
import { useSwipeBack } from '@/hooks/useMobile'
|
||||
|
||||
const Dialog = DialogPrimitive.Root
|
||||
|
||||
@@ -64,7 +64,7 @@ const DialogContent = React.forwardRef<
|
||||
window.addEventListener('resize', check)
|
||||
return () => window.removeEventListener('resize', check)
|
||||
}, [])
|
||||
const { bind: swipeBind } = useSwipeToClose(
|
||||
const { bind: swipeBind } = useSwipeBack(
|
||||
() => closeTriggerRef.current?.click(),
|
||||
{ enabled: isMobileFullscreenMode && mobileSwipeToClose === true && isMobile }
|
||||
)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react'
|
||||
import { AlertTriangle, RefreshCw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
interface Props {
|
||||
children: ReactNode
|
||||
fallback?: ReactNode
|
||||
}
|
||||
|
||||
interface State {
|
||||
error: Error | null
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends Component<Props, State> {
|
||||
state: State = { error: null }
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { error }
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo) {
|
||||
console.error('[ErrorBoundary]', error, info.componentStack)
|
||||
}
|
||||
|
||||
reset = () => this.setState({ error: null })
|
||||
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
if (this.props.fallback) return this.props.fallback
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen gap-6 p-6 text-center bg-background">
|
||||
<AlertTriangle className="w-12 h-12 text-destructive" />
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold text-foreground">Something went wrong</h1>
|
||||
<p className="text-sm text-muted-foreground max-w-sm">
|
||||
{this.state.error.message}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={this.reset} className="gap-2">
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return this.props.children
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,15 @@
|
||||
import { Settings, Bell, HelpCircle, MoreVertical } from "lucide-react";
|
||||
import { Settings } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { BackButton } from "@/components/ui/back-button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
|
||||
import { useTheme } from "@/hooks/useTheme";
|
||||
import { EditSessionTitleDialog } from "@/components/session/EditSessionTitleDialog";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger, DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ReactNode } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
import { X } from "lucide-react";
|
||||
import { usePermissions, useQuestions } from "@/contexts/EventContext";
|
||||
|
||||
interface HeaderProps {
|
||||
children: ReactNode;
|
||||
@@ -163,60 +161,6 @@ function HeaderActions({ children, className }: { children: ReactNode; className
|
||||
return <div className={cn("flex items-center gap-2", className)}>{children}</div>;
|
||||
}
|
||||
|
||||
function HeaderMobileDropdown({ children, className }: { children: ReactNode; className?: string }) {
|
||||
const isMobile = useMobile();
|
||||
const { pendingCount: permissionCount, setShowDialog, navigateToCurrent: navigateToPermission } = usePermissions();
|
||||
const { pendingCount: questionCount, navigateToCurrent } = useQuestions();
|
||||
const { open } = useSettingsDialog();
|
||||
|
||||
const totalPending = permissionCount + questionCount;
|
||||
|
||||
if (!isMobile) return null;
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className={cn("text-foreground border-border hover:bg-accent transition-all duration-200 h-8 w-8 relative", className)}
|
||||
title={totalPending > 0 ? `${totalPending} pending notification${totalPending > 1 ? 's' : ''}` : "Options"}
|
||||
>
|
||||
{totalPending > 0 ? (
|
||||
<>
|
||||
<Bell className="w-4 h-4" />
|
||||
<span className="absolute top-1 right-1 w-2 h-2 rounded-full bg-orange-500 animate-pulse" />
|
||||
</>
|
||||
) : (
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{permissionCount > 0 && (
|
||||
<DropdownMenuItem onClick={() => { navigateToPermission(); setShowDialog(true); }} className="gap-2">
|
||||
<Bell className="w-4 h-4 text-orange-500" />
|
||||
<span>{permissionCount} pending permission{permissionCount > 1 ? 's' : ''}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{questionCount > 0 && (
|
||||
<DropdownMenuItem onClick={navigateToCurrent} className="gap-2">
|
||||
<HelpCircle className="w-4 h-4 text-blue-500" />
|
||||
<span>{questionCount} pending question{questionCount > 1 ? 's' : ''}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{totalPending > 0 && children && <DropdownMenuSeparator />}
|
||||
{children}
|
||||
{children && <DropdownMenuSeparator />}
|
||||
<DropdownMenuItem onClick={open} className="gap-2 bg-muted">
|
||||
<Settings className="w-4 h-4" />
|
||||
<span>Settings</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function HeaderSettingsButton() {
|
||||
const { open } = useSettingsDialog();
|
||||
|
||||
@@ -237,13 +181,11 @@ export const Header = Object.assign(HeaderBase, {
|
||||
Title: HeaderTitle,
|
||||
EditableTitle: HeaderEditableTitle,
|
||||
Actions: HeaderActions,
|
||||
MobileDropdown: HeaderMobileDropdown,
|
||||
Settings: HeaderSettingsButton,
|
||||
}) as typeof HeaderBase & {
|
||||
BackButton: typeof HeaderBackButton;
|
||||
Title: typeof HeaderTitle;
|
||||
EditableTitle: typeof HeaderEditableTitle;
|
||||
Actions: typeof HeaderActions;
|
||||
MobileDropdown: typeof HeaderMobileDropdown;
|
||||
Settings: typeof HeaderSettingsButton;
|
||||
};
|
||||
@@ -1,122 +0,0 @@
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Trash2, Search, GripVertical, Check, Pencil, PencilOff } from "lucide-react";
|
||||
|
||||
interface ListToolbarProps {
|
||||
searchQuery: string;
|
||||
onSearchChange: (query: string) => void;
|
||||
searchPlaceholder?: string;
|
||||
selectedCount: number;
|
||||
totalCount: number;
|
||||
allSelected: boolean;
|
||||
onToggleSelectAll: () => void;
|
||||
onDelete: () => void;
|
||||
onDeleteAll: () => void;
|
||||
reorderMode?: boolean;
|
||||
onToggleReorderMode?: () => void;
|
||||
showReorderToggle?: boolean;
|
||||
manageMode?: boolean;
|
||||
onToggleManageMode?: () => void;
|
||||
}
|
||||
|
||||
export function ListToolbar({
|
||||
searchQuery,
|
||||
onSearchChange,
|
||||
searchPlaceholder = "Search",
|
||||
selectedCount,
|
||||
totalCount,
|
||||
allSelected,
|
||||
onToggleSelectAll,
|
||||
onDelete,
|
||||
onDeleteAll,
|
||||
reorderMode = false,
|
||||
onToggleReorderMode,
|
||||
showReorderToggle = false,
|
||||
manageMode = false,
|
||||
onToggleManageMode,
|
||||
}: ListToolbarProps) {
|
||||
const hasItems = totalCount > 0;
|
||||
const hasSelection = selectedCount > 0;
|
||||
|
||||
const handleMobileDelete = () => {
|
||||
if (hasSelection) {
|
||||
onDelete();
|
||||
} else {
|
||||
onDeleteAll();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={searchPlaceholder}
|
||||
value={searchQuery}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
{manageMode && hasItems && (
|
||||
<Button
|
||||
onClick={onToggleSelectAll}
|
||||
variant={hasSelection ? "default" : "outline"}
|
||||
className="whitespace-nowrap hidden md:flex"
|
||||
>
|
||||
{allSelected ? "Deselect All" : "Select All"}
|
||||
</Button>
|
||||
)}
|
||||
{manageMode && (
|
||||
<Button
|
||||
onClick={onDelete}
|
||||
variant="destructive"
|
||||
disabled={!hasSelection}
|
||||
className="hidden md:flex whitespace-nowrap"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Delete ({selectedCount})
|
||||
</Button>
|
||||
)}
|
||||
{manageMode && (
|
||||
<Button
|
||||
onClick={handleMobileDelete}
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
className="md:hidden shrink-0 size-10"
|
||||
disabled={!hasItems}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
{showReorderToggle && onToggleReorderMode && (
|
||||
<Button
|
||||
onClick={onToggleReorderMode}
|
||||
variant={reorderMode ? "default" : "outline"}
|
||||
size="icon"
|
||||
className="md:hidden shrink-0 size-10"
|
||||
>
|
||||
{reorderMode ? (
|
||||
<Check className="w-4 h-4" />
|
||||
) : (
|
||||
<GripVertical className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{onToggleManageMode && hasItems && (
|
||||
<Button
|
||||
onClick={onToggleManageMode}
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="shrink-0 size-10"
|
||||
>
|
||||
{manageMode ? (
|
||||
<PencilOff className="w-4 h-4" />
|
||||
) : (
|
||||
<Pencil className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -52,12 +52,11 @@ describe("PageHeader", () => {
|
||||
expect(header).toHaveClass("z-10");
|
||||
});
|
||||
|
||||
it("applies background and border styling", () => {
|
||||
it("applies background styling", () => {
|
||||
render(<PageHeader data-testid="header">Content</PageHeader>);
|
||||
const header = screen.getByTestId("header");
|
||||
expect(header).toHaveClass("border-b");
|
||||
expect(header).toHaveClass("border-border");
|
||||
expect(header).toHaveClass("bg-gradient-to-b");
|
||||
expect(header).toHaveClass("from-background");
|
||||
});
|
||||
|
||||
it("applies backdrop-blur-sm for frosted glass effect", () => {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { SideDrawer, SideDrawerHeader, SideDrawerContent } from './side-drawer'
|
||||
|
||||
describe('SideDrawer', () => {
|
||||
it('renders when isOpen is true', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
expect(screen.getByText('Test content')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render when isOpen is false', async () => {
|
||||
const { container } = render(
|
||||
<SideDrawer isOpen={false} onClose={() => {}} ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(container.querySelector('[role="dialog"]')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('calls onClose when backdrop is clicked', () => {
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<SideDrawer isOpen onClose={handleClose} ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const backdrop = document.querySelector('.bg-black\\/40')
|
||||
if (backdrop) {
|
||||
fireEvent.click(backdrop)
|
||||
}
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls onClose when Escape key is pressed', () => {
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<SideDrawer isOpen onClose={handleClose} ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('applies pt-safe and pb-safe classes', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('pt-safe')
|
||||
expect(dialog).toHaveClass('pb-safe')
|
||||
})
|
||||
|
||||
it('defaults to right side', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('right-0')
|
||||
})
|
||||
|
||||
it('applies left side when specified', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} side="left" ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('left-0')
|
||||
})
|
||||
|
||||
it('applies custom widthClass', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} widthClass="w-80" ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('w-80')
|
||||
})
|
||||
})
|
||||
|
||||
describe('SideDrawerHeader', () => {
|
||||
it('renders with title and close button', () => {
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<SideDrawerHeader title="Test Title" onClose={handleClose} />,
|
||||
)
|
||||
expect(screen.getByText('Test Title')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /close/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onClose when close button is clicked', () => {
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<SideDrawerHeader title="Test Title" onClose={handleClose} />,
|
||||
)
|
||||
fireEvent.click(screen.getByRole('button', { name: /close/i }))
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SideDrawerContent', () => {
|
||||
it('renders children with default padding', () => {
|
||||
render(
|
||||
<SideDrawerContent>
|
||||
<div>Content</div>
|
||||
</SideDrawerContent>,
|
||||
)
|
||||
expect(screen.getByText('Content')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(
|
||||
<SideDrawerContent className="custom-class">
|
||||
<div>Content</div>
|
||||
</SideDrawerContent>,
|
||||
)
|
||||
const content = screen.getByText('Content').parentElement
|
||||
expect(content).toHaveClass('custom-class')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { X } from 'lucide-react'
|
||||
|
||||
export interface SideDrawerProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
side?: 'left' | 'right'
|
||||
widthClass?: string
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
ariaLabel?: string
|
||||
}
|
||||
|
||||
export function SideDrawer({
|
||||
isOpen,
|
||||
onClose,
|
||||
side = 'right',
|
||||
widthClass = 'w-[min(85vw,320px)]',
|
||||
className,
|
||||
children,
|
||||
ariaLabel,
|
||||
}: SideDrawerProps) {
|
||||
const [shouldRender, setShouldRender] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setShouldRender(true)
|
||||
} else {
|
||||
const timer = setTimeout(() => setShouldRender(false), MODAL_TRANSITION_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && isOpen) {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('keydown', handleEscape)
|
||||
document.body.style.overflow = 'hidden'
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleEscape)
|
||||
document.body.style.overflow = 'unset'
|
||||
}
|
||||
}, [isOpen, onClose])
|
||||
|
||||
if (!isOpen && !shouldRender) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50"
|
||||
style={{
|
||||
opacity: isOpen ? 1 : 0,
|
||||
pointerEvents: isOpen ? 'auto' : 'none',
|
||||
transition: `opacity ${MODAL_TRANSITION_MS}ms ease-out`,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
'fixed top-0 bottom-0 bg-background border-l border-border pt-safe pb-safe flex flex-col',
|
||||
side === 'right' ? 'right-0' : 'left-0',
|
||||
widthClass,
|
||||
className,
|
||||
)}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface SideDrawerHeaderProps {
|
||||
title: string
|
||||
onClose: () => void
|
||||
meta?: React.ReactNode
|
||||
}
|
||||
|
||||
export function SideDrawerHeader({ title, onClose, meta }: SideDrawerHeaderProps) {
|
||||
return (
|
||||
<div className="flex-shrink-0 border-b border-border bg-background px-4 py-2 flex items-center justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-lg font-semibold text-foreground leading-none">{title}</h2>
|
||||
{meta ? <div className="mt-1 min-w-0">{meta}</div> : null}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-muted transition-colors rounded-sm p-1 shrink-0"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface SideDrawerContentProps {
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export function SideDrawerContent({ className, children }: SideDrawerContentProps) {
|
||||
return (
|
||||
<div className={cn('flex-1 overflow-auto min-h-0 px-4 py-3', className)}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { createContext, useEffect, useState, useCallback, type ReactNode } from 'react'
|
||||
import { createContext, useEffect, useMemo, useState, useCallback, type ReactNode } from 'react'
|
||||
import { useSession, signIn, signUp, signOut, authClient, type AuthUser } from '@/lib/auth-client'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
|
||||
@@ -125,7 +125,7 @@ export function AuthProvider({ children }: AuthProviderProps) {
|
||||
await refetch()
|
||||
}, [refetch])
|
||||
|
||||
const value: AuthContextValue = {
|
||||
const value = useMemo<AuthContextValue>(() => ({
|
||||
user: session?.user ?? null,
|
||||
isAuthenticated: !!session?.user,
|
||||
isLoading: isPending,
|
||||
@@ -137,7 +137,18 @@ export function AuthProvider({ children }: AuthProviderProps) {
|
||||
addPasskey,
|
||||
logout,
|
||||
refreshSession,
|
||||
}
|
||||
}), [
|
||||
session,
|
||||
isPending,
|
||||
config,
|
||||
signInWithEmail,
|
||||
signInWithProvider,
|
||||
signInWithPasskey,
|
||||
signUpWithEmail,
|
||||
addPasskey,
|
||||
logout,
|
||||
refreshSession,
|
||||
])
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={value}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useQueryClient, useQuery } from '@tanstack/react-query'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import { listRepos } from '@/api/repos'
|
||||
@@ -117,7 +117,6 @@ const EventContext = createContext<EventContextValue | null>(null)
|
||||
export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
const [sshHostKeyRequest, setSSHHostKeyRequest] = useState<SSHHostKeyRequest | null>(null)
|
||||
|
||||
@@ -322,22 +321,22 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const repoId = getRepoIdForSession(currentQuestion.sessionID)
|
||||
if (repoId) {
|
||||
const targetPath = `/repos/${repoId}/sessions/${currentQuestion.sessionID}`
|
||||
if (location.pathname !== targetPath) {
|
||||
if (window.location.pathname !== targetPath) {
|
||||
navigate(targetPath)
|
||||
}
|
||||
}
|
||||
}, [currentQuestion, getRepoIdForSession, navigate, location.pathname])
|
||||
}, [currentQuestion, getRepoIdForSession, navigate])
|
||||
|
||||
const navigateToCurrentPermission = useCallback(() => {
|
||||
if (!currentPermission) return
|
||||
const repoId = getRepoIdForSession(currentPermission.sessionID)
|
||||
if (repoId) {
|
||||
const targetPath = `/repos/${repoId}/sessions/${currentPermission.sessionID}`
|
||||
if (location.pathname !== targetPath) {
|
||||
if (window.location.pathname !== targetPath) {
|
||||
navigate(targetPath)
|
||||
}
|
||||
}
|
||||
}, [currentPermission, getRepoIdForSession, navigate, location.pathname])
|
||||
}, [currentPermission, getRepoIdForSession, navigate])
|
||||
|
||||
const fetchInitialPendingData = useCallback(async () => {
|
||||
if (!repos || repos.length === 0) return
|
||||
@@ -534,3 +533,8 @@ export function useQuestions() {
|
||||
const { questions } = useEventContext()
|
||||
return questions
|
||||
}
|
||||
|
||||
export function usePendingAlerts(): boolean {
|
||||
const { permissions, questions } = useEventContext()
|
||||
return permissions.pendingCount + questions.pendingCount > 0
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { SwipeNavigationProvider, useSwipeNavigation } from './SwipeNavigationContext'
|
||||
|
||||
describe('SwipeNavigationContext', () => {
|
||||
it('returns null when used outside provider', () => {
|
||||
const { result } = renderHook(() => useSwipeNavigation())
|
||||
expect(result.current).toBeNull()
|
||||
})
|
||||
|
||||
it('provides suspend/resume/isSuspended when inside provider', () => {
|
||||
const { result } = renderHook(() => useSwipeNavigation(), {
|
||||
wrapper: SwipeNavigationProvider,
|
||||
})
|
||||
|
||||
expect(result.current?.suspend).toBeDefined()
|
||||
expect(result.current?.resume).toBeDefined()
|
||||
expect(result.current?.isSuspended).toBeDefined()
|
||||
})
|
||||
|
||||
it('tracks suspension with ref counting', () => {
|
||||
let current: ReturnType<typeof useSwipeNavigation>
|
||||
|
||||
const { rerender } = renderHook(() => {
|
||||
current = useSwipeNavigation()
|
||||
return null
|
||||
}, {
|
||||
wrapper: SwipeNavigationProvider,
|
||||
})
|
||||
|
||||
expect(current?.isSuspended()).toBe(false)
|
||||
|
||||
current?.suspend()
|
||||
rerender()
|
||||
expect(current?.isSuspended()).toBe(true)
|
||||
|
||||
current?.suspend()
|
||||
rerender()
|
||||
expect(current?.isSuspended()).toBe(true)
|
||||
|
||||
current?.resume()
|
||||
rerender()
|
||||
expect(current?.isSuspended()).toBe(true)
|
||||
|
||||
current?.resume()
|
||||
rerender()
|
||||
expect(current?.isSuspended()).toBe(false)
|
||||
})
|
||||
|
||||
it('clamps resume below zero to zero', () => {
|
||||
let current: ReturnType<typeof useSwipeNavigation>
|
||||
|
||||
const { rerender } = renderHook(() => {
|
||||
current = useSwipeNavigation()
|
||||
return null
|
||||
}, {
|
||||
wrapper: SwipeNavigationProvider,
|
||||
})
|
||||
|
||||
current?.suspend()
|
||||
rerender()
|
||||
expect(current?.isSuspended()).toBe(true)
|
||||
|
||||
current?.resume()
|
||||
rerender()
|
||||
expect(current?.isSuspended()).toBe(false)
|
||||
|
||||
current?.resume()
|
||||
rerender()
|
||||
expect(current?.isSuspended()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { createContext, useContext, useRef, useMemo, type ReactNode } from 'react'
|
||||
|
||||
interface SwipeNavigationValue {
|
||||
suspend: () => void
|
||||
resume: () => void
|
||||
isSuspended: () => boolean
|
||||
}
|
||||
|
||||
export const SwipeNavigationContext = createContext<SwipeNavigationValue | null>(null)
|
||||
|
||||
function SwipeNavigationProvider({ children }: { children: ReactNode }) {
|
||||
const countRef = useRef(0)
|
||||
const value = useMemo<SwipeNavigationValue>(
|
||||
() => ({
|
||||
suspend: () => {
|
||||
countRef.current += 1
|
||||
},
|
||||
resume: () => {
|
||||
countRef.current = Math.max(0, countRef.current - 1)
|
||||
},
|
||||
isSuspended: () => countRef.current > 0,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
return (
|
||||
<SwipeNavigationContext.Provider value={value}>
|
||||
{children}
|
||||
</SwipeNavigationContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useSwipeNavigation(): SwipeNavigationValue | null {
|
||||
return useContext(SwipeNavigationContext)
|
||||
}
|
||||
|
||||
export { SwipeNavigationProvider }
|
||||
@@ -0,0 +1,70 @@
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { useDialogParam } from './useDialogParam'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
describe('useDialogParam', () => {
|
||||
const createWrapper = (initialEntries?: string[]) => {
|
||||
return function wrapper({ children }: { children: React.ReactNode }) {
|
||||
return <MemoryRouter initialEntries={initialEntries}>{children}</MemoryRouter>
|
||||
}
|
||||
}
|
||||
|
||||
it('returns false when dialog param does not match name', () => {
|
||||
const wrapper = createWrapper()
|
||||
const { result } = renderHook(() => useDialogParam('mcp'), { wrapper })
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when dialog param matches name', () => {
|
||||
const wrapper = createWrapper(['/?dialog=mcp'])
|
||||
const { result } = renderHook(() => useDialogParam('mcp'), { wrapper })
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('opening sets dialog param and clears mobileTab', () => {
|
||||
const wrapper = createWrapper(['/?mobileTab=more'])
|
||||
const { result } = renderHook(() => useDialogParam('mcp'), { wrapper })
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current[1](true)
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('closing removes dialog param', () => {
|
||||
const wrapper = createWrapper(['/?dialog=mcp&other=value'])
|
||||
const { result } = renderHook(() => useDialogParam('mcp'), { wrapper })
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
|
||||
act(() => {
|
||||
result.current[1](false)
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('isOpen is true only when dialog exactly matches name', () => {
|
||||
const wrapper1 = createWrapper(['/?dialog=skills'])
|
||||
const { result: result1 } = renderHook(() => useDialogParam('mcp'), { wrapper: wrapper1 })
|
||||
|
||||
const wrapper2 = createWrapper(['/?dialog=skills'])
|
||||
const { result: result2 } = renderHook(() => useDialogParam('skills'), { wrapper: wrapper2 })
|
||||
|
||||
expect(result1.current[0]).toBe(false)
|
||||
expect(result2.current[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('concurrent different names do not interfere', () => {
|
||||
const wrapper = createWrapper(['/?dialog=mcp'])
|
||||
const { result: result1 } = renderHook(() => useDialogParam('mcp'), { wrapper })
|
||||
const { result: result2 } = renderHook(() => useDialogParam('skills'), { wrapper })
|
||||
|
||||
expect(result1.current[0]).toBe(true)
|
||||
expect(result2.current[0]).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
|
||||
export function useDialogParam(name: string): [boolean, (open: boolean) => void] {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const searchRef = useRef(location.search)
|
||||
|
||||
useEffect(() => {
|
||||
searchRef.current = location.search
|
||||
}, [location.search])
|
||||
|
||||
const isOpen = new URLSearchParams(location.search).get('dialog') === name
|
||||
|
||||
const setOpen = useCallback((open: boolean) => {
|
||||
const p = new URLSearchParams(searchRef.current)
|
||||
if (open) {
|
||||
p.set('dialog', name)
|
||||
p.delete('mobileTab')
|
||||
} else if (p.get('dialog') === name) {
|
||||
p.delete('dialog')
|
||||
}
|
||||
navigate({ search: p.toString() }, { replace: true })
|
||||
}, [navigate, name])
|
||||
|
||||
return [isOpen, setOpen]
|
||||
}
|
||||
@@ -12,10 +12,13 @@ vi.mock('../api/git', () => ({
|
||||
gitCommit: vi.fn(),
|
||||
gitStageFiles: vi.fn(),
|
||||
gitUnstageFiles: vi.fn(),
|
||||
gitDiscardFiles: vi.fn(),
|
||||
gitReset: vi.fn(),
|
||||
fetchGitLog: vi.fn(),
|
||||
fetchGitDiff: vi.fn(),
|
||||
createBranch: vi.fn(),
|
||||
switchBranch: vi.fn(),
|
||||
getApiErrorMessage: vi.fn((error: unknown) => typeof error === 'string' ? error : String(error)),
|
||||
}))
|
||||
vi.mock('../lib/toast', () => ({
|
||||
showToast: {
|
||||
@@ -30,13 +33,15 @@ vi.mock('../lib/toast', () => ({
|
||||
}))
|
||||
|
||||
const mockInvalidateQueries = vi.fn()
|
||||
const mockSetQueryData = vi.fn()
|
||||
|
||||
vi.mock('@tanstack/react-query', async () => {
|
||||
const actual = await vi.importActual('@tanstack/react-query')
|
||||
return {
|
||||
...actual,
|
||||
useQueryClient: vi.fn(() => ({
|
||||
invalidateQueries: mockInvalidateQueries
|
||||
invalidateQueries: mockInvalidateQueries,
|
||||
setQueryData: mockSetQueryData,
|
||||
}))
|
||||
}
|
||||
})
|
||||
@@ -134,8 +139,7 @@ describe('useGit', () => {
|
||||
result.current.push.mutateAsync()
|
||||
})
|
||||
|
||||
expect(gitApi.gitPush).toHaveBeenCalledWith(1)
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expect(gitApi.gitPush).toHaveBeenCalledWith(1, false)
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['fileDiff', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitLog', 1] })
|
||||
})
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
|
||||
export function useMemoryPluginStatus() {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['memory-plugin-status'],
|
||||
queryFn: () => settingsApi.getMemoryPluginStatus(),
|
||||
staleTime: 60000,
|
||||
})
|
||||
|
||||
return { memoryPluginEnabled: data?.memoryPluginEnabled ?? false }
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { useSwipeToClose } from './useMobile'
|
||||
import { useNavigationStore } from '@/stores/navigationStore'
|
||||
import { useSwipeBack, useSwipeDismiss } from './useMobile'
|
||||
import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
|
||||
|
||||
describe('useSwipeToClose', () => {
|
||||
describe('useSwipeBack', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
const mockOnSwipeBack = vi.fn()
|
||||
const mockCanSwipeBack = vi.fn()
|
||||
const mockOnBack = vi.fn()
|
||||
const mockCanBack = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnClose.mockClear()
|
||||
mockOnSwipeBack.mockClear()
|
||||
mockCanSwipeBack.mockClear()
|
||||
mockOnBack.mockClear()
|
||||
mockCanBack.mockClear()
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
@@ -23,17 +23,17 @@ describe('useSwipeToClose', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('calls onClose when swipe completes and canSwipeBack is false', () => {
|
||||
mockCanSwipeBack.mockReturnValue(false)
|
||||
it('calls onClose when swipe completes and canBack is false', () => {
|
||||
mockCanBack.mockReturnValue(false)
|
||||
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeToClose(mockOnClose, {
|
||||
useSwipeBack(mockOnClose, {
|
||||
enabled: true,
|
||||
canSwipeBack: mockCanSwipeBack,
|
||||
onSwipeBack: mockOnSwipeBack,
|
||||
canBack: mockCanBack,
|
||||
onBack: mockOnBack,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
@@ -54,25 +54,25 @@ describe('useSwipeToClose', () => {
|
||||
element.dispatchEvent(touchMove)
|
||||
element.dispatchEvent(touchEnd)
|
||||
|
||||
expect(mockCanSwipeBack).toHaveBeenCalled()
|
||||
expect(mockOnSwipeBack).not.toHaveBeenCalled()
|
||||
expect(mockCanBack).toHaveBeenCalled()
|
||||
expect(mockOnBack).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)
|
||||
it('calls onBack when swipe completes and canBack is true', () => {
|
||||
mockCanBack.mockReturnValue(true)
|
||||
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeToClose(mockOnClose, {
|
||||
useSwipeBack(mockOnClose, {
|
||||
enabled: true,
|
||||
canSwipeBack: mockCanSwipeBack,
|
||||
onSwipeBack: mockOnSwipeBack,
|
||||
canBack: mockCanBack,
|
||||
onBack: mockOnBack,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
@@ -93,17 +93,17 @@ describe('useSwipeToClose', () => {
|
||||
element.dispatchEvent(touchMove)
|
||||
element.dispatchEvent(touchEnd)
|
||||
|
||||
expect(mockCanSwipeBack).toHaveBeenCalled()
|
||||
expect(mockOnSwipeBack).toHaveBeenCalled()
|
||||
expect(mockCanBack).toHaveBeenCalled()
|
||||
expect(mockOnBack).toHaveBeenCalled()
|
||||
expect(mockOnClose).not.toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(element)
|
||||
})
|
||||
|
||||
it('falls back to onClose when canSwipeBack is not provided', () => {
|
||||
it('falls back to onClose when canBack is not provided', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeToClose(mockOnClose, {
|
||||
useSwipeBack(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
@@ -115,7 +115,7 @@ describe('useSwipeToClose', () => {
|
||||
|
||||
it('returns swipeStyles for visual feedback', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeToClose(mockOnClose, {
|
||||
useSwipeBack(mockOnClose, {
|
||||
enabled: true,
|
||||
})
|
||||
)
|
||||
@@ -127,7 +127,7 @@ describe('useSwipeToClose', () => {
|
||||
|
||||
it('disables swipe when enabled is false', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeToClose(mockOnClose, {
|
||||
useSwipeBack(mockOnClose, {
|
||||
enabled: false,
|
||||
})
|
||||
)
|
||||
@@ -141,7 +141,7 @@ describe('useSwipeToClose', () => {
|
||||
const removeEventListenerSpy = vi.spyOn(element, 'removeEventListener')
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeToClose(mockOnClose, {
|
||||
useSwipeBack(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
@@ -160,32 +160,343 @@ describe('useSwipeToClose', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('disables route-level swipe-back while active', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeToClose(mockOnClose, {
|
||||
it('suspends route-level swipe-back while active', () => {
|
||||
let swipeNavValue: ReturnType<typeof useSwipeNavigation>
|
||||
|
||||
const { result, unmount } = renderHook(() => {
|
||||
swipeNavValue = useSwipeNavigation()
|
||||
return useSwipeBack(mockOnClose, {
|
||||
enabled: true,
|
||||
})
|
||||
)
|
||||
}, {
|
||||
wrapper: SwipeNavigationProvider,
|
||||
})
|
||||
|
||||
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)
|
||||
expect(swipeNavValue?.isSuspended()).toBe(true)
|
||||
|
||||
unmount()
|
||||
|
||||
const afterUnmountCount = useNavigationStore.getState().swipeDisableCount
|
||||
expect(afterUnmountCount).toBe(initialCount)
|
||||
expect(swipeNavValue?.isSuspended()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSwipeDismiss', () => {
|
||||
const mockOnClose = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnClose.mockClear()
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: 375,
|
||||
})
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('suspends route-level swipe-back while active', () => {
|
||||
let swipeNavValue: ReturnType<typeof useSwipeNavigation>
|
||||
|
||||
const { unmount } = renderHook(() => {
|
||||
swipeNavValue = useSwipeNavigation()
|
||||
return useSwipeDismiss(mockOnClose, {
|
||||
enabled: true,
|
||||
})
|
||||
}, {
|
||||
wrapper: SwipeNavigationProvider,
|
||||
})
|
||||
|
||||
expect(swipeNavValue?.isSuspended()).toBe(true)
|
||||
|
||||
unmount()
|
||||
expect(swipeNavValue?.isSuspended()).toBe(false)
|
||||
})
|
||||
|
||||
it('does not require edge start in vertical mode', () => {
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeDismiss(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 200, clientY: 100 }] as any,
|
||||
})
|
||||
const touchMove = new TouchEvent('touchmove', {
|
||||
touches: [{ clientX: 200, clientY: 200 }] as any,
|
||||
})
|
||||
const touchEnd = new TouchEvent('touchend', {
|
||||
changedTouches: [{ clientX: 200, clientY: 200 }] as any,
|
||||
})
|
||||
|
||||
element.dispatchEvent(touchStart)
|
||||
element.dispatchEvent(touchMove)
|
||||
element.dispatchEvent(touchEnd)
|
||||
vi.advanceTimersByTime(300)
|
||||
|
||||
expect(mockOnClose).toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(element)
|
||||
})
|
||||
|
||||
it('closes on release past distance threshold', () => {
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeDismiss(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 100, clientY: 100 }] as any,
|
||||
})
|
||||
const touchMove = new TouchEvent('touchmove', {
|
||||
touches: [{ clientX: 100, clientY: 190 }] as any,
|
||||
})
|
||||
const touchEnd = new TouchEvent('touchend', {
|
||||
changedTouches: [{ clientX: 100, clientY: 190 }] as any,
|
||||
})
|
||||
|
||||
element.dispatchEvent(touchStart)
|
||||
element.dispatchEvent(touchMove)
|
||||
element.dispatchEvent(touchEnd)
|
||||
vi.advanceTimersByTime(300)
|
||||
|
||||
expect(mockOnClose).toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(element)
|
||||
})
|
||||
|
||||
it('closes on release past velocity threshold even if short distance', () => {
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeDismiss(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 100, clientY: 100 }] as any,
|
||||
})
|
||||
element.dispatchEvent(touchStart)
|
||||
|
||||
vi.advanceTimersByTime(50)
|
||||
|
||||
const touchMove = new TouchEvent('touchmove', {
|
||||
touches: [{ clientX: 100, clientY: 140 }] as any,
|
||||
})
|
||||
element.dispatchEvent(touchMove)
|
||||
|
||||
const touchEnd = new TouchEvent('touchend', {
|
||||
changedTouches: [{ clientX: 100, clientY: 140 }] as any,
|
||||
})
|
||||
element.dispatchEvent(touchEnd)
|
||||
vi.advanceTimersByTime(300)
|
||||
|
||||
expect(mockOnClose).toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(element)
|
||||
})
|
||||
|
||||
it('does NOT close on short slow drag', () => {
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeDismiss(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 100, clientY: 100 }] as any,
|
||||
})
|
||||
element.dispatchEvent(touchStart)
|
||||
|
||||
vi.advanceTimersByTime(500)
|
||||
|
||||
const touchMove = new TouchEvent('touchmove', {
|
||||
touches: [{ clientX: 100, clientY: 140 }] as any,
|
||||
})
|
||||
element.dispatchEvent(touchMove)
|
||||
|
||||
const touchEnd = new TouchEvent('touchend', {
|
||||
changedTouches: [{ clientX: 100, clientY: 140 }] as any,
|
||||
})
|
||||
element.dispatchEvent(touchEnd)
|
||||
|
||||
expect(mockOnClose).not.toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(element)
|
||||
})
|
||||
|
||||
it('does NOT close on upward drag', () => {
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeDismiss(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 100, clientY: 200 }] as any,
|
||||
})
|
||||
const touchMove = new TouchEvent('touchmove', {
|
||||
touches: [{ clientX: 100, clientY: 0 }] as any,
|
||||
})
|
||||
const touchEnd = new TouchEvent('touchend', {
|
||||
changedTouches: [{ clientX: 100, clientY: 0 }] as any,
|
||||
})
|
||||
|
||||
element.dispatchEvent(touchStart)
|
||||
element.dispatchEvent(touchMove)
|
||||
element.dispatchEvent(touchEnd)
|
||||
|
||||
expect(mockOnClose).not.toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(element)
|
||||
})
|
||||
|
||||
it('does NOT close when horizontal swipe dominates', () => {
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeDismiss(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 100, clientY: 100 }] as any,
|
||||
})
|
||||
const touchMove = new TouchEvent('touchmove', {
|
||||
touches: [{ clientX: 250, clientY: 120 }] as any,
|
||||
})
|
||||
const touchEnd = new TouchEvent('touchend', {
|
||||
changedTouches: [{ clientX: 250, clientY: 120 }] as any,
|
||||
})
|
||||
|
||||
element.dispatchEvent(touchStart)
|
||||
element.dispatchEvent(touchMove)
|
||||
element.dispatchEvent(touchEnd)
|
||||
|
||||
expect(mockOnClose).not.toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(element)
|
||||
})
|
||||
|
||||
it('disabled when enabled: false', () => {
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeDismiss(mockOnClose, {
|
||||
enabled: false,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 100, clientY: 100 }] as any,
|
||||
})
|
||||
const touchMove = new TouchEvent('touchmove', {
|
||||
touches: [{ clientX: 100, clientY: 200 }] as any,
|
||||
})
|
||||
const touchEnd = new TouchEvent('touchend', {
|
||||
changedTouches: [{ clientX: 100, clientY: 200 }] as any,
|
||||
})
|
||||
|
||||
element.dispatchEvent(touchStart)
|
||||
element.dispatchEvent(touchMove)
|
||||
element.dispatchEvent(touchEnd)
|
||||
|
||||
expect(mockOnClose).not.toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(element)
|
||||
})
|
||||
|
||||
it('does not start drag when touch originates inside scrolled descendant', () => {
|
||||
const container = document.createElement('div')
|
||||
const scrollable = document.createElement('div')
|
||||
scrollable.style.overflowY = 'auto'
|
||||
scrollable.style.height = '100px'
|
||||
container.appendChild(scrollable)
|
||||
document.body.appendChild(container)
|
||||
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 200, configurable: true })
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 100, configurable: true })
|
||||
scrollable.scrollTop = 50
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeDismiss(mockOnClose, {
|
||||
enabled: true,
|
||||
threshold: 80,
|
||||
})
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(container)
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 100, clientY: 100 }] as any,
|
||||
})
|
||||
Object.defineProperty(touchStart, 'target', { value: scrollable })
|
||||
|
||||
const touchMove = new TouchEvent('touchmove', {
|
||||
touches: [{ clientX: 100, clientY: 200 }] as any,
|
||||
})
|
||||
const touchEnd = new TouchEvent('touchend', {
|
||||
changedTouches: [{ clientX: 100, clientY: 200 }] as any,
|
||||
})
|
||||
|
||||
scrollable.dispatchEvent(touchStart)
|
||||
scrollable.dispatchEvent(touchMove)
|
||||
scrollable.dispatchEvent(touchEnd)
|
||||
|
||||
expect(mockOnClose).not.toHaveBeenCalled()
|
||||
|
||||
if (cleanup) cleanup()
|
||||
document.body.removeChild(container)
|
||||
})
|
||||
})
|
||||
+303
-214
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useCallback, useRef, type CSSProperties } from 'react'
|
||||
import { useNavigationStore } from '@/stores/navigationStore'
|
||||
import { useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
|
||||
|
||||
export function useMobile() {
|
||||
const [isMobile, setIsMobile] = useState(false)
|
||||
@@ -18,253 +18,215 @@ export function useMobile() {
|
||||
return isMobile
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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<SwipeState>({ ...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 || animatingOut) return
|
||||
|
||||
const touch = e.touches[0]
|
||||
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, animatingOut])
|
||||
|
||||
const handleTouchMove = useCallback((e: TouchEvent) => {
|
||||
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.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 p = Math.max(0, Math.min(1, deltaX / window.innerWidth))
|
||||
setProgress(p)
|
||||
setSwipeProgress(p)
|
||||
}
|
||||
}, [enabled, setPhase, setSwipeProgress])
|
||||
|
||||
const handleTouchEnd = useCallback(() => {
|
||||
if (!enabled) return
|
||||
|
||||
const state = swipeRef.current
|
||||
|
||||
if (state.isSwiping) {
|
||||
const deltaX = state.currentX - state.startX
|
||||
const elapsed = Date.now() - state.startTime
|
||||
const velocity = deltaX / elapsed
|
||||
const currentProgress = Math.max(0, Math.min(1, deltaX / window.innerWidth))
|
||||
|
||||
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 {
|
||||
export interface UseSwipeBackOptions {
|
||||
threshold?: number
|
||||
edgeWidth?: number
|
||||
enabled?: boolean
|
||||
canSwipeBack?: () => boolean
|
||||
onSwipeBack?: () => void
|
||||
canBack?: () => boolean
|
||||
onBack?: () => void
|
||||
velocityThreshold?: number
|
||||
suspendsRouteSwipe?: boolean
|
||||
}
|
||||
|
||||
export function useSwipeToClose(
|
||||
export interface UseSwipeDismissOptions {
|
||||
threshold?: number
|
||||
enabled?: boolean
|
||||
velocityThreshold?: number
|
||||
suspendsRouteSwipe?: boolean
|
||||
}
|
||||
|
||||
function useSwipeHandlers(
|
||||
onClose: () => void,
|
||||
options: SwipeToCloseOptions = {}
|
||||
options: UseSwipeBackOptions & { direction: 'horizontal' | 'vertical' } = { direction: 'horizontal' }
|
||||
) {
|
||||
const {
|
||||
threshold = 80,
|
||||
edgeWidth = 30,
|
||||
enabled = true,
|
||||
canSwipeBack,
|
||||
onSwipeBack,
|
||||
canBack,
|
||||
onBack,
|
||||
direction = 'horizontal',
|
||||
velocityThreshold = VELOCITY_THRESHOLD,
|
||||
} = 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 swipeRef = useRef<{
|
||||
startX: number
|
||||
startY: number
|
||||
currentX: number
|
||||
currentY: number
|
||||
isSwiping: boolean
|
||||
isEdgeSwipe: boolean
|
||||
startTime: number
|
||||
blockedByScroll: boolean
|
||||
}>({
|
||||
startX: 0,
|
||||
startY: 0,
|
||||
currentX: 0,
|
||||
currentY: 0,
|
||||
isSwiping: false,
|
||||
isEdgeSwipe: false,
|
||||
startTime: 0,
|
||||
blockedByScroll: false,
|
||||
})
|
||||
const [swipeProgress, setSwipeProgress] = useState(0)
|
||||
const [swipeDeltaPx, setSwipeDeltaPx] = useState(0)
|
||||
const [dismissing, setDismissing] = useState(false)
|
||||
|
||||
useDisableSwipeBack(enabled && isMobile)
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setDismissing(false)
|
||||
setSwipeDeltaPx(0)
|
||||
setSwipeProgress(0)
|
||||
}
|
||||
}, [enabled])
|
||||
|
||||
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,
|
||||
|
||||
if (direction === 'vertical') {
|
||||
const target = e.target as Element
|
||||
let scrollable: Element | null = target
|
||||
while (scrollable && scrollable !== e.currentTarget) {
|
||||
if (scrollable.scrollHeight > scrollable.clientHeight) {
|
||||
const style = window.getComputedStyle(scrollable)
|
||||
if (style.overflowY === 'auto' || style.overflowY === 'scroll' || style.overflow === 'auto' || style.overflow === 'scroll') {
|
||||
break
|
||||
}
|
||||
}
|
||||
scrollable = scrollable.parentElement
|
||||
}
|
||||
const blockedByScroll = scrollable && scrollable !== e.currentTarget && scrollable.scrollTop > 0
|
||||
|
||||
swipeRef.current = {
|
||||
startX: touch.clientX,
|
||||
startY: touch.clientY,
|
||||
currentX: touch.clientX,
|
||||
currentY: touch.clientY,
|
||||
isSwiping: false,
|
||||
isEdgeSwipe: false,
|
||||
startTime: Date.now(),
|
||||
blockedByScroll: !!blockedByScroll,
|
||||
}
|
||||
} else {
|
||||
swipeRef.current = {
|
||||
startX: touch.clientX,
|
||||
startY: touch.clientY,
|
||||
currentX: touch.clientX,
|
||||
currentY: touch.clientY,
|
||||
isSwiping: false,
|
||||
isEdgeSwipe: touch.clientX <= edgeWidth,
|
||||
startTime: Date.now(),
|
||||
blockedByScroll: false,
|
||||
}
|
||||
}
|
||||
}, [enabled, isMobile, edgeWidth])
|
||||
}, [enabled, isMobile, edgeWidth, direction])
|
||||
|
||||
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 (direction === 'vertical') {
|
||||
if (state.blockedByScroll) return
|
||||
|
||||
const deltaX = touch.clientX - state.startX
|
||||
const deltaY = touch.clientY - state.startY
|
||||
|
||||
if (!state.isSwiping) {
|
||||
if (Math.abs(deltaY) > 10 && deltaY > 0 && deltaY > Math.abs(deltaX) * 1.5) {
|
||||
state.isSwiping = true
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (state.isSwiping) {
|
||||
e.preventDefault()
|
||||
state.currentY = touch.clientY
|
||||
const clamped = Math.max(deltaY, 0)
|
||||
setSwipeDeltaPx(clamped)
|
||||
setSwipeProgress(Math.min(clamped / threshold, 1.5))
|
||||
}
|
||||
} else {
|
||||
if (!state.isEdgeSwipe) return
|
||||
|
||||
const deltaX = touch.clientX - state.startX
|
||||
const deltaY = Math.abs(touch.clientY - state.startY)
|
||||
|
||||
if (!state.isSwiping) {
|
||||
if (deltaX > 10 && deltaX > deltaY * 2) {
|
||||
state.isSwiping = true
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (state.isSwiping) {
|
||||
e.preventDefault()
|
||||
state.currentX = touch.clientX
|
||||
setSwipeProgress(Math.min(Math.max(deltaX / threshold, 0), 1.5))
|
||||
}
|
||||
}
|
||||
if (state.isSwiping) {
|
||||
e.preventDefault()
|
||||
state.currentX = touch.clientX
|
||||
setSwipeProgress(Math.min(Math.max(deltaX / threshold, 0), 1.5))
|
||||
}
|
||||
}, [enabled, isMobile, threshold])
|
||||
}, [enabled, isMobile, threshold, direction])
|
||||
|
||||
const handleTouchEnd = useCallback(() => {
|
||||
if (!enabled || !isMobile) return
|
||||
|
||||
const state = swipeRef.current
|
||||
if (state.isSwiping && state.currentX - state.startX >= threshold) {
|
||||
if (canSwipeBack?.()) {
|
||||
onSwipeBack?.()
|
||||
|
||||
if (state.isSwiping) {
|
||||
if (direction === 'vertical') {
|
||||
const deltaY = state.currentY - state.startY
|
||||
const elapsed = Date.now() - state.startTime
|
||||
const velocity = deltaY / Math.max(elapsed, 1)
|
||||
|
||||
if (deltaY >= threshold || velocity >= velocityThreshold) {
|
||||
setDismissing(true)
|
||||
setTimeout(() => {
|
||||
if (canBack?.()) {
|
||||
onBack?.()
|
||||
} else {
|
||||
onClose()
|
||||
}
|
||||
}, ANIMATION_DURATION)
|
||||
} else {
|
||||
setSwipeDeltaPx(0)
|
||||
setSwipeProgress(0)
|
||||
}
|
||||
} else {
|
||||
onClose()
|
||||
const deltaX = state.currentX - state.startX
|
||||
if (deltaX >= threshold) {
|
||||
if (canBack?.()) {
|
||||
onBack?.()
|
||||
} else {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
setSwipeProgress(0)
|
||||
}
|
||||
} else {
|
||||
setSwipeProgress(0)
|
||||
setSwipeDeltaPx(0)
|
||||
}
|
||||
swipeRef.current = { startX: 0, startY: 0, currentX: 0, isSwiping: false, isEdgeSwipe: false }
|
||||
setSwipeProgress(0)
|
||||
}, [enabled, isMobile, threshold, onClose, canSwipeBack, onSwipeBack])
|
||||
|
||||
swipeRef.current = {
|
||||
startX: 0,
|
||||
startY: 0,
|
||||
currentX: 0,
|
||||
currentY: 0,
|
||||
isSwiping: false,
|
||||
isEdgeSwipe: false,
|
||||
startTime: 0,
|
||||
blockedByScroll: false,
|
||||
}
|
||||
}, [enabled, isMobile, threshold, direction, velocityThreshold, onClose, canBack, onBack])
|
||||
|
||||
const bind = useCallback((element: HTMLElement | null) => {
|
||||
if (!element || !enabled || !isMobile) return undefined
|
||||
@@ -280,10 +242,137 @@ export function useSwipeToClose(
|
||||
}
|
||||
}, [enabled, isMobile, handleTouchStart, handleTouchMove, handleTouchEnd])
|
||||
|
||||
const swipeStyles = {
|
||||
transform: swipeProgress > 0 ? `translateX(${swipeProgress * 50}px)` : undefined,
|
||||
transition: swipeProgress === 0 ? 'transform 0.2s ease-out' : undefined,
|
||||
}
|
||||
const swipeStyles: CSSProperties = direction === 'vertical'
|
||||
? dismissing
|
||||
? {
|
||||
transform: 'translateY(100%)',
|
||||
transition: `transform ${ANIMATION_DURATION}ms cubic-bezier(0.4, 0, 0.2, 1)`,
|
||||
}
|
||||
: swipeDeltaPx > 0
|
||||
? { transform: `translateY(${swipeDeltaPx}px)` }
|
||||
: { transform: 'translateY(0)', transition: 'transform 0.2s ease-out' }
|
||||
: {
|
||||
transform: swipeProgress > 0 ? `translateX(${swipeProgress * 50}px)` : undefined,
|
||||
transition: swipeProgress === 0 ? 'transform 0.2s ease-out' : undefined,
|
||||
}
|
||||
|
||||
return { bind, swipeProgress, swipeStyles }
|
||||
}
|
||||
|
||||
export function useSwipeBack(
|
||||
onClose: () => void,
|
||||
options: UseSwipeBackOptions = {}
|
||||
) {
|
||||
const {
|
||||
threshold = 80,
|
||||
edgeWidth = 30,
|
||||
enabled = true,
|
||||
canBack,
|
||||
onBack,
|
||||
velocityThreshold = VELOCITY_THRESHOLD,
|
||||
suspendsRouteSwipe = true,
|
||||
} = options
|
||||
|
||||
const isMobile = useMobile()
|
||||
const swipeNav = useSwipeNavigation()
|
||||
const shouldSuspend = enabled && isMobile && suspendsRouteSwipe !== false
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldSuspend) {
|
||||
swipeNav?.suspend()
|
||||
return () => {
|
||||
swipeNav?.resume()
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}, [shouldSuspend, swipeNav])
|
||||
|
||||
const wrappedOnBack = useCallback(() => {
|
||||
if (!suspendsRouteSwipe && swipeNav?.isSuspended()) {
|
||||
return
|
||||
}
|
||||
onBack?.()
|
||||
}, [onBack, suspendsRouteSwipe, swipeNav])
|
||||
|
||||
const wrappedOnClose = useCallback(() => {
|
||||
if (!suspendsRouteSwipe && swipeNav?.isSuspended()) {
|
||||
return
|
||||
}
|
||||
onClose()
|
||||
}, [onClose, suspendsRouteSwipe, swipeNav])
|
||||
|
||||
const { bind, swipeProgress, swipeStyles } = useSwipeHandlers(wrappedOnClose, {
|
||||
threshold,
|
||||
edgeWidth,
|
||||
enabled,
|
||||
canBack,
|
||||
onBack: wrappedOnBack,
|
||||
velocityThreshold,
|
||||
direction: 'horizontal',
|
||||
})
|
||||
|
||||
const wrappedBind = useCallback(
|
||||
(element: HTMLElement | null) => {
|
||||
const cleanup = bind(element)
|
||||
return () => {
|
||||
cleanup?.()
|
||||
}
|
||||
},
|
||||
[bind]
|
||||
)
|
||||
|
||||
return { bind: wrappedBind, swipeProgress, swipeStyles }
|
||||
}
|
||||
|
||||
export function useSwipeDismiss(
|
||||
onClose: () => void,
|
||||
options: UseSwipeDismissOptions = {}
|
||||
) {
|
||||
const {
|
||||
threshold = 80,
|
||||
enabled = true,
|
||||
velocityThreshold = VELOCITY_THRESHOLD,
|
||||
suspendsRouteSwipe = true,
|
||||
} = options
|
||||
|
||||
const isMobile = useMobile()
|
||||
const swipeNav = useSwipeNavigation()
|
||||
const shouldSuspend = enabled && isMobile && suspendsRouteSwipe !== false
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldSuspend) {
|
||||
swipeNav?.suspend()
|
||||
return () => {
|
||||
swipeNav?.resume()
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}, [shouldSuspend, swipeNav])
|
||||
|
||||
const wrappedOnClose = useCallback(() => {
|
||||
if (!suspendsRouteSwipe && swipeNav?.isSuspended()) {
|
||||
return
|
||||
}
|
||||
onClose()
|
||||
}, [onClose, suspendsRouteSwipe, swipeNav])
|
||||
|
||||
const { bind, swipeProgress, swipeStyles } = useSwipeHandlers(wrappedOnClose, {
|
||||
threshold,
|
||||
edgeWidth: 30,
|
||||
enabled,
|
||||
velocityThreshold,
|
||||
direction: 'vertical',
|
||||
})
|
||||
|
||||
const wrappedBind = useCallback(
|
||||
(element: HTMLElement | null) => {
|
||||
const cleanup = bind(element)
|
||||
return () => {
|
||||
cleanup?.()
|
||||
}
|
||||
},
|
||||
[bind]
|
||||
)
|
||||
|
||||
return { bind: wrappedBind, swipeProgress, swipeStyles }
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { useMobileTabBar, useScheduleTab, type MobileSheetKey } from './useMobileTabBar'
|
||||
|
||||
function renderHookWithRouter<T>(renderFn: () => T) {
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
)
|
||||
return renderHook(renderFn, { wrapper })
|
||||
}
|
||||
|
||||
describe('useMobileTabBar', () => {
|
||||
it('returns null for openSheet when no mobileTab param is present', () => {
|
||||
const { result } = renderHookWithRouter(() => useMobileTabBar())
|
||||
expect(result.current.openSheet).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the correct openSheet when mobileTab param is set', () => {
|
||||
const { result } = renderHook(() => useMobileTabBar(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/?mobileTab=repos']}>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
),
|
||||
})
|
||||
expect(result.current.openSheet).toBe('repos')
|
||||
})
|
||||
|
||||
it('open sets the mobileTab param', () => {
|
||||
const { result } = renderHookWithRouter(() => useMobileTabBar())
|
||||
act(() => {
|
||||
result.current.open('files')
|
||||
})
|
||||
expect(result.current.openSheet).toBe('files')
|
||||
})
|
||||
|
||||
it('close removes the mobileTab param', () => {
|
||||
const { result } = renderHook(() => useMobileTabBar(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/?mobileTab=notifications']}>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
),
|
||||
})
|
||||
expect(result.current.openSheet).toBe('notifications')
|
||||
act(() => {
|
||||
result.current.close()
|
||||
})
|
||||
expect(result.current.openSheet).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves invalid values to null', () => {
|
||||
const { result } = renderHook(() => useMobileTabBar(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/?mobileTab=invalid']}>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
),
|
||||
})
|
||||
expect(result.current.openSheet).toBeNull()
|
||||
})
|
||||
|
||||
it('handles all valid MobileSheetKey values', () => {
|
||||
const validKeys: MobileSheetKey[] = ['repos', 'files', 'notifications', 'more']
|
||||
validKeys.forEach((key) => {
|
||||
const { result } = renderHook(() => useMobileTabBar(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={[`/?mobileTab=${key}`]}>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
),
|
||||
})
|
||||
expect(result.current.openSheet).toBe(key)
|
||||
})
|
||||
})
|
||||
|
||||
it('returns stable openSheet identity across rerenders when search is unchanged', () => {
|
||||
const { result, rerender } = renderHook(() => useMobileTabBar(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/?mobileTab=repos']}>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
),
|
||||
})
|
||||
const firstOpenSheet = result.current.openSheet
|
||||
rerender()
|
||||
expect(result.current.openSheet).toBe(firstOpenSheet)
|
||||
})
|
||||
|
||||
it('open and close callbacks maintain stable identity across rerenders', () => {
|
||||
const { result, rerender } = renderHookWithRouter(() => useMobileTabBar())
|
||||
const firstOpen = result.current.open
|
||||
const firstClose = result.current.close
|
||||
rerender()
|
||||
expect(result.current.open).toBe(firstOpen)
|
||||
expect(result.current.close).toBe(firstClose)
|
||||
})
|
||||
|
||||
it('open callback identity is stable across location.search changes', () => {
|
||||
const { result, rerender } = renderHook(() => useMobileTabBar(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/?foo=1']}>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
),
|
||||
})
|
||||
const firstOpen = result.current.open
|
||||
rerender()
|
||||
expect(result.current.open).toBe(firstOpen)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useScheduleTab', () => {
|
||||
it('defaults to jobs when no param is set', () => {
|
||||
const { result } = renderHook(() => useScheduleTab(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/repos/1/schedules']}>{children}</MemoryRouter>
|
||||
),
|
||||
})
|
||||
expect(result.current.scheduleTab).toBe('jobs')
|
||||
})
|
||||
|
||||
it('reads scheduleTab from URL param', () => {
|
||||
const { result } = renderHook(() => useScheduleTab(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/repos/1/schedules?scheduleTab=runs']}>{children}</MemoryRouter>
|
||||
),
|
||||
})
|
||||
expect(result.current.scheduleTab).toBe('runs')
|
||||
})
|
||||
|
||||
it('setScheduleTab updates the param', () => {
|
||||
const { result } = renderHook(() => useScheduleTab(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/repos/1/schedules']}>{children}</MemoryRouter>
|
||||
),
|
||||
})
|
||||
act(() => {
|
||||
result.current.setScheduleTab('detail')
|
||||
})
|
||||
expect(result.current.scheduleTab).toBe('detail')
|
||||
})
|
||||
|
||||
it('setScheduleTab(jobs) removes the param', () => {
|
||||
const { result } = renderHook(() => useScheduleTab(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/repos/1/schedules?scheduleTab=detail']}>{children}</MemoryRouter>
|
||||
),
|
||||
})
|
||||
expect(result.current.scheduleTab).toBe('detail')
|
||||
act(() => {
|
||||
result.current.setScheduleTab('jobs')
|
||||
})
|
||||
expect(result.current.scheduleTab).toBe('jobs')
|
||||
})
|
||||
|
||||
it('resolves invalid values to jobs', () => {
|
||||
const { result } = renderHook(() => useScheduleTab(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/repos/1/schedules?scheduleTab=invalid']}>{children}</MemoryRouter>
|
||||
),
|
||||
})
|
||||
expect(result.current.scheduleTab).toBe('jobs')
|
||||
})
|
||||
|
||||
it('returns stable scheduleTab identity across rerenders when search is unchanged', () => {
|
||||
const { result, rerender } = renderHook(() => useScheduleTab(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/repos/1/schedules?scheduleTab=runs']}>
|
||||
{children}
|
||||
</MemoryRouter>
|
||||
),
|
||||
})
|
||||
const firstScheduleTab = result.current.scheduleTab
|
||||
rerender()
|
||||
expect(result.current.scheduleTab).toBe(firstScheduleTab)
|
||||
})
|
||||
|
||||
it('setScheduleTab callback maintains stable identity across rerenders', () => {
|
||||
const { result, rerender } = renderHook(() => useScheduleTab(), {
|
||||
wrapper: ({ children }) => (
|
||||
<MemoryRouter initialEntries={['/repos/1/schedules']}>{children}</MemoryRouter>
|
||||
),
|
||||
})
|
||||
const firstSetScheduleTab = result.current.setScheduleTab
|
||||
rerender()
|
||||
expect(result.current.setScheduleTab).toBe(firstSetScheduleTab)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
|
||||
export type MobileSheetKey = 'repos' | 'files' | 'notifications' | 'more'
|
||||
|
||||
export interface UseMobileTabBarReturn {
|
||||
openSheet: MobileSheetKey | null
|
||||
open: (key: MobileSheetKey) => void
|
||||
close: () => void
|
||||
}
|
||||
|
||||
export function useMobileTabBar(): UseMobileTabBarReturn {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const searchRef = useRef(location.search)
|
||||
|
||||
useEffect(() => {
|
||||
searchRef.current = location.search
|
||||
}, [location.search])
|
||||
|
||||
const openSheet = useMemo<MobileSheetKey | null>(() => {
|
||||
const searchParams = new URLSearchParams(location.search)
|
||||
const mobileTabParam = searchParams.get('mobileTab')
|
||||
return (mobileTabParam === 'repos' || mobileTabParam === 'files' || mobileTabParam === 'notifications' || mobileTabParam === 'more')
|
||||
? mobileTabParam
|
||||
: null
|
||||
}, [location.search])
|
||||
|
||||
const open = useCallback((key: MobileSheetKey) => {
|
||||
const newParams = new URLSearchParams(searchRef.current)
|
||||
newParams.set('mobileTab', key)
|
||||
navigate({ search: newParams.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
const close = useCallback(() => {
|
||||
const newParams = new URLSearchParams(searchRef.current)
|
||||
newParams.delete('mobileTab')
|
||||
navigate({ search: newParams.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
return {
|
||||
openSheet,
|
||||
open,
|
||||
close,
|
||||
}
|
||||
}
|
||||
|
||||
export type ScheduleTabKey = 'jobs' | 'detail' | 'runs'
|
||||
|
||||
export interface UseScheduleTabReturn {
|
||||
scheduleTab: ScheduleTabKey
|
||||
setScheduleTab: (tab: ScheduleTabKey) => void
|
||||
}
|
||||
|
||||
export function useScheduleTab(): UseScheduleTabReturn {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const searchRef = useRef(location.search)
|
||||
|
||||
useEffect(() => {
|
||||
searchRef.current = location.search
|
||||
}, [location.search])
|
||||
|
||||
const scheduleTab = useMemo<ScheduleTabKey>(() => {
|
||||
const searchParams = new URLSearchParams(location.search)
|
||||
const tabParam = searchParams.get('scheduleTab')
|
||||
return tabParam === 'detail' || tabParam === 'runs' ? tabParam : 'jobs'
|
||||
}, [location.search])
|
||||
|
||||
const setScheduleTab = useCallback((tab: ScheduleTabKey) => {
|
||||
const newParams = new URLSearchParams(searchRef.current)
|
||||
if (tab === 'jobs') {
|
||||
newParams.delete('scheduleTab')
|
||||
} else {
|
||||
newParams.set('scheduleTab', tab)
|
||||
}
|
||||
navigate({ search: newParams.toString() }, { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
return {
|
||||
scheduleTab,
|
||||
setScheduleTab,
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
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<ReturnType<typeof setTimeout>>(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])
|
||||
}
|
||||
@@ -39,12 +39,12 @@ export function sanitizeForTTS(text: string): string {
|
||||
// Remove inline code, keep content: `code` -> code
|
||||
sanitized = sanitized.replace(/`([^`]+)`/g, '$1')
|
||||
|
||||
// Remove markdown images:  -> alt (must run before link regex to avoid leaving stray !)
|
||||
sanitized = sanitized.replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
|
||||
|
||||
// Remove markdown links, keep display text: [text](url) -> text
|
||||
sanitized = sanitized.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
|
||||
|
||||
// Remove markdown images:  -> alt
|
||||
sanitized = sanitized.replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
|
||||
|
||||
// Remove bold markers: **text** -> text or __text__ -> text
|
||||
sanitized = sanitized.replace(/\*\*([^*]+)\*\*/g, '$1')
|
||||
sanitized = sanitized.replace(/__([^_]+)__/g, '$1')
|
||||
|
||||
@@ -2,12 +2,15 @@ import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { ErrorBoundary } from '@/components/ui/error-boundary'
|
||||
import { registerServiceWorker } from './lib/serviceWorker'
|
||||
|
||||
registerServiceWorker()
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<ErrorBoundary>
|
||||
<App />
|
||||
</ErrorBoundary>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -340,9 +340,9 @@ export function GlobalSchedules() {
|
||||
<Button
|
||||
onClick={() => { setEditingJob(null); setSelectedRepoId(undefined); setDialogOpen(true) }}
|
||||
size="sm"
|
||||
className="sm:hidden"
|
||||
className="sm:hidden h-10 w-10 p-0"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</div>
|
||||
@@ -361,7 +361,7 @@ export function GlobalSchedules() {
|
||||
</div>
|
||||
|
||||
<TabsContent value="jobs" className="mt-0 flex-1 min-h-0 flex flex-col overflow-hidden">
|
||||
<div className="border-b border-border px-4 py-3 space-y-2">
|
||||
<div className="px-4 pt-1 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap hidden sm:inline">Filter by repo:</span>
|
||||
<Combobox
|
||||
@@ -510,7 +510,7 @@ export function GlobalSchedules() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-4 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{!hasJobs ? (
|
||||
<div className="flex min-h-full items-center justify-center">
|
||||
<Card className="max-w-md border-dashed border-border/70">
|
||||
@@ -672,7 +672,7 @@ export function GlobalSchedules() {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="runs" className="mt-0 flex-1 min-h-0 flex flex-col overflow-hidden">
|
||||
<div className="border-b border-border px-4 py-3 space-y-2">
|
||||
<div className="px-4 pt-1 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap hidden sm:inline">Filter by repo:</span>
|
||||
<Combobox
|
||||
@@ -821,7 +821,7 @@ export function GlobalSchedules() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-4 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{runsLoading && allRuns.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
|
||||
@@ -69,7 +69,7 @@ export function Memories() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col">
|
||||
<div className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
|
||||
<Header>
|
||||
<Header.BackButton to={`/repos/${repoId}`} />
|
||||
<div className="min-w-0 flex-1 flex justify-center ml-2">
|
||||
@@ -87,15 +87,15 @@ export function Memories() {
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
New Memory
|
||||
</Button>
|
||||
<Button onClick={() => setCreateOpen(true)} size="sm" className="sm:hidden">
|
||||
<Plus className="w-4 h-4" />
|
||||
<Button onClick={() => setCreateOpen(true)} size="sm" className="sm:hidden h-10 w-10 p-0">
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
|
||||
<div className="flex-1 overflow-auto p-4 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<div className="flex-1 overflow-auto p-4 pb-20 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{stats && (
|
||||
<Card className="mb-6 hidden sm:block">
|
||||
<CardContent className="p-4">
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { getRepo } from "@/api/repos";
|
||||
import { settingsApi } from "@/api/settings";
|
||||
import { SessionList } from "@/components/session/SessionList";
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { Header } from "@/components/ui/header";
|
||||
@@ -12,11 +11,12 @@ import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
|
||||
import { SourceControlPanel } from "@/components/source-control";
|
||||
import { useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { useRepoActivity } from "@/hooks/useRepoActivity";
|
||||
import { useMemoryPluginStatus } from "@/hooks/useMemoryPluginStatus";
|
||||
import { useSSE } from "@/hooks/useSSE";
|
||||
import { useDialogParam } from "@/hooks/useDialogParam";
|
||||
import { OPENCODE_API_ENDPOINT } from "@/config";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
||||
import { Plug, FolderOpen, Plus, GitBranch, GitCommitHorizontal, ShieldOff, Brain, Loader2, CalendarClock, Sparkles } from "lucide-react";
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
@@ -27,12 +27,12 @@ export function RepoDetail() {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const repoId = Number(id) || 0;
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files');
|
||||
const [switchConfigOpen, setSwitchConfigOpen] = useState(false);
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useState(false);
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useState(false);
|
||||
const [sourceControlOpen, setSourceControlOpen] = useState(false);
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useState(false);
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp');
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills');
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
|
||||
|
||||
const { data: repo, isLoading: repoLoading } = useQuery({
|
||||
queryKey: ["repo", repoId],
|
||||
@@ -42,11 +42,7 @@ export function RepoDetail() {
|
||||
|
||||
useRepoActivity(repoId, Boolean(repo));
|
||||
|
||||
const { data: memoryPluginStatus } = useQuery({
|
||||
queryKey: ["memory-plugin-status"],
|
||||
queryFn: () => settingsApi.getMemoryPluginStatus(),
|
||||
staleTime: 60000,
|
||||
});
|
||||
const { memoryPluginEnabled } = useMemoryPluginStatus();
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT;
|
||||
|
||||
@@ -110,7 +106,7 @@ export function RepoDetail() {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col"
|
||||
className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0"
|
||||
>
|
||||
<Header>
|
||||
<Header.BackButton to="/" />
|
||||
@@ -172,7 +168,7 @@ export function RepoDetail() {
|
||||
<ShieldOff className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Reset Permissions</span>
|
||||
</Button>
|
||||
{memoryPluginStatus?.memoryPluginEnabled && (
|
||||
{memoryPluginEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/memories`)}
|
||||
@@ -192,39 +188,22 @@ export function RepoDetail() {
|
||||
<CalendarClock className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Schedules</span>
|
||||
</Button>
|
||||
<Header.MobileDropdown>
|
||||
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
|
||||
<FolderOpen className="w-4 h-4 mr-2" /> Files
|
||||
</DropdownMenuItem>
|
||||
{memoryPluginStatus?.memoryPluginEnabled && (
|
||||
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
|
||||
<Brain className="w-4 h-4 mr-2" /> Memory
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
|
||||
<Plug className="w-4 h-4 mr-2" /> MCP
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setSkillsDialogOpen(true)}>
|
||||
<Sparkles className="w-4 h-4 mr-2" /> Skills
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
|
||||
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/schedules`)}>
|
||||
<CalendarClock className="w-4 h-4 mr-2" /> Schedules
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
|
||||
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
|
||||
</DropdownMenuItem>
|
||||
</Header.MobileDropdown>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
className="hidden sm:inline-flex bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">New Session</span>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
<span>New Session</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="sm:hidden h-10 w-10 p-0 bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
|
||||
@@ -24,23 +24,17 @@ export function Repos() {
|
||||
<Header.Title logo>OpenCode</Header.Title>
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<PendingActionsGroup />
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setFileBrowserOpen(true)}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
|
||||
className="hidden sm:flex text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => navigate('/schedules')}
|
||||
size="icon"
|
||||
className="sm:hidden text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
|
||||
>
|
||||
<CalendarClock className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate('/schedules')}
|
||||
@@ -50,14 +44,20 @@ export function Repos() {
|
||||
<CalendarClock className="w-4 h-4 mr-2" />
|
||||
All Schedules
|
||||
</Button>
|
||||
<Button onClick={() => setAddRepoOpen(true)} size="sm">
|
||||
<Button onClick={() => setAddRepoOpen(true)} size="sm" className="hidden sm:inline-flex">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
Repo
|
||||
</Button>
|
||||
<Header.Settings />
|
||||
<Button onClick={() => setAddRepoOpen(true)} size="sm" className="sm:hidden">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
Repo
|
||||
</Button>
|
||||
<span className="hidden sm:block">
|
||||
<Header.Settings />
|
||||
</span>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
<div className="container mx-auto flex-1 pt-2 px-2 min-h-0 overflow-auto">
|
||||
<div className="container mx-auto flex-1 pt-2 px-2 min-h-0 overflow-auto pb-[calc(env(safe-area-inset-bottom)+60px)] sm:pb-0">
|
||||
|
||||
<RepoList />
|
||||
</div>
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from '@/hooks/useSchedules'
|
||||
import { useRepoActivity } from '@/hooks/useRepoActivity'
|
||||
import { ScheduleJobDialog, JobsTab, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
|
||||
import { useScheduleTab } from '@/hooks/useMobileTabBar'
|
||||
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
|
||||
import { Header } from '@/components/ui/header'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -33,7 +34,7 @@ export function Schedules() {
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingJob, setEditingJob] = useState<ScheduleJob | undefined>()
|
||||
const [deleteJobId, setDeleteJobId] = useState<number | null>(null)
|
||||
const [activeTab, setActiveTab] = useState<'jobs' | 'detail' | 'runs'>('jobs')
|
||||
const { scheduleTab: activeTab, setScheduleTab: setActiveTab } = useScheduleTab()
|
||||
|
||||
const { data: repo, isLoading: repoLoading } = useQuery({
|
||||
queryKey: ['repo', repoId],
|
||||
@@ -66,7 +67,7 @@ export function Schedules() {
|
||||
setSelectedJobId(jobs[0]?.id ?? null)
|
||||
setActiveTab('jobs')
|
||||
}
|
||||
}, [jobs, selectedJobId])
|
||||
}, [jobs, selectedJobId, setActiveTab])
|
||||
|
||||
useEffect(() => {
|
||||
if (!runs?.length) {
|
||||
@@ -194,7 +195,7 @@ export function Schedules() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col">
|
||||
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
|
||||
<Header>
|
||||
<Header.BackButton to={`/repos/${repoId}`} />
|
||||
<div className="min-w-0 flex-1 px-3">
|
||||
@@ -209,8 +210,8 @@ export function Schedules() {
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
New Schedule
|
||||
</Button>
|
||||
<Button onClick={() => { setEditingJob(undefined); setDialogOpen(true) }} size="sm" className="sm:hidden">
|
||||
<Plus className="w-4 h-4" />
|
||||
<Button onClick={() => { setEditingJob(undefined); setDialogOpen(true) }} size="sm" className="sm:hidden h-10 w-10 p-0">
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</div>
|
||||
@@ -275,7 +276,12 @@ export function Schedules() {
|
||||
</div>
|
||||
|
||||
{hasJobs && (
|
||||
<ScheduleTabMenu activeTab={activeTab} onTabChange={setActiveTab} />
|
||||
<div className="sm:block hidden">
|
||||
<ScheduleTabMenu
|
||||
activeTab={activeTab}
|
||||
onTabChange={(tab) => setActiveTab(tab)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ScheduleJobDialog
|
||||
|
||||
@@ -5,7 +5,7 @@ import { getRepo } from "@/api/repos";
|
||||
import { MessageThread } from "@/components/message/MessageThread";
|
||||
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
|
||||
import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
|
||||
import { X, FolderOpen, Plug, Settings, CornerUpLeft, GitCommitHorizontal, Brain, ShieldOff, Code, Sparkles } from "lucide-react";
|
||||
import { X, FolderOpen, Plug, Settings, CornerUpLeft, GitCommitHorizontal, Brain, ShieldOff, Sparkles } from "lucide-react";
|
||||
import { ModelSelectDialog } from "@/components/model/ModelSelectDialog";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { SessionList } from "@/components/session/SessionList";
|
||||
@@ -13,7 +13,6 @@ import { SessionList } from "@/components/session/SessionList";
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
||||
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
|
||||
import { useSession, useAbortSession, useUpdateSession, useMessages, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { useRepoActivity } from "@/hooks/useRepoActivity";
|
||||
@@ -49,6 +48,9 @@ import { MinimizedQuestionIndicator } from "@/components/session/MinimizedQuesti
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
import { SourceControlPanel } from "@/components/source-control";
|
||||
import { SessionTodoDisplay } from "@/components/message/SessionTodoDisplay";
|
||||
import { useDialogParam } from "@/hooks/useDialogParam";
|
||||
import { SessionMoreButton } from "@/components/navigation/SessionMoreButton";
|
||||
import { useMemoryPluginStatus } from "@/hooks/useMemoryPluginStatus";
|
||||
|
||||
const compareMessageIds = (id1: string, id2: string): number => {
|
||||
const num1 = parseInt(id1, 10)
|
||||
@@ -67,12 +69,12 @@ export function SessionDetail() {
|
||||
const promptInputRef = useRef<PromptInputHandle>(null);
|
||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||
const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false);
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
|
||||
const [lspDialogOpen, setLspDialogOpen] = useState(false);
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useState(false);
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useState(false);
|
||||
const [sourceControlOpen, setSourceControlOpen] = useState(false);
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useState(false);
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files');
|
||||
const [lspDialogOpen, setLspDialogOpen] = useDialogParam('lsp');
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp');
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills');
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
|
||||
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
|
||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||
const [hasPromptContent, setHasPromptContent] = useState(false);
|
||||
@@ -109,6 +111,8 @@ export function SessionDetail() {
|
||||
|
||||
useRepoActivity(repoId, Boolean(repo));
|
||||
|
||||
const { memoryPluginEnabled } = useMemoryPluginStatus();
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT;
|
||||
|
||||
const repoDirectory = repo?.fullPath;
|
||||
@@ -259,7 +263,7 @@ export function SessionDetail() {
|
||||
undo: handleUndo,
|
||||
redo: handleRedo,
|
||||
fork: handleFork,
|
||||
toggleSidebar: () => setFileBrowserOpen(prev => !prev),
|
||||
toggleSidebar: () => setFileBrowserOpen(!fileBrowserOpen),
|
||||
toggleMode: () => {
|
||||
const modeButton = document.querySelector(
|
||||
"[data-toggle-mode]",
|
||||
@@ -294,7 +298,7 @@ export function SessionDetail() {
|
||||
|
||||
setSelectedFilePath(pathToOpen)
|
||||
setFileBrowserOpen(true)
|
||||
}, [repo?.fullPath]);
|
||||
}, [repo?.fullPath, setFileBrowserOpen]);
|
||||
|
||||
const handleSessionTitleUpdate = useCallback((newTitle: string) => {
|
||||
if (sessionId) {
|
||||
@@ -305,7 +309,7 @@ export function SessionDetail() {
|
||||
const handleFileBrowserClose = useCallback(() => {
|
||||
setFileBrowserOpen(false)
|
||||
setSelectedFilePath(undefined)
|
||||
}, []);
|
||||
}, [setFileBrowserOpen]);
|
||||
|
||||
const handleChildSessionClick = useCallback((childSessionId: string) => {
|
||||
navigate(`/repos/${repoId}/sessions/${childSessionId}`)
|
||||
@@ -413,11 +417,13 @@ export function SessionDetail() {
|
||||
<FolderOpen className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Files</span>
|
||||
</Button>
|
||||
<LspStatusButton
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={repoDirectory}
|
||||
onClick={() => setLspDialogOpen(true)}
|
||||
/>
|
||||
<div className="hidden md:flex">
|
||||
<LspStatusButton
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={repoDirectory}
|
||||
onClick={() => setLspDialogOpen(true)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -445,15 +451,17 @@ export function SessionDetail() {
|
||||
<GitCommitHorizontal className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Source</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => navigate(`/repos/${repoId}/memories`)}
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Brain className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Memory</span>
|
||||
</Button>
|
||||
{memoryPluginEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => navigate(`/repos/${repoId}/memories`)}
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Brain className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Memory</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -472,29 +480,7 @@ export function SessionDetail() {
|
||||
<Settings className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Settings</span>
|
||||
</Button>
|
||||
<Header.MobileDropdown>
|
||||
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
|
||||
<FolderOpen className="w-4 h-4 mr-2" /> Files
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
|
||||
<Brain className="w-4 h-4 mr-2" /> Memory
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
|
||||
<Plug className="w-4 h-4 mr-2" /> MCP
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setSkillsDialogOpen(true)}>
|
||||
<Sparkles className="w-4 h-4 mr-2" /> Skills
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setLspDialogOpen(true)}>
|
||||
<Code className="w-4 h-4 mr-2" /> LSP
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
|
||||
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
|
||||
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
|
||||
</DropdownMenuItem>
|
||||
</Header.MobileDropdown>
|
||||
<SessionMoreButton />
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
|
||||
@@ -525,9 +511,9 @@ export function SessionDetail() {
|
||||
>
|
||||
<div className="relative w-[94%] md:max-w-4xl">
|
||||
<div className="absolute -top-5 right-0 md:right-4 z-50 flex flex-col items-end gap-2">
|
||||
{ttsEnabled && !hasPromptContent && !hasActiveStream && ((lastAssistantMessage && lastAssistantText) || preferences?.tts?.autoPlay) && (
|
||||
{ttsEnabled && !hasPromptContent && !hasActiveStream && lastAssistantMessage && lastAssistantText && (
|
||||
<FloatingTTSButton
|
||||
messageId={lastAssistantMessage?.info.id ?? ''}
|
||||
messageId={lastAssistantMessage.info.id}
|
||||
content={lastAssistantText}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
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<NavigationStore>((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) })),
|
||||
}))
|
||||
@@ -49,6 +49,10 @@ export default defineConfig(({ mode }) => {
|
||||
},
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
host: "0.0.0.0",
|
||||
port: 5173,
|
||||
},
|
||||
worker: {
|
||||
rollupOptions: {
|
||||
output: {
|
||||
|
||||
+6
-2
@@ -9,14 +9,18 @@
|
||||
"dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"",
|
||||
"dev:backend": "bun --watch-path backend/src --watch backend/src/index.ts",
|
||||
"dev:frontend": "pnpm --filter frontend dev",
|
||||
"start": "concurrently \"pnpm:start:backend\" \"pnpm:start:frontend\"",
|
||||
"start:backend": "bun run backend/dist/index.js",
|
||||
"start:frontend": "pnpm --filter frontend preview",
|
||||
"build": "pnpm run build:backend && pnpm run build:frontend",
|
||||
"build:backend": "pnpm --filter backend build",
|
||||
"build:frontend": "pnpm --filter frontend build",
|
||||
"typecheck": "pnpm run typecheck:frontend && pnpm run typecheck:backend",
|
||||
"typecheck:frontend": "pnpm --filter frontend typecheck",
|
||||
"typecheck:backend": "pnpm --filter backend typecheck",
|
||||
"test": "pnpm run test:backend",
|
||||
"test:backend": "pnpm --filter backend test",
|
||||
"test": "pnpm run test:backend && pnpm run test:frontend",
|
||||
"test:frontend": "pnpm --filter frontend exec vitest run",
|
||||
"test:backend": "pnpm --filter backend exec vitest run",
|
||||
"lint": "pnpm run lint:frontend && pnpm run lint:backend",
|
||||
"lint:frontend": "pnpm --filter frontend lint",
|
||||
"lint:backend": "pnpm --filter backend lint",
|
||||
|
||||
@@ -54,6 +54,8 @@ export const ENV = {
|
||||
PORT: getEnvNumber('OPENCODE_SERVER_PORT', DEFAULTS.OPENCODE.PORT),
|
||||
HOST: getEnvString('OPENCODE_HOST', DEFAULTS.OPENCODE.HOST),
|
||||
PUBLIC_URL: getEnvString('OPENCODE_PUBLIC_URL', ''), // Public URL for OAuth callbacks
|
||||
SERVER_PASSWORD: getEnvString('OPENCODE_SERVER_PASSWORD', ''),
|
||||
SERVER_USERNAME: getEnvString('OPENCODE_SERVER_USERNAME', 'opencode'),
|
||||
},
|
||||
|
||||
DATABASE: {
|
||||
|
||||
Reference in new issue
Block a user