From cd60ab8cbe734173ac16ceaf3593dfd75c0f06c8 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Fri, 19 Sep 2025 00:08:01 +0530 Subject: [PATCH 01/70] use aspect ratio query instead of hard pixel breakpoint for mobile --- src/hooks/useIsMobile.tsx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/hooks/useIsMobile.tsx b/src/hooks/useIsMobile.tsx index 0fae2179..df4e515d 100644 --- a/src/hooks/useIsMobile.tsx +++ b/src/hooks/useIsMobile.tsx @@ -1,17 +1,19 @@ import { useEffect, useState } from "react" -const MOBILE_BREAKPOINT = 768; +const ASPECT_RATIO = '11/9'; +const makeMql = () => window.matchMedia(`(max-aspect-ratio: ${ASPECT_RATIO})`); export function useIsMobile(): boolean { - const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT); + const [isMobile, setIsMobile] = useState(makeMql().matches); useEffect(() => { - const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); + const mql = makeMql(); + const onChange = () => { - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); + setIsMobile(mql.matches); } mql.addEventListener("change", onChange); - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); + setIsMobile(mql.matches); return () => mql.removeEventListener("change", onChange); }, []); From 993b5ece9ce9c9c4c2d0d1d990f724fffe0a89c7 Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Fri, 19 Sep 2025 00:37:11 +0530 Subject: [PATCH 02/70] switch back to width breakpoint for useMobileView @alexgleason pointed out aspect ratio would break screens that were physically wide but not quite the shape 11/9 expects --- src/hooks/useIsMobile.tsx | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/hooks/useIsMobile.tsx b/src/hooks/useIsMobile.tsx index df4e515d..41c1df6c 100644 --- a/src/hooks/useIsMobile.tsx +++ b/src/hooks/useIsMobile.tsx @@ -1,19 +1,17 @@ import { useEffect, useState } from "react" -const ASPECT_RATIO = '11/9'; -const makeMql = () => window.matchMedia(`(max-aspect-ratio: ${ASPECT_RATIO})`); +const MOBILE_BREAKPOINT = 1080; export function useIsMobile(): boolean { - const [isMobile, setIsMobile] = useState(makeMql().matches); + const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT); useEffect(() => { - const mql = makeMql(); - + const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); const onChange = () => { - setIsMobile(mql.matches); + setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); } mql.addEventListener("change", onChange); - setIsMobile(mql.matches); + setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); return () => mql.removeEventListener("change", onChange); }, []); From 1653e5d0182c6c8a0f763ec35ceb1912c0d48d7d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 18 Sep 2025 17:32:42 -0500 Subject: [PATCH 03/70] Add accounts to Nostr Settings --- src/pages/NostrSettings.tsx | 187 +++++++++++++++++++++++++++++++++++- 1 file changed, 182 insertions(+), 5 deletions(-) diff --git a/src/pages/NostrSettings.tsx b/src/pages/NostrSettings.tsx index 88158877..83805e81 100644 --- a/src/pages/NostrSettings.tsx +++ b/src/pages/NostrSettings.tsx @@ -1,13 +1,44 @@ -import { ArrowLeft, Wifi } from 'lucide-react'; +import { ArrowLeft, Wifi, Users, UserPlus, LogOut, Trash2, User } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { Badge } from '@/components/ui/badge'; import { RelaySelector } from '@/components/RelaySelector'; +import LoginDialog from '@/components/auth/LoginDialog'; +import SignupDialog from '@/components/auth/SignupDialog'; import { useIsMobile } from '@/hooks/useIsMobile'; import { useNavigate } from 'react-router-dom'; +import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts'; +import { genUserName } from '@/lib/genUserName'; +import { useState } from 'react'; export function NostrSettings() { const isMobile = useIsMobile(); const navigate = useNavigate(); + const { authors, currentUser, setLogin, removeLogin } = useLoggedInAccounts(); + const [showLoginDialog, setShowLoginDialog] = useState(false); + const [showSignupDialog, setShowSignupDialog] = useState(false); + + const handleSwitchAccount = (accountId: string) => { + setLogin(accountId); + }; + + const handleRemoveAccount = (accountId: string) => { + removeLogin(accountId); + }; + + const handleLoginSuccess = () => { + setShowLoginDialog(false); + }; + + const handleSignupComplete = () => { + setShowSignupDialog(false); + }; + + const getDisplayName = (account: Account) => { + return account.metadata?.name ?? genUserName(account.pubkey); + }; return (
@@ -47,12 +78,158 @@ export function NostrSettings() { )}
+ {/* Account Management */} + + + + + Nostr Accounts + + + + {authors.length === 0 ? ( +
+ +

+ No accounts logged in. Add an account to get started. +

+
+ + +
+
+ ) : ( + <> + {/* Account List */} +
+ {authors.map((account) => ( +
+ + + + {getDisplayName(account).charAt(0).toUpperCase()} + + + +
+
+

+ {getDisplayName(account)} +

+ {currentUser?.id === account.id && ( + + Current + + )} +
+

+ {account.pubkey.slice(0, 16)}... +

+ {account.metadata?.about && ( +

+ {account.metadata.about} +

+ )} +
+ +
+ {currentUser?.id !== account.id && ( + + )} + +
+
+ ))} +
+ + {/* Add Account Actions */} +
+
+ + +
+
+ + )} +
+
+ {/* Relay Configuration */} -
- - -
+ + + + + Relay Configuration + + + +
+ + +
+
+
+ + {/* Login Dialog */} + setShowLoginDialog(false)} + onLogin={handleLoginSuccess} + onSignup={() => { + setShowLoginDialog(false); + setShowSignupDialog(true); + }} + /> + + {/* Signup Dialog */} + setShowSignupDialog(false)} + onComplete={handleSignupComplete} + />
); } From 6c5ee84fe43c131823ad7caaa864a57ef1ed3f7a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 18 Sep 2025 17:34:31 -0500 Subject: [PATCH 04/70] Click account to switch --- src/pages/NostrSettings.tsx | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/src/pages/NostrSettings.tsx b/src/pages/NostrSettings.tsx index 83805e81..dbc8c80a 100644 --- a/src/pages/NostrSettings.tsx +++ b/src/pages/NostrSettings.tsx @@ -111,11 +111,12 @@ export function NostrSettings() { {authors.map((account) => (
currentUser?.id !== account.id && handleSwitchAccount(account.id)} > @@ -145,21 +146,14 @@ export function NostrSettings() { )}
-
- {currentUser?.id !== account.id && ( - - )} +
) : ( <> - {/* Account List */} -
- {authors.map((account) => ( + {/* Account List - Joined Together */} +
+ {authors.map((account, index) => (
-
-

- {getDisplayName(account)} -

- {currentUser?.id === account.id && ( - - Current - - )} -
-

- {account.pubkey.slice(0, 16)}... +

+ {getDisplayName(account)}

- {account.metadata?.about && ( -

- {account.metadata.about} -

- )}
@@ -165,7 +150,7 @@ export function NostrSettings() {
{/* Add Account Actions */} -
+
- + {/* Add Account Button - Integrated into the list */} +
setShowLoginDialog(true)} + > +
+ +
+
+

+ Add Account +

+
From 9c358bb230cd7133b928d4e155238e757675cd3d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 18 Sep 2025 21:39:49 -0500 Subject: [PATCH 07/70] Simplify sidebar navigation --- src/components/ProjectSidebar.test.tsx | 34 ++++++++++++++++++++------ src/components/ProjectSidebar.tsx | 28 +++++++++++++++++---- 2 files changed, 49 insertions(+), 13 deletions(-) diff --git a/src/components/ProjectSidebar.test.tsx b/src/components/ProjectSidebar.test.tsx index be2ff20f..f3aaf27c 100644 --- a/src/components/ProjectSidebar.test.tsx +++ b/src/components/ProjectSidebar.test.tsx @@ -19,12 +19,12 @@ vi.mock('@tanstack/react-query', () => ({ }) })); -// Mock the LoginArea component -vi.mock('@/components/auth/LoginArea', () => ({ - LoginArea: ({ className }: { className?: string }) => ( -
Login Area
- ) -})); +// Mock window.open for help button test +const mockWindowOpen = vi.fn(); +Object.defineProperty(window, 'open', { + value: mockWindowOpen, + writable: true +}); const mockUseProjects = vi.mocked(useProjects); const mockUseLocalStorage = vi.mocked(useLocalStorage); @@ -81,7 +81,7 @@ describe('ProjectSidebar', () => { expect(screen.queryByLabelText('Collapse sidebar')).not.toBeInTheDocument(); }); - it('renders login area at the bottom', () => { + it('renders settings and help buttons at the bottom', () => { render( { /> ); - expect(screen.getByTestId('login-area')).toBeInTheDocument(); + expect(screen.getByText('Settings')).toBeInTheDocument(); + expect(screen.getByLabelText('Help')).toBeInTheDocument(); }); it('shows new project button', () => { @@ -102,4 +103,21 @@ describe('ProjectSidebar', () => { expect(screen.getByText('New Project')).toBeInTheDocument(); }); + + it('opens help documentation when help button is clicked', () => { + render( + + ); + + const helpButton = screen.getByLabelText('Help'); + fireEvent.click(helpButton); + + expect(mockWindowOpen).toHaveBeenCalledWith( + 'https://soapbox.pub/shakespeare-resources/', + '_blank' + ); + }); }); \ No newline at end of file diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 2c3a1635..2136eb08 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,10 +1,9 @@ import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } 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'; -import { LoginArea } from '@/components/auth/LoginArea'; import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; @@ -224,9 +223,28 @@ export function ProjectSidebar({
- {/* Account Selector at Bottom */} -
- + {/* Settings and Help at Bottom */} +
+
+ + +
); From 395111ac07a54b48f8dd892b2d1781adedfe4b05 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Thu, 18 Sep 2025 20:59:38 -0700 Subject: [PATCH 08/70] added dark mode --- src/components/ProjectSidebar.tsx | 2 ++ src/components/SettingsLayout.tsx | 10 +++++----- src/components/ThemeToggle.tsx | 20 ++++++++++++++++++++ src/pages/NotFound.tsx | 8 ++++---- 4 files changed, 31 insertions(+), 9 deletions(-) create mode 100644 src/components/ThemeToggle.tsx diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 2136eb08..5dc3db04 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -11,6 +11,7 @@ import { useIsMobile } from '@/hooks/useIsMobile'; import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; +import { ThemeToggle } from '@/components/ThemeToggle'; interface ProjectItemProps { project: Project; @@ -235,6 +236,7 @@ export function ProjectSidebar({ Settings + + ); +} diff --git a/src/pages/NotFound.tsx b/src/pages/NotFound.tsx index 85e429d4..987de499 100644 --- a/src/pages/NotFound.tsx +++ b/src/pages/NotFound.tsx @@ -18,11 +18,11 @@ const NotFound = () => { }, [location.pathname]); return ( -
+
From af86b50141324a3962325510dbac8d3d061c3bc2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 19 Sep 2025 11:38:18 -0500 Subject: [PATCH 09/70] Fix sidebar tests --- src/components/ProjectSidebar.test.tsx | 88 ++++++++++++++++---------- 1 file changed, 55 insertions(+), 33 deletions(-) diff --git a/src/components/ProjectSidebar.test.tsx b/src/components/ProjectSidebar.test.tsx index f3aaf27c..a94ca9e6 100644 --- a/src/components/ProjectSidebar.test.tsx +++ b/src/components/ProjectSidebar.test.tsx @@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { ProjectSidebar } from './ProjectSidebar'; import { useProjects } from '@/hooks/useProjects'; import { useLocalStorage } from '@/hooks/useLocalStorage'; +import { TestApp } from '@/test/TestApp'; // Mock the hooks vi.mock('@/hooks/useProjects'); @@ -10,14 +11,23 @@ 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() - }) -})); +vi.mock('react-router-dom', async (importOriginal) => { + const actual = await importOriginal() as Record; + return { + ...actual, + useNavigate: () => vi.fn() + }; +}); +vi.mock('@tanstack/react-query', async (importOriginal) => { + const actual = await importOriginal() as Record; + return { + ...actual, + useQueryClient: () => ({ + invalidateQueries: vi.fn(), + resetQueries: vi.fn() + }) + }; +}); // Mock window.open for help button test const mockWindowOpen = vi.fn(); @@ -42,10 +52,12 @@ describe('ProjectSidebar', () => { it('renders sidebar header with logo', () => { render( - + + + ); expect(screen.getByText('🎭')).toBeInTheDocument(); @@ -56,11 +68,13 @@ describe('ProjectSidebar', () => { const mockToggle = vi.fn(); render( - + + + ); const collapseButton = screen.getByLabelText('Collapse sidebar'); @@ -72,10 +86,12 @@ describe('ProjectSidebar', () => { it('does not show collapse button when onToggleSidebar is not provided', () => { render( - + + + ); expect(screen.queryByLabelText('Collapse sidebar')).not.toBeInTheDocument(); @@ -83,10 +99,12 @@ describe('ProjectSidebar', () => { it('renders settings and help buttons at the bottom', () => { render( - + + + ); expect(screen.getByText('Settings')).toBeInTheDocument(); @@ -95,10 +113,12 @@ describe('ProjectSidebar', () => { it('shows new project button', () => { render( - + + + ); expect(screen.getByText('New Project')).toBeInTheDocument(); @@ -106,10 +126,12 @@ describe('ProjectSidebar', () => { it('opens help documentation when help button is clicked', () => { render( - + + + ); const helpButton = screen.getByLabelText('Help'); From 579dd93d6d7095ccca06d9530f00a87f79fb7d9b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 19 Sep 2025 11:44:07 -0500 Subject: [PATCH 10/70] Sidebar dark theme improvements --- src/components/ProjectSidebar.tsx | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 5dc3db04..4d23dfed 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,6 +1,6 @@ import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Sun, Moon } 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'; @@ -8,10 +8,10 @@ import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; +import { useTheme } from '@/hooks/useTheme'; import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; -import { ThemeToggle } from '@/components/ThemeToggle'; interface ProjectItemProps { project: Project; @@ -92,6 +92,7 @@ export function ProjectSidebar({ const { data: projects = [], isLoading, error } = useProjects(); const [favorites] = useLocalStorage('project-favorites', []); const isMobile = useIsMobile(); + const { theme, setTheme } = useTheme(); const navigate = useNavigate(); @@ -230,21 +231,30 @@ export function ProjectSidebar({ - +
From 20778f5045f534b9e4a2c369a34d2871c258c2cc Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 19 Sep 2025 12:03:38 -0500 Subject: [PATCH 11/70] Add dark support to code blocks in AI messages --- src/components/AIMessageItem.tsx | 3 +++ src/hooks/useSystemTheme.ts | 24 ++++++++++++++++++++++++ src/hooks/useTheme.ts | 13 ++++++++++++- src/index.css | 4 ++++ 4 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/hooks/useSystemTheme.ts diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index 9c693988..0f8a9354 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -5,6 +5,7 @@ import type { AIMessage } from '@/lib/SessionManager'; import { cn } from '@/lib/utils'; import { UserMessage } from '@/components/UserMessage'; import OpenAI from 'openai'; +import { useTheme } from '@/hooks/useTheme'; interface AIMessageItemProps { message: AIMessage; @@ -18,6 +19,7 @@ export const AIMessageItem = memo(({ toolCall }: AIMessageItemProps) => { const [isToolExpanded, setIsToolExpanded] = useState(false); + const { displayTheme } = useTheme(); // Get content to display const getContent = () => { @@ -232,6 +234,7 @@ export const AIMessageItem = memo(({ {getContent()} diff --git a/src/hooks/useSystemTheme.ts b/src/hooks/useSystemTheme.ts new file mode 100644 index 00000000..d561c776 --- /dev/null +++ b/src/hooks/useSystemTheme.ts @@ -0,0 +1,24 @@ +import { useEffect, useState } from "react"; + +export function useSystemTheme() { + const getSystemTheme = (): "dark" | "light" => + window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; + + const [theme, setTheme] = useState<"dark" | "light">(getSystemTheme); + + useEffect(() => { + const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); + + const handler = (event: MediaQueryListEvent): void => { + setTheme(event.matches ? "dark" : "light"); + }; + + // Attach listener + mediaQuery.addEventListener("change", handler); + + // Cleanup + return () => mediaQuery.removeEventListener("change", handler); + }, []); + + return theme; +} diff --git a/src/hooks/useTheme.ts b/src/hooks/useTheme.ts index 24f7a5d6..8ad41716 100644 --- a/src/hooks/useTheme.ts +++ b/src/hooks/useTheme.ts @@ -1,15 +1,26 @@ import { type Theme } from "@/contexts/AppContext"; import { useAppContext } from "@/hooks/useAppContext"; +import { useSystemTheme } from "./useSystemTheme"; /** * Hook to get and set the active theme * @returns Theme context with theme and setTheme */ -export function useTheme(): { theme: Theme; setTheme: (theme: Theme) => void } { +export function useTheme(): { + theme: Theme; + systemTheme: "light" | "dark"; + displayTheme: "light" | "dark"; + setTheme: (theme: Theme) => void; +} { const { config, updateConfig } = useAppContext(); + const systemTheme = useSystemTheme(); + const displayTheme = config.theme === 'system' ? systemTheme : config.theme; + return { theme: config.theme, + systemTheme, + displayTheme, setTheme: (theme: Theme) => { updateConfig((currentConfig) => ({ ...currentConfig, diff --git a/src/index.css b/src/index.css index 0feb937c..8a6259b7 100644 --- a/src/index.css +++ b/src/index.css @@ -247,6 +247,10 @@ max-height: 100dvh; } + pre.shiki { + background-color: transparent !important; + } + /* Fallback for browsers that don't support dvh */ @supports not (height: 100dvh) { .h-dvh { From 656cce0159be703cd830a6c7b67ab92a5873f6ca Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 19 Sep 2025 12:10:57 -0500 Subject: [PATCH 12/70] Add Preferences page to settings --- src/AppRouter.tsx | 2 + src/components/SettingsLayout.tsx | 9 +++- src/components/ThemePicker.tsx | 55 +++++++++++++++++++++++ src/pages/Preferences.tsx | 73 +++++++++++++++++++++++++++++++ src/pages/Settings.tsx | 9 +++- 5 files changed, 146 insertions(+), 2 deletions(-) create mode 100644 src/components/ThemePicker.tsx create mode 100644 src/pages/Preferences.tsx diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index 848d8385..c78e2a63 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -5,6 +5,7 @@ import { SessionMonitor } from "./components/SessionMonitor"; import Index from "./pages/Index"; import Clone from "./pages/Clone"; import Settings from "./pages/Settings"; +import Preferences from "./pages/Preferences"; import NostrSettings from "./pages/NostrSettings"; import AISettings from "./pages/AISettings"; import GitSettings from "./pages/GitSettings"; @@ -26,6 +27,7 @@ export function AppRouter() { } /> }> } /> + } /> } /> } /> } /> diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index ecac4948..48d6de46 100644 --- a/src/components/SettingsLayout.tsx +++ b/src/components/SettingsLayout.tsx @@ -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, Bot, GitBranch, Database, Wifi } from 'lucide-react'; +import { Menu, Bot, GitBranch, Database, Wifi, Settings2 } from 'lucide-react'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -19,6 +19,13 @@ interface SettingsItem { } const settingsItems: SettingsItem[] = [ + { + id: 'preferences', + title: 'Preferences', + description: 'General application preferences and appearance', + icon: Settings2, + href: '/settings/preferences', + }, { id: 'ai', title: 'AI Settings', diff --git a/src/components/ThemePicker.tsx b/src/components/ThemePicker.tsx new file mode 100644 index 00000000..3cc806b6 --- /dev/null +++ b/src/components/ThemePicker.tsx @@ -0,0 +1,55 @@ +import { ChevronsUpDown, Monitor, Moon, Sun } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { useTheme } from "@/hooks/useTheme"; +import { type Theme } from "@/contexts/AppContext"; + +export function ThemePicker() { + const { theme, setTheme } = useTheme(); + + const themeOptions: { value: Theme; label: string; icon: React.ComponentType<{ className?: string }> }[] = [ + { value: "system", label: "System", icon: Monitor }, + { value: "light", label: "Light", icon: Sun }, + { value: "dark", label: "Dark", icon: Moon }, + ]; + + const currentTheme = themeOptions.find(option => option.value === theme); + const CurrentIcon = currentTheme?.icon || Monitor; + + return ( + + + + + + {themeOptions.map((option) => { + const Icon = option.icon; + return ( + setTheme(option.value)} + className="flex items-center gap-2" + > + + {option.label} + {theme === option.value && ( +
+ )} + + ); + })} + + + ); +} \ No newline at end of file diff --git a/src/pages/Preferences.tsx b/src/pages/Preferences.tsx new file mode 100644 index 00000000..a99d4e45 --- /dev/null +++ b/src/pages/Preferences.tsx @@ -0,0 +1,73 @@ +import { Settings2, ArrowLeft } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { ThemePicker } from "@/components/ThemePicker"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Label } from "@/components/ui/label"; +import { useIsMobile } from "@/hooks/useIsMobile"; +import { useNavigate } from "react-router-dom"; + +export function Preferences() { + const isMobile = useIsMobile(); + const navigate = useNavigate(); + + return ( +
+ {isMobile && ( +
+ +
+

+ + Preferences +

+

+ Manage your general application preferences and appearance settings. +

+
+
+ )} + + {!isMobile && ( +
+

+ + Preferences +

+

+ Manage your general application preferences and appearance settings. +

+
+ )} + + + + Appearance + + Customize how the application looks and feels. + + + +
+ +
+ +
+

+ Choose between light, dark, or system theme preference. +

+
+
+
+
+ ); +} + +export default Preferences; \ No newline at end of file diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index cff1c07e..5e9f3431 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -1,5 +1,5 @@ import { useNavigate } from 'react-router-dom'; -import { Bot, GitBranch, Database, Wifi } from 'lucide-react'; +import { Bot, GitBranch, Database, Wifi, Settings2 } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; interface SettingsItem { @@ -11,6 +11,13 @@ interface SettingsItem { } const settingsItems: SettingsItem[] = [ + { + id: 'preferences', + title: 'Preferences', + description: 'General application preferences and appearance', + icon: Settings2, + href: '/settings/preferences', + }, { id: 'ai', title: 'AI Settings', From 743711805114ec23011c0a888bbb9f236552d847 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 19 Sep 2025 12:16:11 -0500 Subject: [PATCH 13/70] Remove ThemeToggle --- src/components/ProjectSidebar.tsx | 16 ++-------------- src/components/ThemeToggle.tsx | 20 -------------------- 2 files changed, 2 insertions(+), 34 deletions(-) delete mode 100644 src/components/ThemeToggle.tsx diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 4d23dfed..48653446 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,6 +1,6 @@ import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Sun, Moon } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } 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'; @@ -8,7 +8,6 @@ import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; -import { useTheme } from '@/hooks/useTheme'; import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; @@ -91,9 +90,8 @@ export function ProjectSidebar({ const queryClient = useQueryClient(); const { data: projects = [], isLoading, error } = useProjects(); const [favorites] = useLocalStorage('project-favorites', []); - const isMobile = useIsMobile(); - const { theme, setTheme } = useTheme(); + const isMobile = useIsMobile(); const navigate = useNavigate(); // Custom navigate function that closes sidebar on mobile @@ -237,16 +235,6 @@ export function ProjectSidebar({ Settings - - ); -} From 1cccd8c254bc71a12a03c55dcd5e364616568950 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 19 Sep 2025 12:22:10 -0500 Subject: [PATCH 14/70] Add loading skeleton to NostrSettings page --- src/components/auth/AccountSwitcher.test.tsx | 6 +++-- src/components/auth/LoginArea.test.tsx | 12 ++++++---- src/hooks/useLoggedInAccounts.ts | 3 ++- src/pages/NostrSettings.tsx | 25 ++++++++++++++++++-- 4 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/components/auth/AccountSwitcher.test.tsx b/src/components/auth/AccountSwitcher.test.tsx index e503b526..5899e82b 100644 --- a/src/components/auth/AccountSwitcher.test.tsx +++ b/src/components/auth/AccountSwitcher.test.tsx @@ -33,7 +33,8 @@ describe('AccountSwitcher', () => { }, otherUsers: [], setLogin: vi.fn(), - removeLogin: vi.fn() + removeLogin: vi.fn(), + isLoading: false }); render(); @@ -53,7 +54,8 @@ describe('AccountSwitcher', () => { currentUser: undefined, otherUsers: [], setLogin: vi.fn(), - removeLogin: vi.fn() + removeLogin: vi.fn(), + isLoading: false }); const { container } = render(); diff --git a/src/components/auth/LoginArea.test.tsx b/src/components/auth/LoginArea.test.tsx index a17600b8..492995b1 100644 --- a/src/components/auth/LoginArea.test.tsx +++ b/src/components/auth/LoginArea.test.tsx @@ -62,7 +62,8 @@ describe('LoginArea', () => { }, otherUsers: [], setLogin: vi.fn(), - removeLogin: vi.fn() + removeLogin: vi.fn(), + isLoading: false }); render(); @@ -76,7 +77,8 @@ describe('LoginArea', () => { currentUser: undefined, otherUsers: [], setLogin: vi.fn(), - removeLogin: vi.fn() + removeLogin: vi.fn(), + isLoading: false }); render(); @@ -97,7 +99,8 @@ describe('LoginArea', () => { currentUser: undefined, otherUsers: [], setLogin: vi.fn(), - removeLogin: vi.fn() + removeLogin: vi.fn(), + isLoading: false }); const { rerender } = render(); @@ -119,7 +122,8 @@ describe('LoginArea', () => { }, otherUsers: [], setLogin: vi.fn(), - removeLogin: vi.fn() + removeLogin: vi.fn(), + isLoading: false }); rerender(); diff --git a/src/hooks/useLoggedInAccounts.ts b/src/hooks/useLoggedInAccounts.ts index bffdbab2..22f79db4 100644 --- a/src/hooks/useLoggedInAccounts.ts +++ b/src/hooks/useLoggedInAccounts.ts @@ -14,7 +14,7 @@ export function useLoggedInAccounts() { const { nostr } = useNostr(); const { logins, setLogin, removeLogin } = useNostrLogin(); - const { data: authors = [] } = useQuery({ + const { data: authors = [], isLoading } = useQuery({ queryKey: ['logins', logins.map((l) => l.id).join(';')], queryFn: async ({ signal }) => { const events = await nostr.query( @@ -52,5 +52,6 @@ export function useLoggedInAccounts() { otherUsers, setLogin, removeLogin, + isLoading, }; } \ No newline at end of file diff --git a/src/pages/NostrSettings.tsx b/src/pages/NostrSettings.tsx index 59c495c1..5587769a 100644 --- a/src/pages/NostrSettings.tsx +++ b/src/pages/NostrSettings.tsx @@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { Skeleton } from '@/components/ui/skeleton'; import { RelaySelector } from '@/components/RelaySelector'; import LoginDialog from '@/components/auth/LoginDialog'; import SignupDialog from '@/components/auth/SignupDialog'; @@ -15,7 +16,7 @@ import { useState } from 'react'; export function NostrSettings() { const isMobile = useIsMobile(); const navigate = useNavigate(); - const { authors, currentUser, setLogin, removeLogin } = useLoggedInAccounts(); + const { authors, currentUser, setLogin, removeLogin, isLoading } = useLoggedInAccounts(); const [showLoginDialog, setShowLoginDialog] = useState(false); const [showSignupDialog, setShowSignupDialog] = useState(false); @@ -86,7 +87,27 @@ export function NostrSettings() { - {authors.length === 0 ? ( + {isLoading ? ( +
+ {/* Loading skeleton for accounts */} + {[...Array(2)].map((_, i) => ( +
+ +
+ +
+ +
+ ))} + {/* Add account button skeleton */} +
+ +
+ +
+
+
+ ) : authors.length === 0 ? (

From dd970c2ca7b64f366b3849c6636036c2632d4571 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 19 Sep 2025 12:26:48 -0500 Subject: [PATCH 15/70] Darken settings hover state on light theme --- src/components/ProjectSidebar.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 48653446..b36a201f 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -229,7 +229,7 @@ export function ProjectSidebar({ diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index 60a71e4e..004dcf82 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -1,6 +1,7 @@ import { createContext } from "react"; export type Theme = "dark" | "light" | "system"; +export type Language = "en" | "pt"; export interface AppConfig { /** Current theme */ @@ -9,6 +10,8 @@ export interface AppConfig { relayUrl: string; /** Deploy server domain (e.g., "shakespeare.wtf") */ deployServer: string; + /** Selected language */ + language: Language; } export interface AppContextType { diff --git a/src/hooks/useTranslation.ts b/src/hooks/useTranslation.ts new file mode 100644 index 00000000..f466023f --- /dev/null +++ b/src/hooks/useTranslation.ts @@ -0,0 +1,2 @@ +// Re-export useTranslation from react-i18next for consistency +export { useTranslation } from 'react-i18next'; \ No newline at end of file diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts new file mode 100644 index 00000000..dc2aca57 --- /dev/null +++ b/src/lib/i18n.ts @@ -0,0 +1,159 @@ +import i18n from 'i18next'; +import { initReactI18next } from 'react-i18next'; + +// Translation resources +const resources = { + en: { + translation: { + // Navigation and Layout + preferences: 'Preferences', + settings: 'Settings', + backToSettings: 'Back to Settings', + + // Preferences Page + preferencesTitle: 'Preferences', + preferencesDescription: 'Manage your general application preferences and appearance settings.', + + // Appearance Section + appearance: 'Appearance', + appearanceDescription: 'Customize how the application looks and feels.', + theme: 'Theme', + themeDescription: 'Choose between light, dark, or system theme preference.', + + // Language Section + language: 'Language', + languageDescription: 'Select your preferred language for the interface.', + + // Language Options + english: 'English', + portuguese: 'Portuguese', + + // Theme Options + light: 'Light', + dark: 'Dark', + system: 'System', + + // Common UI Elements + save: 'Save', + cancel: 'Cancel', + close: 'Close', + open: 'Open', + edit: 'Edit', + delete: 'Delete', + create: 'Create', + update: 'Update', + loading: 'Loading...', + error: 'Error', + success: 'Success', + warning: 'Warning', + info: 'Information', + + // Shakespeare Main Page + buildNostrApps: 'Build Nostr apps with AI', + whatToBuild: 'What would you like to build?', + createProject: 'Create Project', + generating: 'Generating...', + creating: 'Creating...', + chooseModel: 'Choose a model...', + selectModelFirst: "Please select a model below, then describe what you'd like to build...", + examplePrompt: "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...", + + // Settings Page + settingsTitle: 'Settings', + settingsDescription: 'Manage your application settings and preferences.', + aiSettings: 'AI Settings', + aiSettingsDescription: 'Configure AI providers and API keys', + gitSettings: 'Git Settings', + gitSettingsDescription: 'Configure Git credentials for HTTP authentication', + nostrSettings: 'Nostr Settings', + nostrSettingsDescription: 'Configure relay connections and Nostr preferences', + dataSettings: 'Data', + dataSettingsDescription: 'Export files and manage local data', + } + }, + pt: { + translation: { + // Navigation and Layout + preferences: 'Preferências', + settings: 'Configurações', + backToSettings: 'Voltar às Configurações', + + // Preferences Page + preferencesTitle: 'Preferências', + preferencesDescription: 'Gerencie suas preferências gerais da aplicação e configurações de aparência.', + + // Appearance Section + appearance: 'Aparência', + appearanceDescription: 'Personalize como a aplicação se parece e funciona.', + theme: 'Tema', + themeDescription: 'Escolha entre preferência de tema claro, escuro ou do sistema.', + + // Language Section + language: 'Idioma', + languageDescription: 'Selecione seu idioma preferido para a interface.', + + // Language Options + english: 'Inglês', + portuguese: 'Português', + + // Theme Options + light: 'Claro', + dark: 'Escuro', + system: 'Sistema', + + // Common UI Elements + save: 'Salvar', + cancel: 'Cancelar', + close: 'Fechar', + open: 'Abrir', + edit: 'Editar', + delete: 'Excluir', + create: 'Criar', + update: 'Atualizar', + loading: 'Carregando...', + error: 'Erro', + success: 'Sucesso', + warning: 'Aviso', + info: 'Informação', + + // Shakespeare Main Page + buildNostrApps: 'Construa aplicativos Nostr com IA', + whatToBuild: 'O que você gostaria de construir?', + createProject: 'Criar Projeto', + generating: 'Gerando...', + creating: 'Criando...', + chooseModel: 'Escolha um modelo...', + selectModelFirst: "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...", + examplePrompt: "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...", + + // Settings Page + settingsTitle: 'Configurações', + settingsDescription: 'Gerencie as configurações e preferências da aplicação.', + aiSettings: 'Configurações de IA', + aiSettingsDescription: 'Configure provedores de IA e chaves de API', + gitSettings: 'Configurações do Git', + gitSettingsDescription: 'Configure credenciais do Git para autenticação HTTP', + nostrSettings: 'Configurações do Nostr', + nostrSettingsDescription: 'Configure conexões de relay e preferências do Nostr', + dataSettings: 'Dados', + dataSettingsDescription: 'Exporte arquivos e gerencie dados locais', + } + } +}; + +// Initialize i18next +i18n + .use(initReactI18next) + .init({ + resources, + lng: 'en', // Default language + fallbackLng: 'en', + interpolation: { + escapeValue: false, // React already escapes values + }, + react: { + useSuspense: false, // Disable suspense for better compatibility + } + }); + +export default i18n; \ No newline at end of file diff --git a/src/main.tsx b/src/main.tsx index 5dfd85d9..65eae552 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -3,6 +3,9 @@ import { createRoot } from 'react-dom/client'; // Import polyfills first import './lib/polyfills.ts'; +// Import i18n configuration +import './lib/i18n'; + import App from './App.tsx'; import './index.css'; diff --git a/src/pages/Preferences.test.tsx b/src/pages/Preferences.test.tsx new file mode 100644 index 00000000..a169202d --- /dev/null +++ b/src/pages/Preferences.test.tsx @@ -0,0 +1,40 @@ +import { describe, it, expect } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { TestApp } from '@/test/TestApp'; +import { Preferences } from './Preferences'; + +describe('Preferences', () => { + it('renders preferences page with language and theme sections', () => { + render( + + + + ); + + // Should show the preferences title + expect(screen.getByText('Preferences')).toBeInTheDocument(); + + // Should show appearance section + expect(screen.getByText('Appearance')).toBeInTheDocument(); + + // Should show theme and language labels + expect(screen.getByText('Theme')).toBeInTheDocument(); + expect(screen.getByText('Language')).toBeInTheDocument(); + + // Should show language picker + expect(screen.getByRole('combobox')).toBeInTheDocument(); + }); + + it('displays translated content correctly', () => { + render( + + + + ); + + // Check for key translated strings + expect(screen.getByText('Manage your general application preferences and appearance settings.')).toBeInTheDocument(); + expect(screen.getByText('Customize how the application looks and feels.')).toBeInTheDocument(); + expect(screen.getByText('Select your preferred language for the interface.')).toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/pages/Preferences.tsx b/src/pages/Preferences.tsx index a99d4e45..9f7dc90d 100644 --- a/src/pages/Preferences.tsx +++ b/src/pages/Preferences.tsx @@ -1,12 +1,15 @@ import { Settings2, ArrowLeft } from "lucide-react"; +import { useTranslation } from 'react-i18next'; import { Button } from "@/components/ui/button"; import { ThemePicker } from "@/components/ThemePicker"; +import { LanguagePicker } from "@/components/LanguagePicker"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Label } from "@/components/ui/label"; import { useIsMobile } from "@/hooks/useIsMobile"; import { useNavigate } from "react-router-dom"; export function Preferences() { + const { t } = useTranslation(); const isMobile = useIsMobile(); const navigate = useNavigate(); @@ -21,15 +24,15 @@ export function Preferences() { className="h-8 w-auto px-2 -ml-2" > - Back to Settings + {t('backToSettings')}

- Preferences + {t('preferencesTitle')}

- Manage your general application preferences and appearance settings. + {t('preferencesDescription')}

@@ -39,29 +42,39 @@ export function Preferences() {

- Preferences + {t('preferencesTitle')}

- Manage your general application preferences and appearance settings. + {t('preferencesDescription')}

)} - Appearance + {t('appearance')} - Customize how the application looks and feels. + {t('appearanceDescription')} - +
- +

- Choose between light, dark, or system theme preference. + {t('themeDescription')} +

+
+ +
+ +
+ +
+

+ {t('languageDescription')}

diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index 5e9f3431..1239ce7b 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -1,4 +1,5 @@ import { useNavigate } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; import { Bot, GitBranch, Database, Wifi, Settings2 } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -10,55 +11,59 @@ interface SettingsItem { href: string; } -const settingsItems: SettingsItem[] = [ +// Define settings items as a function to get fresh translations +const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [ { id: 'preferences', - title: 'Preferences', - description: 'General application preferences and appearance', + title: t('preferences'), + description: t('preferencesDescription'), icon: Settings2, href: '/settings/preferences', }, { id: 'ai', - title: 'AI Settings', - description: 'Configure AI providers and API keys', + title: t('aiSettings'), + description: t('aiSettingsDescription'), icon: Bot, href: '/settings/ai', }, { id: 'git', - title: 'Git Settings', - description: 'Configure Git credentials for HTTP authentication', + title: t('gitSettings'), + description: t('gitSettingsDescription'), icon: GitBranch, href: '/settings/git', }, { id: 'nostr', - title: 'Nostr Settings', - description: 'Configure relay connections and Nostr preferences', + title: t('nostrSettings'), + description: t('nostrSettingsDescription'), icon: Wifi, href: '/settings/nostr', }, { id: 'data', - title: 'Data', - description: 'Export files and manage local data', + title: t('dataSettings'), + description: t('dataSettingsDescription'), icon: Database, href: '/settings/data', }, ]; export function Settings() { + const { t } = useTranslation(); const navigate = useNavigate(); const isMobile = useIsMobile(); + const settingsItems = getSettingsItems(t); + if (isMobile) { return (
-

Settings

+

{t('settingsTitle')}

- Manage your application settings and preferences. + {t('settingsDescription')}

diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index 1dd162a3..1bdc7924 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -11,6 +11,7 @@ import { LightningFSAdapter } from '@/lib/LightningFSAdapter'; import { AISettingsProvider } from '@/components/AISettingsProvider'; import { GitSettingsProvider } from '@/components/GitSettingsProvider'; import { SessionManagerProvider } from '@/components/SessionManagerProvider'; +import '@/lib/i18n'; interface TestAppProps { children: React.ReactNode; @@ -30,6 +31,7 @@ export function TestApp({ children }: TestAppProps) { theme: 'light', relayUrl: 'wss://relay.nostr.band', deployServer: 'shakespeare.wtf', + language: 'en', }; // Initialize LightningFS for testing From 03b712a91771c07fb53acfd471f8b24a614b2a42 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 19 Sep 2025 14:04:07 -0500 Subject: [PATCH 17/70] Translate all the strings --- src/components/ModelSelector.tsx | 26 +- src/components/ProjectSidebar.tsx | 16 +- src/components/SettingsLayout.tsx | 34 +- src/components/Shakespeare/ChatPane.tsx | 34 +- src/components/Shakespeare/FileEditor.tsx | 10 +- src/components/Shakespeare/FileTree.tsx | 8 +- src/components/auth/LoginArea.test.tsx | 18 -- src/components/auth/LoginArea.tsx | 12 +- src/lib/i18n.ts | 374 +++++++++++++++++++++- src/pages/AISettings.tsx | 52 +-- src/pages/DataSettings.tsx | 68 ++-- src/pages/GitSettings.tsx | 54 ++-- src/pages/Index.tsx | 16 +- src/pages/NostrSettings.tsx | 26 +- src/pages/NotFound.tsx | 6 +- src/pages/Preferences.tsx | 4 +- src/pages/Settings.tsx | 2 +- 17 files changed, 569 insertions(+), 191 deletions(-) diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index ea43dc36..5cafa3ec 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -1,5 +1,6 @@ import { useState, useMemo } from 'react'; import { useNavigate } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -23,8 +24,9 @@ export function ModelSelector({ onChange, className, disabled = false, - placeholder = "Select or enter a model...", + placeholder, }: ModelSelectorProps) { + const { t } = useTranslation(); const [open, setOpen] = useState(false); const [isCustomInput, setIsCustomInput] = useState(false); const [customValue, setCustomValue] = useState(''); @@ -32,6 +34,8 @@ export function ModelSelector({ const { models, isLoading, error, refetch } = useProviderModels(); const navigate = useNavigate(); + const defaultPlaceholder = t('selectOrEnterModel'); + const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]); // Group models by provider @@ -125,14 +129,14 @@ export function ModelSelector({ disabled={disabled} > - {value || placeholder} + {value || placeholder || defaultPlaceholder} - {isConfigured && } + {isConfigured && } {/* Custom model option and manage providers */} @@ -143,7 +147,7 @@ export function ModelSelector({ className="cursor-pointer" > - Enter custom model... + {t('enterCustomModel')} )} - Manage providers... + {t('manageProviders')} @@ -160,13 +164,13 @@ export function ModelSelector({
-

No models found.

-

Try using a custom model instead.

+

{t('noModelsFound')}

+

{t('tryCustomModel')}

{recentlyUsedModels.length > 0 && ( - + {recentlyUsedModels.map((model) => ( +
@@ -203,7 +207,7 @@ export function ModelSelector({ {/* Error state */} {error && !isLoading && ( - +
@@ -216,7 +220,7 @@ export function ModelSelector({ className="h-7 text-xs" > - Retry + {t('retry')}
diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index b36a201f..a99d2c7d 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,5 +1,6 @@ import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; @@ -87,6 +88,7 @@ export function ProjectSidebar({ onToggleSidebar, onClose }: ProjectSidebarProps) { + const { t } = useTranslation(); const queryClient = useQueryClient(); const { data: projects = [], isLoading, error } = useProjects(); const [favorites] = useLocalStorage('project-favorites', []); @@ -144,7 +146,7 @@ export function ProjectSidebar({ size="sm" className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2" onClick={handleToggleSidebar} - aria-label={(onClose && isMobile) ? "Close sidebar" : "Collapse sidebar"} + aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')} > {(onClose && isMobile) ? ( @@ -167,7 +169,7 @@ export function ProjectSidebar({ className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors" > - New Project + {t('newProject')}
@@ -182,7 +184,7 @@ export function ProjectSidebar({ className="flex items-center gap-2 w-full" > - Import Repository + {t('importRepository')} @@ -204,8 +206,8 @@ export function ProjectSidebar({ ) : projects.length === 0 ? (
-

No projects yet

-

Create your first project to get started

+

{t('noProjectsYet')}

+

{t('createFirstProject')}

) : (
@@ -233,14 +235,14 @@ export function ProjectSidebar({ onClick={() => navigateAndClose('/settings')} > - Settings + {t('settings')} diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index 48d6de46..285bf973 100644 --- a/src/components/SettingsLayout.tsx +++ b/src/components/SettingsLayout.tsx @@ -1,5 +1,6 @@ import { useState, useEffect } from 'react'; import { useNavigate, useLocation, Outlet } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Menu, Bot, GitBranch, Database, Wifi, Settings2 } from 'lucide-react'; @@ -18,45 +19,47 @@ interface SettingsItem { href: string; } -const settingsItems: SettingsItem[] = [ +// Define settings items as a function to get fresh translations +const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [ { id: 'preferences', - title: 'Preferences', - description: 'General application preferences and appearance', + title: t('preferences'), + description: t('preferencesDescription'), icon: Settings2, href: '/settings/preferences', }, { id: 'ai', - title: 'AI Settings', - description: 'Configure AI providers and API keys', + title: t('aiSettings'), + description: t('aiSettingsDescription'), icon: Bot, href: '/settings/ai', }, { id: 'git', - title: 'Git Settings', - description: 'Configure Git credentials for HTTP authentication', + title: t('gitSettings'), + description: t('gitSettingsDescription'), icon: GitBranch, href: '/settings/git', }, { id: 'nostr', - title: 'Nostr Settings', - description: 'Configure relay connections and Nostr preferences', + title: t('nostrSettings'), + description: t('nostrSettingsDescription'), icon: Wifi, href: '/settings/nostr', }, { id: 'data', - title: 'Data', - description: 'Export files and manage local data', + title: t('dataSettings'), + description: t('dataSettingsDescription'), icon: Database, href: '/settings/data', }, ]; export function SettingsLayout() { + const { t } = useTranslation(); const navigate = useNavigate(); const location = useLocation(); const isMobile = useIsMobile(); @@ -104,6 +107,7 @@ export function SettingsLayout() { }; // Get current settings page + const settingsItems = getSettingsItems(t); const currentPath = location.pathname; const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id; @@ -117,11 +121,11 @@ export function SettingsLayout() { variant="ghost" size="sm" onClick={() => setIsSidebarVisible(!isSidebarVisible)} - aria-label="Toggle sidebar" + aria-label={t('toggleSidebar')} > -

Settings

+

{t('settings')}

@@ -176,13 +180,13 @@ export function SettingsLayout() { size="sm" onClick={() => setIsSidebarVisible(true)} className="h-8 w-8 p-0" - aria-label="Open sidebar" + aria-label={t('openSidebar')} > )}

- Settings + {t('settings')}

diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 5ddeaf12..09479658 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -1,5 +1,6 @@ import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo, useCallback } from 'react'; import { useSearchParams } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Skeleton } from '@/components/ui/skeleton'; @@ -67,6 +68,7 @@ export const ChatPane = forwardRef(({ isBuildLoading: externalIsBuildLoading, isDeployLoading: externalIsDeployLoading }, ref) => { + const { t } = useTranslation(); const [input, setInput] = useState(''); const [systemPrompt, setSystemPrompt] = useState(''); const [showScrollToBottom, setShowScrollToBottom] = useState(false); @@ -417,12 +419,12 @@ export const ChatPane = forwardRef(({
🤖
-

AI Assistant Not Configured

+

{t('aiNotConfigured')}

- Please configure your AI settings to start building with AI assistance. + {t('configureAI')}

- Use the menu in the top bar to access AI Settings. + {t('useMenuForAI')}

@@ -445,16 +447,16 @@ export const ChatPane = forwardRef(({
🎭

- Welcome to Shakespeare + {t('welcomeToShakespeare')}

- Your AI-powered development assistant is ready to help you build, edit, and enhance your project. + {t('aiAssistantReady')}

-

💡 Ask me to add new features

-

📝 Request file edits and improvements

-

🔧 Get help with debugging and optimization

-

🚀 Build and deploy your project

+

{t('askMeFeatures')}

+

{t('requestEdits')}

+

{t('getHelp')}

+

{t('buildDeploy')}

@@ -512,7 +514,7 @@ export const ChatPane = forwardRef(({
- Running {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}... + {t('running')} {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
@@ -543,7 +545,7 @@ export const ChatPane = forwardRef(({ onKeyDown={handleKeyDown} onPaste={handlePaste} onFocus={handleFirstInteraction} - placeholder={providerModel.trim() ? "Ask me to add features, edit files, or build your project..." : "Please select a model to start chatting..."} + placeholder={providerModel.trim() ? t('askToAddFeatures') : t('selectModelFirst')} className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground" disabled={isLoading || !providerModel.trim()} rows={1} @@ -583,7 +585,11 @@ export const ChatPane = forwardRef(({
-

Context usage: {lastInputTokens.toLocaleString()} / {currentModel.contextLength.toLocaleString()} tokens ({contextUsagePercentage.toFixed(1)}%)

+

{t('contextUsage', { + tokens: lastInputTokens.toLocaleString(), + total: currentModel.contextLength.toLocaleString(), + percentage: contextUsagePercentage.toFixed(1) + })}

@@ -599,7 +605,7 @@ export const ChatPane = forwardRef(({
-

Total cost for this chat session

+

{t('totalCostSession')}

@@ -612,7 +618,7 @@ export const ChatPane = forwardRef(({ onChange={setProviderModel} className="w-full" disabled={isLoading} - placeholder="Choose a model..." + placeholder={t('chooseModel')} />
diff --git a/src/components/Shakespeare/FileEditor.tsx b/src/components/Shakespeare/FileEditor.tsx index 05ae0ab4..3e79d416 100644 --- a/src/components/Shakespeare/FileEditor.tsx +++ b/src/components/Shakespeare/FileEditor.tsx @@ -1,4 +1,5 @@ import { useState, useEffect } from 'react'; +import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { CardContent, CardHeader, CardTitle } from '@/components/ui/card'; @@ -15,6 +16,7 @@ interface FileEditorProps { } export function FileEditor({ filePath, content, onSave, isLoading, projectId }: FileEditorProps) { + const { t } = useTranslation(); const [editedContent, setEditedContent] = useState(content); const [isSaving, setIsSaving] = useState(false); const [hasChanges, setHasChanges] = useState(false); @@ -99,7 +101,7 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }: {filePath}
{hasChanges && ( - Unsaved changes + {t('unsavedChanges')} )}
- Language: {getLanguageFromPath(filePath)} + {t('languageLabel')}: {getLanguageFromPath(filePath)}
diff --git a/src/components/Shakespeare/FileTree.tsx b/src/components/Shakespeare/FileTree.tsx index c88c949f..e6f50651 100644 --- a/src/components/Shakespeare/FileTree.tsx +++ b/src/components/Shakespeare/FileTree.tsx @@ -1,4 +1,5 @@ import { useState, useEffect, useCallback } from 'react'; +import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; import { useGitStatus } from '@/hooks/useGitStatus'; @@ -22,6 +23,7 @@ interface FileNode { } export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) { + const { t } = useTranslation(); const [tree, setTree] = useState([]); const [filteredTree, setFilteredTree] = useState([]); const [isLoading, setIsLoading] = useState(true); @@ -179,7 +181,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp for (const node of nodes) { if (node.type === 'file') { const fileNameMatch = node.name.toLowerCase().includes(searchTermLower); - + if (fileNameMatch) { results.push(node); } @@ -296,7 +298,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
setSearchTerm(e.target.value)} className="pl-8" @@ -313,7 +315,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
) : filteredTree.length === 0 ? (
- {searchTerm ? 'No files found matching your search' : 'No files found'} + {searchTerm ? t('noFilesFoundSearch') : t('noFilesFound')}
) : ( filteredTree.map(node => renderNode(node)) diff --git a/src/components/auth/LoginArea.test.tsx b/src/components/auth/LoginArea.test.tsx index 492995b1..62df7a0e 100644 --- a/src/components/auth/LoginArea.test.tsx +++ b/src/components/auth/LoginArea.test.tsx @@ -71,24 +71,6 @@ describe('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(), - isLoading: false - }); - - render(); - - // Should show anonymous user display - expect(screen.getByText('Anonymous')).toBeInTheDocument(); - - // Should show the dropdown trigger button - expect(screen.getByRole('button')).toBeInTheDocument(); - }); diff --git a/src/components/auth/LoginArea.tsx b/src/components/auth/LoginArea.tsx index 7be3feef..67a10ff0 100644 --- a/src/components/auth/LoginArea.tsx +++ b/src/components/auth/LoginArea.tsx @@ -2,6 +2,7 @@ // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; import { User, UserPlus, ChevronDown, Settings, HelpCircle } from 'lucide-react'; import { DropdownMenu, @@ -23,6 +24,7 @@ export interface LoginAreaProps { } export function LoginArea({ className }: LoginAreaProps) { + const { t } = useTranslation(); const { currentUser } = useLoggedInAccounts(); const navigate = useNavigate(); const [loginDialogOpen, setLoginDialogOpen] = useState(false); @@ -47,7 +49,7 @@ export function LoginArea({ className }: LoginAreaProps) {
-

Anonymous

+

{t('anonymous')}

@@ -58,14 +60,14 @@ export function LoginArea({ className }: LoginAreaProps) { className='flex items-center gap-2 cursor-pointer p-2 rounded-md' > - Settings + {t('settings')} window.open('https://soapbox.pub/shakespeare-resources/', '_blank')} className='flex items-center gap-2 cursor-pointer p-2 rounded-md' > - Help + {t('help')} - Log in + {t('logIn')} setSignupDialogOpen(true)} className='flex items-center gap-2 cursor-pointer p-2 rounded-md' > - Sign up + {t('signUp')} diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index dc2aca57..1c68d14d 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -9,9 +9,14 @@ const resources = { preferences: 'Preferences', settings: 'Settings', backToSettings: 'Back to Settings', + help: 'Help', + anonymous: 'Anonymous', + + // Authentication + logIn: 'Log in', + signUp: 'Sign up', // Preferences Page - preferencesTitle: 'Preferences', preferencesDescription: 'Manage your general application preferences and appearance settings.', // Appearance Section @@ -47,6 +52,9 @@ const resources = { success: 'Success', warning: 'Warning', info: 'Information', + add: 'Add', + remove: 'Remove', + retry: 'Retry', // Shakespeare Main Page buildNostrApps: 'Build Nostr apps with AI', @@ -55,11 +63,10 @@ const resources = { generating: 'Generating...', creating: 'Creating...', chooseModel: 'Choose a model...', - selectModelFirst: "Please select a model below, then describe what you'd like to build...", + selectModelToDescribe: "Please select a model below, then describe what you'd like to build...", examplePrompt: "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...", // Settings Page - settingsTitle: 'Settings', settingsDescription: 'Manage your application settings and preferences.', aiSettings: 'AI Settings', aiSettingsDescription: 'Configure AI providers and API keys', @@ -69,6 +76,180 @@ const resources = { nostrSettingsDescription: 'Configure relay connections and Nostr preferences', dataSettings: 'Data', dataSettingsDescription: 'Export files and manage local data', + + // Project Sidebar + newProject: 'New Project', + importRepository: 'Import Repository', + noProjectsYet: 'No projects yet', + createFirstProject: 'Create your first project to get started', + closeSidebar: 'Close sidebar', + collapseSidebar: 'Collapse sidebar', + + // Chat Interface + welcomeToShakespeare: 'Welcome to Shakespeare', + aiAssistantReady: 'Your AI-powered development assistant is ready to help you build, edit, and enhance your project.', + askMeFeatures: '💡 Ask me to add new features', + requestEdits: '📝 Request file edits and improvements', + getHelp: '🔧 Get help with debugging and optimization', + buildDeploy: '🚀 Build and deploy your project', + aiNotConfigured: 'AI Assistant Not Configured', + configureAI: 'Please configure your AI settings to start building with AI assistance.', + useMenuForAI: 'Use the menu in the top bar to access AI Settings.', + askToAddFeatures: 'Ask me to add features, edit files, or build your project...', + selectModelFirst: 'Please select a model to start chatting...', + sendMessage: 'Send message', + stopGeneration: 'Stop generation', + running: 'Running', + + // File Editor + unsavedChanges: 'Unsaved changes', + saving: 'Saving...', + languageLabel: 'Language', + + // File Tree + searchFiles: 'Search files...', + noFilesFound: 'No files found', + noFilesFoundSearch: 'No files found matching your search', + + // Git Dialog + gitRepositoryStatus: 'Git Repository Status', + repositoryStatusDescription: 'View repository status and sync with remote repositories', + repositoryInformation: 'Repository Information', + currentBranch: 'Current Branch', + totalCommits: 'Total Commits', + latestCommit: 'Latest Commit', + remotes: 'Remotes', + notGitRepository: 'Not a Git repository', + gitAuthentication: 'Authentication', + credentialsDescription: 'Credentials for push/pull operations', + configured: 'Configured', + noCredentials: 'No credentials', + noCredentialsWarning: 'No credentials configured for {{provider}}. Push/pull operations may fail for private repositories.', + configureCredentials: 'Configure credentials', + syncStatus: 'Sync Status', + pull: 'Pull', + push: 'Push', + pulling: 'Pulling...', + pushing: 'Pushing...', + upToDate: 'Up to date', + commitsAhead: '{{count}} commit ahead | {{count}} commits ahead', + commitsBehind: '{{count}} commit behind | {{count}} commits behind', + uncommittedChanges: '{{count}} uncommitted change | {{count}} uncommitted changes', + noRemoteConfigured: 'No remote configured', + workingDirectoryChanges: 'Working Directory Changes', + filesWithChanges: '{{count}} file with changes | {{count}} files with changes', + workingDirectoryClean: 'Working directory is clean', + noUncommittedChanges: 'No uncommitted changes', + cannotPush: 'Cannot push', + cannotPull: 'Cannot pull', + notGitRepoOrBranch: 'Not a git repository or no current branch', + noRemoteRepositories: 'No remote repositories configured', + nothingToPush: 'Nothing to push', + noCommitsAhead: 'No commits ahead of remote. Commit your changes first.', + pushSuccessful: 'Push successful', + pushFailed: 'Push failed', + pullSuccessful: 'Pull successful', + pullFailed: 'Pull failed', + + // AI Settings + aiSettingsDescriptionLong: 'Configure AI providers by adding your API keys. Settings are automatically saved and stored locally in your browser.', + configuredProviders: 'Configured Providers', + addProvider: 'Add Provider', + getApiKey: 'Get API key', + getToken: 'Get token', + enterApiKey: 'Enter your API key', + enterToken: 'Enter your token', + enterCashuToken: 'Enter a Cashu token', + addCustomProvider: 'Add Custom Provider', + providerName: 'Provider Name', + baseUrl: 'Base URL', + apiKey: 'API Key', + authentication: 'Authentication', + addCustomProviderButton: 'Add Custom Provider', + providerExists: 'Provider with this name already exists', + custom: 'Custom', + connecting: 'Connecting...', + connectToGitHub: 'Connect to GitHub', + + // Git Settings + gitSettingsDescriptionLong: 'Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.', + configuredCredentials: 'Configured Credentials', + origin: 'Origin', + username: 'Username', + password: 'Password', + enterPassword: 'Enter your password/token', + credentialsExist: 'Credentials for this origin already exist', + corsProxy: 'CORS Proxy', + corsProxyDescription: 'CORS proxy server used for all Git operations with remote repositories. Required for browser-based Git operations.', + + // Data Settings + dataSettingsDescriptionLong: 'Export files and manage local data.', + exportFiles: 'Export Files', + exportFilesDescription: 'Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally.', + exportAllFiles: 'Export All Files', + exporting: 'Exporting...', + clearAllData: 'Clear All Data', + clearAllDataDescription: 'Permanently delete all local data including projects, settings, and cached information. This action cannot be undone.', + clearing: 'Clearing...', + areYouSure: 'Are you absolutely sure?', + clearDataWarning: 'This action will permanently delete all local data from this browser, including:', + allProjects: 'All projects and their files', + aiSettingsAndKeys: 'AI settings and API keys', + gitCredentialsSettings: 'Git credentials and settings', + userPreferences: 'User preferences and themes', + cachedData: 'Cached data and session information', + actionCannotBeUndone: 'This action cannot be undone. Consider exporting your files first.', + yesClearAllData: 'Yes, clear all data', + used: 'Used', + available: 'Available', + usagePercentage: '{{percentage}}% used', + usageUnavailable: 'Usage percentage unavailable', + loadingStorageInfo: 'Loading storage information...', + filesExportedSuccessfully: 'Files exported successfully', + filesExportedDescription: 'Your project files have been downloaded as a zip file.', + failedToExportFiles: 'Failed to export files', + dataClearedSuccessfully: 'Data cleared successfully', + dataClearedDescription: 'All local data has been removed. Redirecting to homepage...', + failedToClearData: 'Failed to clear data', + + // 404 Page + pageNotFound: 'Oops! Page not found', + returnToHome: 'Return to Home', + + // Model Selector + selectOrEnterModel: 'Select or enter a model...', + searchModels: 'Search models...', + enterCustomModel: 'Enter custom model...', + manageProviders: 'Manage providers...', + noModelsFound: 'No models found.', + tryCustomModel: 'Try using a custom model instead.', + recentlyUsed: 'Recently Used', + errorLoadingModels: 'Error Loading Models', + + // Context and Cost + contextUsage: 'Context usage: {{tokens}} / {{total}} tokens ({{percentage}}%)', + totalCostSession: 'Total cost for this chat session', + + // File Status + added: 'added', + deleted: 'deleted', + modified: 'modified', + staged: 'staged', + untracked: 'untracked', + + // Settings Layout + toggleSidebar: 'Toggle sidebar', + openSidebar: 'Open sidebar', + + // Nostr Settings + nostrSettingsDescriptionLong: 'Configure your Nostr connection settings and relay preferences.', + nostrAccounts: 'Nostr Accounts', + noAccountsLoggedIn: 'No accounts logged in. Add an account to get started.', + createAccount: 'Create Account', + addExistingAccount: 'Add Existing Account', + addAccount: 'Add Account', + relayConfiguration: 'Relay Configuration', + selectedRelay: 'Selected Relay', } }, pt: { @@ -77,9 +258,14 @@ const resources = { preferences: 'Preferências', settings: 'Configurações', backToSettings: 'Voltar às Configurações', + help: 'Ajuda', + anonymous: 'Anônimo', + + // Authentication + logIn: 'Entrar', + signUp: 'Cadastrar', // Preferences Page - preferencesTitle: 'Preferências', preferencesDescription: 'Gerencie suas preferências gerais da aplicação e configurações de aparência.', // Appearance Section @@ -115,6 +301,9 @@ const resources = { success: 'Sucesso', warning: 'Aviso', info: 'Informação', + add: 'Adicionar', + remove: 'Remover', + retry: 'Tentar novamente', // Shakespeare Main Page buildNostrApps: 'Construa aplicativos Nostr com IA', @@ -123,11 +312,10 @@ const resources = { generating: 'Gerando...', creating: 'Criando...', chooseModel: 'Escolha um modelo...', - selectModelFirst: "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...", + selectModelToDescribe: "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...", examplePrompt: "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...", // Settings Page - settingsTitle: 'Configurações', settingsDescription: 'Gerencie as configurações e preferências da aplicação.', aiSettings: 'Configurações de IA', aiSettingsDescription: 'Configure provedores de IA e chaves de API', @@ -137,6 +325,180 @@ const resources = { nostrSettingsDescription: 'Configure conexões de relay e preferências do Nostr', dataSettings: 'Dados', dataSettingsDescription: 'Exporte arquivos e gerencie dados locais', + + // Project Sidebar + newProject: 'Novo Projeto', + importRepository: 'Importar Repositório', + noProjectsYet: 'Nenhum projeto ainda', + createFirstProject: 'Crie seu primeiro projeto para começar', + closeSidebar: 'Fechar barra lateral', + collapseSidebar: 'Recolher barra lateral', + + // Chat Interface + welcomeToShakespeare: 'Bem-vindo ao Shakespeare', + aiAssistantReady: 'Seu assistente de desenvolvimento com IA está pronto para ajudá-lo a construir, editar e aprimorar seu projeto.', + askMeFeatures: '💡 Peça para adicionar novos recursos', + requestEdits: '📝 Solicite edições e melhorias de arquivos', + getHelp: '🔧 Obtenha ajuda com depuração e otimização', + buildDeploy: '🚀 Construa e implante seu projeto', + aiNotConfigured: 'Assistente de IA Não Configurado', + configureAI: 'Configure suas configurações de IA para começar a construir com assistência de IA.', + useMenuForAI: 'Use o menu na barra superior para acessar as Configurações de IA.', + askToAddFeatures: 'Peça para adicionar recursos, editar arquivos ou construir seu projeto...', + selectModelFirst: 'Selecione um modelo para começar a conversar...', + sendMessage: 'Enviar mensagem', + stopGeneration: 'Parar geração', + running: 'Executando', + + // File Editor + unsavedChanges: 'Alterações não salvas', + saving: 'Salvando...', + languageLabel: 'Linguagem', + + // File Tree + searchFiles: 'Buscar arquivos...', + noFilesFound: 'Nenhum arquivo encontrado', + noFilesFoundSearch: 'Nenhum arquivo encontrado correspondente à sua busca', + + // Git Dialog + gitRepositoryStatus: 'Status do Repositório Git', + repositoryStatusDescription: 'Visualizar status do repositório e sincronizar com repositórios remotos', + repositoryInformation: 'Informações do Repositório', + currentBranch: 'Branch Atual', + totalCommits: 'Total de Commits', + latestCommit: 'Último Commit', + remotes: 'Remotos', + notGitRepository: 'Não é um repositório Git', + gitAuthentication: 'Autenticação', + credentialsDescription: 'Credenciais para operações de push/pull', + configured: 'Configurado', + noCredentials: 'Sem credenciais', + noCredentialsWarning: 'Nenhuma credencial configurada para {{provider}}. Operações de push/pull podem falhar para repositórios privados.', + configureCredentials: 'Configurar credenciais', + syncStatus: 'Status de Sincronização', + pull: 'Pull', + push: 'Push', + pulling: 'Fazendo pull...', + pushing: 'Fazendo push...', + upToDate: 'Atualizado', + commitsAhead: '{{count}} commit à frente | {{count}} commits à frente', + commitsBehind: '{{count}} commit atrás | {{count}} commits atrás', + uncommittedChanges: '{{count}} alteração não commitada | {{count}} alterações não commitadas', + noRemoteConfigured: 'Nenhum remoto configurado', + workingDirectoryChanges: 'Alterações do Diretório de Trabalho', + filesWithChanges: '{{count}} arquivo com alterações | {{count}} arquivos com alterações', + workingDirectoryClean: 'Diretório de trabalho limpo', + noUncommittedChanges: 'Nenhuma alteração não commitada', + cannotPush: 'Não é possível fazer push', + cannotPull: 'Não é possível fazer pull', + notGitRepoOrBranch: 'Não é um repositório git ou não há branch atual', + noRemoteRepositories: 'Nenhum repositório remoto configurado', + nothingToPush: 'Nada para fazer push', + noCommitsAhead: 'Nenhum commit à frente do remoto. Faça commit de suas alterações primeiro.', + pushSuccessful: 'Push realizado com sucesso', + pushFailed: 'Push falhou', + pullSuccessful: 'Pull realizado com sucesso', + pullFailed: 'Pull falhou', + + // AI Settings + aiSettingsDescriptionLong: 'Configure provedores de IA adicionando suas chaves de API. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.', + configuredProviders: 'Provedores Configurados', + addProvider: 'Adicionar Provedor', + getApiKey: 'Obter chave de API', + getToken: 'Obter token', + enterApiKey: 'Digite sua chave de API', + enterToken: 'Digite seu token', + enterCashuToken: 'Digite um token Cashu', + addCustomProvider: 'Adicionar Provedor Personalizado', + providerName: 'Nome do Provedor', + baseUrl: 'URL Base', + apiKey: 'Chave de API', + authentication: 'Autenticação', + addCustomProviderButton: 'Adicionar Provedor Personalizado', + providerExists: 'Provedor com este nome já existe', + custom: 'Personalizado', + connecting: 'Conectando...', + connectToGitHub: 'Conectar ao GitHub', + + // Git Settings + gitSettingsDescriptionLong: 'Configure credenciais do Git para autenticação HTTP. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.', + configuredCredentials: 'Credenciais Configuradas', + origin: 'Origem', + username: 'Nome de usuário', + password: 'Senha', + enterPassword: 'Digite sua senha/token', + credentialsExist: 'Credenciais para esta origem já existem', + corsProxy: 'Proxy CORS', + corsProxyDescription: 'Servidor proxy CORS usado para todas as operações Git com repositórios remotos. Necessário para operações Git baseadas no navegador.', + + // Data Settings + dataSettingsDescriptionLong: 'Exporte arquivos e gerencie dados locais.', + exportFiles: 'Exportar Arquivos', + exportFilesDescription: 'Baixe todos os seus projetos e arquivos como um arquivo ZIP. Isso inclui todos os arquivos de projeto, configurações e dados armazenados localmente.', + exportAllFiles: 'Exportar Todos os Arquivos', + exporting: 'Exportando...', + clearAllData: 'Limpar Todos os Dados', + clearAllDataDescription: 'Exclua permanentemente todos os dados locais, incluindo projetos, configurações e informações em cache. Esta ação não pode ser desfeita.', + clearing: 'Limpando...', + areYouSure: 'Você tem certeza absoluta?', + clearDataWarning: 'Esta ação excluirá permanentemente todos os dados locais deste navegador, incluindo:', + allProjects: 'Todos os projetos e seus arquivos', + aiSettingsAndKeys: 'Configurações de IA e chaves de API', + gitCredentialsSettings: 'Credenciais e configurações do Git', + userPreferences: 'Preferências do usuário e temas', + cachedData: 'Dados em cache e informações de sessão', + actionCannotBeUndone: 'Esta ação não pode ser desfeita. Considere exportar seus arquivos primeiro.', + yesClearAllData: 'Sim, limpar todos os dados', + used: 'Usado', + available: 'Disponível', + usagePercentage: '{{percentage}}% usado', + usageUnavailable: 'Porcentagem de uso indisponível', + loadingStorageInfo: 'Carregando informações de armazenamento...', + filesExportedSuccessfully: 'Arquivos exportados com sucesso', + filesExportedDescription: 'Seus arquivos de projeto foram baixados como um arquivo zip.', + failedToExportFiles: 'Falha ao exportar arquivos', + dataClearedSuccessfully: 'Dados limpos com sucesso', + dataClearedDescription: 'Todos os dados locais foram removidos. Redirecionando para a página inicial...', + failedToClearData: 'Falha ao limpar dados', + + // 404 Page + pageNotFound: 'Ops! Página não encontrada', + returnToHome: 'Voltar ao Início', + + // Model Selector + selectOrEnterModel: 'Selecione ou digite um modelo...', + searchModels: 'Buscar modelos...', + enterCustomModel: 'Digite modelo personalizado...', + manageProviders: 'Gerenciar provedores...', + noModelsFound: 'Nenhum modelo encontrado.', + tryCustomModel: 'Tente usar um modelo personalizado.', + recentlyUsed: 'Usados Recentemente', + errorLoadingModels: 'Erro ao Carregar Modelos', + + // Context and Cost + contextUsage: 'Uso de contexto: {{tokens}} / {{total}} tokens ({{percentage}}%)', + totalCostSession: 'Custo total para esta sessão de chat', + + // File Status + added: 'adicionado', + deleted: 'excluído', + modified: 'modificado', + staged: 'preparado', + untracked: 'não rastreado', + + // Settings Layout + toggleSidebar: 'Alternar barra lateral', + openSidebar: 'Abrir barra lateral', + + // Nostr Settings + nostrSettingsDescriptionLong: 'Configure suas configurações de conexão Nostr e preferências de relay.', + nostrAccounts: 'Contas Nostr', + noAccountsLoggedIn: 'Nenhuma conta logada. Adicione uma conta para começar.', + createAccount: 'Criar Conta', + addExistingAccount: 'Adicionar Conta Existente', + addAccount: 'Adicionar Conta', + relayConfiguration: 'Configuração de Relay', + selectedRelay: 'Relay Selecionado', } } }; diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index 61810ad4..a9e30866 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -1,4 +1,5 @@ import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; import { Check, Bot, ArrowLeft, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -79,6 +80,7 @@ const PRESET_PROVIDERS: PresetProvider[] = [ ]; export function AISettings() { + const { t } = useTranslation(); const { settings, addProvider, removeProvider, updateProvider } = useAISettings(); const isMobile = useIsMobile(); const navigate = useNavigate(); @@ -154,15 +156,15 @@ export function AISettings() { className="h-8 w-auto px-2 -ml-2" > - Back to Settings + {t('backToSettings')}

- AI Settings + {t('aiSettings')}

- Configure AI providers by adding your API keys. Settings are automatically saved and stored locally in your browser. + {t('aiSettingsDescriptionLong')}

@@ -172,10 +174,10 @@ export function AISettings() {

- AI Settings + {t('aiSettings')}

- Configure AI providers by adding your API keys. Settings are automatically saved and stored locally in your browser. + {t('aiSettingsDescriptionLong')}

)} @@ -184,7 +186,7 @@ export function AISettings() { {/* Configured Providers */} {configuredProviderIds.length > 0 && (
-

Configured Providers

+

{t('configuredProviders')}

{configuredProviderIds.map((providerId) => { const preset = PRESET_PROVIDERS.find(p => p.id === providerId); @@ -199,7 +201,7 @@ export function AISettings() { {preset?.name || providerId} - {isCustom && Custom} + {isCustom && {t('custom')}}
)}
{!preset.nostr && ( setPresetApiKeys(prev => ({ @@ -306,7 +308,7 @@ export function AISettings() { disabled={!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim()} size="sm" > - Add + {t('add')}
@@ -322,12 +324,12 @@ export function AISettings() { -

Add Custom Provider

+

{t('addCustomProvider')}

- +
- +
- +
{customAuthMethod === 'api-key' && (
- + setCustomApiKey(e.target.value)} /> @@ -386,11 +388,11 @@ export function AISettings() { className="gap-2" > - Add Custom Provider + {t('addCustomProviderButton')} {customProviderName.trim() in settings.providers && (

- Provider with this name already exists + {t('providerExists')}

)}
diff --git a/src/pages/DataSettings.tsx b/src/pages/DataSettings.tsx index 8b1fcebe..568a22c3 100644 --- a/src/pages/DataSettings.tsx +++ b/src/pages/DataSettings.tsx @@ -1,5 +1,6 @@ import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; import { Download, Trash2, AlertTriangle, Loader2, Database, Info } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; @@ -23,6 +24,7 @@ interface StorageInfo { } export function DataSettings() { + const { t } = useTranslation(); const [isExporting, setIsExporting] = useState(false); const [isClearing, setIsClearing] = useState(false); const [storageInfo, setStorageInfo] = useState(null); @@ -130,14 +132,14 @@ export function DataSettings() { await exportFilesAsZip(); toast({ - title: "Files exported successfully", - description: "Your project files have been downloaded as a zip file.", + title: t('filesExportedSuccessfully'), + description: t('filesExportedDescription'), }); } catch (error) { console.error('Failed to export files:', error); toast({ - title: "Failed to export files", - description: error instanceof Error ? error.message : "An unexpected error occurred", + title: t('failedToExportFiles'), + description: error instanceof Error ? error.message : t('error'), variant: "destructive", }); } finally { @@ -172,8 +174,8 @@ export function DataSettings() { await Promise.all(deletePromises); toast({ - title: "Data cleared successfully", - description: "All local data has been removed. Redirecting to homepage...", + title: t('dataClearedSuccessfully'), + description: t('dataClearedDescription'), }); // Small delay to show the toast, then redirect @@ -183,8 +185,8 @@ export function DataSettings() { } catch (error) { console.error('Failed to clear data:', error); toast({ - title: "Failed to clear data", - description: error instanceof Error ? error.message : "An unexpected error occurred", + title: t('failedToClearData'), + description: error instanceof Error ? error.message : t('error'), variant: "destructive", }); } finally { @@ -197,10 +199,10 @@ export function DataSettings() {

- Data + {t('dataSettings')}

- Export files and manage local data. + {t('dataSettingsDescriptionLong')}

@@ -216,8 +218,8 @@ export function DataSettings() { {/* Usage Progress */}
- Used: {formatBytes(storageInfo.usage)} - Available: {formatBytes(storageInfo.quota)} + {t('used')}: {formatBytes(storageInfo.usage)} + {t('available')}: {formatBytes(storageInfo.quota)}
0 ? (storageInfo.usage / storageInfo.quota) * 100 : 0} @@ -225,8 +227,8 @@ export function DataSettings() { />
{storageInfo.quota > 0 - ? `${((storageInfo.usage / storageInfo.quota) * 100).toFixed(1)}% used` - : 'Usage percentage unavailable' + ? t('usagePercentage', { percentage: ((storageInfo.usage / storageInfo.quota) * 100).toFixed(1) }) + : t('usageUnavailable') }
@@ -235,7 +237,7 @@ export function DataSettings() { ) : (
- Loading storage information... + {t('loadingStorageInfo')}
)} @@ -244,10 +246,10 @@ export function DataSettings() { - Export Files + {t('exportFiles')} - Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally. + {t('exportFilesDescription')} @@ -259,12 +261,12 @@ export function DataSettings() { {isExporting ? ( <> - Exporting... + {t('exporting')} ) : ( <> - Export All Files + {t('exportAllFiles')} )} @@ -276,10 +278,10 @@ export function DataSettings() { - Clear All Data + {t('clearAllData')} - Permanently delete all local data including projects, settings, and cached information. This action cannot be undone. + {t('clearAllDataDescription')} @@ -293,12 +295,12 @@ export function DataSettings() { {isClearing ? ( <> - Clearing... + {t('clearing')} ) : ( <> - Clear All Data + {t('clearAllData')} )} @@ -307,31 +309,31 @@ export function DataSettings() { - Are you absolutely sure? + {t('areYouSure')}

- This action will permanently delete all local data from this browser, including: + {t('clearDataWarning')}

    -
  • All projects and their files
  • -
  • AI settings and API keys
  • -
  • Git credentials and settings
  • -
  • User preferences and themes
  • -
  • Cached data and session information
  • +
  • {t('allProjects')}
  • +
  • {t('aiSettingsAndKeys')}
  • +
  • {t('gitCredentialsSettings')}
  • +
  • {t('userPreferences')}
  • +
  • {t('cachedData')}

- This action cannot be undone. Consider exporting your files first. + {t('actionCannotBeUndone')}

- Cancel + {t('cancel')} - Yes, clear all data + {t('yesClearAllData')} diff --git a/src/pages/GitSettings.tsx b/src/pages/GitSettings.tsx index a306ce50..338d1754 100644 --- a/src/pages/GitSettings.tsx +++ b/src/pages/GitSettings.tsx @@ -1,4 +1,5 @@ import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; import { Check, GitBranch, ArrowLeft, Github, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -38,6 +39,7 @@ const PRESET_PROVIDERS: PresetProvider[] = [ ]; export function GitSettings() { + const { t } = useTranslation(); const { settings, addCredential, removeCredential, updateCredential, updateSettings } = useGitSettings(); const { initiateOAuth, isLoading: isOAuthLoading, error: oauthError, isOAuthConfigured } = useGitHubOAuth(); const isMobile = useIsMobile(); @@ -107,15 +109,15 @@ export function GitSettings() { className="h-8 w-auto px-2 -ml-2" > - Back to Settings + {t('backToSettings')}

- Git Settings + {t('gitSettings')}

- Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser. + {t('gitSettingsDescriptionLong')}

@@ -125,10 +127,10 @@ export function GitSettings() {

- Git Settings + {t('gitSettings')}

- Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser. + {t('gitSettingsDescriptionLong')}

)} @@ -137,7 +139,7 @@ export function GitSettings() { {/* Configured Credentials */} {configuredOrigins.length > 0 && (
-

Configured Credentials

+

{t('configuredCredentials')}

{configuredOrigins.map((origin) => { const preset = PRESET_PROVIDERS.find(p => p.origin === origin); @@ -152,7 +154,7 @@ export function GitSettings() { {preset?.name || new URL(origin).hostname} - {isCustom && Custom} + {isCustom && {t('custom')}}
)} @@ -262,7 +264,7 @@ export function GitSettings() { ) : (
- Add + {t('add')}
) @@ -289,7 +291,7 @@ export function GitSettings() { // Standard rendering for other providers
- Add + {t('add')}
)} @@ -325,12 +327,12 @@ export function GitSettings() { -

Add Custom Provider

+

{t('addCustomProvider')}

- +
- +
- + setCustomPassword(e.target.value)} /> @@ -369,11 +371,11 @@ export function GitSettings() { className="gap-2" > - Add Custom Provider + {t('addCustomProviderButton')} {customOrigin.trim() in settings.credentials && (

- Credentials for this origin already exist + {t('credentialsExist')}

)}
@@ -385,7 +387,7 @@ export function GitSettings() { -

CORS Proxy

+

{t('corsProxy')}

@@ -397,7 +399,7 @@ export function GitSettings() { onChange={(e) => updateSettings({ corsProxy: e.target.value })} />

- CORS proxy server used for all Git operations with remote repositories. Required for browser-based Git operations. + {t('corsProxyDescription')}

diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 69e41b4d..d8f3b6d6 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -1,5 +1,6 @@ import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useAIProjectId } from '@/hooks/useAIProjectId'; import { useFS } from '@/hooks/useFS'; @@ -17,6 +18,7 @@ import { Plus } from 'lucide-react'; import { useSeoMeta } from '@unhead/react'; export default function Index() { + const { t } = useTranslation(); const [prompt, setPrompt] = useState(''); const [isCreating, setIsCreating] = useState(false); const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', ''); @@ -127,10 +129,10 @@ export default function Index() {
🎭

- Build Nostr apps with AI + {t('buildNostrApps')}

- What would you like to build? + {t('whatToBuild')}

@@ -140,8 +142,8 @@ export default function Index() {