mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Merge branch 'main' into drag-and-drop
This commit is contained in:
commit
758ed90bb7
19 files changed
+849
-137
No files matched your search
@@ -27,6 +27,7 @@ export default tseslint.config(
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
"react-hooks/exhaustive-deps": "error",
|
||||
"react-refresh/only-export-components": [
|
||||
"warn",
|
||||
{ allowConstantExport: true },
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon-192.png",
|
||||
"src": "/favicon.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icon-512.png",
|
||||
"src": "/favicon.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import Settings from "./pages/Settings";
|
||||
import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
@@ -21,6 +22,7 @@ export function AppRouter() {
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
|
||||
@@ -4,7 +4,7 @@ import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Menu, Columns2 } from 'lucide-react';
|
||||
import { Menu } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
interface AppLayoutProps {
|
||||
@@ -129,6 +129,7 @@ export function AppLayout({
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={handleProjectSelect}
|
||||
className="h-screen sticky top-0"
|
||||
onToggleSidebar={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -136,16 +137,16 @@ export function AppLayout({
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col bg-background">
|
||||
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 relative">
|
||||
{/* Toggle Button - positioned absolutely in top-left corner */}
|
||||
{showSidebar && (
|
||||
{/* Show open button when sidebar is collapsed */}
|
||||
{showSidebar && !isSidebarVisible && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
onClick={() => setIsSidebarVisible(true)}
|
||||
className="absolute top-2 left-4 h-8 w-8 p-0 z-10 bg-transparent backdrop-blur-sm hover:bg-transparent text-foreground/70 hover:text-foreground"
|
||||
aria-label="Toggle sidebar"
|
||||
aria-label="Open sidebar"
|
||||
>
|
||||
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { ProjectSidebar } from './ProjectSidebar';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
|
||||
// Mock the hooks
|
||||
vi.mock('@/hooks/useProjects');
|
||||
vi.mock('@/hooks/useLocalStorage');
|
||||
vi.mock('@/hooks/useProjectSessionStatus', () => ({
|
||||
useProjectSessionStatus: () => ({ hasRunningSessions: false })
|
||||
}));
|
||||
vi.mock('react-router-dom', () => ({
|
||||
useNavigate: () => vi.fn()
|
||||
}));
|
||||
vi.mock('@tanstack/react-query', () => ({
|
||||
useQueryClient: () => ({
|
||||
invalidateQueries: vi.fn()
|
||||
})
|
||||
}));
|
||||
|
||||
// Mock the LoginArea component
|
||||
vi.mock('@/components/auth/LoginArea', () => ({
|
||||
LoginArea: ({ className }: { className?: string }) => (
|
||||
<div data-testid="login-area" className={className}>Login Area</div>
|
||||
)
|
||||
}));
|
||||
|
||||
const mockUseProjects = vi.mocked(useProjects);
|
||||
const mockUseLocalStorage = vi.mocked(useLocalStorage);
|
||||
|
||||
describe('ProjectSidebar', () => {
|
||||
beforeEach(() => {
|
||||
mockUseProjects.mockReturnValue({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
error: null
|
||||
} as unknown as ReturnType<typeof useProjects>);
|
||||
|
||||
mockUseLocalStorage.mockReturnValue([[], vi.fn()]);
|
||||
});
|
||||
|
||||
it('renders sidebar header with logo', () => {
|
||||
render(
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('🎭')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows collapse button when onToggleSidebar is provided', () => {
|
||||
const mockToggle = vi.fn();
|
||||
|
||||
render(
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
onToggleSidebar={mockToggle}
|
||||
/>
|
||||
);
|
||||
|
||||
const collapseButton = screen.getByLabelText('Collapse sidebar');
|
||||
expect(collapseButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(collapseButton);
|
||||
expect(mockToggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not show collapse button when onToggleSidebar is not provided', () => {
|
||||
render(
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByLabelText('Collapse sidebar')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders login area at the bottom', () => {
|
||||
render(
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('login-area')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows new project button', () => {
|
||||
render(
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('New Project')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Plus, Folder, GitBranch, Settings, Loader2, ChevronDown, Star } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
@@ -76,12 +76,14 @@ interface ProjectSidebarProps {
|
||||
selectedProject: Project | null;
|
||||
onSelectProject: (project: Project | null) => void;
|
||||
className?: string;
|
||||
onToggleSidebar?: () => void;
|
||||
}
|
||||
|
||||
export function ProjectSidebar({
|
||||
selectedProject,
|
||||
onSelectProject,
|
||||
className
|
||||
className,
|
||||
onToggleSidebar
|
||||
}: ProjectSidebarProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
@@ -116,16 +118,19 @@ export function ProjectSidebar({
|
||||
Shakespeare
|
||||
</h1>
|
||||
</button>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
|
||||
onClick={() => navigate('/settings')}
|
||||
>
|
||||
<Settings className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
</Button>
|
||||
</div>
|
||||
{onToggleSidebar && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
|
||||
onClick={onToggleSidebar}
|
||||
aria-label="Collapse sidebar"
|
||||
>
|
||||
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Menu, Columns2, Bot, GitBranch, Database } from 'lucide-react';
|
||||
import { Menu, Bot, GitBranch, Database } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
@@ -61,7 +61,7 @@ export function SettingsLayout() {
|
||||
// Set initial sidebar state based on projects and device type
|
||||
if (!hasSetInitialState && !isMobile) {
|
||||
// On desktop, show sidebar if there are projects
|
||||
setIsSidebarVisible(projectList.length > 0);
|
||||
setIsSidebarVisible(true);
|
||||
setHasSetInitialState(true);
|
||||
} else if (!hasSetInitialState && isMobile) {
|
||||
// On mobile, always start hidden
|
||||
@@ -145,6 +145,7 @@ export function SettingsLayout() {
|
||||
selectedProject={null}
|
||||
onSelectProject={handleProjectSelect}
|
||||
className="h-full"
|
||||
onToggleSidebar={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -154,15 +155,17 @@ export function SettingsLayout() {
|
||||
{/* Header with toggle button */}
|
||||
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
|
||||
</Button>
|
||||
{!isSidebarVisible && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(true)}
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label="Open sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<h1 className="text-xl font-bold flex items-center gap-2">
|
||||
Settings
|
||||
</h1>
|
||||
|
||||
@@ -298,18 +298,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [projectId, scrolledProjects]);
|
||||
|
||||
// Also scroll on initial mount if we have a projectId
|
||||
useEffect(() => {
|
||||
if (projectId && !scrolledProjects.has(projectId)) {
|
||||
const timer = setTimeout(() => {
|
||||
scrollToBottom();
|
||||
scrolledProjects.add(projectId);
|
||||
}, 100);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, []); // Empty dependency array = runs on mount
|
||||
|
||||
const handleFileSelect = (file: File) => {
|
||||
setAttachedFiles(prev => [...prev, file]);
|
||||
};
|
||||
|
||||
@@ -2,9 +2,10 @@ import { useState, useEffect, useCallback } from 'react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { ChevronRight, ChevronDown, File, Folder } from 'lucide-react';
|
||||
import { ChevronRight, ChevronDown, File, Folder, Search } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { createGitignoreFilter, normalizePathForGitignore } from '@/lib/gitignore';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
interface FileTreeProps {
|
||||
projectId: string;
|
||||
@@ -22,11 +23,14 @@ interface FileNode {
|
||||
|
||||
export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) {
|
||||
const [tree, setTree] = useState<FileNode[]>([]);
|
||||
const [filteredTree, setFilteredTree] = useState<FileNode[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [gitignoreFilter, setGitignoreFilter] = useState<{
|
||||
isIgnored: (path: string) => boolean;
|
||||
shouldShow: (path: string) => boolean;
|
||||
} | null>(null);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
@@ -127,6 +131,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
|
||||
const structure = await buildFileTree(projectId, '');
|
||||
setTree(structure);
|
||||
setFilteredTree(structure);
|
||||
} catch (_error) {
|
||||
console.error('Failed to load file tree:', _error);
|
||||
} finally {
|
||||
@@ -151,7 +156,9 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
});
|
||||
};
|
||||
|
||||
// Update both the original tree and filtered tree
|
||||
setTree(prev => toggleNode(prev));
|
||||
setFilteredTree(prev => toggleNode(prev));
|
||||
};
|
||||
|
||||
const handleFileClick = (filePath: string, type: 'file' | 'directory') => {
|
||||
@@ -162,6 +169,58 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
}
|
||||
};
|
||||
|
||||
// Search functions
|
||||
const searchInFiles = useCallback(async (nodes: FileNode[], term: string): Promise<FileNode[]> => {
|
||||
if (!term.trim()) return nodes;
|
||||
|
||||
const results: FileNode[] = [];
|
||||
const searchTermLower = term.toLowerCase();
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.type === 'file') {
|
||||
const fileNameMatch = node.name.toLowerCase().includes(searchTermLower);
|
||||
|
||||
if (fileNameMatch) {
|
||||
results.push(node);
|
||||
}
|
||||
} else if (node.type === 'directory' && node.children) {
|
||||
const childResults = await searchInFiles(node.children, term);
|
||||
if (childResults.length > 0) {
|
||||
// Create a filtered directory node with matching children
|
||||
results.push({
|
||||
...node,
|
||||
children: childResults,
|
||||
isOpen: true, // Auto-expand directories with matches
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results }, []);
|
||||
|
||||
// Perform search when search term changes
|
||||
useEffect(() => {
|
||||
const performSearch = async () => {
|
||||
if (!searchTerm.trim()) {
|
||||
setFilteredTree(tree);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSearching(true);
|
||||
try {
|
||||
const results = await searchInFiles(tree, searchTerm);
|
||||
setFilteredTree(results);
|
||||
} catch (error) {
|
||||
console.error('Search failed:', error);
|
||||
setFilteredTree([]);
|
||||
} finally {
|
||||
setIsSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
performSearch();
|
||||
}, [searchTerm, tree, searchInFiles]);
|
||||
|
||||
const renderNode = (node: FileNode, depth: number = 0) => {
|
||||
const isSelected = selectedFile === node.path;
|
||||
|
||||
@@ -232,12 +291,32 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
|
||||
return (
|
||||
<div className="p-2">
|
||||
{tree.length === 0 ? (
|
||||
<div className="text-center text-sm text-muted-foreground py-8">
|
||||
No files found
|
||||
{/* Search Section */}
|
||||
<div className="mb-3">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search files..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* File Tree */}
|
||||
{isSearching ? (
|
||||
<div className="space-y-2">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<div key={i} className="h-6 bg-muted rounded animate-pulse"></div>
|
||||
))}
|
||||
</div>
|
||||
) : filteredTree.length === 0 ? (
|
||||
<div className="text-center text-sm text-muted-foreground py-4">
|
||||
{searchTerm ? 'No files found matching your search' : 'No files found'}
|
||||
</div>
|
||||
) : (
|
||||
tree.map(node => renderNode(node))
|
||||
filteredTree.map(node => renderNode(node))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { AccountSwitcher } from './AccountSwitcher';
|
||||
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
||||
|
||||
// Mock the hooks
|
||||
vi.mock('@/hooks/useLoggedInAccounts');
|
||||
vi.mock('react-router-dom', () => ({
|
||||
useNavigate: () => vi.fn()
|
||||
}));
|
||||
|
||||
// Mock the RelaySelector component
|
||||
vi.mock('@/components/RelaySelector', () => ({
|
||||
RelaySelector: ({ className }: { className?: string }) => (
|
||||
<div data-testid="relay-selector" className={className}>Relay Selector</div>
|
||||
)
|
||||
}));
|
||||
|
||||
const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts);
|
||||
|
||||
describe('AccountSwitcher', () => {
|
||||
it('renders account switcher with dropdown trigger', () => {
|
||||
mockUseLoggedInAccounts.mockReturnValue({
|
||||
authors: [{
|
||||
id: 'user1',
|
||||
pubkey: 'pubkey1',
|
||||
metadata: { name: 'Test User' }
|
||||
}],
|
||||
currentUser: {
|
||||
id: 'user1',
|
||||
pubkey: 'pubkey1',
|
||||
metadata: { name: 'Test User' }
|
||||
},
|
||||
otherUsers: [],
|
||||
setLogin: vi.fn(),
|
||||
removeLogin: vi.fn()
|
||||
});
|
||||
|
||||
render(<AccountSwitcher onAddAccountClick={vi.fn()} />);
|
||||
|
||||
// Should show the user's name
|
||||
expect(screen.getByText('Test User')).toBeInTheDocument();
|
||||
|
||||
// Should show dropdown trigger button
|
||||
expect(screen.getByRole('button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('returns null when no current user', () => {
|
||||
mockUseLoggedInAccounts.mockReturnValue({
|
||||
authors: [],
|
||||
currentUser: undefined,
|
||||
otherUsers: [],
|
||||
setLogin: vi.fn(),
|
||||
removeLogin: vi.fn()
|
||||
});
|
||||
|
||||
const { container } = render(<AccountSwitcher onAddAccountClick={vi.fn()} />);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
// NOTE: This file is stable and usually should not be modified.
|
||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||
|
||||
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
|
||||
import { ChevronDown, LogOut, UserIcon, UserPlus, Settings, HelpCircle } from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -13,6 +13,7 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx'
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
interface AccountSwitcherProps {
|
||||
onAddAccountClick: () => void;
|
||||
@@ -20,6 +21,7 @@ interface AccountSwitcherProps {
|
||||
|
||||
export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
const { currentUser, otherUsers, setLogin, removeLogin } = useLoggedInAccounts();
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (!currentUser) return null;
|
||||
|
||||
@@ -63,6 +65,20 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigate('/settings')}
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
>
|
||||
<Settings className='w-4 h-4' />
|
||||
<span>Settings</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
>
|
||||
<HelpCircle className='w-4 h-4' />
|
||||
<span>Help</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={onAddAccountClick}
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { LoginArea } from './LoginArea';
|
||||
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
||||
|
||||
// Mock the hooks
|
||||
vi.mock('@/hooks/useLoggedInAccounts');
|
||||
vi.mock('@/hooks/useAppContext', () => ({
|
||||
useAppContext: () => ({
|
||||
config: { relayUrl: 'wss://relay.damus.io' },
|
||||
updateConfig: vi.fn(),
|
||||
presetRelays: [
|
||||
{ name: 'Damus', url: 'wss://relay.damus.io' }
|
||||
]
|
||||
})
|
||||
}));
|
||||
|
||||
// Mock the components
|
||||
vi.mock('./AccountSwitcher', () => ({
|
||||
AccountSwitcher: ({ onAddAccountClick }: { onAddAccountClick: () => void }) => (
|
||||
<div data-testid="account-switcher">
|
||||
<button onClick={onAddAccountClick}>Add Account</button>
|
||||
</div>
|
||||
)
|
||||
}));
|
||||
|
||||
// Mock react-router-dom
|
||||
vi.mock('react-router-dom', () => ({
|
||||
useNavigate: () => vi.fn()
|
||||
}));
|
||||
|
||||
vi.mock('@/components/RelaySelector', () => ({
|
||||
RelaySelector: ({ className }: { className?: string }) => (
|
||||
<div data-testid="relay-selector" className={className}>Relay Selector</div>
|
||||
)
|
||||
}));
|
||||
|
||||
vi.mock('./LoginDialog', () => ({
|
||||
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
|
||||
isOpen ? <div data-testid="login-dialog">Login Dialog</div> : null
|
||||
}));
|
||||
|
||||
vi.mock('./SignupDialog', () => ({
|
||||
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
|
||||
isOpen ? <div data-testid="signup-dialog">Signup Dialog</div> : null
|
||||
}));
|
||||
|
||||
const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts);
|
||||
|
||||
describe('LoginArea', () => {
|
||||
it('shows AccountSwitcher when user is logged in', () => {
|
||||
mockUseLoggedInAccounts.mockReturnValue({
|
||||
authors: [{
|
||||
id: 'user1',
|
||||
pubkey: 'pubkey1',
|
||||
metadata: { name: 'Test User' }
|
||||
}],
|
||||
currentUser: {
|
||||
id: 'user1',
|
||||
pubkey: 'pubkey1',
|
||||
metadata: { name: 'Test User' }
|
||||
},
|
||||
otherUsers: [],
|
||||
setLogin: vi.fn(),
|
||||
removeLogin: vi.fn()
|
||||
});
|
||||
|
||||
render(<LoginArea />);
|
||||
|
||||
expect(screen.getByTestId('account-switcher')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows anonymous user menu when user is not logged in', () => {
|
||||
mockUseLoggedInAccounts.mockReturnValue({
|
||||
authors: [],
|
||||
currentUser: undefined,
|
||||
otherUsers: [],
|
||||
setLogin: vi.fn(),
|
||||
removeLogin: vi.fn()
|
||||
});
|
||||
|
||||
render(<LoginArea />);
|
||||
|
||||
// Should show anonymous user display
|
||||
expect(screen.getByText('Anonymous')).toBeInTheDocument();
|
||||
|
||||
// Should show the dropdown trigger button
|
||||
expect(screen.getByRole('button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('maintains consistent layout structure whether logged in or not', () => {
|
||||
// Test logged out state
|
||||
mockUseLoggedInAccounts.mockReturnValue({
|
||||
authors: [],
|
||||
currentUser: undefined,
|
||||
otherUsers: [],
|
||||
setLogin: vi.fn(),
|
||||
removeLogin: vi.fn()
|
||||
});
|
||||
|
||||
const { rerender } = render(<LoginArea />);
|
||||
|
||||
const loggedOutContainer = screen.getByRole('button');
|
||||
expect(loggedOutContainer).toHaveClass('flex', 'items-center', 'gap-3', 'p-3', 'rounded-full');
|
||||
|
||||
// Test logged in state
|
||||
mockUseLoggedInAccounts.mockReturnValue({
|
||||
authors: [{
|
||||
id: 'user1',
|
||||
pubkey: 'pubkey1',
|
||||
metadata: { name: 'Test User' }
|
||||
}],
|
||||
currentUser: {
|
||||
id: 'user1',
|
||||
pubkey: 'pubkey1',
|
||||
metadata: { name: 'Test User' }
|
||||
},
|
||||
otherUsers: [],
|
||||
setLogin: vi.fn(),
|
||||
removeLogin: vi.fn()
|
||||
});
|
||||
|
||||
rerender(<LoginArea />);
|
||||
|
||||
// Both states should maintain similar structure
|
||||
expect(screen.getByTestId('account-switcher')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -2,13 +2,22 @@
|
||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||
|
||||
import { useState } from 'react';
|
||||
import { User, UserPlus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button.tsx';
|
||||
import { User, UserPlus, ChevronDown, Settings, HelpCircle } from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu.tsx';
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar.tsx';
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import LoginDialog from './LoginDialog';
|
||||
import SignupDialog from './SignupDialog';
|
||||
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
||||
import { AccountSwitcher } from './AccountSwitcher';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
export interface LoginAreaProps {
|
||||
className?: string;
|
||||
@@ -16,6 +25,7 @@ export interface LoginAreaProps {
|
||||
|
||||
export function LoginArea({ className }: LoginAreaProps) {
|
||||
const { currentUser } = useLoggedInAccounts();
|
||||
const navigate = useNavigate();
|
||||
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
|
||||
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
|
||||
|
||||
@@ -29,22 +39,55 @@ export function LoginArea({ className }: LoginAreaProps) {
|
||||
{currentUser ? (
|
||||
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
|
||||
) : (
|
||||
<div className="flex gap-3 justify-center">
|
||||
<Button
|
||||
onClick={() => setLoginDialogOpen(true)}
|
||||
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
|
||||
>
|
||||
<User className='w-4 h-4' />
|
||||
<span className='truncate'>Log in</span>
|
||||
</Button><Button
|
||||
onClick={() => setSignupDialogOpen(true)}
|
||||
variant="outline"
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
|
||||
>
|
||||
<UserPlus className="w-4 h-4" />
|
||||
<span>Sign Up</span>
|
||||
</Button>
|
||||
</div>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
|
||||
<Avatar className='w-10 h-10'>
|
||||
<AvatarFallback>
|
||||
<User className='w-5 h-5 text-muted-foreground' />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className='flex-1 text-left truncate'>
|
||||
<p className='font-medium text-sm truncate'>Anonymous</p>
|
||||
</div>
|
||||
<ChevronDown className='w-4 h-4 text-muted-foreground' />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
|
||||
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
|
||||
<RelaySelector className="w-full" />
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigate('/settings')}
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
>
|
||||
<Settings className='w-4 h-4' />
|
||||
<span>Settings</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
>
|
||||
<HelpCircle className='w-4 h-4' />
|
||||
<span>Help</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => setLoginDialogOpen(true)}
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
>
|
||||
<User className='w-4 h-4' />
|
||||
<span>Log in</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setSignupDialogOpen(true)}
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
>
|
||||
<UserPlus className='w-4 h-4' />
|
||||
<span>Sign up</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
|
||||
<LoginDialog
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useGitHubOAuth } from './useGitHubOAuth';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock crypto.subtle for PKCE testing
|
||||
const mockCryptoSubtle = {
|
||||
digest: vi.fn(),
|
||||
};
|
||||
|
||||
const mockCrypto = {
|
||||
getRandomValues: vi.fn(),
|
||||
randomUUID: vi.fn(),
|
||||
subtle: mockCryptoSubtle,
|
||||
};
|
||||
|
||||
Object.defineProperty(global, 'crypto', {
|
||||
value: mockCrypto,
|
||||
writable: true,
|
||||
});
|
||||
|
||||
// Mock btoa for base64 encoding
|
||||
global.btoa = vi.fn((str: string) => Buffer.from(str, 'binary').toString('base64'));
|
||||
|
||||
describe('useGitHubOAuth PKCE', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
|
||||
// Setup crypto mocks
|
||||
mockCrypto.getRandomValues.mockImplementation((array: Uint8Array) => {
|
||||
// Fill with predictable values for testing
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
array[i] = i % 256;
|
||||
}
|
||||
return array;
|
||||
});
|
||||
|
||||
mockCrypto.randomUUID.mockReturnValue('test-state-uuid');
|
||||
|
||||
// Mock SHA-256 digest to return predictable hash
|
||||
mockCryptoSubtle.digest.mockResolvedValue(
|
||||
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32])
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('should validate state parameter in callback', async () => {
|
||||
// Setup stored state
|
||||
localStorage.setItem('github_oauth_state', 'correct-state');
|
||||
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
|
||||
|
||||
const { result } = renderHook(() => useGitHubOAuth(), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
// Mock fetch for token exchange and user info
|
||||
const mockFetch = vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ access_token: 'test-token' }),
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ login: 'testuser' }),
|
||||
});
|
||||
|
||||
global.fetch = mockFetch;
|
||||
|
||||
let success: boolean | undefined;
|
||||
await act(async () => {
|
||||
success = await result.current.handleCallback('test-code', 'correct-state');
|
||||
});
|
||||
|
||||
expect(success).toBe(true);
|
||||
expect(localStorage.getItem('github_oauth_state')).toBeNull();
|
||||
expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull();
|
||||
});
|
||||
|
||||
it('should reject invalid state parameter', async () => {
|
||||
localStorage.setItem('github_oauth_state', 'correct-state');
|
||||
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
|
||||
|
||||
const { result } = renderHook(() => useGitHubOAuth(), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
let success: boolean | undefined;
|
||||
await act(async () => {
|
||||
success = await result.current.handleCallback('test-code', 'wrong-state');
|
||||
});
|
||||
|
||||
expect(success).toBe(false);
|
||||
expect(result.current.error).toBe('Invalid OAuth state parameter');
|
||||
// Should clean up on error
|
||||
expect(localStorage.getItem('github_oauth_state')).toBeNull();
|
||||
expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull();
|
||||
});
|
||||
|
||||
it('should reject missing code verifier', async () => {
|
||||
localStorage.setItem('github_oauth_state', 'correct-state');
|
||||
// Don't set code verifier
|
||||
|
||||
const { result } = renderHook(() => useGitHubOAuth(), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
let success: boolean | undefined;
|
||||
await act(async () => {
|
||||
success = await result.current.handleCallback('test-code', 'correct-state');
|
||||
});
|
||||
|
||||
expect(success).toBe(false);
|
||||
expect(result.current.error).toBe('PKCE code verifier not found. Please restart the OAuth flow.');
|
||||
});
|
||||
|
||||
it('should include code_verifier in token request', async () => {
|
||||
localStorage.setItem('github_oauth_state', 'correct-state');
|
||||
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
|
||||
|
||||
const { result } = renderHook(() => useGitHubOAuth(), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
const mockFetch = vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ access_token: 'test-token' }),
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ login: 'testuser' }),
|
||||
});
|
||||
|
||||
global.fetch = mockFetch;
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCallback('test-code', 'correct-state');
|
||||
});
|
||||
|
||||
// Check that the token request includes the code verifier
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('github.com/login/oauth/access_token'),
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: expect.stringContaining('"code_verifier":"test-verifier"'),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+73
-19
@@ -25,7 +25,28 @@ export function useGitHubOAuth() {
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET
|
||||
);
|
||||
|
||||
const initiateOAuth = useCallback(() => {
|
||||
// Generate a cryptographically secure random string for PKCE code verifier
|
||||
const generateCodeVerifier = (): string => {
|
||||
const array = new Uint8Array(32);
|
||||
crypto.getRandomValues(array);
|
||||
return btoa(String.fromCharCode(...array))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
};
|
||||
|
||||
// Create SHA-256 hash of the code verifier for PKCE code challenge
|
||||
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(codeVerifier);
|
||||
const digest = await crypto.subtle.digest('SHA-256', data);
|
||||
return btoa(String.fromCharCode(...new Uint8Array(digest)))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
};
|
||||
|
||||
const initiateOAuth = useCallback(async () => {
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
|
||||
if (!clientId) {
|
||||
@@ -33,19 +54,36 @@ export function useGitHubOAuth() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
localStorage.setItem('github_oauth_state', state);
|
||||
try {
|
||||
// Generate PKCE parameters
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||
|
||||
// Redirect to GitHub OAuth
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
redirect_uri: window.location.origin + '/',
|
||||
scope: 'repo',
|
||||
state: state,
|
||||
});
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
|
||||
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
|
||||
// Store both state and code verifier for later use
|
||||
localStorage.setItem('github_oauth_state', state);
|
||||
localStorage.setItem('github_oauth_code_verifier', codeVerifier);
|
||||
|
||||
// Redirect to GitHub OAuth with PKCE parameters
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
redirect_uri: window.location.origin + '/oauth/github',
|
||||
scope: 'repo',
|
||||
state: state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
|
||||
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to initiate OAuth with PKCE:', error);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
error: 'Failed to generate PKCE parameters. Please try again.'
|
||||
}));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleCallback = useCallback(async (code: string, state: string) => {
|
||||
@@ -58,8 +96,15 @@ export function useGitHubOAuth() {
|
||||
throw new Error('Invalid OAuth state parameter');
|
||||
}
|
||||
|
||||
// Clean up stored state
|
||||
// Get the stored code verifier for PKCE
|
||||
const codeVerifier = localStorage.getItem('github_oauth_code_verifier');
|
||||
if (!codeVerifier) {
|
||||
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
|
||||
}
|
||||
|
||||
// Clean up stored values
|
||||
localStorage.removeItem('github_oauth_state');
|
||||
localStorage.removeItem('github_oauth_code_verifier');
|
||||
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET;
|
||||
@@ -68,18 +113,22 @@ export function useGitHubOAuth() {
|
||||
throw new Error('GitHub OAuth credentials not configured');
|
||||
}
|
||||
|
||||
// Exchange code for access token
|
||||
// Exchange code for access token with PKCE code verifier
|
||||
const tokenRequestBody = {
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code: code,
|
||||
redirect_uri: window.location.origin + '/oauth/github',
|
||||
code_verifier: codeVerifier,
|
||||
};
|
||||
|
||||
const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code: code,
|
||||
}),
|
||||
body: JSON.stringify(tokenRequestBody),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
@@ -116,6 +165,11 @@ export function useGitHubOAuth() {
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('GitHub OAuth error:', error);
|
||||
|
||||
// Clean up any remaining OAuth data on error
|
||||
localStorage.removeItem('github_oauth_state');
|
||||
localStorage.removeItem('github_oauth_code_verifier');
|
||||
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isLoading: false,
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Github } from 'lucide-react';
|
||||
|
||||
export default function GitHubOAuth() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const { handleCallback } = useGitHubOAuth();
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
const error = searchParams.get('error');
|
||||
const errorDescription = searchParams.get('error_description');
|
||||
const storedState = localStorage.getItem('github_oauth_state');
|
||||
const storedCodeVerifier = localStorage.getItem('github_oauth_code_verifier');
|
||||
|
||||
// Handle OAuth errors
|
||||
if (error) {
|
||||
toast({
|
||||
title: "GitHub OAuth Error",
|
||||
description: errorDescription || error,
|
||||
variant: "destructive",
|
||||
});
|
||||
navigate('/settings/git');
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle successful OAuth callback
|
||||
if (code && state && storedState && storedCodeVerifier) {
|
||||
handleCallback(code, state).then((success) => {
|
||||
if (success) {
|
||||
toast({
|
||||
title: "GitHub Connected",
|
||||
description: "Successfully connected to GitHub. You can now push and pull from GitHub repositories.",
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Connection Failed",
|
||||
description: "Failed to connect to GitHub. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
// Always redirect to Git settings after handling the callback
|
||||
navigate('/settings/git');
|
||||
});
|
||||
} else if (code && state && storedState && !storedCodeVerifier) {
|
||||
// Missing code verifier - likely an incomplete PKCE flow
|
||||
toast({
|
||||
title: "Authentication Error",
|
||||
description: "OAuth flow is incomplete. Please try connecting to GitHub again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
// Clean up any remaining OAuth data
|
||||
localStorage.removeItem('github_oauth_state');
|
||||
localStorage.removeItem('github_oauth_code_verifier');
|
||||
navigate('/settings/git');
|
||||
} else {
|
||||
// No code or state parameters - redirect to Git settings
|
||||
navigate('/settings/git');
|
||||
}
|
||||
}, [searchParams, handleCallback, toast, navigate]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-center">
|
||||
<Github className="h-12 w-12 text-primary" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold">Connecting to GitHub</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Processing your GitHub authentication...
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-center">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -236,7 +236,7 @@ export function GitSettings() {
|
||||
<Button
|
||||
onClick={initiateOAuth}
|
||||
disabled={isOAuthLoading}
|
||||
className="w-full gap-2"
|
||||
className="w-full max-w-full gap-2"
|
||||
variant="default"
|
||||
>
|
||||
{isOAuthLoading ? (
|
||||
@@ -247,7 +247,9 @@ export function GitSettings() {
|
||||
) : (
|
||||
<>
|
||||
<Github className="h-4 w-4" />
|
||||
Connect to GitHub
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to GitHub
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
+1
-27
@@ -1,13 +1,11 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useAIProjectId } from '@/hooks/useAIProjectId';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
@@ -24,14 +22,11 @@ export default function Index() {
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { fs } = useFS();
|
||||
const { generateProjectId, isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId();
|
||||
const { settings, addRecentlyUsedModel } = useAISettings();
|
||||
const { handleCallback: handleGitHubCallback } = useGitHubOAuth();
|
||||
const { toast } = useToast();
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
@@ -51,27 +46,6 @@ export default function Index() {
|
||||
description: 'Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment.',
|
||||
});
|
||||
|
||||
// Handle GitHub OAuth callback
|
||||
useEffect(() => {
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
|
||||
if (code && state) {
|
||||
// Handle GitHub OAuth callback
|
||||
handleGitHubCallback(code, state).then((success) => {
|
||||
if (success) {
|
||||
// Clean up URL parameters
|
||||
setSearchParams({});
|
||||
// Show success toast
|
||||
toast({
|
||||
title: "GitHub Connected",
|
||||
description: "Successfully connected to GitHub. You can now push and pull from GitHub repositories.",
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [searchParams, setSearchParams, handleGitHubCallback, toast]);
|
||||
|
||||
// Restore prompt from local storage on mount
|
||||
useEffect(() => {
|
||||
if (storedPrompt) {
|
||||
|
||||
+25
-22
@@ -9,7 +9,7 @@ import { ProjectInfoDialog } from '@/components/ProjectInfoDialog';
|
||||
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ArrowLeft, MessageSquare, Eye, Code, Menu, Columns2 } from 'lucide-react';
|
||||
import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ActionsMenu } from '@/components/ActionsMenu';
|
||||
|
||||
@@ -371,6 +371,7 @@ export function ProjectView() {
|
||||
navigate('/');
|
||||
}
|
||||
}}
|
||||
onToggleSidebar={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
className="h-full"
|
||||
/>
|
||||
</div>
|
||||
@@ -385,32 +386,34 @@ export function ProjectView() {
|
||||
{/* Chat Header */}
|
||||
<div className="h-12 px-4 border-b flex-shrink-0">
|
||||
<div className="flex items-center justify-between h-12">
|
||||
{/* Left side - Sidebar toggle */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Columns2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Center - Project title */}
|
||||
<div className="flex flex-1 min-w-0 px-4 truncate">
|
||||
{project ? (
|
||||
{/* Left side - Sidebar toggle (when collapsed) */}
|
||||
<div className="flex items-center gap-3">
|
||||
{!isSidebarVisible && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="block p-0 h-auto font-semibold text-lg truncate hover:bg-transparent hover:text-primary"
|
||||
onClick={() => setIsProjectInfoOpen(true)}
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(true)}
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label="Open sidebar"
|
||||
>
|
||||
{project.name}
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Skeleton className="h-6 w-40" />
|
||||
)}
|
||||
|
||||
{/* Project title */}
|
||||
<div className="flex flex-1 min-w-0 truncate">
|
||||
{project ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="block p-0 h-auto font-semibold text-lg truncate hover:bg-transparent hover:text-primary"
|
||||
onClick={() => setIsProjectInfoOpen(true)}
|
||||
>
|
||||
{project.name}
|
||||
</Button>
|
||||
) : (
|
||||
<Skeleton className="h-6 w-40" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right side - Star and Actions Menu */}
|
||||
|
||||
Reference in new issue
Block a user