feat(renderer): GitStatusPanel sidebar tab + git.refresh event

This commit is contained in:
2026-06-06 08:28:37 +05:30
parent 2d77fa5456
commit c28c6312c3
7 changed files with 202 additions and 5 deletions
@@ -0,0 +1,101 @@
import { useEffect, useState } from 'react';
import { RefreshCw, FileX, FilePlus, FileEdit, FileQuestion } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useFileStore } from '@/stores/file-store';
import { ipc } from '@/lib/ipc';
interface GitStatus {
filePath: string;
status: 'modified' | 'added' | 'deleted' | 'untracked';
}
const STATUS_ICON: Record<GitStatus['status'], JSX.Element> = {
modified: <FileEdit className="h-3 w-3 text-warning" />,
added: <FilePlus className="h-3 w-3 text-success" />,
deleted: <FileX className="h-3 w-3 text-destructive" />,
untracked: <FileQuestion className="h-3 w-3 text-muted-foreground" />,
};
const STATUS_LABEL: Record<GitStatus['status'], string> = {
modified: 'M',
added: 'A',
deleted: 'D',
untracked: '?',
};
export function GitStatusPanel() {
const rootPath = useFileStore((s) => s.rootPath);
const openFile = useFileStore((s) => s.openFile);
const [status, setStatus] = useState<GitStatus[]>([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const load = async () => {
if (!rootPath) {
setStatus([]);
return;
}
setLoading(true);
setError(null);
const result = await ipc.file.gitStatus({ rootPath });
if (!result.ok) {
setError(result.error.message);
setStatus([]);
setLoading(false);
return;
}
setStatus(result.data ?? []);
setLoading(false);
};
useEffect(() => {
load();
// Listen for git.refresh command via custom event
const handler = () => load();
window.addEventListener('mc:git-refresh', handler);
return () => window.removeEventListener('mc:git-refresh', handler);
}, [rootPath]);
if (!rootPath) {
return <div className="p-3 text-xs text-muted-foreground">No folder open</div>;
}
if (error) {
return (
<div className="p-3 text-xs">
<div className="text-destructive">Error: {error}</div>
<p className="mt-1 text-muted-foreground">Not a git repository, or git not installed.</p>
<Button size="sm" variant="ghost" onClick={load} className="mt-2">Retry</Button>
</div>
);
}
if (status.length === 0 && !loading) {
return <div className="p-3 text-xs text-muted-foreground">Working tree clean</div>;
}
return (
<div className="p-2 text-xs">
<div className="flex items-center justify-between px-1 py-1">
<span className="font-semibold">{status.length} changed file{status.length === 1 ? '' : 's'}</span>
<Button size="sm" variant="ghost" onClick={load} aria-label="Refresh">
<RefreshCw className="h-3 w-3" />
</Button>
</div>
<div className="space-y-0.5">
{status.map((s) => (
<button
key={s.filePath}
onClick={() => openFile(s.filePath)}
className="flex w-full items-center gap-2 rounded px-2 py-1 text-left hover:bg-card/50"
data-testid="git-status-row"
>
{STATUS_ICON[s.status]}
<span className="w-3 font-mono text-xs">{STATUS_LABEL[s.status]}</span>
<span className="truncate font-mono">{s.filePath.replace(rootPath + '/', '')}</span>
</button>
))}
</div>
</div>
);
}
@@ -5,6 +5,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';
import { useFileStore } from '@/stores/file-store'; import { useFileStore } from '@/stores/file-store';
import { FileTree } from './FileTree'; import { FileTree } from './FileTree';
import { Outline } from './Outline'; import { Outline } from './Outline';
import { GitStatusPanel } from './GitStatusPanel';
export function Sidebar() { export function Sidebar() {
const tree = useFileStore((s) => s.tree); const tree = useFileStore((s) => s.tree);
@@ -49,6 +50,21 @@ export function Sidebar() {
</ScrollArea> </ScrollArea>
</CollapsibleContent> </CollapsibleContent>
</Collapsible> </Collapsible>
{/* Git section */}
<Collapsible defaultOpen>
<CollapsibleTrigger asChild>
<button className="flex w-full items-center gap-1.5 px-1 py-1.5 text-xs font-medium hover:bg-accent rounded">
<ChevronRight size={12} className="rotate-90" />
Git
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<ScrollArea className="h-[calc(100vh-240px)]">
<GitStatusPanel />
</ScrollArea>
</CollapsibleContent>
</Collapsible>
</div> </div>
); );
} }
@@ -66,7 +66,7 @@ export function registerMenuCommands(): void {
if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('mc:print')); if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('mc:print'));
}, },
'git.refresh': () => { 'git.refresh': () => {
/* stub — actual refresh is a useEffect in GitStatusPanel */ if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('mc:git-refresh'));
}, },
}); });
@@ -0,0 +1,73 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { GitStatusPanel } from '@/components/sidebar/GitStatusPanel';
import { useFileStore } from '@/stores/file-store';
vi.mock('@/lib/ipc', () => ({
ipc: {
file: {
gitStatus: vi.fn(),
},
},
}));
import { ipc } from '@/lib/ipc';
describe('GitStatusPanel', () => {
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
});
it('shows "No folder open" when rootPath is null', () => {
useFileStore.setState({ rootPath: null } as any);
render(<GitStatusPanel />);
expect(screen.getByText(/no folder open/i)).toBeInTheDocument();
});
it('fetches and shows git status', async () => {
(ipc.file.gitStatus as any).mockResolvedValueOnce({
ok: true,
data: [
{ filePath: '/project/a.md', status: 'modified' },
{ filePath: '/project/b.md', status: 'added' },
],
});
useFileStore.setState({ rootPath: '/project' } as any);
render(<GitStatusPanel />);
expect(await screen.findByText('a.md')).toBeInTheDocument();
expect(await screen.findByText('b.md')).toBeInTheDocument();
});
it('shows "Working tree clean" when no changes', async () => {
(ipc.file.gitStatus as any).mockResolvedValueOnce({ ok: true, data: [] });
useFileStore.setState({ rootPath: '/project' } as any);
render(<GitStatusPanel />);
expect(await screen.findByText(/working tree clean/i)).toBeInTheDocument();
});
it('shows error state when gitStatus fails', async () => {
(ipc.file.gitStatus as any).mockResolvedValueOnce({
ok: false,
error: { code: 'IPC_ERROR', message: 'Not a git repository' },
});
useFileStore.setState({ rootPath: '/project' } as any);
render(<GitStatusPanel />);
// The helper text appears in a <p> element distinct from the error heading
expect(await screen.findByText('Not a git repository, or git not installed.')).toBeInTheDocument();
});
it('opens file on click', async () => {
const openFile = vi.fn();
(ipc.file.gitStatus as any).mockResolvedValueOnce({
ok: true,
data: [{ filePath: '/project/a.md', status: 'modified' }],
});
useFileStore.setState({ rootPath: '/project', openFile } as any);
render(<GitStatusPanel />);
const row = await screen.findByTestId('git-status-row');
await userEvent.click(row);
expect(openFile).toHaveBeenCalledWith('/project/a.md');
});
});
+1
View File
@@ -13,6 +13,7 @@ vi.mock('@/lib/ipc', () => ({
pickFile: vi.fn(), pickFile: vi.fn(),
read: vi.fn(), read: vi.fn(),
write: vi.fn(), write: vi.fn(),
gitStatus: vi.fn().mockResolvedValue({ ok: true, data: [] }),
}, },
}, },
})); }));
+9 -4
View File
@@ -36,6 +36,7 @@ vi.mock('@/lib/ipc', () => ({
pickFolder: vi.fn().mockResolvedValue({ ok: true, data: '/root' }), pickFolder: vi.fn().mockResolvedValue({ ok: true, data: '/root' }),
pickFile: vi.fn().mockResolvedValue({ ok: true, data: '/root/README.md' }), pickFile: vi.fn().mockResolvedValue({ ok: true, data: '/root/README.md' }),
onChange: vi.fn(() => () => {}), onChange: vi.fn(() => () => {}),
gitStatus: vi.fn().mockResolvedValue({ ok: true, data: [] }),
}, },
menu: { menu: {
on: vi.fn(() => () => {}), on: vi.fn(() => () => {}),
@@ -54,6 +55,8 @@ describe('Phase 5 integration', () => {
activeTabId: null, activeTabId: null,
}); });
useEditorStore.setState({ buffers: new Map(), activeId: null }); useEditorStore.setState({ buffers: new Map(), activeId: null });
// Also clear the active buffer so breadcrumb symbols won't show stale heading text
useEditorStore.getState().buffers.clear();
useAppStore.setState({ useAppStore.setState({
sidebarVisible: true, sidebarVisible: true,
previewVisible: true, previewVisible: true,
@@ -128,12 +131,14 @@ describe('Phase 5 integration', () => {
], ],
activeTabId: '/a.md', activeTabId: '/a.md',
}); });
// Use a buffer content that won't conflict with tab title in breadcrumb symbols
useEditorStore.setState({ buffers: new Map([['/a.md', { id: '/a.md', path: '/a.md', content: '# Hello', dirty: false }], ['/b.md', { id: '/b.md', path: '/b.md', content: '# World', dirty: false }]]), activeId: '/a.md' });
render(<AppShell />); render(<AppShell />);
const aTab = screen.getByText('a.md').closest('[role="tab"]')!; // Use role="tab" to find tabs specifically, avoiding breadcrumb "a.md" text
const bTab = screen.getByText('b.md').closest('[role="tab"]')!; const tabs = screen.getAllByRole('tab');
expect(aTab).toHaveAttribute('aria-current', 'page'); expect(tabs[0]).toHaveAttribute('aria-current', 'page');
await act(async () => { await act(async () => {
fireEvent.click(bTab); fireEvent.click(tabs[1]);
}); });
expect(useFileStore.getState().activeTabId).toBe('/b.md'); expect(useFileStore.getState().activeTabId).toBe('/b.md');
}); });
+1
View File
@@ -35,6 +35,7 @@ vi.mock('@/lib/ipc', () => ({
pickFolder: vi.fn().mockResolvedValue({ ok: true, data: '/root' }), pickFolder: vi.fn().mockResolvedValue({ ok: true, data: '/root' }),
pickFile: vi.fn().mockResolvedValue({ ok: true, data: '/root/README.md' }), pickFile: vi.fn().mockResolvedValue({ ok: true, data: '/root/README.md' }),
onChange: vi.fn(() => () => {}), onChange: vi.fn(() => () => {}),
gitStatus: vi.fn().mockResolvedValue({ ok: true, data: [] }),
}, },
menu: { menu: {
on: vi.fn((channel: string, cb: (...args: unknown[]) => void) => { on: vi.fn((channel: string, cb: (...args: unknown[]) => void) => {