mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
Merge origin/main into feat/linked-opencode-servers
Keep the schedule reports list added on main and the remote-route gating for activity, repos, and assistant entries added on this branch.
This commit is contained in:
commit
3a7227a602
16 files changed
+658
-87
No files matched your search
@@ -2,6 +2,7 @@ import { useState } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useDesktop } from '@/hooks/useDesktop'
|
||||
import { useSidebarCollapsed } from '@/hooks/useSidebarCollapsed'
|
||||
import { useSidebarWidth } from '@/hooks/useSidebarWidth'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
|
||||
@@ -24,6 +25,7 @@ export function DesktopSidebar() {
|
||||
const { updateParams } = useUrlParams()
|
||||
const openNavItem = useOpenNavItem()
|
||||
const [collapsed, toggle] = useSidebarCollapsed()
|
||||
const [sidebarWidth, setSidebarWidth] = useSidebarWidth()
|
||||
const [repoSwitcherOpen, setRepoSwitcherOpen] = useState(false)
|
||||
const { isAuthenticated, isLoading, logout } = useAuth()
|
||||
|
||||
@@ -63,7 +65,13 @@ export function DesktopSidebar() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Sidebar collapsed={collapsed} onToggle={toggle} className='mt-2'>
|
||||
<Sidebar
|
||||
collapsed={collapsed}
|
||||
onToggle={toggle}
|
||||
width={sidebarWidth}
|
||||
onWidthChange={setSidebarWidth}
|
||||
className='mt-2'
|
||||
>
|
||||
{primary.length > 0 && (
|
||||
<SidebarSection collapsed={collapsed}>
|
||||
{primary.map((item: NavPrimaryCta) => (
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useAuth } from '@/hooks/useAuth'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { getRepo } from '@/api/repos'
|
||||
import type { ActiveWorkItem } from '@/lib/activeWork'
|
||||
import type { UnreadScheduleRun } from '@/api/schedules'
|
||||
|
||||
vi.mock('@/hooks/useAuth')
|
||||
vi.mock('@/hooks/useServerHealth')
|
||||
@@ -32,6 +33,16 @@ vi.mock('@/hooks/useActiveWork', () => ({
|
||||
useRepoActivityState: () => null,
|
||||
}))
|
||||
|
||||
const scheduleMocks = vi.hoisted(() => ({
|
||||
useUnreadScheduleRuns: vi.fn(),
|
||||
useMarkAllScheduleRunsViewed: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useUnreadScheduleRuns: scheduleMocks.useUnreadScheduleRuns,
|
||||
useMarkAllScheduleRunsViewed: scheduleMocks.useMarkAllScheduleRunsViewed,
|
||||
}))
|
||||
|
||||
function createActiveWorkItem(): ActiveWorkItem {
|
||||
const now = Date.now()
|
||||
return {
|
||||
@@ -61,6 +72,33 @@ function createActiveWorkItem(): ActiveWorkItem {
|
||||
}
|
||||
}
|
||||
|
||||
function createUnreadScheduleRun(): UnreadScheduleRun {
|
||||
const now = Date.now()
|
||||
return {
|
||||
id: 1,
|
||||
jobId: 1,
|
||||
repoId: 1,
|
||||
triggerSource: 'schedule',
|
||||
status: 'completed',
|
||||
startedAt: now - 60000,
|
||||
finishedAt: now - 30000,
|
||||
viewedAt: null,
|
||||
createdAt: now - 60000,
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
logText: null,
|
||||
responseText: null,
|
||||
errorText: null,
|
||||
runBranch: null,
|
||||
commitHash: null,
|
||||
worktreePath: null,
|
||||
jobName: 'Nightly report',
|
||||
repoName: 'repo1',
|
||||
repoPath: '/path/to/repo1',
|
||||
preview: 'Report ready',
|
||||
}
|
||||
}
|
||||
|
||||
function setActivityGroups(groups: {
|
||||
needsInput?: ActiveWorkItem[]
|
||||
running?: ActiveWorkItem[]
|
||||
@@ -158,6 +196,8 @@ describe('MoreDrawer', () => {
|
||||
})
|
||||
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
|
||||
setActivityGroups({})
|
||||
scheduleMocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 0, failed: 0 } })
|
||||
scheduleMocks.useMarkAllScheduleRunsViewed.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
})
|
||||
|
||||
it('renders Settings and Logout menu items', () => {
|
||||
@@ -385,4 +425,21 @@ describe('MoreDrawer', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: 'Activity' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows unread reports and marks them all read', () => {
|
||||
const markAllReportsViewed = vi.fn()
|
||||
mockAuth()
|
||||
mockServerHealth()
|
||||
scheduleMocks.useUnreadScheduleRuns.mockReturnValue({
|
||||
data: { runs: [createUnreadScheduleRun()], total: 1, failed: 0 },
|
||||
})
|
||||
scheduleMocks.useMarkAllScheduleRunsViewed.mockReturnValue({ mutate: markAllReportsViewed, isPending: false })
|
||||
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1', routePath: '/repos/:id/sessions/:sessionId' })
|
||||
|
||||
expect(screen.getByText('Nightly report')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Mark all read' }))
|
||||
|
||||
expect(markAllReportsViewed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,8 @@ import { getRepo } from '@/api/repos'
|
||||
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
|
||||
import { SideDrawer, SideDrawerContent } from '@/components/ui/side-drawer'
|
||||
import { CompactActivityList } from '@/components/activity/CompactActivityList'
|
||||
import { ScheduleReportsList } from '@/components/notifications/ScheduleReportsBell'
|
||||
import { useMarkAllScheduleRunsViewed, useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { buildMoreItems, buildNavModel, isManagerOnlyNavItem, isSessionDetailPath, type MoreDrawerItem } from './moreDrawerItems'
|
||||
import { useSwipeBack } from '@/hooks/useMobile'
|
||||
import { cn, getRepoDisplayName } from '@/lib/utils'
|
||||
@@ -79,6 +81,9 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
|
||||
const isAssistantSession = isSessionDetail && searchParams.get('assistant') === '1'
|
||||
const isRemoteRoute = !isLocalOpenCodeServer(useRouteOpenCodeServerId())
|
||||
const { open: openMobileSheet } = useMobileTabBar()
|
||||
const { data: unreadReports } = useUnreadScheduleRuns()
|
||||
const markAllReportsViewed = useMarkAllScheduleRunsViewed()
|
||||
const total = unreadReports?.total ?? 0
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen && swipeRef.current) {
|
||||
@@ -188,6 +193,18 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
|
||||
)}
|
||||
</div>
|
||||
<SideDrawerContent className="flex flex-col gap-4 pb-3">
|
||||
{total > 0 && (
|
||||
<div className="overflow-hidden rounded-lg border border-border">
|
||||
<ScheduleReportsList
|
||||
runs={unreadReports?.runs ?? []}
|
||||
total={total}
|
||||
rowClassName="py-3"
|
||||
onMarkAllRead={() => markAllReportsViewed.mutate()}
|
||||
markAllPending={markAllReportsViewed.isPending}
|
||||
maxHeightClass=""
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{isOpen && !isRemoteRoute && (
|
||||
<CompactActivityList onNavigate={(path) => navigate(path)} />
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SessionMoreButton } from './SessionMoreButton'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
open: vi.fn(),
|
||||
useUnreadScheduleRuns: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobileTabBar', () => ({
|
||||
useMobileTabBar: () => ({ open: mocks.open, openSheet: null, close: vi.fn() }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useUnreadScheduleRuns: mocks.useUnreadScheduleRuns,
|
||||
}))
|
||||
|
||||
describe('SessionMoreButton', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('shows the unread report count and opens the drawer', () => {
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 4, failed: 0 } })
|
||||
render(<SessionMoreButton />)
|
||||
|
||||
const button = screen.getByRole('button', { name: 'More, 4 unread reports' })
|
||||
expect(screen.getByText('4')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(mocks.open).toHaveBeenCalledWith('more')
|
||||
})
|
||||
|
||||
it('shows no count when there are no unread reports', () => {
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 0, failed: 0 } })
|
||||
render(<SessionMoreButton />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'More' })).toBeInTheDocument()
|
||||
expect(screen.queryByText('0')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,19 +1,25 @@
|
||||
import { MoreVertical } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScheduleReportsBadge } from '@/components/notifications/ScheduleReportsBadge'
|
||||
import { useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
|
||||
export function SessionMoreButton() {
|
||||
const { open } = useMobileTabBar()
|
||||
const { data } = useUnreadScheduleRuns()
|
||||
const total = data?.total ?? 0
|
||||
const failed = data?.failed ?? 0
|
||||
|
||||
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"
|
||||
className="relative md:hidden h-10 w-10 p-0 text-foreground border-border hover:bg-accent"
|
||||
aria-label={total > 0 ? `More, ${total} unread reports` : 'More'}
|
||||
>
|
||||
<MoreVertical className="w-5 h-5" />
|
||||
<ScheduleReportsBadge total={total} failed={failed} />
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface ScheduleReportsBadgeProps {
|
||||
total: number
|
||||
failed: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function ScheduleReportsBadge({ total, failed, className }: ScheduleReportsBadgeProps) {
|
||||
if (total <= 0) return null
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'absolute -top-1 -right-1 min-w-4 rounded-full px-1 text-center text-[10px] font-medium leading-4 text-primary-foreground',
|
||||
failed > 0 ? 'bg-destructive' : 'bg-primary',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{total > 9 ? '9+' : total}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -14,10 +14,6 @@ vi.mock('@/hooks/useSchedules', () => ({
|
||||
useMarkAllScheduleRunsViewed: mocks.useMarkAllScheduleRunsViewed,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: vi.fn(() => false),
|
||||
}))
|
||||
|
||||
function renderBell() {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
@@ -50,7 +46,7 @@ describe('ScheduleReportsBell', () => {
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 3, failed: 1 } })
|
||||
renderBell()
|
||||
|
||||
expect(screen.getByTestId('schedule-reports-count')).toHaveClass('bg-destructive')
|
||||
expect(screen.getByText('3')).toHaveClass('bg-destructive')
|
||||
})
|
||||
|
||||
it('renders nothing when there are no unread runs', () => {
|
||||
|
||||
@@ -4,28 +4,11 @@ import { CheckCircle2, Inbox, XCircle } from 'lucide-react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components/ui/bottom-sheet'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { ScheduleReportsBadge } from '@/components/notifications/ScheduleReportsBadge'
|
||||
import { useMarkAllScheduleRunsViewed, useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { UnreadScheduleRun } from '@/api/schedules'
|
||||
|
||||
function ScheduleReportsCount({ total, failed }: { total: number; failed: number }) {
|
||||
if (total <= 0) return null
|
||||
|
||||
return (
|
||||
<span
|
||||
data-testid="schedule-reports-count"
|
||||
className={cn(
|
||||
'absolute -top-1 -right-1 min-w-4 rounded-full px-1 text-center text-[10px] font-medium leading-4 text-primary-foreground',
|
||||
failed > 0 ? 'bg-destructive' : 'bg-primary',
|
||||
)}
|
||||
>
|
||||
{total > 9 ? '9+' : total}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function ScheduleReportRow({ run, rowClassName, onClick }: { run: UnreadScheduleRun; rowClassName?: string; onClick: () => void }) {
|
||||
const failed = run.status === 'failed'
|
||||
const StatusIcon = failed ? XCircle : CheckCircle2
|
||||
@@ -66,9 +49,19 @@ interface ScheduleReportsListProps {
|
||||
markAllPending: boolean
|
||||
onNavigate?: () => void
|
||||
showTitle?: boolean
|
||||
maxHeightClass?: string
|
||||
}
|
||||
|
||||
function ScheduleReportsList({ runs, total, rowClassName, onMarkAllRead, markAllPending, onNavigate, showTitle = true }: ScheduleReportsListProps) {
|
||||
export function ScheduleReportsList({
|
||||
runs,
|
||||
total,
|
||||
rowClassName,
|
||||
onMarkAllRead,
|
||||
markAllPending,
|
||||
onNavigate,
|
||||
showTitle = true,
|
||||
maxHeightClass = 'max-h-[60vh]',
|
||||
}: ScheduleReportsListProps) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const openRun = (runId: number) => {
|
||||
@@ -99,7 +92,7 @@ function ScheduleReportsList({ runs, total, rowClassName, onMarkAllRead, markAll
|
||||
<p className="text-xs text-muted-foreground">New scheduled reports will show up here.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-[60vh] overflow-y-auto">
|
||||
<div className={cn('overflow-y-auto', maxHeightClass)}>
|
||||
{runs.map((run) => (
|
||||
<ScheduleReportRow key={run.id} run={run} rowClassName={rowClassName} onClick={() => openRun(run.id)} />
|
||||
))}
|
||||
@@ -117,7 +110,6 @@ function ScheduleReportsList({ runs, total, rowClassName, onMarkAllRead, markAll
|
||||
}
|
||||
|
||||
export function ScheduleReportsBell() {
|
||||
const isMobile = useMobile()
|
||||
const { data } = useUnreadScheduleRuns()
|
||||
const markAllViewed = useMarkAllScheduleRunsViewed()
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -132,44 +124,19 @@ export function ScheduleReportsBell() {
|
||||
|
||||
if (total === 0 && !open) return null
|
||||
|
||||
const trigger = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={`Reports, ${total} unread`}
|
||||
onClick={isMobile ? () => setOpen(true) : undefined}
|
||||
className="relative h-10 w-10 text-muted-foreground transition-all duration-200 hover:bg-accent hover:text-foreground sm:h-8 sm:w-8"
|
||||
>
|
||||
<Inbox className="h-5 w-5 sm:h-4 sm:w-4" />
|
||||
<ScheduleReportsCount total={total} failed={failed} />
|
||||
</Button>
|
||||
)
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<>
|
||||
{trigger}
|
||||
<BottomSheet isOpen={open} onClose={() => setOpen(false)} ariaLabel="Reports">
|
||||
<BottomSheetHeader title="Reports" />
|
||||
<BottomSheetContent className="px-0 pt-0">
|
||||
<ScheduleReportsList
|
||||
runs={runs}
|
||||
total={total}
|
||||
rowClassName="py-3"
|
||||
onMarkAllRead={markAllRead}
|
||||
markAllPending={markAllViewed.isPending}
|
||||
onNavigate={() => setOpen(false)}
|
||||
showTitle={false}
|
||||
/>
|
||||
</BottomSheetContent>
|
||||
</BottomSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={`Reports, ${total} unread`}
|
||||
className="relative hidden h-10 w-10 text-muted-foreground transition-all duration-200 hover:bg-accent hover:text-foreground sm:h-8 sm:w-8 md:inline-flex"
|
||||
>
|
||||
<Inbox className="h-5 w-5 sm:h-4 sm:w-4" />
|
||||
<ScheduleReportsBadge total={total} failed={failed} />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-96 p-0">
|
||||
<ScheduleReportsList
|
||||
runs={runs}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { ContextUsageIndicator } from './ContextUsageIndicator'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useContextUsage: vi.fn(),
|
||||
useMobile: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useContextUsage', () => ({
|
||||
useContextUsage: mocks.useContextUsage,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: mocks.useMobile,
|
||||
}))
|
||||
|
||||
function renderIndicator() {
|
||||
return render(<ContextUsageIndicator sessionID="ses_1" isConnected={true} />)
|
||||
}
|
||||
|
||||
describe('ContextUsageIndicator', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders tokens and percentage on desktop', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: 42 }, isLoading: false })
|
||||
renderIndicator()
|
||||
|
||||
expect(screen.getByText('1,234 (42%)')).toBeInTheDocument()
|
||||
expect(screen.queryByText('42%')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders only the percentage on mobile', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: 42 }, isLoading: false })
|
||||
renderIndicator()
|
||||
|
||||
expect(screen.getByText('42%')).toBeInTheDocument()
|
||||
expect(screen.queryByText('1,234 (42%)')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders only the token count on mobile without a percentage', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: null }, isLoading: false })
|
||||
renderIndicator()
|
||||
|
||||
expect(screen.getByText('1,234')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useContextUsage } from '@/hooks/useContextUsage'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
|
||||
interface ContextUsageIndicatorProps {
|
||||
directory?: string
|
||||
@@ -22,6 +23,7 @@ export function ContextUsageIndicator({
|
||||
revertMessageID,
|
||||
}: ContextUsageIndicatorProps) {
|
||||
const { usage, isLoading } = useContextUsage(sessionID, directory, revertMessageID)
|
||||
const isMobile = useMobile()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -43,14 +45,18 @@ export function ContextUsageIndicator({
|
||||
return null
|
||||
}
|
||||
|
||||
const tokenText = usage.usagePercentage === null
|
||||
const compactText = usage.usagePercentage === null
|
||||
? usage.totalTokens.toLocaleString()
|
||||
: `${usage.usagePercentage}%`
|
||||
|
||||
const fullText = usage.usagePercentage === null
|
||||
? usage.totalTokens.toLocaleString()
|
||||
: `${usage.totalTokens.toLocaleString()} (${usage.usagePercentage}%)`
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`text-xs font-medium whitespace-nowrap ${getUsageTextColor(usage.usagePercentage ?? 0)}`}>
|
||||
{tokenText}
|
||||
{isMobile ? compactText : fullText}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -2,8 +2,13 @@ import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { Sidebar, SidebarSection, SidebarItem, SidebarCollapseToggle } from './sidebar'
|
||||
import { TooltipProvider } from './tooltip'
|
||||
import { SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH } from '@/hooks/useSidebarWidth'
|
||||
import { Folder } from 'lucide-react'
|
||||
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
|
||||
describe('Sidebar', () => {
|
||||
it('renders children', () => {
|
||||
render(
|
||||
@@ -34,6 +39,153 @@ describe('Sidebar', () => {
|
||||
|
||||
expect(container.firstChild).toHaveClass('w-60')
|
||||
})
|
||||
|
||||
it('renders an inline width instead of the width class when width is provided', () => {
|
||||
const { container } = render(
|
||||
<Sidebar collapsed={false} onToggle={vi.fn()} width={320} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const aside = container.firstChild as HTMLElement
|
||||
expect(aside.style.width).toBe('320px')
|
||||
expect(aside).not.toHaveClass('w-60')
|
||||
})
|
||||
|
||||
it('keeps the collapsed width class when collapsed even if width is provided', () => {
|
||||
const { container } = render(
|
||||
<Sidebar collapsed={true} onToggle={vi.fn()} width={320} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const aside = container.firstChild as HTMLElement
|
||||
expect(aside).toHaveClass('w-14')
|
||||
expect(aside.style.width).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Sidebar resize handle', () => {
|
||||
it('is not rendered when collapsed', () => {
|
||||
render(
|
||||
<Sidebar collapsed={true} onToggle={vi.fn()} width={320} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
expect(screen.queryByRole('separator')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('is not rendered without onWidthChange', () => {
|
||||
render(
|
||||
<Sidebar collapsed={false} onToggle={vi.fn()} width={320}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
expect(screen.queryByRole('separator')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('exposes the current width via aria attributes', () => {
|
||||
render(
|
||||
<Sidebar collapsed={false} onToggle={vi.fn()} width={320} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
expect(handle).toHaveAttribute('aria-valuenow', '320')
|
||||
expect(handle).toHaveAttribute('aria-valuemin', String(SIDEBAR_MIN_WIDTH))
|
||||
expect(handle).toHaveAttribute('aria-valuemax', String(SIDEBAR_MAX_WIDTH))
|
||||
expect(handle).toHaveAttribute('aria-orientation', 'vertical')
|
||||
})
|
||||
|
||||
it('reports the dragged width from the first pointer move', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
const { container } = render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientX: 300 })
|
||||
fireEvent.pointerMove(handle, { pointerId: 1, clientX: 340 })
|
||||
|
||||
expect(handleWidthChange).toHaveBeenCalledWith(340)
|
||||
expect(container.firstChild).toHaveClass('transition-none')
|
||||
})
|
||||
|
||||
it('ignores pointer moves from another pointer id', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientX: 300 })
|
||||
fireEvent.pointerMove(handle, { pointerId: 2, clientX: 400 })
|
||||
|
||||
expect(handleWidthChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stops reporting after pointer up and restores the transition classes', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
const { container } = render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientX: 300 })
|
||||
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 320 })
|
||||
fireEvent.pointerMove(handle, { pointerId: 1, clientX: 360 })
|
||||
|
||||
expect(handleWidthChange).not.toHaveBeenCalled()
|
||||
expect(container.firstChild).toHaveClass('transition-[width]')
|
||||
})
|
||||
|
||||
it('adjusts the width from the keyboard', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'ArrowRight' })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(316)
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'ArrowLeft' })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(284)
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'ArrowRight', shiftKey: true })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(364)
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'Home' })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(SIDEBAR_MIN_WIDTH)
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'End' })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(SIDEBAR_MAX_WIDTH)
|
||||
})
|
||||
|
||||
it('ignores unhandled keys', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
fireEvent.keyDown(screen.getByRole('separator', { name: 'Resize sidebar' }), { key: 'a' })
|
||||
|
||||
expect(handleWidthChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SidebarSection', () => {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
SIDEBAR_MAX_WIDTH,
|
||||
SIDEBAR_MIN_WIDTH,
|
||||
} from '@/hooks/useSidebarWidth'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
|
||||
export interface SidebarProps {
|
||||
@@ -11,6 +16,14 @@ export interface SidebarProps {
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
ariaLabel?: string
|
||||
width?: number
|
||||
onWidthChange?: (width: number) => void
|
||||
}
|
||||
|
||||
interface SidebarDragState {
|
||||
pointerId: number
|
||||
startX: number
|
||||
startWidth: number
|
||||
}
|
||||
|
||||
export function Sidebar({
|
||||
@@ -21,17 +34,112 @@ export function Sidebar({
|
||||
className,
|
||||
children,
|
||||
ariaLabel = 'Sidebar',
|
||||
width,
|
||||
onWidthChange,
|
||||
}: SidebarProps) {
|
||||
const dragRef = useRef<SidebarDragState | null>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0 || width === undefined || !onWidthChange) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
event.currentTarget.setPointerCapture?.(event.pointerId)
|
||||
dragRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
startX: event.clientX,
|
||||
startWidth: width,
|
||||
}
|
||||
setIsDragging(true)
|
||||
},
|
||||
[onWidthChange, width]
|
||||
)
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const drag = dragRef.current
|
||||
if (!drag || drag.pointerId !== event.pointerId || !onWidthChange) {
|
||||
return
|
||||
}
|
||||
onWidthChange(drag.startWidth + event.clientX - drag.startX)
|
||||
},
|
||||
[onWidthChange]
|
||||
)
|
||||
|
||||
const handlePointerEnd = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const drag = dragRef.current
|
||||
if (!drag || drag.pointerId !== event.pointerId) {
|
||||
return
|
||||
}
|
||||
if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture?.(event.pointerId)
|
||||
}
|
||||
dragRef.current = null
|
||||
setIsDragging(false)
|
||||
}, [])
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (!onWidthChange || width === undefined) {
|
||||
return
|
||||
}
|
||||
const step = event.shiftKey ? 64 : 16
|
||||
let nextWidth: number
|
||||
switch (event.key) {
|
||||
case 'ArrowLeft':
|
||||
nextWidth = width - step
|
||||
break
|
||||
case 'ArrowRight':
|
||||
nextWidth = width + step
|
||||
break
|
||||
case 'Home':
|
||||
nextWidth = SIDEBAR_MIN_WIDTH
|
||||
break
|
||||
case 'End':
|
||||
nextWidth = SIDEBAR_MAX_WIDTH
|
||||
break
|
||||
default:
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
onWidthChange(nextWidth)
|
||||
},
|
||||
[onWidthChange, width]
|
||||
)
|
||||
|
||||
const showResizeHandle = !collapsed && width !== undefined && onWidthChange !== undefined
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
'relative z-20 flex-shrink-0 border-r border-border bg-card/50 backdrop-blur-sm h-full flex flex-col pt-safe pb-safe transition-[width] duration-200',
|
||||
collapsed ? collapsedWidthClass : widthClass,
|
||||
'relative z-20 flex-shrink-0 border-r border-border bg-card/50 backdrop-blur-sm h-full flex flex-col pt-safe pb-safe',
|
||||
isDragging ? 'transition-none select-none' : 'transition-[width] duration-200',
|
||||
collapsed ? collapsedWidthClass : width === undefined ? widthClass : undefined,
|
||||
className
|
||||
)}
|
||||
style={!collapsed && width !== undefined ? { width } : undefined}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
{onToggle && <SidebarCollapseToggle collapsed={collapsed} onToggle={onToggle} />}
|
||||
{showResizeHandle && (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Resize sidebar"
|
||||
tabIndex={0}
|
||||
aria-valuenow={width}
|
||||
aria-valuemin={SIDEBAR_MIN_WIDTH}
|
||||
aria-valuemax={SIDEBAR_MAX_WIDTH}
|
||||
className="absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize touch-none bg-transparent hover:bg-highlight/30 focus-visible:bg-highlight/30 focus-visible:outline-none"
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerEnd}
|
||||
onPointerCancel={handlePointerEnd}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
)}
|
||||
{children}
|
||||
</aside>
|
||||
)
|
||||
|
||||
@@ -1,23 +1,8 @@
|
||||
import { useState, useCallback } from 'react'
|
||||
|
||||
function readStorage(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeStorage(key: string, value: unknown): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
import { readStoredValue, writeStoredValue } from '@/lib/persistentStorage'
|
||||
|
||||
function readStoredBoolean(key: string, fallback: boolean): boolean {
|
||||
const stored = readStorage(key)
|
||||
const stored = readStoredValue(key)
|
||||
if (stored === null) {
|
||||
return fallback
|
||||
}
|
||||
@@ -39,7 +24,7 @@ export function usePersistentBoolean(key: string, fallback: boolean): [boolean,
|
||||
const toggle = useCallback(() => {
|
||||
setValue((prev: boolean) => {
|
||||
const newValue = !prev
|
||||
writeStorage(key, newValue)
|
||||
writeStoredValue(key, newValue)
|
||||
return newValue
|
||||
})
|
||||
}, [key])
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import {
|
||||
clampSidebarWidth,
|
||||
useSidebarWidth,
|
||||
SIDEBAR_DEFAULT_WIDTH,
|
||||
SIDEBAR_MAX_WIDTH,
|
||||
SIDEBAR_MIN_WIDTH,
|
||||
} from './useSidebarWidth'
|
||||
|
||||
const localStorageMock = {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
}
|
||||
|
||||
describe('useSidebarWidth', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: localStorageMock,
|
||||
writable: true,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: window.localStorage,
|
||||
writable: true,
|
||||
})
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('falls back to the default width when nothing is stored', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarWidth())
|
||||
|
||||
expect(localStorageMock.getItem).toHaveBeenCalledWith('oc:sidebar:width')
|
||||
expect(result.current[0]).toBe(SIDEBAR_DEFAULT_WIDTH)
|
||||
})
|
||||
|
||||
it('reads a stored width', () => {
|
||||
localStorageMock.getItem.mockReturnValue('320')
|
||||
|
||||
const { result } = renderHook(() => useSidebarWidth())
|
||||
|
||||
expect(result.current[0]).toBe(320)
|
||||
})
|
||||
|
||||
it.each(['not json', '"320"', 'null', 'true', '{}'])(
|
||||
'ignores the malformed stored value %s',
|
||||
(stored) => {
|
||||
localStorageMock.getItem.mockReturnValue(stored)
|
||||
|
||||
const { result } = renderHook(() => useSidebarWidth())
|
||||
|
||||
expect(result.current[0]).toBe(SIDEBAR_DEFAULT_WIDTH)
|
||||
}
|
||||
)
|
||||
|
||||
it('clamps and persists the setter value below the minimum', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarWidth())
|
||||
|
||||
act(() => {
|
||||
result.current[1](100)
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(SIDEBAR_MIN_WIDTH)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:width', '200')
|
||||
})
|
||||
|
||||
it('clamps and persists the setter value above the maximum', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarWidth())
|
||||
|
||||
act(() => {
|
||||
result.current[1](900)
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(SIDEBAR_MAX_WIDTH)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:width', '480')
|
||||
})
|
||||
|
||||
it('rounds and clamps in clampSidebarWidth', () => {
|
||||
expect(clampSidebarWidth(250.6)).toBe(251)
|
||||
expect(clampSidebarWidth(100.4)).toBe(SIDEBAR_MIN_WIDTH)
|
||||
expect(clampSidebarWidth(900)).toBe(SIDEBAR_MAX_WIDTH)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useCallback, useState } from 'react'
|
||||
import { readStoredValue, writeStoredValue } from '@/lib/persistentStorage'
|
||||
|
||||
export const SIDEBAR_DEFAULT_WIDTH = 240
|
||||
export const SIDEBAR_MIN_WIDTH = 200
|
||||
export const SIDEBAR_MAX_WIDTH = 480
|
||||
|
||||
const STORAGE_KEY = 'oc:sidebar:width'
|
||||
|
||||
export function clampSidebarWidth(width: number): number {
|
||||
return Math.min(SIDEBAR_MAX_WIDTH, Math.max(SIDEBAR_MIN_WIDTH, Math.round(width)))
|
||||
}
|
||||
|
||||
function readStoredWidth(): number {
|
||||
const stored = readStoredValue(STORAGE_KEY)
|
||||
if (stored === null) {
|
||||
return SIDEBAR_DEFAULT_WIDTH
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(stored)
|
||||
return typeof parsed === 'number' && Number.isFinite(parsed)
|
||||
? clampSidebarWidth(parsed)
|
||||
: SIDEBAR_DEFAULT_WIDTH
|
||||
} catch {
|
||||
return SIDEBAR_DEFAULT_WIDTH
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists the desktop sidebar width under `oc:sidebar:width` and returns it with a clamped setter.
|
||||
* Falls back to `SIDEBAR_DEFAULT_WIDTH` when the stored value is missing, malformed, or not finite.
|
||||
*/
|
||||
export function useSidebarWidth(): [number, (width: number) => void] {
|
||||
const [width, setWidth] = useState<number>(readStoredWidth)
|
||||
|
||||
const updateWidth = useCallback((next: number) => {
|
||||
const clamped = clampSidebarWidth(next)
|
||||
writeStoredValue(STORAGE_KEY, clamped)
|
||||
setWidth(clamped)
|
||||
}, [])
|
||||
|
||||
return [width, updateWidth]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export function readStoredValue(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function writeStoredValue(key: string, value: unknown): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user