Compare commits

..
Author SHA1 Message Date
lemonknowsall 029f3f6c58 remove unused 2025-11-24 13:36:24 -08:00
lemonknowsall 1f685296de animate logo spin 2025-11-24 13:20:37 -08:00
lemonknowsall e0accea7ab chat input singleton 2025-11-24 12:55:59 -08:00
49 changed files with 386 additions and 1688 deletions

No files matched your search

@@ -38,14 +38,7 @@ class JSONRPCClient {
}
}
/**
* Generic JSON-RPC call method
* @param {string} method - The RPC method name
* @param {object} params - Parameters for the method
* @param {number} timeout - Timeout in milliseconds (default: 10000)
* @returns {Promise} - Resolves with the result or rejects with error
*/
async call(method, params, timeout = 10000) {
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
@@ -54,25 +47,21 @@ class JSONRPCClient {
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method,
params,
method: "fetch",
params: { request },
id,
}, "*");
// Timeout handling
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`RPC call to ${method} with ID ${id} timed out`));
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, timeout);
}, 10000);
});
}
async fetch(request) {
return this.call("fetch", { request }, 10000);
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
@@ -164,38 +153,6 @@ class ConsoleInterceptor {
}
}
// Nostr Bridge - proxies window.nostr calls to parent window
class NostrBridge {
constructor(rpcClient) {
this.rpcClient = rpcClient;
console.log('[NostrBridge] initializing...');
this.injectNostr();
}
injectNostr() {
// Create the window.nostr object
window.nostr = {
getPublicKey: () => this.callNostrMethod('getPublicKey', []),
signEvent: (event) => this.callNostrMethod('signEvent', [event]),
nip04: {
encrypt: (pubkey, plaintext) => this.callNostrMethod('nip04.encrypt', [pubkey, plaintext]),
decrypt: (pubkey, ciphertext) => this.callNostrMethod('nip04.decrypt', [pubkey, ciphertext]),
},
nip44: {
encrypt: (pubkey, plaintext) => this.callNostrMethod('nip44.encrypt', [pubkey, plaintext]),
decrypt: (pubkey, ciphertext) => this.callNostrMethod('nip44.decrypt', [pubkey, ciphertext]),
},
};
console.log('[NostrBridge] window.nostr injected');
}
async callNostrMethod(method, args) {
// Use the generic RPC client call method
// Extension prompts may take time, so use 30 second timeout
return this.rpcClient.call('nostr', { method, args }, 30000);
}
}
// Navigation Handler - manages iframe navigation and history
class NavigationHandler {
constructor() {
@@ -362,8 +319,8 @@ class NavigationHandler {
// Main Fetch Client
class FetchClient {
constructor(rpcClient) {
this.rpcClient = rpcClient;
constructor() {
this.rpcClient = new JSONRPCClient();
this.consoleInterceptor = new ConsoleInterceptor();
this.navigationHandler = new NavigationHandler();
this.init();
@@ -436,8 +393,8 @@ class FetchClient {
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => { },
removeEventListener: () => { },
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
@@ -612,14 +569,8 @@ const setupGlobalErrorHandlers = () => {
// Initialize
setupGlobalErrorHandlers();
const init = () => {
const rpcClient = new JSONRPCClient();
new FetchClient(rpcClient);
new NostrBridge(rpcClient);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
init();
}
new FetchClient();
}
+2 -2
View File
@@ -99,7 +99,7 @@ export function AppLayout({
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={(project) => {
@@ -123,7 +123,7 @@ export function AppLayout({
<div className="min-h-screen flex bg-background">
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
{showSidebar && isSidebarVisible && (
<div className="w-72 border-r bg-sidebar transition-all duration-300">
<div className="w-80 border-r bg-sidebar transition-all duration-300">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={handleProjectSelect}
+14 -127
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import QRCode from 'qrcode';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } from 'lucide-react';
@@ -85,33 +85,17 @@ const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
interface LightningPaymentProps {
invoice: string;
amount: number;
paymentId: string;
provider: AIProvider;
onClose: () => void;
onPaymentCompleted: () => void;
}
function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPaymentCompleted }: LightningPaymentProps) {
function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { config } = useAppContext();
const queryClient = useQueryClient();
const [qrDataUrl, setQrDataUrl] = useState<string>('');
const [isWebLNAvailable, setIsWebLNAvailable] = useState(false);
const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false);
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false);
const [paymentCompleted, setPaymentCompleted] = useState(false);
const { toast } = useToast();
const formatCurrency = useCallback((amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
}, []);
useEffect(() => {
// Generate QR code
QRCode.toDataURL(invoice, {
@@ -129,98 +113,6 @@ function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPay
setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window);
}, [invoice]);
// Poll payment status
useEffect(() => {
// Don't poll if payment already completed
if (paymentCompleted) return;
let intervalId: NodeJS.Timeout | null = null;
const pollPaymentStatus = async () => {
// Double-check in case state updated during async operation
if (paymentCompleted) return;
try {
const ai = createAIClient(provider, user, config.corsProxy);
const payment = await ai.get(`/credits/payments/${paymentId}`) as Payment;
if (payment.status === 'completed') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
// Update credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Update payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Show toast
toast({
title: t('paymentCompleted'),
description: t('creditsAddedToAccount', { amount: formatCurrency(payment.amount) }),
});
// Close dialog immediately
onPaymentCompleted();
} else if (payment.status === 'failed') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
toast({
title: t('paymentFailed'),
description: t('paymentFailed'),
variant: 'destructive',
});
} else if (payment.status === 'expired') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
toast({
title: t('paymentExpired'),
description: t('paymentExpiredMessage'),
variant: 'destructive',
});
}
} catch (error) {
console.error('Failed to poll payment status:', error);
}
};
// Poll immediately on mount
pollPaymentStatus();
// Then poll every 3 seconds
intervalId = setInterval(pollPaymentStatus, 3000);
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
}, [paymentId, provider, user, config.corsProxy, queryClient, toast, t, onPaymentCompleted, formatCurrency, paymentCompleted]);
const handleWebLNPay = async () => {
if (!window.webln) return;
@@ -253,6 +145,15 @@ function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPay
setTimeout(() => setShowCopiedTooltip(false), 2000);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
return (
<div className="space-y-4">
<div className="text-center">
@@ -322,7 +223,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
const [amount, setAmount] = useState<number>(10);
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
const [lightningPaymentId, setLightningPaymentId] = useState<string | null>(null);
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
const [giftcardAmount, setGiftcardAmount] = useState<number>(10);
const [giftcardQuantity, setGiftcardQuantity] = useState<number>(1);
@@ -401,7 +301,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
} else if (payment.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(payment.url);
setLightningPaymentId(payment.id);
}
// Refresh payments list
@@ -587,7 +486,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
} else if (paymentPreview.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(paymentPreview.url);
setLightningPaymentId(paymentPreview.id);
}
// Refresh payments list
@@ -984,22 +882,12 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</DialogHeader>
{/* Lightning Payment Interface */}
{lightningInvoice && lightningPaymentId ? (
{lightningInvoice ? (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<LightningPayment
invoice={lightningInvoice}
amount={amount}
paymentId={lightningPaymentId}
provider={provider}
onClose={() => {
setLightningInvoice(null);
setLightningPaymentId(null);
}}
onPaymentCompleted={() => {
// Close the lightning payment view immediately
setLightningInvoice(null);
setLightningPaymentId(null);
}}
onClose={() => setLightningInvoice(null)}
/>
</div>
) : (
@@ -1166,7 +1054,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
setLightningPaymentId(payment.id);
} else {
window.open(payment.url, '_blank');
}
@@ -1285,7 +1172,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</AccordionItem>
{/* Your Gift Cards Accordion */}
<AccordionItem value="list">
<AccordionItem value="list" className="border-b-0">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
+2
View File
@@ -182,6 +182,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await git.checkout({
dir: projectPath,
ref: branchName,
force: true,
});
toast({
@@ -1288,6 +1289,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await git.checkout({
dir: projectPath,
ref: pr.sourceBranch,
force: true,
});
await refetchGitStatus();
toast({
+1 -1
View File
@@ -269,7 +269,7 @@ export function MCPServersSection() {
{/* Add New MCP Server */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-server">
<AccordionItem value="add-server" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
-67
View File
@@ -1,67 +0,0 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Alert,
AlertDescription,
AlertTitle,
} from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
interface NostrPermissionDialogProps {
open: boolean;
onResponse: (granted: boolean) => void;
}
export function NostrPermissionDialog({ open, onResponse }: NostrPermissionDialogProps) {
return (
<Dialog open={open} onOpenChange={(isOpen) => {
if (!isOpen) {
onResponse(false);
}
}}>
<DialogContent>
<DialogHeader>
<DialogTitle>Allow Nostr Access?</DialogTitle>
<DialogDescription className="space-y-3">
<p>
This project is requesting access to your Nostr signer (window.nostr).
</p>
<Alert variant="destructive">
<AlertTitle>Warning</AlertTitle>
<AlertDescription>
Granting access will allow this app to take actions on your behalf, including:
<ul className="list-disc list-inside mt-2 space-y-1">
<li>Read your public key</li>
<li>Sign events (publish posts, reactions, etc.)</li>
<li>Encrypt and decrypt messages</li>
</ul>
</AlertDescription>
</Alert>
<p className="text-sm text-muted-foreground">
Only grant access if you trust this application.
</p>
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2">
<Button
variant="outline"
onClick={() => onResponse(false)}
>
Deny
</Button>
<Button
onClick={() => onResponse(true)}
>
Allow
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -1,65 +0,0 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
interface NostrSignerRequiredDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function NostrSignerRequiredDialog({ open, onOpenChange }: NostrSignerRequiredDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Nostr Signer Required</DialogTitle>
<DialogDescription className="space-y-3">
<p>
This page tried to use a NIP-07 signer, but you don't have one installed!
</p>
<p>
Please install a Nostr signer extension to continue:
</p>
<div className="space-y-2 mt-4">
<a
href="https://github.com/soapbox-pub/soapbox-signer"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• Soapbox Signer
</a>
<a
href="https://getalby.com/"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• Alby
</a>
<a
href="https://github.com/fiatjaf/nos2x"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• nos2x
</a>
</div>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+11 -27
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';
import { Sparkles, X } from 'lucide-react';
import { Sparkles } from 'lucide-react';
/**
* Component that prompts users to update when a new service worker is available
@@ -52,38 +52,22 @@ export function PWAUpdatePrompt() {
updateServiceWorker(true);
};
const handleDismiss = (e: React.MouseEvent) => {
e.stopPropagation();
setShowPrompt(false);
};
if (!showPrompt) {
return null;
}
return (
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 md:top-4 md:right-4 md:bottom-auto md:left-auto md:translate-x-0 z-50 animate-in slide-in-from-bottom-4 md:slide-in-from-top-4 duration-500 max-w-full">
<div className="relative group">
<button
onClick={handleUpdate}
disabled={isUpdating}
className={`relative flex items-center gap-2 px-4 py-2.5 ${!isUpdating ? 'pr-10' : ''} bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate`}
>
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
</span>
</button>
{!isUpdating && (
<button
onClick={handleDismiss}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded-full hover:bg-amber-200 dark:hover:bg-amber-800 transition-colors duration-200"
aria-label="Dismiss update notification"
>
<X className="h-4 w-4 text-amber-700 dark:text-amber-300" />
</button>
)}
</div>
<button
onClick={handleUpdate}
disabled={isUpdating}
className="group relative flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate"
>
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
</span>
</button>
</div>
);
}
+1 -1
View File
@@ -122,7 +122,7 @@ export function PluginsSection() {
{/* Add Plugin Section */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-plugin">
<AccordionItem value="add-plugin" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
+6 -41
View File
@@ -1,10 +1,9 @@
import React, { useEffect, useState, useMemo } from 'react';
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, Search } 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 { Input } from '@/components/ui/input';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
@@ -94,24 +93,10 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const [searchQuery, setSearchQuery] = useState('');
const isMobile = useIsMobile();
const navigate = useNavigate();
// Fast in-memory search filtering
const filteredProjects = useMemo(() => {
if (!searchQuery.trim()) {
return projects;
}
const query = searchQuery.toLowerCase();
return projects.filter(project =>
project.id.toLowerCase().includes(query) ||
project.name.toLowerCase().includes(query)
);
}, [projects, searchQuery]);
// Custom navigate function that closes sidebar on mobile
const navigateAndClose = (path: string) => {
navigate(path);
@@ -181,12 +166,12 @@ export function ProjectSidebar({
<div className="flex-1 overflow-y-auto">
<div className="p-2">
<div className="mb-2 space-y-3">
<div className="mb-2">
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
<div className="flex">
<button
onClick={handleNewProject}
className="flex-1 flex items-center justify-center px-3 py-2.5 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
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"
>
<Plus className="h-4 w-4 mr-2" />
{t('newProject')}
@@ -194,7 +179,7 @@ export function ProjectSidebar({
<div className="w-px bg-white/20" />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="px-3 py-2.5 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<button className="px-2 py-2 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<ChevronDown className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
@@ -210,20 +195,6 @@ export function ProjectSidebar({
</DropdownMenu>
</div>
</div>
{/* Search Input */}
{projects.length > 0 && (
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
<Input
type="text"
placeholder={t('searchProjects')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 text-sm bg-sidebar-accent/50 border-sidebar-border focus-visible:ring-primary/50"
/>
</div>
)}
</div>
{isLoading ? (
@@ -243,15 +214,9 @@ export function ProjectSidebar({
<p className="text-sm">{t('noProjectsYet')}</p>
<p className="text-xs">{t('createFirstProject')}</p>
</div>
) : filteredProjects.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Search className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">{t('noProjectsFound')}</p>
<p className="text-xs">{t('tryDifferentSearch')}</p>
</div>
) : (
<div className="space-y-1">
{filteredProjects.map((project) => (
{projects.map((project) => (
<ProjectItem
key={project.id}
project={project}
+1 -7
View File
@@ -197,13 +197,7 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
message: error.message
? `AI service error: ${error.message}`
: 'Sorry, I encountered an unexpected error. Please try again.',
actions: onTryAgain ? [{
label: 'Try again',
onClick: () => {
onTryAgain();
onDismiss();
},
}] : [],
actions: [],
};
};
-99
View File
@@ -1,99 +0,0 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch } from 'lucide-react';
import type { Repository } from '@/hooks/useUserRepositories';
import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { genUserName } from '@/lib/genUserName';
import { useNavigate } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
interface RepositoryCardProps {
repo: Repository;
}
export function RepositoryCard({ repo }: RepositoryCardProps) {
const { data: authorData } = useAuthor(repo.pubkey);
const navigate = useNavigate();
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
const profileImage = authorData?.metadata?.picture;
// Construct Nostr clone URL
const nostrCloneUrl = `nostr://${nip19.npubEncode(repo.pubkey)}/${repo.repoId}`;
const handleClone = () => {
// Navigate to clone page with Nostr URL parameter
navigate(`/clone?url=${encodeURIComponent(nostrCloneUrl)}`);
};
return (
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow cursor-pointer" onClick={handleClone}>
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and author */}
<div className="mb-4">
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
{repo.name}
</h3>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Avatar className="h-4 w-4">
{profileImage && (
<AvatarImage src={profileImage} alt={displayName} />
)}
<AvatarFallback className="text-[8px]">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="truncate">{displayName}</span>
</div>
</div>
{/* Description */}
{repo.description && (
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
{repo.description}
</p>
)}
{/* Tags */}
{repo.repoTags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-4">
{repo.repoTags.slice(0, 3).map((tag, index) => (
<Badge key={index} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
{repo.repoTags.length > 3 && (
<Badge variant="secondary" className="text-xs">
+{repo.repoTags.length - 3}
</Badge>
)}
</div>
)}
{/* Personal fork badge */}
{repo.isPersonalFork && (
<div className="mb-4">
<Badge variant="outline" className="text-xs">
Personal Fork
</Badge>
</div>
)}
{/* Actions */}
<div className="mt-auto">
<Button
size="sm"
className="w-full"
onClick={handleClone}
>
<GitBranch className="h-4 w-4 mr-2" />
Clone
</Button>
</div>
</CardContent>
</Card>
);
}
-57
View File
@@ -1,57 +0,0 @@
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface SettingsItemProps {
icon: React.ComponentType<{ className?: string }>;
title: string;
onClick: () => void;
isActive?: boolean;
className?: string;
}
export function SettingsItem({
icon: Icon,
title,
onClick,
isActive = false,
className,
}: SettingsItemProps) {
return (
<button
onClick={onClick}
className={cn(
'group w-full text-left p-2 rounded-lg transition-all duration-200 border',
{
'bg-primary/10 border-primary/20 shadow-sm': isActive,
'border-transparent hover:bg-muted/60 hover:shadow-sm': !isActive,
},
className
)}
>
<div className="flex items-center gap-2.5">
<div className="rounded-md transition-all duration-200">
<Icon className={cn('h-4 w-4 flex-shrink-0 transition-colors duration-200', {
'text-primary': isActive,
'text-muted-foreground group-hover:text-foreground': !isActive,
})} />
</div>
<div className="flex-1 min-w-0">
<div className={cn('text-sm font-medium transition-colors duration-200', {
'text-primary': isActive,
'text-foreground': !isActive,
})}>
{title}
</div>
</div>
<ChevronRight className={cn(
'h-4 w-4 flex-shrink-0 transition-all duration-200',
'opacity-0 -translate-x-1 group-hover:opacity-100 group-hover:translate-x-0',
{
'text-primary opacity-60': isActive,
'text-muted-foreground': !isActive,
}
)} />
</div>
</button>
);
}
-43
View File
@@ -1,43 +0,0 @@
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface SettingsItemMobileProps {
icon: React.ComponentType<{ className?: string }>;
title: string;
onClick: () => void;
isFirst?: boolean;
isLast?: boolean;
}
export function SettingsItemMobile({
icon: Icon,
title,
onClick,
isFirst = false,
isLast = false,
}: SettingsItemMobileProps) {
return (
<button
onClick={onClick}
className={cn(
'w-full text-left px-4 py-3.5 bg-background transition-colors active:bg-muted/50',
'flex items-center gap-3',
'border-b border-border last:border-b-0',
{
'rounded-t-xl': isFirst,
'rounded-b-xl': isLast,
}
)}
>
<div className="flex items-center justify-center w-7 h-7 rounded-lg bg-primary/10">
<Icon className="h-4 w-4 text-primary flex-shrink-0" />
</div>
<div className="flex-1 min-w-0">
<div className="text-base text-foreground">
{title}
</div>
</div>
<ChevronRight className="h-5 w-5 text-muted-foreground/50 flex-shrink-0" />
</button>
);
}
+36 -31
View File
@@ -8,8 +8,8 @@ import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile';
import { type Project } from '@/lib/ProjectsManager';
import { getSettingsCategories } from '@/lib/settingsItems';
import { SettingsItem } from '@/components/SettingsItem';
import { cn } from '@/lib/utils';
import { getSettingsItems } from '@/lib/settingsItems';
export function SettingsLayout() {
const { t } = useTranslation();
@@ -60,11 +60,9 @@ export function SettingsLayout() {
};
// Get current settings page
const settingsCategories = getSettingsCategories(t);
const settingsItems = getSettingsItems(t);
const currentPath = location.pathname;
const currentSettingsId = settingsCategories
.flatMap(category => category.items)
.find(item => item.href === currentPath)?.id;
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
if (isMobile) {
return (
@@ -91,7 +89,7 @@ export function SettingsLayout() {
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={null}
onSelectProject={(project) => {
@@ -114,7 +112,7 @@ export function SettingsLayout() {
<div className="h-screen flex bg-background overflow-hidden">
{/* Left Column - Projects Sidebar (optionally hidden) */}
{isSidebarVisible && (
<div className="w-72 border-r bg-sidebar flex-shrink-0">
<div className="w-80 border-r bg-sidebar flex-shrink-0">
<ProjectSidebar
selectedProject={null}
onSelectProject={handleProjectSelect}
@@ -125,7 +123,7 @@ export function SettingsLayout() {
)}
{/* Middle Column - Settings Navigation */}
<div className="w-72 border-r bg-background flex flex-col flex-shrink-0">
<div className="w-96 border-r bg-background flex flex-col flex-shrink-0">
{/* Header with toggle button */}
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
<div className="flex items-center gap-3">
@@ -148,29 +146,36 @@ export function SettingsLayout() {
{/* Settings Navigation - Scrollable */}
<ScrollArea className="flex-1">
<div className="p-4 space-y-6">
{settingsCategories.map((category) => (
<div key={category.id}>
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-2">
{category.title}
</h3>
<div className="space-y-1">
{category.items.map((item) => {
const isActive = currentSettingsId === item.id;
<div className="p-4">
<div className="space-y-2">
{settingsItems.map((item) => {
const Icon = item.icon;
const isActive = currentSettingsId === item.id;
return (
<SettingsItem
key={item.id}
icon={item.icon}
title={item.title}
onClick={() => navigate(item.href)}
isActive={isActive}
/>
);
})}
</div>
</div>
))}
return (
<button
key={item.id}
onClick={() => navigate(item.href)}
className={cn('w-full text-left p-3 rounded-lg transition-colors border border-transparent', {
'bg-primary/10 border border-primary/20': isActive,
'hover:bg-muted/50': !isActive,
})}
>
<div className="flex items-start gap-3">
<Icon className={`h-5 w-5 mt-0.5 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
<div className="flex-1 min-w-0">
<div className={`font-medium ${isActive ? 'text-primary' : 'text-foreground'}`}>
{item.title}
</div>
<div className="text-sm text-muted-foreground mt-0.5">
{item.description}
</div>
</div>
</div>
</button>
);
})}
</div>
</div>
</ScrollArea>
</div>
+3 -180
View File
@@ -7,7 +7,6 @@ import { useFSPaths } from '@/hooks/useFSPaths';
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useBuildProject } from '@/hooks/useBuildProject';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
@@ -26,8 +25,6 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { NostrPermissionDialog } from '@/components/NostrPermissionDialog';
import { NostrSignerRequiredDialog } from '@/components/NostrSignerRequiredDialog';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -60,16 +57,6 @@ interface JSONRPCRequest {
id: number;
}
interface NostrRPCRequest {
jsonrpc: '2.0';
method: 'nostr';
params: {
method: string;
args: unknown[];
};
id: number;
}
interface JSONRPCResponse {
jsonrpc: '2.0';
result?: {
@@ -106,7 +93,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const projectsManager = useProjectsManager();
const { user } = useCurrentUser();
// Use console error state from provider
const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError();
@@ -333,155 +319,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
// Track which projects have been granted Nostr access
const [nostrPermissions, setNostrPermissions] = useState<Set<string>>(new Set());
const [nostrPermissionDialog, setNostrPermissionDialog] = useState<{
open: boolean;
projectId: string;
resolve: (granted: boolean) => void;
} | null>(null);
const [noSignerDialog, setNoSignerDialog] = useState(false);
const requestNostrPermission = useCallback(async (projectId: string): Promise<boolean> => {
// Check if permission already granted
if (nostrPermissions.has(projectId)) {
return true;
}
// Show permission dialog and wait for user response
return new Promise<boolean>((resolve) => {
setNostrPermissionDialog({
open: true,
projectId,
resolve,
});
});
}, [nostrPermissions]);
const handleNostrPermissionResponse = useCallback((granted: boolean) => {
if (nostrPermissionDialog) {
const { projectId, resolve } = nostrPermissionDialog;
if (granted) {
// Grant permission for this project
setNostrPermissions(prev => new Set([...prev, projectId]));
}
// Close dialog and resolve the promise
setNostrPermissionDialog(null);
resolve(granted);
}
}, [nostrPermissionDialog]);
const handleNostr = useCallback(async (request: NostrRPCRequest) => {
const { params, id } = request;
const { method, args } = params;
console.log('[NOSTR BRIDGE] Handling request:', method, args);
try {
// Check if user is logged in with a signer
if (!user?.signer) {
// Show the "no signer" dialog
setNoSignerDialog(true);
throw new Error('NO_SIGNER_INSTALLED');
}
// Request permission if this is the first Nostr access from this project
const hasPermission = await requestNostrPermission(projectId);
if (!hasPermission) {
throw new Error('User denied Nostr access');
}
let result: unknown;
// Route to appropriate signer method
switch (method) {
case 'getPublicKey':
result = await user.signer.getPublicKey();
break;
case 'signEvent':
if (!args[0] || typeof args[0] !== 'object') {
throw new Error('Invalid event object');
}
result = await user.signer.signEvent(args[0] as Parameters<typeof user.signer.signEvent>[0]);
break;
case 'nip04.encrypt':
if (!user.signer.nip04?.encrypt) {
throw new Error('NIP-04 encryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip04.encrypt');
}
result = await user.signer.nip04.encrypt(args[0], args[1]);
break;
case 'nip04.decrypt':
if (!user.signer.nip04?.decrypt) {
throw new Error('NIP-04 decryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip04.decrypt');
}
result = await user.signer.nip04.decrypt(args[0], args[1]);
break;
case 'nip44.encrypt':
if (!user.signer.nip44?.encrypt) {
throw new Error('NIP-44 encryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip44.encrypt');
}
result = await user.signer.nip44.encrypt(args[0], args[1]);
break;
case 'nip44.decrypt':
if (!user.signer.nip44?.decrypt) {
throw new Error('NIP-44 decryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip44.decrypt');
}
result = await user.signer.nip44.decrypt(args[0], args[1]);
break;
default:
throw new Error(`Unsupported Nostr method: ${method}`);
}
console.log('[NOSTR BRIDGE] Success:', method, result);
// Send success response
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage({
jsonrpc: '2.0',
result,
id
}, targetOrigin);
}
} catch (error) {
console.error('[NOSTR BRIDGE] Error:', method, error);
// Send error response
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage({
jsonrpc: '2.0',
error: {
code: -32000,
message: error instanceof Error ? error.message : String(error),
},
id
}, targetOrigin);
}
}
}, [user, projectId, previewDomain, requestNostrPermission]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -604,7 +441,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
// Verify origin for security
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message with source ${event.data.source} from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
return;
}
@@ -612,8 +449,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'nostr') {
handleNostr(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
handleConsoleMessage(message);
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
@@ -623,7 +458,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleNostr, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
useEffect(() => {
if (selectedFile) {
@@ -1113,18 +948,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
onOpenChange={setDeployDialogOpen}
/>
)}
{/* Nostr Permission Dialog */}
<NostrPermissionDialog
open={nostrPermissionDialog?.open ?? false}
onResponse={handleNostrPermissionResponse}
/>
{/* No Signer Installed Dialog */}
<NostrSignerRequiredDialog
open={noSignerDialog}
onOpenChange={setNoSignerDialog}
/>
</div>
);
}
}
+1
View File
@@ -223,6 +223,7 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
await git.checkout({
dir: projectPath,
ref: branchName,
force: true,
});
toast({
+1 -1
View File
@@ -12,7 +12,7 @@ const AccordionItem = React.forwardRef<
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border rounded-lg bg-card text-card-foreground shadow-sm", className)}
className={cn("border-b", className)}
{...props}
/>
))
+1 -1
View File
@@ -11,7 +11,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-xs border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
+1 -1
View File
@@ -17,7 +17,7 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:bg-border/20 dark:hover:bg-border/50 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
-43
View File
@@ -1,43 +0,0 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
/**
* Hook to get the user's contact list (kind 3 follow list)
* Returns an array of pubkeys that the user follows
*/
export function useContacts(userPubkey?: string) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'contacts', userPubkey],
queryFn: async (): Promise<string[]> => {
if (!userPubkey) {
return [];
}
// Get the user's contact list (kind 3)
const events = await nostr.query([{
kinds: [3],
authors: [userPubkey],
limit: 1,
}], { signal: AbortSignal.timeout(3000) });
if (events.length === 0) {
return [];
}
// Get the most recent contact list event
const contactList = events.sort((a, b) => b.created_at - a.created_at)[0];
// Extract pubkeys from 'p' tags
const followedPubkeys = contactList.tags
.filter(tag => tag[0] === 'p' && tag[1])
.map(tag => tag[1]);
return followedPubkeys;
},
enabled: !!userPubkey,
staleTime: 60000, // 1 minute
refetchInterval: 300000, // 5 minutes
});
}
-92
View File
@@ -1,92 +0,0 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import type { Repository } from './useUserRepositories';
// Kind 30617 for repository announcements (NIP-34)
const REPOSITORY_KIND = 30617;
/**
* Hook to get repositories from a list of followed users
*/
export function useFollowedRepositories(followedPubkeys: string[] = []) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
queryFn: async (): Promise<Repository[]> => {
if (followedPubkeys.length === 0) {
return [];
}
// Get all repository announcements from followed users
const events = await nostr.query([{
kinds: [REPOSITORY_KIND],
authors: followedPubkeys,
limit: 500, // Increased limit to get more repos from follows
}], { signal: AbortSignal.timeout(5000) });
// Process repository events
const repositories: Repository[] = [];
const repoMap = new Map<string, NostrEvent>();
// Group by author+d-tag to get latest version of each repo
for (const event of events) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const key = `${event.pubkey}:${dTag}`;
const existing = repoMap.get(key);
if (!existing || event.created_at > existing.created_at) {
repoMap.set(key, event);
}
}
// Convert to Repository objects
for (const [, event] of repoMap) {
try {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
// Filter out invalid repositories without clone URLs
if (cloneUrls.length === 0) {
console.warn('Skipping repository without clone URLs:', dTag);
continue;
}
repositories.push({
...event,
repoId: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
repoTags,
earliestUniqueCommit,
isPersonalFork,
});
} catch (error) {
console.warn('Failed to parse repository:', error);
}
}
// Sort by created_at (newest first)
return repositories.sort((a, b) => b.created_at - a.created_at);
},
enabled: followedPubkeys.length > 0,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
-96
View File
@@ -1,96 +0,0 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
// Kind 30617 for repository announcements (NIP-34)
const REPOSITORY_KIND = 30617;
export interface Repository extends NostrEvent {
repoId: string;
name: string;
description: string;
webUrls: string[];
cloneUrls: string[];
relays: string[];
maintainers: string[];
repoTags: string[];
earliestUniqueCommit?: string;
isPersonalFork: boolean;
}
export function useUserRepositories(userPubkey?: string) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'user-repositories', userPubkey],
queryFn: async (): Promise<Repository[]> => {
if (!userPubkey) {
return [];
}
// Get all repository announcements for this user
const events = await nostr.query([{
kinds: [REPOSITORY_KIND],
authors: [userPubkey],
limit: 100,
}], { signal: AbortSignal.timeout(3000) });
// Process repository events
const repositories: Repository[] = [];
const repoMap = new Map<string, NostrEvent>();
// Group by d-tag (repo-id) to get latest version
for (const event of events) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const existing = repoMap.get(dTag);
if (!existing || event.created_at > existing.created_at) {
repoMap.set(dTag, event);
}
}
// Convert to Repository objects
for (const [dTag, event] of repoMap) {
try {
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
// Filter out invalid repositories without clone URLs
if (cloneUrls.length === 0) {
console.warn('Skipping repository without clone URLs:', dTag);
continue;
}
repositories.push({
...event,
repoId: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
repoTags,
earliestUniqueCommit,
isPersonalFork,
});
} catch (error) {
console.warn('Failed to parse repository:', error);
}
}
return repositories;
},
enabled: !!userPubkey,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
+1 -1
View File
@@ -37,7 +37,7 @@
--input: 220 13% 91%;
--ring: 271 81% 56%;
--radius: 0.75rem;
--radius: 0.375rem;
/* Sidebar colors - Enhanced purple theme */
--sidebar-background: 271 81% 96%;
+2
View File
@@ -122,6 +122,7 @@ export class GitCheckoutCommand implements GitSubcommand {
await this.git.checkout({
dir: cwd,
ref: branchName,
force: true,
});
return createSuccessResult(`Switched to branch '${branchName}'\n`);
@@ -164,6 +165,7 @@ export class GitCheckoutCommand implements GitSubcommand {
await this.git.checkout({
dir: cwd,
ref: branchName,
force: true,
});
return createSuccessResult(`Switched to a new branch '${branchName}'\n`);
+1
View File
@@ -1244,6 +1244,7 @@ export class Git {
fs: this.fs,
dir: options.dir,
ref: expectedBranch,
force: true,
});
} catch (checkoutError) {
console.warn(`Failed to checkout branch ${expectedBranch}:`, checkoutError);
+55 -70
View File
@@ -2,87 +2,72 @@ import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } fro
export interface SettingsItem {
id: string;
icon: React.ComponentType<{ className?: string }>;
title: string;
description: string;
icon: React.ComponentType<{ className?: string }>;
href: string;
}
export interface SettingsCategory {
id: string;
title: string;
items: SettingsItem[];
}
/**
* Get the categorized list of settings items with translations
* Get the list of settings items with translations
* @param t - Translation function from useTranslation hook
* @returns Array of settings categories with translated items
* @returns Array of settings items
*/
export const getSettingsCategories = (t: (key: string) => string): SettingsCategory[] => [
export const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
{
id: 'general',
title: t('general'),
items: [
{
id: 'preferences',
icon: Settings2,
title: t('preferences'),
href: '/settings/preferences',
},
],
id: 'preferences',
title: t('preferences'),
description: t('preferencesDescription'),
icon: Settings2,
href: '/settings/preferences',
},
{
id: 'integrations',
title: t('integrations'),
items: [
{
id: 'ai',
icon: Bot,
title: t('aiSettings'),
href: '/settings/ai',
},
{
id: 'git',
icon: GitBranch,
title: t('gitSettings'),
href: '/settings/git',
},
{
id: 'nostr',
icon: Wifi,
title: t('nostrSettings'),
href: '/settings/nostr',
},
{
id: 'deploy',
icon: Rocket,
title: t('deploySettings'),
href: '/settings/deploy',
},
],
id: 'ai',
title: t('aiSettings'),
description: t('aiSettingsDescription'),
icon: Bot,
href: '/settings/ai',
},
{
id: 'advanced',
title: t('advanced'),
items: [
{
id: 'storage',
icon: Database,
title: t('storageSettings'),
href: '/settings/storage',
},
{
id: 'system',
icon: Settings,
title: t('systemSettings'),
href: '/settings/system',
},
{
id: 'about',
icon: Info,
title: t('aboutShakespeare'),
href: '/settings/about',
},
],
id: 'git',
title: t('gitSettings'),
description: t('gitSettingsDescription'),
icon: GitBranch,
href: '/settings/git',
},
{
id: 'deploy',
title: t('deploySettings'),
description: t('deploySettingsDescription'),
icon: Rocket,
href: '/settings/deploy',
},
{
id: 'nostr',
title: t('nostrSettings'),
description: t('nostrSettingsDescription'),
icon: Wifi,
href: '/settings/nostr',
},
{
id: 'storage',
title: t('storageSettings'),
description: t('storageSettingsDescription'),
icon: Database,
href: '/settings/storage',
},
{
id: 'system',
title: t('systemSettings'),
description: t('systemSettingsDescription'),
icon: Settings,
href: '/settings/system',
},
{
id: 'about',
title: t('aboutShakespeare'),
description: t('aboutShakespeareDescription'),
icon: Info,
href: '/settings/about',
},
];
+4 -4
View File
@@ -29,7 +29,7 @@ export const defaultSystemPrompt = `{% if mode === "init" %}You are Shakespeare,
# Your Environment
You are operating within **Shakespeare**, an AI-powered website builder that allows users to create custom applications through natural language conversation.
You are operating within **Shakespeare**, an AI-powered Nostr website builder that allows users to create custom Nostr applications through natural language conversation.
- **Current Date**: {{ date }}
- **Current Page**: {{ location.href }}
@@ -38,7 +38,7 @@ You are operating within **Shakespeare**, an AI-powered website builder that all
## What Shakespeare Is
Shakespeare is a web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
Shakespeare is a web-based development environment where users can build Nostr websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
**Important Architecture Notes:**
@@ -140,11 +140,11 @@ Shakespeare operates on a browser-based virtual filesystem (VFS) that persists a
As the AI assistant in Shakespeare, you help users by:
- Understanding their requirements through natural conversation
- Writing and modifying code files to build their applications
- Writing and modifying code files to build their Nostr applications
- Explaining technical concepts in accessible terms
- Providing suggestions and best practices
- Troubleshooting issues and implementing fixes
- Building complete, functional websites and applications
- Building complete, functional Nostr websites and applications
- Learning from existing projects in the VFS to provide better solutions
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.
-54
View File
@@ -185,58 +185,4 @@ describe('GitCommitTool', () => {
expect(result).toContain('✅ Successfully committed');
});
it('should error when HEAD is detached (currentBranch returns null)', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state - currentBranch returns null
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(null);
await expect(tool.execute({ message: 'Test commit' })).rejects.toThrow('❌ Cannot commit: Git is in a detached HEAD state');
// Verify commit was never called
expect(mockGitInstance.commit).not.toHaveBeenCalled();
});
it('should error when HEAD is detached (currentBranch returns undefined)', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state - currentBranch returns undefined
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(undefined);
await expect(tool.execute({ message: 'Test commit' })).rejects.toThrow('❌ Cannot commit: Git is in a detached HEAD state');
// Verify commit was never called
expect(mockGitInstance.commit).not.toHaveBeenCalled();
});
it('should provide helpful instructions when HEAD is detached', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(null);
try {
await tool.execute({ message: 'Test commit' });
expect.fail('Should have thrown an error');
} catch (error) {
const errorMessage = (error as Error).message;
// Verify the error message contains safe instructions that preserve changes
expect(errorMessage).toContain('git checkout -b temp-branch');
expect(errorMessage).toContain('try the commit again');
expect(errorMessage).toContain('preserving all changes');
}
});
});
+10 -20
View File
@@ -41,26 +41,6 @@ export class GitCommitTool implements Tool<GitCommitParams> {
throw new Error(`❌ Commit message cannot be empty.`);
}
// Check for detached HEAD state before doing any work
// currentBranch returns null when HEAD is detached
const currentBranch = await this.git.currentBranch({
dir: this.cwd,
});
if (currentBranch === null || currentBranch === undefined) {
throw new Error(
`❌ Cannot commit: Git is in a detached HEAD state.\n\n` +
`This usually happens after checking out a specific commit. ` +
`Your changes need to be on a branch before committing.\n\n` +
`To fix this and preserve your staged changes:\n` +
` 1. Run: git checkout -b temp-branch\n` +
` (This creates a new branch from your current state, preserving all changes)\n` +
` 2. Then try the commit again\n` +
` 3. After committing, you can merge to main with:\n` +
` git checkout main && git merge temp-branch`
);
}
// Get git status to see what files have changed
const statusMatrix = await this.git.statusMatrix({
dir: this.cwd,
@@ -99,6 +79,16 @@ export class GitCommitTool implements Tool<GitCommitParams> {
}
}
// Get current branch name
let currentBranch = 'main';
try {
currentBranch = await this.git.currentBranch({
dir: this.cwd,
}) || 'main';
} catch {
// Default to 'main' if we can't get the current branch
}
// Commit the changes (author/committer will be set automatically by Git class)
const commitSha = await this.git.commit({
dir: this.cwd,
+6 -6
View File
@@ -3,9 +3,6 @@
"settings": "Settings",
"backToSettings": "Back to Settings",
"help": "Help",
"general": "General",
"integrations": "Integrations",
"advanced": "Advanced",
"anonymous": "Anonymous",
"logIn": "Log in",
"signUp": "Sign up",
@@ -97,12 +94,14 @@
"chooseModel": "Choose a model...",
"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...",
"settingsDescription": "Manage your application settings and preferences.",
"aiSettings": "AI",
"aiSettingsDescription": "Configure AI providers and API keys",
"gitSettings": "Git",
"gitSettingsDescription": "Configure Git credentials for HTTP authentication",
"deploySettings": "Deployment",
"deploySettingsDescription": "Configure deployment providers",
"deploySettingsDescriptionLong": "Configure deployment providers to deploy your projects to various hosting platforms.",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "Configure relay connections and Nostr preferences",
"storageSettings": "Storage",
@@ -113,9 +112,6 @@
"importRepository": "Import Repository",
"noProjectsYet": "No projects yet",
"createFirstProject": "Create your first project to get started",
"searchProjects": "Search projects...",
"noProjectsFound": "No projects found",
"tryDifferentSearch": "Try a different search term",
"closeSidebar": "Close sidebar",
"collapseSidebar": "Collapse sidebar",
"welcomeToShakespeare": "Welcome to Shakespeare",
@@ -183,6 +179,7 @@
"pushFailed": "Push failed",
"pullSuccessful": "Pull successful",
"pullFailed": "Pull failed",
"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",
@@ -208,6 +205,7 @@
"shakespeareDeployNostrAuth": "This provider uses Nostr authentication. Make sure you are logged in to deploy.",
"providerType": "Provider Type",
"selectProviderType": "Select a provider type",
"gitSettingsDescriptionLong": "Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.",
"configuredCredentials": "Configured Credentials",
"origin": "Origin",
"username": "Username",
@@ -228,6 +226,7 @@
"license": "License",
"loadingLicense": "Loading license...",
"failedToLoadLicense": "Failed to load license",
"dataSettingsDescriptionLong": "Export files and manage local data.",
"offlineCache": "Offline Cache",
"offlineCacheDescription": "Shakespeare caches files locally to enable offline functionality. Clear the cache to free up space or troubleshoot issues.",
"cacheSize": "Cache size",
@@ -295,6 +294,7 @@
"untracked": "untracked",
"toggleSidebar": "Toggle sidebar",
"openSidebar": "Open sidebar",
"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",
+4 -6
View File
@@ -3,9 +3,6 @@
"settings": "Saitunan",
"backToSettings": "Koma zuwa Saitunan",
"help": "Taimako",
"general": "Gabaɗaya",
"integrations": "Haɗin Kai",
"advanced": "Ci Gaba",
"anonymous": "Maras Suna",
"logIn": "Shiga",
"signUp": "Yi Rajista",
@@ -108,9 +105,6 @@
"importRepository": "Shigo da Repository",
"noProjectsYet": "Babu ayyuka har yanzu",
"createFirstProject": "Ƙirƙiri aikin farko don farawa",
"searchProjects": "Nemo ayyuka...",
"noProjectsFound": "Ba a sami ayyuka ba",
"tryDifferentSearch": "Gwada kalmar nema daban",
"closeSidebar": "Rufe gefen mashigi",
"collapseSidebar": "Rufe gefen mashigi",
"welcomeToShakespeare": "Maraba da Shakespeare",
@@ -178,6 +172,7 @@
"pushFailed": "Turawa ta gaza",
"pullSuccessful": "Ja ya yi nasara",
"pullFailed": "Ja ya gaza",
"aiSettingsDescriptionLong": "Saita masu samar da AI ta hanyar ƙara maɓallan API. Saitunan ana ajiye su kai tsaye kuma ana adana su a cikin burauzar ku.",
"configuredProviders": "Masu Samarwa da aka Saita",
"addProvider": "Ƙara Mai Samarwa",
"getApiKey": "Sami maɓallin API",
@@ -203,6 +198,7 @@
"shakespeareDeployNostrAuth": "Wannan mai samarwa yana amfani da tabbatar da Nostr. Tabbatar cewa kun shiga don tura.",
"providerType": "Nau'in Mai Samarwa",
"selectProviderType": "Zaɓi nau'in mai samarwa",
"gitSettingsDescriptionLong": "Saita bayanan shaidar Git don tabbatar da HTTP. Saitunan ana ajiye su kai tsaye kuma ana adana su a cikin burauzar ku.",
"configuredCredentials": "Bayanan Shaidar da aka Saita",
"origin": "Asali",
"username": "Sunan mai amfani",
@@ -214,6 +210,7 @@
"gitEmail": "Imel Git",
"coAuthoredByShakespeare": "Haɗin marubuta da Shakespeare",
"gitIdentityDescription": "Idan an saita suna da imel, za a yi amfani da su azaman marubucin aikin. In ba haka ba, za a yi amfani da shakespeare.diy. Lokacin da aka kunna haɗin marubuta, za a ƙara Shakespeare azaman haɗin marubuta.",
"dataSettingsDescriptionLong": "Fitar da fayiloli da sarrafa bayanan gida.",
"exportFiles": "Fitar da Fayiloli",
"exportFilesDescription": "Sauke duk ayyukanku da fayiloli azaman ajiyar ZIP. Wannan ya haɗa da duk fayilolin aikin, saitunan, da bayanan da aka adana a gida.",
"exportAllFiles": "Fitar da Duk Fayiloli",
@@ -283,6 +280,7 @@
"untracked": "ba a bi ba",
"toggleSidebar": "Juya gefen mashigi",
"openSidebar": "Buɗe gefen mashigi",
"nostrSettingsDescriptionLong": "Saita saitunan haɗin Nostr da zaɓuɓɓukan relay.",
"nostrAccounts": "Asusun Nostr",
"noAccountsLoggedIn": "Babu asusun da aka shiga. Ƙara asusu don farawa.",
"createAccount": "Ƙirƙiri Asusu",
+4 -6
View File
@@ -3,9 +3,6 @@
"settings": "Ntọala",
"backToSettings": "Laghachi na Ntọala",
"help": "Enyemaka",
"general": "Izugbe",
"integrations": "Njikọta",
"advanced": "Dị elu",
"anonymous": "Onye na-amaghị aha",
"logIn": "Banye",
"signUp": "Debanye aha",
@@ -108,9 +105,6 @@
"importRepository": "Bubata Repository",
"noProjectsYet": "Enwebeghị ọrụ ọ bụla",
"createFirstProject": "Mepụta ọrụ mbụ gị iji malite",
"searchProjects": "Chọọ ọrụ...",
"noProjectsFound": "Achọtaghị ọrụ ọ bụla",
"tryDifferentSearch": "Nwalee okwu ọchụchọ dị iche",
"closeSidebar": "Mechie sidebar",
"collapseSidebar": "Gbakọọ sidebar",
"welcomeToShakespeare": "Nnọọ na Shakespeare",
@@ -178,6 +172,7 @@
"pushFailed": "Nkwanye dara",
"pullSuccessful": "Ndọta gara nke ọma",
"pullFailed": "Ndọta dara",
"aiSettingsDescriptionLong": "Hazie ndị na-enye AI site na ịtinye igodo API gị. Ntọala na-echekwa onwe ya ma chekwaa ya na mpaghara na browser gị.",
"configuredProviders": "Ndị Na-enye Ahaziri",
"addProvider": "Tinye Onye Na-enye",
"getApiKey": "Nweta igodo API",
@@ -203,6 +198,7 @@
"shakespeareDeployNostrAuth": "Onye na-enye a na-eji nkwenye Nostr. Jide n'aka na ị banyere iji bufee.",
"providerType": "Ụdị Onye Na-enye",
"selectProviderType": "Họrọ ụdị onye na-enye",
"gitSettingsDescriptionLong": "Hazie nzere Git maka nkwenye HTTP. Ntọala na-echekwa onwe ya ma chekwaa ya na mpaghara na browser gị.",
"configuredCredentials": "Nzere Ahaziri",
"origin": "Mmalite",
"username": "Aha onye ọrụ",
@@ -214,6 +210,7 @@
"gitEmail": "Ozi-eletrọniki Git",
"coAuthoredByShakespeare": "Ndekọ ọnụ na Shakespeare",
"gitIdentityDescription": "Ọ bụrụ na ahaziri aha na ozi-eletrọniki, a ga-eji ha dị ka onye dere ya. Ma ọ bụghị, a ga-eji shakespeare.diy. Mgbe emere ndekọ ọnụ, a ga-etinye Shakespeare dị ka ndekọ ọnụ.",
"dataSettingsDescriptionLong": "Bupụta faịlụ ma jikwaa data mpaghara.",
"exportFiles": "Bupụta Faịlụ",
"exportFilesDescription": "Budata ọrụ gị niile na faịlụ dị ka mkpokọta ZIP. Nke a gụnyere faịlụ ọrụ niile, ntọala, na data echekwara na mpaghara.",
"exportAllFiles": "Bupụta Faịlụ Niile",
@@ -280,6 +277,7 @@
"untracked": "na-esoghị",
"toggleSidebar": "Gbanwee sidebar",
"openSidebar": "Meghee sidebar",
"nostrSettingsDescriptionLong": "Hazie ntọala njikọ Nostr gị na nhọrọ relay.",
"nostrAccounts": "Akaụntụ Nostr",
"noAccountsLoggedIn": "Enweghị akaụntụ banyere. Tinye akaụntụ iji malite.",
"createAccount": "Mepụta Akaụntụ",
+5 -6
View File
@@ -3,9 +3,6 @@
"settings": "Configurações",
"backToSettings": "Voltar às Configurações",
"help": "Ajuda",
"general": "Geral",
"integrations": "Integrações",
"advanced": "Avançado",
"anonymous": "Anônimo",
"logIn": "Entrar",
"signUp": "Cadastrar",
@@ -100,6 +97,7 @@
"gitSettingsDescription": "Configure credenciais do Git para autenticação HTTP",
"deploySettings": "Implantação",
"deploySettingsDescription": "Configure provedores de implantação",
"deploySettingsDescriptionLong": "Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "Configure conexões de relay e preferências do Nostr",
"storageSettings": "Armazenamento",
@@ -110,9 +108,6 @@
"importRepository": "Importar Repositório",
"noProjectsYet": "Nenhum projeto ainda",
"createFirstProject": "Crie seu primeiro projeto para começar",
"searchProjects": "Pesquisar projetos...",
"noProjectsFound": "Nenhum projeto encontrado",
"tryDifferentSearch": "Tente um termo de pesquisa diferente",
"closeSidebar": "Fechar barra lateral",
"collapseSidebar": "Recolher barra lateral",
"welcomeToShakespeare": "Bem-vindo ao Shakespeare",
@@ -180,6 +175,7 @@
"pushFailed": "Push falhou",
"pullSuccessful": "Pull realizado com sucesso",
"pullFailed": "Pull falhou",
"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",
@@ -205,6 +201,7 @@
"shakespeareDeployNostrAuth": "Este provedor usa autenticação Nostr. Certifique-se de estar logado para implantar.",
"providerType": "Tipo de Provedor",
"selectProviderType": "Selecione um tipo de provedor",
"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",
@@ -216,6 +213,7 @@
"gitEmail": "Email Git",
"coAuthoredByShakespeare": "Co-autoria de Shakespeare",
"gitIdentityDescription": "Se nome e email estiverem configurados, eles serão usados como autor do commit. Caso contrário, shakespeare.diy será usado. Quando co-autoria estiver ativada, Shakespeare será adicionado como co-autor.",
"dataSettingsDescriptionLong": "Exporte arquivos e gerencie dados locais.",
"offlineCache": "Cache Offline",
"offlineCacheDescription": "O Shakespeare armazena arquivos localmente para permitir funcionalidade offline. Limpe o cache para liberar espaço ou solucionar problemas.",
"cacheSize": "Tamanho do cache",
@@ -292,6 +290,7 @@
"untracked": "não rastreado",
"toggleSidebar": "Alternar barra lateral",
"openSidebar": "Abrir barra lateral",
"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",
+4 -6
View File
@@ -3,9 +3,6 @@
"settings": "Awọn eto",
"backToSettings": "Pada si Awọn eto",
"help": "Iranlọwọ",
"general": "Gbogbogbo",
"integrations": "Awọn isopọ",
"advanced": "To siwaju",
"anonymous": "Alainidamọ",
"logIn": "Wọle",
"signUp": "Forukọsilẹ",
@@ -108,9 +105,6 @@
"importRepository": "Gbe Repository wọle",
"noProjectsYet": "Ko si awọn iṣẹ akanṣe sibẹsibẹ",
"createFirstProject": "Ṣẹda iṣẹ akanṣe akọkọ rẹ lati bẹrẹ",
"searchProjects": "Wa awọn iṣẹ akanṣe...",
"noProjectsFound": "Ko ri awọn iṣẹ akanṣe",
"tryDifferentSearch": "Gbiyanju ọrọ wiwa miiran",
"closeSidebar": "Ti ẹgbẹ sidebar",
"collapseSidebar": "Subu sidebar",
"welcomeToShakespeare": "Kaabo si Shakespeare",
@@ -178,6 +172,7 @@
"pushFailed": "Titari kuna",
"pullSuccessful": "Fifa ni aṣeyọri",
"pullFailed": "Fifa kuna",
"aiSettingsDescriptionLong": "Tunto awọn olupese AI nipa fifi awọn bọtini API rẹ kun. Awọn eto ni a fi pamọ laifọwọyi ati pe a tọju wọn ni agbegbe ninu awọn aṣawakiri rẹ.",
"configuredProviders": "Awọn Olupese Ti a Tunto",
"addProvider": "Fi Olupese kun",
"getApiKey": "Gba bọtini API",
@@ -203,6 +198,7 @@
"shakespeareDeployNostrAuth": "Olupese yii nlo ijẹrisi Nostr. Rii daju pe o ti wọle lati gbe jade.",
"providerType": "Iru Olupese",
"selectProviderType": "Yan iru olupese kan",
"gitSettingsDescriptionLong": "Tunto awọn ẹri Git fun ijẹrisi HTTP. Awọn eto ni a fi pamọ laifọwọyi ati pe a tọju wọn ni agbegbe ninu awọn aṣawakiri rẹ.",
"configuredCredentials": "Awọn Ẹri Ti a Tunto",
"origin": "Ipilẹṣẹ",
"username": "Orukọ olumulo",
@@ -214,6 +210,7 @@
"gitEmail": "Imeeli Git",
"coAuthoredByShakespeare": "Ajọpọ onkọwe pẹlu Shakespeare",
"gitIdentityDescription": "Ti a ba tunto orukọ ati imeeli, wọn yoo jẹ lilo bi onkọwe. Bibẹẹkọ, shakespeare.diy yoo jẹ lilo. Nigbati a ba mu ajọpọ onkọwe ṣiṣẹ, Shakespeare yoo jẹ fifikun bi ajọpọ onkọwe.",
"dataSettingsDescriptionLong": "Gbe awọn faili jade ati ṣakoso data agbegbe.",
"exportFiles": "Gbe Awọn faili jade",
"exportFilesDescription": "Gba gbogbo awọn iṣẹ akanṣe ati awọn faili rẹ gẹgẹbi apo ZIP. Eyi pẹlu gbogbo awọn faili iṣẹ akanṣe, awọn eto, ati data ti a tọju ni agbegbe.",
"exportAllFiles": "Gbe Gbogbo Awọn faili jade",
@@ -280,6 +277,7 @@
"untracked": "ti a ko tọpa",
"toggleSidebar": "Yipada sidebar",
"openSidebar": "Ṣi sidebar",
"nostrSettingsDescriptionLong": "Tunto awọn eto asopọ Nostr rẹ ati awọn ayanfẹ relay.",
"nostrAccounts": "Awọn Akọọlẹ Nostr",
"noAccountsLoggedIn": "Ko si awọn akọọlẹ ti o wọle. Fi akọọlẹ kun lati bẹrẹ.",
"createAccount": "Ṣẹda Akọọlẹ",
+5 -6
View File
@@ -3,9 +3,6 @@
"settings": "设置",
"backToSettings": "返回设置",
"help": "帮助",
"general": "常规",
"integrations": "集成",
"advanced": "高级",
"anonymous": "匿名",
"logIn": "登录",
"signUp": "注册",
@@ -100,6 +97,7 @@
"gitSettingsDescription": "配置HTTP身份验证的Git凭据",
"deploySettings": "部署",
"deploySettingsDescription": "配置部署提供商",
"deploySettingsDescriptionLong": "配置部署提供商以将您的项目部署到各种托管平台。",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "配置中继连接和Nostr偏好",
"storageSettings": "存储",
@@ -110,9 +108,6 @@
"importRepository": "导入仓库",
"noProjectsYet": "还没有项目",
"createFirstProject": "创建您的第一个项目开始使用",
"searchProjects": "搜索项目...",
"noProjectsFound": "未找到项目",
"tryDifferentSearch": "尝试不同的搜索词",
"closeSidebar": "关闭侧边栏",
"collapseSidebar": "折叠侧边栏",
"welcomeToShakespeare": "欢迎使用Shakespeare",
@@ -180,6 +175,7 @@
"pushFailed": "推送失败",
"pullSuccessful": "拉取成功",
"pullFailed": "拉取失败",
"aiSettingsDescriptionLong": "通过添加您的API密钥来配置AI提供商。设置会自动保存并存储在您的浏览器本地。",
"configuredProviders": "已配置的提供商",
"addProvider": "添加提供商",
"getApiKey": "获取API密钥",
@@ -205,6 +201,7 @@
"shakespeareDeployNostrAuth": "此提供商使用Nostr身份验证。请确保您已登录以进行部署。",
"providerType": "提供商类型",
"selectProviderType": "选择提供商类型",
"gitSettingsDescriptionLong": "配置HTTP身份验证的Git凭据。设置会自动保存并存储在您的浏览器本地。",
"configuredCredentials": "已配置的凭据",
"origin": "源",
"username": "用户名",
@@ -216,6 +213,7 @@
"gitEmail": "Git邮箱",
"coAuthoredByShakespeare": "Shakespeare共同作者",
"gitIdentityDescription": "如果配置了名称和邮箱,它们将用作提交作者。否则,将使用shakespeare.diy。启用共同作者时,Shakespeare将被添加为共同作者。",
"dataSettingsDescriptionLong": "导出文件和管理本地数据。",
"offlineCache": "离线缓存",
"offlineCacheDescription": "Shakespeare在本地缓存文件以启用离线功能。清除缓存以释放空间或解决问题。",
"cacheSize": "缓存大小",
@@ -292,6 +290,7 @@
"untracked": "未跟踪",
"toggleSidebar": "切换侧边栏",
"openSidebar": "打开侧边栏",
"nostrSettingsDescriptionLong": "配置您的Nostr连接设置和中继偏好。",
"nostrAccounts": "Nostr账户",
"noAccountsLoggedIn": "没有账户登录。添加账户开始使用。",
"createAccount": "创建账户",
+39 -42
View File
@@ -26,7 +26,6 @@ import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Card, CardContent } from '@/components/ui/card';
import { CreditsBadge } from '@/components/CreditsBadge';
import { CreditsDialog } from '@/components/CreditsDialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
@@ -304,7 +303,7 @@ export function AISettings() {
{t('aiSettings')}
</h1>
<p className="text-muted-foreground">
{t('aiSettingsDescription')}
{t('aiSettingsDescriptionLong')}
</p>
</div>
</div>
@@ -317,7 +316,7 @@ export function AISettings() {
{t('aiSettings')}
</h1>
<p className="text-muted-foreground">
{t('aiSettingsDescription')}
{t('aiSettingsDescriptionLong')}
</p>
</div>
)}
@@ -369,44 +368,43 @@ export function AISettings() {
const showNostrLoginRequired = isNostrPreset && !isLoggedIntoNostr;
return (
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</div>
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button
asChild
className="w-full"
>
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : (
<div className="space-y-2">
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button
asChild
className="w-full"
>
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : (
<div className="space-y-2">
<div className="flex gap-2">
{!preset.nostr && (
<PasswordInput
@@ -471,8 +469,7 @@ export function AISettings() {
</div>
</div>
)}
</CardContent>
</Card>
</div>
);
})}
</div>
@@ -482,7 +479,7 @@ export function AISettings() {
{/* Custom Provider */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider">
<AccordionItem value="custom-provider" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</AccordionTrigger>
+13 -18
View File
@@ -5,7 +5,6 @@ import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code, Globe } fr
import { Button } from '@/components/ui/button';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Card, CardContent } from '@/components/ui/card';
import { useIsMobile } from '@/hooks/useIsMobile';
import { EmailSubscription } from '@/components/EmailSubscription';
@@ -86,7 +85,7 @@ export function AboutSettings() {
<div className="space-y-3">
{/* Mirrors */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="mirrors">
<AccordionItem value="mirrors" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Globe className="h-5 w-5" />
@@ -132,25 +131,21 @@ export function AboutSettings() {
</Accordion>
{/* Project Information */}
<Card>
<CardContent className="p-0">
<Button
variant="ghost"
className="w-full h-12 flex items-center gap-2 justify-start text-base"
asChild
>
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
<Code className="!size-5" />
{t('sourceCode')}
<ExternalLink className="ml-auto" />
</a>
</Button>
</CardContent>
</Card>
<Button
variant="outline"
className="w-full h-12 flex items-center gap-2 justify-start text-base"
asChild
>
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
<Code className="!size-5" />
{t('sourceCode')}
<ExternalLink className="ml-auto" />
</a>
</Button>
{/* License */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="license-text">
<AccordionItem value="license-text" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Info className="h-5 w-5" />
-135
View File
@@ -10,14 +10,6 @@ import { useToast } from '@/hooks/useToast';
import { ZipImportDialog } from '@/components/ZipImportDialog';
import { useSeoMeta } from '@unhead/react';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useUserRepositories } from '@/hooks/useUserRepositories';
import { useContacts } from '@/hooks/useContacts';
import { useFollowedRepositories } from '@/hooks/useFollowedRepositories';
import { RepositoryCard } from '@/components/RepositoryCard';
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
export default function Clone() {
const { t } = useTranslation();
@@ -30,11 +22,6 @@ export default function Clone() {
const { toast } = useToast();
const autoCloneInitiatedRef = useRef(false);
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
const { user } = useCurrentUser();
const { data: repositories = [], isLoading: isLoadingRepos } = useUserRepositories(user?.pubkey);
const { data: contacts = [] } = useContacts(user?.pubkey);
const { data: followedRepositories = [], isLoading: isLoadingFollowedRepos } = useFollowedRepositories(contacts);
const [activeTab, setActiveTab] = useState<'my-projects' | 'follows'>('my-projects');
useSeoMeta({
title: `${t('importRepository')} - Shakespeare`,
@@ -289,128 +276,6 @@ export default function Clone() {
open={isZipDialogOpen}
onOpenChange={setIsZipDialogOpen}
/>
{/* NIP-34 Repositories with Tabs */}
{user && (
<div className="mt-16 max-w-7xl mx-auto">
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'my-projects' | 'follows')}>
<TabsList className="mb-6">
<TabsTrigger value="my-projects">
My Projects
</TabsTrigger>
<TabsTrigger value="follows">
Follows
</TabsTrigger>
</TabsList>
<TabsContent value="my-projects">
{isLoadingRepos ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{Array.from({ length: 3 }).map((_, i) => (
<Card key={i} className="h-full flex flex-col">
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start gap-3 mb-4">
<Skeleton className="w-12 h-12 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-4 w-24" />
</div>
</div>
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
<div className="flex gap-1 mb-4">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
</div>
<div className="mt-auto flex gap-2">
<Skeleton className="h-9 flex-1" />
<Skeleton className="h-9 w-9" />
</div>
</CardContent>
</Card>
))}
</div>
) : repositories.length > 0 ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{repositories.map((repo) => (
<RepositoryCard key={repo.id} repo={repo} />
))}
</div>
) : (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
No repositories found. Publish your first repository to Nostr to see it here.
</p>
</div>
</CardContent>
</Card>
)}
</TabsContent>
<TabsContent value="follows">
{isLoadingFollowedRepos ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{Array.from({ length: 6 }).map((_, i) => (
<Card key={i} className="h-full flex flex-col">
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start gap-3 mb-4">
<Skeleton className="w-12 h-12 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-4 w-24" />
</div>
</div>
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
<div className="flex gap-1 mb-4">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
</div>
<div className="mt-auto flex gap-2">
<Skeleton className="h-9 flex-1" />
<Skeleton className="h-9 w-9" />
</div>
</CardContent>
</Card>
))}
</div>
) : followedRepositories.length > 0 ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{followedRepositories.map((repo) => (
<RepositoryCard key={repo.id} repo={repo} />
))}
</div>
) : contacts.length > 0 ? (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
None of the people you follow have published repositories yet.
</p>
</div>
</CardContent>
</Card>
) : (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
You're not following anyone yet. Follow people on Nostr to see their repositories here.
</p>
</div>
</CardContent>
</Card>
)}
</TabsContent>
</Tabs>
</div>
)}
</AppLayout>
);
}
+33 -35
View File
@@ -32,7 +32,6 @@ import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Card, CardContent } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth';
@@ -84,6 +83,7 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
ref={setNodeRef}
style={style}
value={String(index)}
className="border rounded-lg"
>
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
@@ -519,7 +519,7 @@ export function DeploySettings() {
{t('deploySettings')}
</h1>
<p className="text-muted-foreground">
{t('deploySettingsDescription')}
{t('deploySettingsDescriptionLong')}
</p>
</div>
</div>
@@ -532,7 +532,7 @@ export function DeploySettings() {
{t('deploySettings')}
</h1>
<p className="text-muted-foreground">
{t('deploySettingsDescription')}
{t('deploySettingsDescriptionLong')}
</p>
</div>
)}
@@ -591,37 +591,36 @@ export function DeploySettings() {
const oauthError = oauthHook?.error ?? null;
return (
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.apiKeyURL && !isOAuthConfigured && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeyURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<h5 className="font-medium">{preset.name}</h5>
</div>
<p className="text-sm text-muted-foreground">{preset.description}</p>
{preset.apiKeyURL && !isOAuthConfigured && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeyURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</div>
<p className="text-sm text-muted-foreground">{preset.description}</p>
{showNostrLoginRequired ? (
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
@@ -725,8 +724,7 @@ export function DeploySettings() {
</div>
</div>
)}
</CardContent>
</Card>
</div>
);
})}
</div>
@@ -736,7 +734,7 @@ export function DeploySettings() {
{/* Custom Provider */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider">
<AccordionItem value="custom-provider" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</AccordionTrigger>
+26 -29
View File
@@ -6,7 +6,6 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Card, CardContent } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import {
DropdownMenu,
@@ -127,7 +126,7 @@ export function GitSettings() {
{t('gitSettings')}
</h1>
<p className="text-muted-foreground">
{t('gitSettingsDescription')}
{t('gitSettingsDescriptionLong')}
</p>
</div>
</div>
@@ -140,7 +139,7 @@ export function GitSettings() {
{t('gitSettings')}
</h1>
<p className="text-muted-foreground">
{t('gitSettingsDescription')}
{t('gitSettingsDescriptionLong')}
</p>
</div>
)}
@@ -157,7 +156,7 @@ export function GitSettings() {
const isCustom = !preset;
return (
<AccordionItem key={origin} value={origin}>
<AccordionItem key={origin} value={origin} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<ExternalFavicon
@@ -224,29 +223,28 @@ export function GitSettings() {
<h4 className="text-sm font-medium">{t('addProvider')}</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{availablePresets.map((preset) => (
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.origin}
size={16}
fallback={<GitBranch size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.tokenURL, '_blank')}
>
{t('getToken')}
</button>
)}
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.origin}
size={16}
fallback={<GitBranch size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.tokenURL, '_blank')}
>
{t('getToken')}
</button>
)}
</div>
{preset.id === 'github' ? (
{preset.id === 'github' ? (
// Special rendering for GitHub - OAuth button if configured, otherwise token input
isOAuthConfigured && !forceManualEntry[preset.id] ? (
<div className="space-y-3">
@@ -351,8 +349,7 @@ export function GitSettings() {
</Button>
</div>
)}
</CardContent>
</Card>
</div>
))}
</div>
</div>
@@ -361,7 +358,7 @@ export function GitSettings() {
{/* Custom Provider */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider">
<AccordionItem value="custom-provider" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</AccordionTrigger>
@@ -422,7 +419,7 @@ export function GitSettings() {
{/* Git Identity */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="git-identity">
<AccordionItem value="git-identity" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('gitIdentity')}</h4>
</AccordionTrigger>
+33 -156
View File
@@ -4,8 +4,6 @@ import { useTranslation } from 'react-i18next';
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 { useAppContext } from '@/hooks/useAppContext';
import { AppLayout } from '@/components/AppLayout';
@@ -16,11 +14,7 @@ import { Quilly } from '@/components/Quilly';
import { DotAI } from '@/lib/DotAI';
import type { AIMessage } from '@/lib/SessionManager';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ModelSelector } from '@/components/ModelSelector';
import { FileAttachment } from '@/components/ui/file-attachment';
import { ArrowUp } from 'lucide-react';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { useSeoMeta } from '@unhead/react';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { AppShowcase } from '@/components/AppShowcase';
@@ -29,9 +23,7 @@ import { useToast } from '@/hooks/useToast';
export default function Index() {
const { t } = useTranslation();
const { toast } = useToast();
const [prompt, setPrompt] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
const [showOnboarding, setShowOnboarding] = useState(false);
const [showAct1Dialog, setShowAct1Dialog] = useState(false);
const [showGiftCardDialog, setShowGiftCardDialog] = useState(false);
@@ -48,10 +40,9 @@ export default function Index() {
// Initialize with first recently used model if available, otherwise empty
return settings.recentlyUsedModels?.[0] || '';
});
const isMobile = useIsMobile();
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [isDragOver, setIsDragOver] = useState(false);
const [quillyError, setQuillyError] = useState<Error | null>(null);
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
// Check if any providers are configured
const hasProvidersConfigured = settings.providers.length > 0;
@@ -67,12 +58,6 @@ export default function Index() {
description: 'Build custom apps with AI assistance using Shakespeare, an AI-powered development environment.',
});
// Restore prompt from local storage on mount
useEffect(() => {
if (storedPrompt) {
setPrompt(storedPrompt);
}
}, [storedPrompt]);
// Check for Act 1 users and show welcome dialog
useEffect(() => {
@@ -106,21 +91,6 @@ export default function Index() {
}
}, [location, navigate]);
// Sync prompt with local storage
const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newPrompt = e.target.value;
setPrompt(newPrompt);
setStoredPrompt(newPrompt);
};
const handleFileSelect = (file: File) => {
setAttachedFiles(prev => [...prev, file]);
};
const handleFileRemove = (fileToRemove: File) => {
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
};
// Drag and drop handlers
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault();
@@ -154,41 +124,10 @@ export default function Index() {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
if (isCreating || isGeneratingId || !providerModel.trim()) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
};
// Handle keyboard shortcuts (physical keyboards only)
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter') {
// On mobile devices, always allow Enter to create new lines
// since there's no Shift key available for multi-line input
if (isMobile) {
return;
}
if (e.shiftKey) {
// Shift+Enter on desktop: Allow new line (default behavior)
return;
}
// Enter without Shift on desktop: Submit only if no newlines exist in prompt and model is selected
if (!prompt.includes('\n') && providerModel.trim()) {
e.preventDefault();
handleCreateProject();
}
// If prompt contains newlines or no model selected, allow Enter to create new line (default behavior)
}
};
// Handle textarea click - show onboarding if no providers configured
const handleTextareaClick = () => {
// Handle textarea focus - show onboarding if no providers configured
const handleTextareaFocus = () => {
if (!hasProvidersConfigured) {
setShowOnboarding(true);
}
@@ -200,10 +139,7 @@ export default function Index() {
};
const handleQuillyNewChat = () => {
// Clear current prompt and start fresh
setPrompt('');
setStoredPrompt('');
setAttachedFiles([]);
// Clear error - ChatInput manages its own state
setQuillyError(null);
};
@@ -215,23 +151,21 @@ export default function Index() {
setQuillyError(null);
};
const handleCreateProject = async () => {
if (!prompt.trim() || !providerModel.trim()) return;
// Clear stored prompt when creating project
setStoredPrompt('');
const handleSend = async (input: string, files: File[]) => {
if (!input.trim() && files.length === 0) return;
if (!providerModel.trim()) return;
setIsCreating(true);
try {
// Use AI to generate project ID
const projectId = await generateProjectId(providerModel, prompt.trim());
const projectId = await generateProjectId(providerModel, input.trim());
// Add model to recently used when creating project with AI
addRecentlyUsedModel(providerModel.trim());
// Create project with AI-generated ID and handle template update errors
const project = await projectsManager.createProject(
prompt.trim(),
input.trim(),
config.projectTemplate,
projectId,
() => {
@@ -247,8 +181,8 @@ export default function Index() {
// Build message content from input and attached files
// Images are converted to base64-encoded data URLs
const messageContent = await buildMessageContent(
prompt.trim(),
attachedFiles,
input.trim(),
files,
fs,
undefined
);
@@ -263,9 +197,6 @@ export default function Index() {
};
await dotAI.setHistory(sessionName, [initialMessage]);
// Clear attached files after successful creation
setAttachedFiles([]);
// Navigate to the project with autostart parameter and model
const searchParams = new URLSearchParams({
autostart: 'true',
@@ -289,7 +220,7 @@ export default function Index() {
<div className="max-w-4xl mx-auto">
<div className="text-center mb-8 md:mb-12">
<div className="mb-4 md:mb-6">
<ShakespeareLogo className="w-20 h-20 md:w-24 md:h-24 mx-auto" />
<ShakespeareLogo className={`w-20 h-20 md:w-24 md:h-24 mx-auto transition-transform duration-300 ${isCreating || isGeneratingId ? 'animate-spin' : ''}`} />
</div>
<h1 className="text-3xl md:text-4xl font-bold mb-3 md:mb-4 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{t('buildNostrApps')}
@@ -313,84 +244,30 @@ export default function Index() {
</div>
)}
{/* Chat Input Container - matching the ChatPane style */}
<div
className={`relative rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
{/* Chat Input */}
<ChatInput
isLoading={isCreating || isGeneratingId}
isConfigured={hasProvidersConfigured}
providerModel={providerModel}
onProviderModelChange={setProviderModel}
onSend={handleSend}
onStop={() => {
// No-op for Index page - project creation can't be stopped
}}
onFocus={handleTextareaFocus}
onFirstInteraction={() => {
// No-op for Index page
}}
isModelSelectorOpen={isModelSelectorOpen}
onModelSelectorOpenChange={setIsModelSelectorOpen}
contextUsagePercentage={0}
totalCost={0}
isDragOver={isDragOver}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<Textarea
placeholder={
!hasProvidersConfigured
? t('examplePrompt')
: !providerModel.trim()
? t('selectModelToDescribe')
: t('examplePrompt')
}
value={prompt}
onChange={handlePromptChange}
onKeyDown={handleKeyDown}
onClick={handleTextareaClick}
className="min-h-[120px] max-h-64 resize-none border-0 bg-transparent px-4 py-3 pb-16 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isCreating || isGeneratingId || (hasProvidersConfigured && !providerModel.trim())}
rows={4}
style={{
height: 'auto',
minHeight: '120px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 256) + 'px';
}}
/>
{/* Bottom Controls Row */}
<div className="absolute bottom-3 left-3 right-3 flex items-center justify-end gap-4 overflow-hidden">
{/* File Attachment */}
<FileAttachment
className="mr-auto"
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isCreating || isGeneratingId}
multiple={true}
/>
{/* Model Selector - always show to allow configuration */}
<div className="overflow-hidden">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="w-full"
disabled={isCreating || isGeneratingId}
placeholder={t('chooseModel')}
/>
</div>
{/* Create Project Button */}
<Button
onClick={handleCreateProject}
disabled={
!prompt.trim() ||
isCreating ||
isGeneratingId ||
(hasProvidersConfigured && !providerModel.trim())
}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
{isCreating || isGeneratingId ? (
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white" />
) : (
<ArrowUp />
)}
</Button>
</div>
</div>
/>
</div>
</div>
+2 -2
View File
@@ -150,7 +150,7 @@ export function NostrSettings() {
{t('nostrSettings')}
</h1>
<p className="text-muted-foreground">
{t('nostrSettingsDescription')}
{t('nostrSettingsDescriptionLong')}
</p>
</div>
</div>
@@ -163,7 +163,7 @@ export function NostrSettings() {
{t('nostrSettings')}
</h1>
<p className="text-muted-foreground">
{t('nostrSettingsDescription')}
{t('nostrSettingsDescriptionLong')}
</p>
</div>
)}
+2 -2
View File
@@ -199,7 +199,7 @@ export function ProjectView() {
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={project}
onSelectProject={(selectedProject) => {
@@ -314,7 +314,7 @@ export function ProjectView() {
return (
<div className="h-screen flex bg-background">
{/* Fixed Sidebar */}
<div className={`w-72 border-r bg-sidebar duration-300 ${isSidebarVisible ? 'block' : 'hidden'}`}>
<div className={`w-80 border-r bg-sidebar duration-300 ${isSidebarVisible ? 'block' : 'hidden'}`}>
<ProjectSidebar
selectedProject={project}
onSelectProject={(selectedProject) => {
+28 -24
View File
@@ -1,38 +1,42 @@
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '@/hooks/useIsMobile';
import { getSettingsCategories } from '@/lib/settingsItems';
import { SettingsItemMobile } from '@/components/SettingsItemMobile';
import { getSettingsItems } from '@/lib/settingsItems';
export function Settings() {
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
const settingsCategories = getSettingsCategories(t);
const settingsItems = getSettingsItems(t);
if (isMobile) {
return (
<div className="p-4 space-y-8">
{settingsCategories.map((category) => (
<div key={category.id}>
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-2">
{category.title}
</h3>
<div className="overflow-hidden rounded-xl border border-border shadow-sm">
{category.items.map((item, index) => (
<SettingsItemMobile
key={item.id}
icon={item.icon}
title={item.title}
onClick={() => navigate(item.href)}
isFirst={index === 0}
isLast={index === category.items.length - 1}
/>
))}
</div>
</div>
))}
<div className="p-6 space-y-4">
<div className="space-y-2">
<h2 className="text-xl font-bold">{t('settings')}</h2>
<p className="text-muted-foreground">
{t('settingsDescription')}
</p>
</div>
<div className="space-y-3">
{settingsItems.map((item) => {
const Icon = item.icon;
return (
<div
key={item.id}
className="flex items-center gap-3 p-4 rounded-lg border hover:border-primary/20 hover:bg-primary/5 cursor-pointer transition-colors"
onClick={() => navigate(item.href)}
>
<Icon className="h-5 w-5 text-primary flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="font-medium">{item.title}</div>
<div className="text-sm text-muted-foreground">{item.description}</div>
</div>
</div>
);
})}
</div>
{import.meta.env.VERSION && (
<div className="text-center text-xs text-muted-foreground/60 pt-4">
v{import.meta.env.VERSION}
@@ -43,4 +47,4 @@ export function Settings() {
}
}
export default Settings;
export default Settings;
+1 -1
View File
@@ -15,7 +15,7 @@ describe('StorageSettings', () => {
expect(screen.getByText('Storage')).toBeInTheDocument();
// Check for description
expect(screen.getByText('Export files and manage local data')).toBeInTheDocument();
expect(screen.getByText('Export files and manage local data.')).toBeInTheDocument();
// Check for Persist Data section
expect(screen.getByText('Persist Data')).toBeInTheDocument();
+2 -2
View File
@@ -288,7 +288,7 @@ export function StorageSettings() {
{t('storageSettings')}
</h1>
<p className="text-muted-foreground">
{t('storageSettingsDescription')}
{t('dataSettingsDescriptionLong')}
</p>
</div>
</div>
@@ -301,7 +301,7 @@ export function StorageSettings() {
{t('storageSettings')}
</h1>
<p className="text-muted-foreground">
{t('storageSettingsDescription')}
{t('dataSettingsDescriptionLong')}
</p>
</div>
)}
+11 -11
View File
@@ -308,7 +308,7 @@ export function SystemSettings() {
<div className="space-y-3 max-w-xl">
{/* Service Worker Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="service-worker">
<AccordionItem value="service-worker" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('serviceWorker')}</h4>
</AccordionTrigger>
@@ -411,7 +411,7 @@ export function SystemSettings() {
{/* Project Template Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="project-template">
<AccordionItem value="project-template" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
@@ -459,7 +459,7 @@ export function SystemSettings() {
{/* CORS Proxy Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="cors-proxy">
<AccordionItem value="cors-proxy" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
@@ -507,7 +507,7 @@ export function SystemSettings() {
{/* Favicon URL Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="favicon-url">
<AccordionItem value="favicon-url" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
@@ -555,7 +555,7 @@ export function SystemSettings() {
{/* JavaScript CDN Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="esm-url">
<AccordionItem value="esm-url" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
@@ -604,7 +604,7 @@ export function SystemSettings() {
{/* Preview Domain Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="preview-domain">
<AccordionItem value="preview-domain" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
@@ -652,7 +652,7 @@ export function SystemSettings() {
{/* Showcase Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="showcase">
<AccordionItem value="showcase" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('showcase')}</h4>
@@ -746,7 +746,7 @@ export function SystemSettings() {
{/* Sentry DSN Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="sentry-dsn">
<AccordionItem value="sentry-dsn" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
@@ -794,7 +794,7 @@ export function SystemSettings() {
{/* Filesystem Paths Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="filesystem-paths">
<AccordionItem value="filesystem-paths" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
@@ -1016,7 +1016,7 @@ export function SystemSettings() {
{/* System Prompt Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="system-prompt">
<AccordionItem value="system-prompt" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('systemPrompt')}</h4>
@@ -1063,7 +1063,7 @@ export function SystemSettings() {
{/* Terminal */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="terminal">
<AccordionItem value="terminal" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('terminal')}</h4>
+1 -2
View File
@@ -81,8 +81,7 @@ export default {
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)',
xs: '2px'
sm: 'calc(var(--radius) - 4px)'
},
keyframes: {
'accordion-down': {