mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
898c6a8286 | ||
|
|
7f14194ae4 | ||
|
|
2ea05addcc | ||
|
|
9507177aaa | ||
|
|
669bbb8a1f | ||
|
|
d1d8f1dd15 | ||
|
|
66d08d05de | ||
|
|
bb8912dd57 | ||
|
|
804cdbd789 | ||
|
|
f022332595 | ||
|
|
ba509584b7 | ||
|
|
787877d2c7 | ||
|
|
0b269f78a4 | ||
|
|
7a11137aed | ||
|
|
1d0231bc03 | ||
|
|
8b62ba8e7e | ||
|
|
4e0625721e | ||
|
|
3529d43b91 | ||
|
|
93a636589d | ||
|
|
eba609ae73 | ||
|
|
8c60a3a8bc | ||
|
|
939deabb5b | ||
|
|
2ec32f5537 | ||
|
|
124e9d5937 | ||
|
|
b064c9ff86 | ||
|
|
a9a5cafcac | ||
|
|
2db9d5e513 | ||
|
|
e8156243d0 | ||
|
|
e9c73693ce | ||
|
|
1a9a553523 | ||
|
|
fc6a70793f | ||
|
|
fba1328e5f | ||
|
|
a45e29578c | ||
|
|
c1cbbed05c | ||
|
|
d95abf2499 | ||
|
|
4316b766e2 | ||
|
|
8800a55eed | ||
|
|
48dfd2d99e | ||
|
|
cb971955ae | ||
|
|
deb593c1b6 | ||
|
|
3b3637009d | ||
|
|
dc50d41928 | ||
|
|
15567ee4cf | ||
|
|
2d163e8fed | ||
|
|
f6f9a0038b | ||
|
|
c26f447072 | ||
|
|
3253b198c7 |
No files matched your search
+1
-1
@@ -9,7 +9,7 @@
|
||||
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
|
||||
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<link rel="icon" type="image/png" href="/shakespeare.png">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/favicon.png",
|
||||
"src": "/shakespeare.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/favicon.png",
|
||||
"src": "/shakespeare.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="レイヤー_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
|
||||
y="0px" viewBox="0 0 128 128" style="enable-background:new 0 0 128 128;" xml:space="preserve">
|
||||
<g>
|
||||
<g>
|
||||
<path style="fill:#F45125;" d="M110.28,61.32l2.63,8.84c0,0,7.24-1.6,7.62,3.2c0.38,4.8-6.77,8-6.77,8l2.26,10.63
|
||||
c0,0,7.9-6.4,8-15.61c0,0,0.66-11.29-6.11-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
|
||||
<path style="fill:#F45125;" d="M68.71,94.99c0,0-11.1-4.7-16.46,1.98c-0.75,0.94-1.41,1.88-2.16,2.82
|
||||
c-0.56,0.75-1.13,1.5-1.69,2.16c-0.47,0.56-1.03,1.13-1.69,1.5c-0.66,0.38-1.32,0.66-2.07,0.85c-0.94,0.19-1.88,0.19-2.82,0.09
|
||||
c-1.32-0.09-2.63-0.38-3.95-0.66c-0.47-0.09-0.85-0.19-1.22-0.28c-0.09,0-0.19-0.09-0.28-0.09s-0.19-0.09-0.28-0.09
|
||||
c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98c1.32,0.66,2.73,1.03,4.14,1.13
|
||||
c0.09,0,0.38,0,0.47,0.09c0.19,0.19-0.28,0.47-0.47,0.56c-0.28,0.19-0.47,0.28-0.75,0.38c-0.85,0.38-1.79,0.56-2.63,0.75
|
||||
c-0.85,0.19-1.69,0.28-2.45,0.28c-0.47,0-0.85,0.09-1.22,0.09c-0.28,0-0.56-0.09-0.85,0s0.09,0.47,0.28,0.56
|
||||
c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38c1.32-0.19,2.63-0.56,3.86-1.03
|
||||
c6.77-3.1,6.21-9.59,12.42-10.16c4.61-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
|
||||
<path style="fill:#F45125;" d="M19.79,38.28c0,0-12.13,1.98-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22-9.41
|
||||
c0,0-13.07-1.32-12.32-6.3c0.94-6.21,11.85-5.64,11.85-5.64L19.79,38.28z"/>
|
||||
<path style="fill:#F45125;" d="M20.73,70.92c0,0-1.88,0.56-4.61,2.54c-1.88,1.32-4.42,3.01-6.87,5.93
|
||||
c-1.22,1.41-2.16,3.1-2.82,4.89c-0.47,1.22-0.66,2.45-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66
|
||||
c0.09-0.09,0.19-0.38,0.28-0.47c0.19-0.47,0.47-0.85,0.75-1.22c0.85-1.13,1.88-2.16,3.01-3.01c0.38-0.28,0.75-0.47,1.13-0.66
|
||||
c0.28-0.28,0.75-0.66,0.94-0.28c0.09,0.19-0.09,0.47-0.19,0.66c-0.09,0.28-0.19,0.66-0.19,0.94c-0.38,1.5-0.56,3.01-0.75,4.51
|
||||
c-0.09,0.85-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19
|
||||
c0.09-0.09,0.09-0.19,0.19-0.38c0.19-0.28,0.28-0.66,0.47-0.94c0.47-0.85,0.94-1.69,1.5-2.63c0.66-1.13,1.41-2.16,2.16-3.1
|
||||
c0.85-1.13,1.88-2.26,2.92-3.2c1.13-1.03,2.35-2.07,3.67-2.92c0.75-0.47,1.6-0.94,2.45-1.32L20.73,70.92z"/>
|
||||
<g>
|
||||
<path style="fill:#FCC21B;" d="M116.4,79.29c-1.13-5.55-2.73-11.01-4.51-16.46c-1.5-4.61-3.1-9.31-5.83-13.36
|
||||
c-1.22-1.79-3.01-3.01-5.27-3.86c-4.33-1.69-9.97-1.98-13.73-1.98c-5.64,0-11.48,1.22-16.74,3.67
|
||||
c-1.88,5.64-7.05,19.94-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23
|
||||
c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66
|
||||
c2.54-1.13,4.61-2.92,6.3-5.08c1.79-2.26,3.2-4.8,4.42-7.43c1.88-3.95,3.86-8.37,4.14-12.89
|
||||
C117.99,87.38,117.24,83.24,116.4,79.29z"/>
|
||||
<path style="fill:#429ADF;" d="M77.64,33.57c-0.28-1.03-1.03-2.07-1.6-3.01c-6.3-11.01-20.04-16.27-32.26-15.52
|
||||
c-3.76,0.28-9.31,0.85-13.54,2.73c-2.07,0.94-3.86,2.35-4.99,4.14c-2.54,4.23-3.76,8.94-5.08,13.64
|
||||
C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89-1.41,10.25-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32
|
||||
c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94-0.19,1.98-0.28,2.92-0.56
|
||||
c1.88-0.47,3.67-1.13,5.46-1.79c7.52-3.01,13.64-7.43,17.68-14.58c1.69-3.1,3.1-6.4,4.42-9.69c0.09-0.19,0.19-0.38,0.19-0.56
|
||||
c1.98-5.46,3.29-11.19,4.61-16.84c0.66-2.73,1.41-5.55,1.79-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
|
||||
</g>
|
||||
</g>
|
||||
<path style="fill:#193D51;" d="M23.09,40.53c1.69-3.1,5.74-5.55,9.31-5.08c0.56,0.09,1.22,0.19,1.79,0.47
|
||||
c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75-0.66,0.85-1.22,0.38c-1.98-1.69-3.57-3.01-6.21-3.67c-2.16-0.56-4.61-0.28-6.68,0.28
|
||||
c-0.47,0.09-1.22,0.56-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
|
||||
<path style="fill:#193D51;" d="M62.21,64.9c-1.03,1.6-2.45,3.01-3.86,4.33c-0.38,0.28-0.66,0.66-1.03,0.94
|
||||
c-5.64,4.7-13.26,7.05-20.51,5.27c-1.98-0.47-4.14-1.5-5.74-2.73c-1.22-0.94-2.45-2.16-3.48-3.39c-1.88-2.26-3.29-4.89-4.23-7.62
|
||||
c-0.47-1.41-0.75-2.73-0.94-4.23c0-0.47-0.66-5.46,0.85-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03
|
||||
c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09
|
||||
c5.08-0.28,10.25-1.79,14.86-3.76c0.38-0.19,0.85-0.47,1.32-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
|
||||
<path style="fill:#193D51;" d="M67.58,51.16c0,0.47-0.19,1.13-0.75,1.03c-0.47-0.09-0.85-0.94-1.13-1.22
|
||||
c-1.32-1.69-3.86-3.57-6.4-4.14c-3.01-0.75-5.27,0.56-8.28,0.85c-0.85,0.09-1.32-0.28-0.94-1.03c1.6-3.48,5.83-6.21,10.25-5.46
|
||||
c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
|
||||
<path style="fill:#9B7515;" d="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41-0.09,2.26,0.09,1.88,1.69
|
||||
c-0.75,3.29-3.86,5.17-6.87,5.83c-0.75,0.19-1.5,0.19-2.26,0.19c-1.41-0.09-2.82-0.66-4.04-1.5c-2.63-1.79-4.61-4.89-5.17-8
|
||||
C89.68,63.67,90.25,62.83,91.84,63.86z"/>
|
||||
<path style="fill:#9B7515;" d="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51-2.35,9.03-5.93,11.38-10.63
|
||||
c0.85-1.79,1.79-1.41,2.45,0.28c1.13,3.1,1.03,6.87-0.38,9.88c-0.66,1.41-1.6,2.63-2.82,3.57c-0.66,0.47-1.32,0.75-2.07,1.03
|
||||
C71.43,83.33,67.58,83.24,65.22,80.79z"/>
|
||||
<path style="fill:#9B7515;" d="M110,96.41c-0.38,0-0.94-0.38-1.41-0.66c-0.47-0.28-0.94-0.66-1.22-0.85
|
||||
c-1.13-0.56-2.45-1.13-3.67-1.5c-3.76-1.22-7.9-1.22-11.57,0c-2.63,0.85-5.17,2.45-7.24,4.33c-2.26,2.16-3.95,4.8-6.11,7.05
|
||||
c-0.28,0.28-0.56,0.56-0.85,0.75c-0.56,0.28-1.13-0.09-1.32-0.66c-0.94-3.95,1.69-9.5,3.67-12.89c2.26-3.76,5.55-6.77,9.78-8
|
||||
c2.07-0.66,4.33-0.66,6.49-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 5.8 KiB |
+1
-1
@@ -38,7 +38,7 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
theme: "system",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
deployServer: "shakespeare.wtf",
|
||||
};
|
||||
|
||||
+1
-2
@@ -11,7 +11,7 @@ import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
import EmailSettings from "./pages/EmailSettings";
|
||||
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
@@ -34,7 +34,6 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="data" element={<DataSettings />} />
|
||||
<Route path="email" element={<EmailSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
|
||||
@@ -18,7 +18,6 @@ interface AppLayoutProps {
|
||||
export function AppLayout({
|
||||
children,
|
||||
selectedProject = null,
|
||||
title = "Shakespeare",
|
||||
showSidebar = true,
|
||||
headerContent
|
||||
}: AppLayoutProps) {
|
||||
@@ -85,9 +84,6 @@ export function AppLayout({
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{title}
|
||||
</h1>
|
||||
</div>
|
||||
{headerContent}
|
||||
</header>
|
||||
|
||||
@@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
|
||||
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg">
|
||||
{lightningInvoice ? (
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSubscription() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0');
|
||||
const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`;
|
||||
const tag = '8982396';
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Submit to Mailchimp
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = url.href;
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = tag;
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = honeypot;
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('emailUpdatesDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -47,7 +47,7 @@ import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"];
|
||||
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"];
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
@@ -62,6 +62,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [isPushingToNostr, setIsPushingToNostr] = useState(false);
|
||||
const [originUrl, setOriginUrl] = useState('');
|
||||
const [isSavingOrigin, setIsSavingOrigin] = useState(false);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
@@ -334,6 +335,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
title: "Push to Nostr failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPushingToNostr(false);
|
||||
@@ -395,6 +397,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
title: "Push failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
@@ -425,6 +428,12 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
|
||||
// Get the current HEAD commit before pulling
|
||||
const beforeCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
await git.pull({
|
||||
dir: projectPath,
|
||||
ref: gitStatus.currentBranch,
|
||||
@@ -436,20 +445,38 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
|
||||
});
|
||||
|
||||
// Get the current HEAD commit after pulling
|
||||
const afterCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
// Check if the repository actually changed
|
||||
const repoChanged = beforeCommit !== afterCommit;
|
||||
|
||||
toast({
|
||||
title: "Pull successful",
|
||||
description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`,
|
||||
description: repoChanged
|
||||
? `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`
|
||||
: `Already up to date with ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
|
||||
// Refresh git status after pull
|
||||
await refetchGitStatus();
|
||||
|
||||
// Only trigger build if the repository actually changed
|
||||
if (repoChanged) {
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.set('build', '');
|
||||
setSearchParams(newSearchParams);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
title: "Pull failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPulling(false);
|
||||
|
||||
@@ -18,7 +18,6 @@ const GIT_KINDS = [
|
||||
const GIT_RELAYS = [
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
];
|
||||
|
||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
|
||||
@@ -42,7 +42,7 @@ describe('OnboardingDialog', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading
|
||||
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now
|
||||
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -8,12 +8,13 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
interface OnboardingDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -119,8 +120,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] sm:max-h-[80vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{step === 'model-selection' && (
|
||||
<Button
|
||||
@@ -132,18 +133,28 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'conclusion' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('model-selection')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<span className="text-xl">
|
||||
{step === 'welcome' && 'Welcome to Shakespeare!'}
|
||||
{step === 'model-selection' && 'Choose Your AI Model'}
|
||||
{step === 'conclusion' && "You're All Set!"}
|
||||
</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<div className="flex-1 overflow-y-auto min-h-0">
|
||||
{step === 'welcome' && (
|
||||
<div className="text-center space-y-6 py-4">
|
||||
<div className="text-6xl mb-4">🎭</div>
|
||||
<div className="mb-4">
|
||||
<ShakespeareLogo className="w-16 h-16 mx-auto" />
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Welcome to Shakespeare!
|
||||
@@ -191,15 +202,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
)}
|
||||
|
||||
{step === 'model-selection' && (
|
||||
<div className="space-y-4">
|
||||
<div className="text-center space-y-2">
|
||||
<p className="text-muted-foreground">
|
||||
Choose an AI model to power your development experience.
|
||||
Different models offer various capabilities and pricing.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-96">
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex-1 overflow-y-auto min-h-0 my-4">
|
||||
<div className="space-y-3 p-1">
|
||||
{isLoadingModels ? (
|
||||
<>
|
||||
@@ -232,6 +236,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
shakespeareModels.map((model) => {
|
||||
const isSelected = selectedModel === model.fullId;
|
||||
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
|
||||
const isPremium = !isFree;
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -244,12 +249,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1">
|
||||
<CardTitle className="text-base font-semibold">
|
||||
{model.description || model.name || model.id}
|
||||
<CardTitle className={`text-xl font-semibold ${isPremium ? 'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent' : ''}`}>
|
||||
{ model.name || model.description || model.id}
|
||||
</CardTitle>
|
||||
{model.description && (
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{model.name || model.id}
|
||||
{model.description || model.id}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -259,6 +264,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
Free
|
||||
</Badge>
|
||||
)}
|
||||
{isPremium && (
|
||||
<Badge className="text-xs bg-primary text-white border-0">
|
||||
Premium
|
||||
</Badge>
|
||||
)}
|
||||
{isSelected && (
|
||||
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
|
||||
<Check className="h-3 w-3 text-primary-foreground" />
|
||||
@@ -268,12 +278,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<div className="flex items-end justify-end gap-4 text-xs text-muted-foreground">
|
||||
{model.pricing && (
|
||||
<>
|
||||
<span>Input: {formatPrice(model.pricing.prompt)}</span>
|
||||
<span>Output: {formatPrice(model.pricing.completion)}</span>
|
||||
</>
|
||||
<div className="text-right">
|
||||
<div>Input: {formatPrice(model.pricing.prompt)}</div>
|
||||
<div>Output: {formatPrice(model.pricing.completion)}</div>
|
||||
</div>
|
||||
)}
|
||||
{model.contextLength && (
|
||||
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
|
||||
@@ -285,9 +295,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-4 border-t">
|
||||
<div className="flex justify-end gap-2 pt-4 border-t flex-shrink-0">
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
disabled={!selectedModel}
|
||||
@@ -310,11 +320,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
Just enter your prompt to start building amazing Nostr applications.
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
|
||||
<p className="text-sm text-muted-foreground italic">
|
||||
"Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..."
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={handleFinish} size="lg" className="gap-2">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Start Building
|
||||
|
||||
@@ -0,0 +1,685 @@
|
||||
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Upload, FileArchive, AlertCircle, FileText, Trash2, FolderOpen, CheckSquare, Square, AlertTriangle } from 'lucide-react';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface ProjectInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
files: string[];
|
||||
isConflict: boolean;
|
||||
selected: boolean;
|
||||
}
|
||||
|
||||
interface ProjectImportDialogProps {
|
||||
mode?: 'single' | 'bulk';
|
||||
onImport: (data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] }, overwrite: boolean) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ProjectImportDialog({
|
||||
mode = 'single',
|
||||
onImport,
|
||||
disabled = false,
|
||||
className,
|
||||
open,
|
||||
onOpenChange
|
||||
}: ProjectImportDialogProps) {
|
||||
// Use controlled state if props are provided, otherwise use internal state
|
||||
const [internalIsOpen, setInternalIsOpen] = useState(false);
|
||||
const isOpen = open !== undefined ? open : internalIsOpen;
|
||||
const setIsOpen = onOpenChange || setInternalIsOpen;
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [generatedId, setGeneratedId] = useState('');
|
||||
const [discoveredProjects, setDiscoveredProjects] = useState<ProjectInfo[]>([]);
|
||||
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||
const [zipData, setZipData] = useState<JSZip | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { data: existingProjects = [] } = useProjects();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
// Analyze ZIP for bulk import
|
||||
const analyzeZipForProjects = useCallback(async (zip: JSZip): Promise<ProjectInfo[]> => {
|
||||
const projects: ProjectInfo[] = [];
|
||||
const projectPaths = new Set<string>();
|
||||
|
||||
// Find all potential project directories
|
||||
for (const [path] of Object.entries(zip.files)) {
|
||||
const pathParts = path.split('/').filter(part => part !== '');
|
||||
|
||||
// Skip files in root directory - we're looking for project directories
|
||||
if (pathParts.length < 2) continue;
|
||||
|
||||
// Check if this looks like a project indicator file
|
||||
if (isProjectIndicator(path)) {
|
||||
let projectPath: string;
|
||||
|
||||
// If structure is projects/project-name/file, extract project-name
|
||||
if (pathParts[0] === 'projects' && pathParts.length >= 3) {
|
||||
projectPath = `projects/${pathParts[1]}`;
|
||||
} else {
|
||||
// Otherwise, assume first directory is the project
|
||||
projectPath = pathParts[0];
|
||||
}
|
||||
|
||||
projectPaths.add(projectPath);
|
||||
}
|
||||
}
|
||||
|
||||
// For each discovered project path, gather information
|
||||
for (const projectPath of projectPaths) {
|
||||
const files: string[] = [];
|
||||
|
||||
// Collect all files in this project directory
|
||||
for (const [path, zipEntry] of Object.entries(zip.files)) {
|
||||
if (path.startsWith(projectPath + '/') && !zipEntry.dir) {
|
||||
const relativePath = path.substring(projectPath.length + 1);
|
||||
files.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate project ID and name from directory path
|
||||
let id: string;
|
||||
let name: string;
|
||||
|
||||
if (projectPath.startsWith('projects/')) {
|
||||
const projectName = projectPath.substring('projects/'.length);
|
||||
id = projectName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
name = projectName;
|
||||
} else {
|
||||
id = projectPath
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
name = projectPath;
|
||||
}
|
||||
|
||||
// Skip if no files found (empty directory)
|
||||
if (files.length === 0) continue;
|
||||
|
||||
// Check if this project conflicts with existing projects
|
||||
const isConflict = existingProjects.some(existing => existing.id === id);
|
||||
|
||||
projects.push({
|
||||
id,
|
||||
name,
|
||||
path: projectPath,
|
||||
files,
|
||||
isConflict,
|
||||
selected: !isConflict, // Auto-select non-conflicting projects
|
||||
});
|
||||
}
|
||||
|
||||
return projects;
|
||||
}, [existingProjects]);
|
||||
|
||||
// Handle file selection
|
||||
const handleFileSelect = useCallback(async (file: File) => {
|
||||
// Only accept zip files
|
||||
if (!file.name.toLowerCase().endsWith('.zip')) {
|
||||
setError('Please select a ZIP file');
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFile(file);
|
||||
setError(null);
|
||||
setGeneratedId('');
|
||||
|
||||
// Auto-generate ID from file name for single mode
|
||||
if (mode === 'single') {
|
||||
const baseName = file.name.replace(/\.zip$/i, '');
|
||||
const id = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
setGeneratedId(id);
|
||||
}
|
||||
|
||||
// For bulk mode, analyze the ZIP to discover projects
|
||||
if (mode === 'bulk') {
|
||||
setIsAnalyzing(true);
|
||||
setDiscoveredProjects([]);
|
||||
|
||||
try {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||
setZipData(zip);
|
||||
|
||||
const projects = await analyzeZipForProjects(zip);
|
||||
setDiscoveredProjects(projects);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to analyze ZIP file');
|
||||
} finally {
|
||||
setIsAnalyzing(false);
|
||||
}
|
||||
}
|
||||
}, [mode, analyzeZipForProjects]);
|
||||
|
||||
|
||||
const isProjectIndicator = (path: string): boolean => {
|
||||
const indicators = [
|
||||
'package.json',
|
||||
'index.html',
|
||||
'src/',
|
||||
'public/',
|
||||
'tsconfig.json',
|
||||
'vite.config.',
|
||||
'webpack.config.',
|
||||
'README.md',
|
||||
'.git/',
|
||||
];
|
||||
|
||||
return indicators.some(indicator => path.includes('/' + indicator));
|
||||
};
|
||||
|
||||
// Check for existing project when generated ID changes (single mode)
|
||||
useEffect(() => {
|
||||
if (mode === 'single' && generatedId && existingProjects.length > 0) {
|
||||
const existing = existingProjects.find(project => project.id === generatedId);
|
||||
if (existing) {
|
||||
setError(`A project with ID "${generatedId}" already exists. You can choose to overwrite it.`);
|
||||
} else {
|
||||
setError(null);
|
||||
}
|
||||
}
|
||||
}, [generatedId, existingProjects, mode]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, [handleFileSelect]);
|
||||
|
||||
const handleClickUpload = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileRemove = () => {
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setDiscoveredProjects([]);
|
||||
setZipData(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
// Bulk import project selection handlers
|
||||
const handleProjectToggle = (projectId: string, checked: boolean) => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project =>
|
||||
project.id === projectId ? { ...project, selected: checked } : project
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleSelectAll = () => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project => ({ ...project, selected: true }))
|
||||
);
|
||||
};
|
||||
|
||||
const handleDeselectAll = () => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project => ({ ...project, selected: false }))
|
||||
);
|
||||
};
|
||||
|
||||
const selectedProjects = discoveredProjects.filter(project => project.selected);
|
||||
const conflictingProjects = selectedProjects.filter(project => project.isConflict);
|
||||
|
||||
const handleImport = async (overwrite = false) => {
|
||||
if (!selectedFile) return;
|
||||
|
||||
setIsImporting(true);
|
||||
setImportProgress(0);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (mode === 'single') {
|
||||
// Single project import
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||
}, 200);
|
||||
|
||||
await onImport({ file: selectedFile, projectId: generatedId }, overwrite);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
} else {
|
||||
// Bulk project import
|
||||
const projectsToImport = await Promise.all(
|
||||
selectedProjects.map(async (project) => {
|
||||
const files = await projectsManager.extractFilesFromZip(zipData!, project.path);
|
||||
return {
|
||||
id: project.id,
|
||||
files,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 5, 90));
|
||||
}, 100);
|
||||
|
||||
await onImport({ projects: projectsToImport }, overwrite);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
}
|
||||
|
||||
// Close dialog and reset state immediately
|
||||
setIsOpen(false);
|
||||
handleFileRemove();
|
||||
setImportProgress(0);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import projects');
|
||||
setImportProgress(0);
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportWithOverwriteCheck = async () => {
|
||||
if (mode === 'single') {
|
||||
// For single mode, check if project exists
|
||||
const existingProject = existingProjects.find(project => project.id === generatedId);
|
||||
if (existingProject) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
} else {
|
||||
// For bulk mode, check for conflicts
|
||||
if (conflictingProjects.length > 0) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const confirmOverwrite = async () => {
|
||||
setShowOverwriteDialog(false);
|
||||
await handleImport(true);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
if (!isImporting && !isAnalyzing) {
|
||||
setIsOpen(false);
|
||||
handleFileRemove();
|
||||
setImportProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||
|
||||
const canImport = mode === 'single'
|
||||
? selectedFile && generatedId
|
||||
: selectedProjects.length > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
{!isControlled && (
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn("gap-2", className)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
{mode === 'single' ? 'Import ZIP' : 'Import Projects'}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
|
||||
<DialogContent className={cn(
|
||||
"h-auto max-h-[90vh] flex flex-col",
|
||||
mode === 'single' ? "sm:max-w-md" : "sm:max-w-xl"
|
||||
)}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
{mode === 'single' ? 'Import Project from ZIP' : 'Import Multiple Projects'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{mode === 'single'
|
||||
? 'Upload a ZIP file containing your project source code to import it into Shakespeare.'
|
||||
: 'Upload a ZIP file containing multiple projects to import them into Shakespeare.'
|
||||
}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 flex flex-col overflow-hidden min-h-0 space-y-4">
|
||||
{!isImporting && !isAnalyzing && (
|
||||
<>
|
||||
{/* Drag and Drop Area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative border-2 border-dashed rounded-lg p-4 text-center transition-colors cursor-pointer",
|
||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||
)}
|
||||
onClick={handleClickUpload}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}}
|
||||
accept=".zip"
|
||||
className="hidden"
|
||||
disabled={isImporting || isAnalyzing}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-center">
|
||||
{selectedFile ? (
|
||||
<FileText className="h-6 w-6 text-green-600" />
|
||||
) : (
|
||||
<Upload className="h-6 w-6 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{selectedFile ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-green-600">
|
||||
{selectedFile.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFileRemove();
|
||||
}}
|
||||
className="text-xs text-destructive hover:underline"
|
||||
>
|
||||
Remove file
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
Drop your ZIP file here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{mode === 'single'
|
||||
? 'Supports ZIP files up to 50MB'
|
||||
: 'Supports ZIP files containing exported Shakespeare projects'
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-amber-600 mb-4">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project List (Bulk Mode Only) */}
|
||||
{mode === 'bulk' && discoveredProjects.length > 0 && (
|
||||
<div className="space-y-3 flex-1 flex flex-col min-h-0">
|
||||
<div className="flex items-center justify-between flex-shrink-0">
|
||||
<h3 className="text-sm font-medium">
|
||||
Found {discoveredProjects.length} project{discoveredProjects.length !== 1 ? 's' : ''}
|
||||
</h3>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleSelectAll}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
<CheckSquare className="h-3 w-3 mr-1" />
|
||||
Select All
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDeselectAll}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
<Square className="h-3 w-3 mr-1" />
|
||||
Deselect All
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<ScrollArea className="h-64">
|
||||
<div className="p-2 space-y-1">
|
||||
{discoveredProjects.map((project) => (
|
||||
<div
|
||||
key={project.id}
|
||||
className={cn(
|
||||
"flex items-start space-x-3 p-2 rounded-lg border transition-colors",
|
||||
project.selected ? "bg-primary/5 border-primary/20" : "bg-background",
|
||||
project.isConflict && "border-amber-200 bg-amber-50/50 dark:border-amber-800 dark:bg-amber-950/20"
|
||||
)}
|
||||
>
|
||||
<Checkbox
|
||||
id={`project-${project.id}`}
|
||||
checked={project.selected}
|
||||
onCheckedChange={(checked) => handleProjectToggle(project.id, checked as boolean)}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div className="flex-1 min-w-0 space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderOpen className="h-4 w-4 text-primary flex-shrink-0" />
|
||||
<span className="font-medium text-sm truncate">{project.name}</span>
|
||||
{project.isConflict && (
|
||||
<div className="hidden sm:flex items-center gap-1 text-amber-600 flex-shrink-0">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs">Conflict</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{project.isConflict && (
|
||||
<div className="sm:hidden flex items-center gap-1 text-amber-600">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs font-medium">Conflict - Will overwrite existing project</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{project.files.length} file{project.files.length !== 1 ? 's' : ''}
|
||||
{project.isConflict && <span className="hidden sm:inline"> • Will overwrite existing project</span>}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Button */}
|
||||
{selectedFile && (mode === 'single' || discoveredProjects.length > 0) && (
|
||||
<div className="flex justify-end gap-2 pt-3 border-t flex-shrink-0">
|
||||
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImportWithOverwriteCheck}
|
||||
disabled={!canImport || isImporting}
|
||||
className={mode === 'single' && error ? "bg-amber-600 hover:bg-amber-700" : conflictingProjects.length > 0 ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{mode === 'single' ? (
|
||||
error ? (
|
||||
<>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Overwrite Project
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Import Project
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{conflictingProjects.length > 0 ? <Trash2 className="mr-2 h-4 w-4" /> : <Upload className="mr-2 h-4 w-4" />}
|
||||
{conflictingProjects.length > 0 ? 'Import & Overwrite' : 'Import Projects'} ({selectedProjects.length})
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Analysis Progress (Bulk Mode Only) */}
|
||||
{mode === 'bulk' && isAnalyzing && (
|
||||
<div className="space-y-2 py-6">
|
||||
<div className="flex items-center gap-2 text-sm justify-center">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||
Analyzing ZIP file...
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Discovering projects and checking for conflicts...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Progress */}
|
||||
{isImporting && (
|
||||
<div className="space-y-3 py-6">
|
||||
<div className="flex items-center gap-2 text-sm justify-center">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div >
|
||||
{mode === 'single' ? 'Importing project...' : `Importing ${selectedProjects.length} project${selectedProjects.length !== 1 ? 's' : ''}...`}
|
||||
</div>
|
||||
<Progress value={importProgress} className="w-full" />
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Extracting files and setting up projects...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success State */}
|
||||
{!isImporting && !isAnalyzing && importProgress === 100 && (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600 justify-center py-3">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
{mode === 'single' ? 'Project imported successfully!' : 'Projects imported successfully!'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Overwrite Confirmation Dialog */}
|
||||
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||
{mode === 'single' ? 'Overwrite Existing Project' : 'Overwrite Existing Projects'}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-3">
|
||||
{mode === 'single' ? (
|
||||
<>
|
||||
<p>
|
||||
A project with ID "<strong>{generatedId}</strong>" already exists.
|
||||
Overwriting it will:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in project</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
You have selected <strong>{conflictingProjects.length}</strong> project{conflictingProjects.length !== 1 ? 's' : ''} that already exist:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2 max-h-32 overflow-y-auto">
|
||||
{conflictingProjects.map((project) => (
|
||||
<li key={project.id}>
|
||||
<strong>{project.name}</strong> (ID: {project.id})
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>Overwriting will:</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in these projects</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
<p className="text-amber-600 font-medium">
|
||||
This action cannot be undone. Are you sure you want to continue?
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmOverwrite}
|
||||
className="bg-amber-600 hover:bg-amber-700"
|
||||
>
|
||||
Yes, {mode === 'single' ? 'Overwrite Project' : 'Overwrite Projects'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -60,7 +60,7 @@ describe('ProjectSidebar', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('🎭')).toBeInTheDocument();
|
||||
expect(screen.getByAltText('Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState } 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, FileArchive } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
@@ -9,12 +9,10 @@ import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
@@ -95,9 +93,6 @@ export function ProjectSidebar({
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
@@ -123,25 +118,6 @@ export function ProjectSidebar({
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
|
||||
try {
|
||||
// Import project from zip file
|
||||
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
|
||||
|
||||
// Show success toast
|
||||
toast({
|
||||
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
|
||||
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
|
||||
});
|
||||
|
||||
// Navigate to the imported project
|
||||
navigate(`/project/${project.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to import project:', error);
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
}, [favorites, queryClient]);
|
||||
@@ -159,7 +135,7 @@ export function ProjectSidebar({
|
||||
onClick={() => navigateAndClose('/')}
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<span className="text-2xl">🎭</span>
|
||||
<ShakespeareLogo className="w-6 h-6" />
|
||||
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Shakespeare
|
||||
</h1>
|
||||
@@ -211,13 +187,6 @@ export function ProjectSidebar({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
@@ -280,13 +249,6 @@ export function ProjectSidebar({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ZIP Import Dialog */}
|
||||
<ZipImportDialog
|
||||
onImport={handleImportZip}
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
@@ -56,13 +56,6 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
@@ -34,13 +34,14 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -51,6 +52,8 @@ interface ChatPaneProps {
|
||||
onLoadingChange?: (isLoading: boolean) => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
consoleError?: ProjectPreviewConsoleError | null;
|
||||
onDismissConsoleError?: () => void;
|
||||
}
|
||||
|
||||
export interface ChatPaneRef {
|
||||
@@ -64,6 +67,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onLoadingChange,
|
||||
isLoading: externalIsLoading,
|
||||
isBuildLoading: externalIsBuildLoading,
|
||||
consoleError,
|
||||
onDismissConsoleError,
|
||||
}, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -80,18 +85,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
|
||||
// Console error handling
|
||||
useEffect(() => {
|
||||
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||
// Only show console errors if there's no existing AI error
|
||||
if (!aiError) {
|
||||
setAIError(error);
|
||||
}
|
||||
};
|
||||
|
||||
addErrorListener(handleConsoleError);
|
||||
return () => removeErrorListener(handleConsoleError);
|
||||
}, [aiError]);
|
||||
// Determine which error to show - console error takes priority over AI errors
|
||||
const displayError = consoleError || aiError;
|
||||
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
@@ -185,7 +180,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
artist: `Working on ${projectId}...`,
|
||||
artwork: [
|
||||
{
|
||||
src: '/favicon.png',
|
||||
src: '/shakespeare.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
@@ -225,6 +220,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
sendMessage('Read the console messages and fix any errors present.', providerModel);
|
||||
}, [sendMessage, providerModel]);
|
||||
|
||||
// Handle error dismissal
|
||||
const handleErrorDismiss = useCallback(() => {
|
||||
if (consoleError && onDismissConsoleError) {
|
||||
onDismissConsoleError();
|
||||
} else {
|
||||
setAIError(null);
|
||||
}
|
||||
}, [consoleError, onDismissConsoleError]);
|
||||
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
||||
|
||||
@@ -525,7 +529,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
{messages.length === 0 && !streamingMessage && !isLoading && (
|
||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||
<div className="text-6xl mb-6">🎭</div>
|
||||
<div className="mb-6">
|
||||
<ShakespeareLogo className="w-16 h-16 mx-auto" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('welcomeToShakespeare')}
|
||||
@@ -608,11 +614,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI Error Alert */}
|
||||
{aiError && (
|
||||
{/* Error Alert (Console or AI) */}
|
||||
{displayError && (
|
||||
<Quilly
|
||||
error={aiError}
|
||||
onDismiss={() => setAIError(null)}
|
||||
error={displayError}
|
||||
onDismiss={handleErrorDismiss}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={openModelSelector}
|
||||
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
@@ -27,6 +27,7 @@ import { cn } from '@/lib/utils';
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
// Get iframe domain from environment variable
|
||||
@@ -76,7 +77,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [fileContent, setFileContent] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer');
|
||||
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor' | 'terminal'>('explorer');
|
||||
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
|
||||
const isMobile = useIsMobile();
|
||||
const [hasBuiltProject, setHasBuiltProject] = useState(false);
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
@@ -455,6 +457,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
setSelectedFile(null);
|
||||
setFileContent('');
|
||||
setMobileCodeView('explorer');
|
||||
setDesktopCodeView('files');
|
||||
|
||||
// Reset navigation history and state
|
||||
setCurrentPath('/');
|
||||
@@ -729,18 +732,48 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
|
||||
<TabsContent value="code" className="h-full mt-0">
|
||||
{isMobile ? (
|
||||
<div className="h-full flex flex-col">
|
||||
<div className="h-full flex flex-col min-h-0">
|
||||
{mobileCodeView === 'explorer' ? (
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
<div className="flex-1 relative min-h-0">
|
||||
<ScrollArea className="h-full">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
{/* Floating Terminal Button */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView('terminal')}
|
||||
className="fixed right-4 bottom-safe-nav z-20 h-12 w-12 p-0 rounded-full shadow-lg bg-background border-2"
|
||||
>
|
||||
<Terminal className="h-6 w-6" />
|
||||
</Button>
|
||||
</div>
|
||||
) : mobileCodeView === 'terminal' ? (
|
||||
<>
|
||||
<div className="h-12 px-3 flex items-center gap-2 bg-black text-purple-400 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView('explorer')}
|
||||
className="p-1 hover:bg-transparent hover:text-white"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h3 className="font-semibold">
|
||||
Terminal
|
||||
</h3>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="flex-1 min-h-0">
|
||||
<TerminalComponent projectId={projectId} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
|
||||
@@ -803,50 +836,73 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
{t('backToPreview')}
|
||||
</Button>
|
||||
<div className="flex-1" />
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{/* Code view header without back button for non-previewable projects */}
|
||||
{!isMobile && !isPreviewable && (
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
|
||||
<div className="flex-1" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
</Button>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 flex min-h-0">
|
||||
<div className="w-1/3 border-r flex flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
{desktopCodeView === 'terminal' ? (
|
||||
<div className="flex-1">
|
||||
<TerminalComponent projectId={projectId} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-1/3 border-r flex flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
<FileEditor
|
||||
filePath={selectedFile}
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-muted-foreground">
|
||||
{t('selectFileFromExplorer')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
<FileEditor
|
||||
filePath={selectedFile}
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-muted-foreground">
|
||||
{t('selectFileFromExplorer')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export interface ShakespeareLogoProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
|
||||
return (
|
||||
<img
|
||||
src="/shakespeare.svg"
|
||||
alt="Shakespeare"
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Copy } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
|
||||
interface TerminalProps {
|
||||
projectId: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface TerminalLine {
|
||||
id: string;
|
||||
type: 'input' | 'output' | 'error';
|
||||
content: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export function Terminal({ projectId, className }: TerminalProps) {
|
||||
const [lines, setLines] = useState<TerminalLine[]>([]);
|
||||
const [currentInput, setCurrentInput] = useState('');
|
||||
const [isExecuting, setIsExecuting] = useState(false);
|
||||
const [commandHistory, setCommandHistory] = useState<string[]>([]);
|
||||
const [historyIndex, setHistoryIndex] = useState(-1);
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const shellToolRef = useRef<ShellTool | null>(null);
|
||||
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git);
|
||||
|
||||
// Add welcome message
|
||||
setLines([{
|
||||
id: Date.now().toString(),
|
||||
type: 'output',
|
||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
}, [projectId, fs, git]);
|
||||
|
||||
// Auto-scroll to bottom when new lines are added or execution state changes
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [lines, isExecuting]);
|
||||
|
||||
// Focus input when component mounts
|
||||
useEffect(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Refocus input after command execution
|
||||
useEffect(() => {
|
||||
if (!isExecuting && inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, [isExecuting]);
|
||||
|
||||
const addLine = useCallback((type: TerminalLine['type'], content: string) => {
|
||||
const newLine: TerminalLine = {
|
||||
id: Date.now().toString() + Math.random(),
|
||||
type,
|
||||
content,
|
||||
timestamp: new Date()
|
||||
};
|
||||
setLines(prev => [...prev, newLine]);
|
||||
}, []);
|
||||
|
||||
const executeCommand = useCallback(async (command: string) => {
|
||||
if (!shellToolRef.current || !command.trim()) return;
|
||||
|
||||
// Add command to history
|
||||
if (command.trim() && !commandHistory.includes(command.trim())) {
|
||||
setCommandHistory(prev => [...prev, command.trim()]);
|
||||
}
|
||||
setHistoryIndex(-1);
|
||||
|
||||
// Add input line
|
||||
addLine('input', command);
|
||||
|
||||
setIsExecuting(true);
|
||||
|
||||
try {
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else if (command.trim() === 'clear') {
|
||||
setLines([]);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
addLine('error', `Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (currentInput.trim() && !isExecuting) {
|
||||
executeCommand(currentInput);
|
||||
setCurrentInput('');
|
||||
}
|
||||
}, [currentInput, isExecuting, executeCommand]);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
if (commandHistory.length > 0) {
|
||||
const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1);
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentInput(commandHistory[newIndex]);
|
||||
}
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
if (historyIndex >= 0) {
|
||||
const newIndex = historyIndex + 1;
|
||||
if (newIndex >= commandHistory.length) {
|
||||
setHistoryIndex(-1);
|
||||
setCurrentInput('');
|
||||
} else {
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentInput(commandHistory[newIndex]);
|
||||
}
|
||||
}
|
||||
} else if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
// Basic tab completion could be added here
|
||||
}
|
||||
}, [commandHistory, historyIndex]);
|
||||
|
||||
const copyToClipboard = useCallback(async (content: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Focus input when clicking anywhere in the terminal
|
||||
const handleTerminalClick = useCallback(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className={cn("h-full flex flex-col bg-black text-slate-300 font-mono text-sm", className)}>
|
||||
{/* Terminal Content */}
|
||||
<div className="flex-1 flex flex-col min-h-0" onClick={handleTerminalClick}>
|
||||
<ScrollArea className="flex-1" ref={scrollRef}>
|
||||
<div className="p-2 space-y-1">
|
||||
{lines.map((line) => (
|
||||
<div
|
||||
key={line.id}
|
||||
className={cn(
|
||||
"group relative",
|
||||
line.type === 'input' && "text-white",
|
||||
line.type === 'error' && "text-red-400",
|
||||
line.type === 'output' && "text-slate-300"
|
||||
)}
|
||||
>
|
||||
<pre className="whitespace-pre-wrap break-words font-mono leading-relaxed">
|
||||
{line.type === 'input' ? (
|
||||
<span className="text-purple-400 font-mono whitespace-nowrap">
|
||||
${' '}
|
||||
</span>
|
||||
) : null}
|
||||
{line.content}
|
||||
</pre>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyToClipboard(line.content);
|
||||
}}
|
||||
className="absolute right-0 top-0 h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-gray-500 hover:text-white hover:bg-gray-700"
|
||||
>
|
||||
<Copy className="h-2 w-2" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Current Command Input - inline with content */}
|
||||
{!isExecuting && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-purple-400 font-mono whitespace-nowrap">
|
||||
$
|
||||
</span>
|
||||
<form onSubmit={handleSubmit} className="flex-1 relative">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={currentInput}
|
||||
onChange={(e) => setCurrentInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isExecuting}
|
||||
className="w-full bg-transparent border-none outline-none text-white font-mono placeholder-gray-500 caret-white leading-relaxed"
|
||||
placeholder=""
|
||||
autoComplete="off"
|
||||
spellCheck="false"
|
||||
autoCapitalize="off"
|
||||
autoCorrect="off"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ZipImportDialog } from './ZipImportDialog';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the useProjects hook
|
||||
const mockProjects = [
|
||||
{ id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() }
|
||||
];
|
||||
|
||||
vi.mock('@/hooks/useProjects', () => ({
|
||||
useProjects: () => ({
|
||||
data: mockProjects,
|
||||
isLoading: false,
|
||||
error: null
|
||||
})
|
||||
}));
|
||||
|
||||
describe('ZipImportDialog', () => {
|
||||
const mockOnImport = vi.fn();
|
||||
const defaultProps = {
|
||||
onImport: mockOnImport,
|
||||
disabled: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnImport.mockClear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders dialog trigger button', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Import ZIP')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens dialog when trigger is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('processes file selection without displaying project ID', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
// Verify that the file name is displayed (from the file selection area)
|
||||
expect(screen.getByText('my-project.zip')).toBeInTheDocument();
|
||||
// Verify that Project ID label is not displayed
|
||||
expect(screen.queryByText('Project ID')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows overwrite warning when project ID already exists', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file that will generate an existing project ID
|
||||
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('calls onImport with correct parameters when import button is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
// Wait for file to be processed
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('new-project.zip')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click import button
|
||||
const importButton = screen.getByText('Import Project');
|
||||
fireEvent.click(importButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project");
|
||||
});
|
||||
});
|
||||
|
||||
it('shows overwrite confirmation dialog when overwrite button is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file that will generate an existing project ID
|
||||
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
// Wait for overwrite button to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click overwrite button
|
||||
const overwriteButton = screen.getByText('Overwrite Project');
|
||||
fireEvent.click(overwriteButton);
|
||||
|
||||
// Check for overwrite confirmation dialog
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument();
|
||||
// Use a more flexible matcher for the text that might be split across elements
|
||||
const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent');
|
||||
if (dialogContent) {
|
||||
expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists');
|
||||
}
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
|
||||
it('does not show project ID input field (simplified interface)', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Check that there's no input field for project ID
|
||||
expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,397 +0,0 @@
|
||||
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ZipImportDialogProps {
|
||||
onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) {
|
||||
// Use controlled state if props are provided, otherwise use internal state
|
||||
const [internalIsOpen, setInternalIsOpen] = useState(false);
|
||||
const isOpen = open !== undefined ? open : internalIsOpen;
|
||||
const setIsOpen = onOpenChange || setInternalIsOpen;
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [generatedId, setGeneratedId] = useState('');
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null);
|
||||
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { data: projects = [] } = useProjects();
|
||||
|
||||
const handleFileSelect = (file: File) => {
|
||||
// Only accept zip files
|
||||
if (!file.name.toLowerCase().endsWith('.zip')) {
|
||||
setError('Please select a ZIP file');
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFile(file);
|
||||
setError(null);
|
||||
|
||||
// Auto-generate ID from file name
|
||||
const baseName = file.name.replace(/\.zip$/i, '');
|
||||
const id = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
setGeneratedId(id);
|
||||
};
|
||||
|
||||
// Check for existing project when generated ID changes
|
||||
useEffect(() => {
|
||||
if (generatedId && projects.length > 0) {
|
||||
const existing = projects.find(project => project.id === generatedId);
|
||||
setExistingProject(existing || null);
|
||||
} else {
|
||||
setExistingProject(null);
|
||||
}
|
||||
}, [generatedId, projects]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleDragOverDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeaveDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDropDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleClickUpload = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileRemove = () => {
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleImport = async (overwrite = false) => {
|
||||
if (!selectedFile) return;
|
||||
|
||||
setIsImporting(true);
|
||||
setImportProgress(0);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Simulate progress for better UX
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||
}, 200);
|
||||
|
||||
await onImport(selectedFile, overwrite, generatedId);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
|
||||
// Close dialog after a short delay
|
||||
setTimeout(() => {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setImportProgress(0);
|
||||
setExistingProject(null);
|
||||
}, 1000);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import project');
|
||||
setImportProgress(0);
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportWithOverwriteCheck = async () => {
|
||||
if (!selectedFile || !generatedId) return;
|
||||
|
||||
// Check if project with this ID already exists
|
||||
try {
|
||||
// This would ideally be passed as a prop or through context
|
||||
// For now, we'll assume the parent will handle the check and pass existing project info
|
||||
if (existingProject) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking existing project:', error);
|
||||
await handleImport(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmOverwrite = async () => {
|
||||
setShowOverwriteDialog(false);
|
||||
await handleImport(true);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
if (!isImporting) {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
setImportProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||
// (no open/onOpenChange props provided)
|
||||
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
{!isControlled && (
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn("gap-2", className)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
|
||||
<DialogContent
|
||||
className="sm:max-w-md"
|
||||
onDragOver={handleDragOverDialog}
|
||||
onDragLeave={handleDragLeaveDialog}
|
||||
onDrop={handleDropDialog}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Import Project from ZIP
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Upload a ZIP file containing your project source code to import it into Shakespeare.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{!isImporting && (
|
||||
<>
|
||||
{/* Drag and Drop Area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
|
||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||
)}
|
||||
onClick={handleClickUpload}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}}
|
||||
accept=".zip"
|
||||
className="hidden"
|
||||
disabled={isImporting}
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-center">
|
||||
{selectedFile ? (
|
||||
<FileText className="h-8 w-8 text-green-600" />
|
||||
) : (
|
||||
<Upload className="h-8 w-8 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{selectedFile ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-green-600">
|
||||
{selectedFile.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFileRemove();
|
||||
}}
|
||||
className="text-xs text-destructive hover:underline"
|
||||
>
|
||||
Remove file
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
Drop your ZIP file here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Supports ZIP files up to 50MB
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Overwrite Warning */}
|
||||
{existingProject && (
|
||||
<div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 p-2 rounded">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
A project with this ID already exists. You can choose to overwrite it.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Button */}
|
||||
<div className="flex justify-end gap-2 pt-4">
|
||||
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImportWithOverwriteCheck}
|
||||
disabled={!selectedFile || !generatedId || isImporting}
|
||||
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{existingProject ? (
|
||||
<>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Overwrite Project
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Import Project
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Import Progress */}
|
||||
{isImporting && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||
Importing project...
|
||||
</div>
|
||||
<Progress value={importProgress} className="w-full" />
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Extracting files and setting up project...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success State */}
|
||||
{!isImporting && importProgress === 100 && (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
Project imported successfully!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Overwrite Confirmation Dialog */}
|
||||
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||
Overwrite Existing Project
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-2">
|
||||
<p>
|
||||
A project with the ID "<strong>{generatedId}</strong>" already exists.
|
||||
Overwriting it will:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in the project</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
<p className="text-amber-600 font-medium">
|
||||
This action cannot be undone. Are you sure you want to continue?
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmOverwrite}
|
||||
className="bg-amber-600 hover:bg-amber-700"
|
||||
>
|
||||
Yes, Overwrite Project
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+12
-4
@@ -110,11 +110,13 @@
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground font-sans;
|
||||
background-color: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
font-family: 'Inter Variable', 'Inter', 'system-ui', 'sans-serif';
|
||||
font-feature-settings: "rlig" 1, "calt" 1;
|
||||
}
|
||||
|
||||
@@ -138,8 +140,10 @@
|
||||
}
|
||||
|
||||
/* GitHub-style focus rings */
|
||||
.focus-ring {
|
||||
@apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2;
|
||||
.focus-ring:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px hsl(var(--ring));
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Smooth transitions for theme switching */
|
||||
@@ -256,6 +260,10 @@
|
||||
padding-top: env(safe-area-inset-top);
|
||||
}
|
||||
|
||||
.bottom-safe-nav {
|
||||
bottom: calc(env(safe-area-inset-bottom) + 3.75rem);
|
||||
}
|
||||
|
||||
/* Mobile navigation button styles - text/icon highlighting only */
|
||||
.mobile-nav-button,
|
||||
.mobile-nav-button:hover,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ProjectsManager } from './ProjectsManager';
|
||||
import { JSRuntimeFS } from './JSRuntime';
|
||||
import { Git } from './git';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
import type JSZip from 'jszip';
|
||||
|
||||
const createMockNostr = (): NPool => ({
|
||||
req: vi.fn(),
|
||||
@@ -438,6 +439,50 @@ describe('ProjectsManager', () => {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
|
||||
it('should prevent zip slip attacks during bulk file extraction', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create a mock ZIP with malicious paths for bulk import
|
||||
const mockZip = {
|
||||
files: {
|
||||
'projects/project1/../../../etc/passwd': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
|
||||
},
|
||||
'projects/project1/../../outside.txt': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
|
||||
},
|
||||
'projects/project1/safe-file.txt': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Spy on console.warn to check for security warnings
|
||||
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
try {
|
||||
// Extract files from the malicious ZIP for bulk import
|
||||
const files = await projectsManager.extractFilesFromZip(mockZip as unknown as JSZip, 'projects/project1');
|
||||
|
||||
// Should only contain safe files
|
||||
expect(Object.keys(files)).toEqual(['safe-file.txt']);
|
||||
expect(files['safe-file.txt']).toEqual(new Uint8Array([7, 8, 9]));
|
||||
|
||||
// Should have logged a security warning about skipped files
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Skipped 2 files due to resolving to paths outside of project directory:'),
|
||||
['projects/project1/../../../etc/passwd', 'projects/project1/../../outside.txt']
|
||||
);
|
||||
|
||||
} finally {
|
||||
// Restore mocks
|
||||
consoleSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('renameProject', () => {
|
||||
|
||||
+398
-102
@@ -46,59 +46,259 @@ export class ProjectsManager {
|
||||
async createProject(name: string, customId?: string): Promise<Project> {
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||
|
||||
// Delete README.md if it exists
|
||||
// Delete README.md if it exists (template-specific cleanup)
|
||||
try {
|
||||
await this.fs.unlink(`${project.path}/README.md`);
|
||||
} catch {
|
||||
// README.md might not exist, ignore error
|
||||
}
|
||||
|
||||
// Delete .git directory and reinitialize
|
||||
try {
|
||||
await this.deleteDirectory(`${project.path}/.git`);
|
||||
} catch {
|
||||
// .git directory might not exist, ignore error
|
||||
}
|
||||
|
||||
// Initialize new git repository
|
||||
await this.git.init({
|
||||
dir: project.path,
|
||||
defaultBranch: 'main',
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(project.path, {
|
||||
isOverwrite: false,
|
||||
commitMessage: 'New project created with Shakespeare',
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
// Add all files to git
|
||||
const files = await this.getAllFiles(project.path);
|
||||
for (const file of files) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
await this.git.add({
|
||||
dir: project.path,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: project.path,
|
||||
message: 'New project created with Shakespeare',
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
|
||||
// Automatically request persistent storage after project creation
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project creation if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project creation:', error);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified method for setting up project infrastructure.
|
||||
* Handles git initialization/management, .ai directory creation, and persistent storage.
|
||||
*/
|
||||
private async setupProjectInfrastructure(
|
||||
projectPath: string,
|
||||
options: {
|
||||
isOverwrite?: boolean;
|
||||
commitMessage?: string;
|
||||
skipPersistentStorage?: boolean;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const { isOverwrite = false, commitMessage = 'Project setup', skipPersistentStorage = false } = options;
|
||||
|
||||
// Initialize git repository if there's no .git directory
|
||||
try {
|
||||
await this.fs.stat(`${projectPath}/.git`);
|
||||
|
||||
// If git exists and we're overwriting, stage the new files
|
||||
if (isOverwrite) {
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
} catch {
|
||||
// Ignore git add errors for files that might be gitignored
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make commit for the overwrite
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: commitMessage,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// No .git directory found, initialize new repository
|
||||
await this.git.init({
|
||||
dir: projectPath,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git (excluding .ai directory)
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: commitMessage,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create .ai/history directory
|
||||
try {
|
||||
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
// Automatically request persistent storage (unless skipped)
|
||||
if (!skipPersistentStorage) {
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project setup if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project setup:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified project import method that handles both ZIP files and direct file objects
|
||||
*/
|
||||
async importProject(
|
||||
source: File | { files: { [path: string]: Uint8Array } },
|
||||
options: {
|
||||
projectId?: string;
|
||||
overwrite?: boolean;
|
||||
projectName?: string;
|
||||
} = {}
|
||||
): Promise<Project> {
|
||||
const { projectId, overwrite = false, projectName } = options;
|
||||
|
||||
let finalProjectId: string;
|
||||
let finalProjectName: string;
|
||||
let files: { [path: string]: Uint8Array };
|
||||
|
||||
if (source instanceof File) {
|
||||
// Handle ZIP file import
|
||||
finalProjectId = projectId || await this.generateUniqueProjectId(source.name.replace(/\.zip$/i, ''));
|
||||
finalProjectName = projectName || this.formatProjectName(finalProjectId);
|
||||
|
||||
// Extract files from ZIP
|
||||
const arrayBuffer = await source.arrayBuffer();
|
||||
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||
|
||||
files = {};
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||
if (zipEntry.dir) continue;
|
||||
|
||||
// Validate extraction path is within project directory
|
||||
const projectPath = `${this.dir}/${finalProjectId}`;
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = await zipEntry.async('uint8array');
|
||||
files[relativePath] = content;
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
|
||||
}
|
||||
} else {
|
||||
// Handle direct files import
|
||||
finalProjectId = projectId || await this.generateUniqueProjectId('imported-project');
|
||||
finalProjectName = projectName || this.formatProjectName(finalProjectId);
|
||||
files = source.files;
|
||||
}
|
||||
|
||||
const projectPath = `${this.dir}/${finalProjectId}`;
|
||||
const projectExists = await this.projectExists(finalProjectId);
|
||||
|
||||
// Check if project with this ID already exists when not overwriting
|
||||
if (projectExists && !overwrite) {
|
||||
throw new Error(`Project with ID "${finalProjectId}" already exists`);
|
||||
}
|
||||
|
||||
try {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
|
||||
// If overwriting, delete existing files except .ai directory and .git directory
|
||||
if (projectExists && overwrite) {
|
||||
const existingFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of existingFiles) {
|
||||
// Preserve .ai directory and .git directory
|
||||
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/${file}`);
|
||||
} catch {
|
||||
// Ignore deletion errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract all files with security validation
|
||||
const extractedFiles: string[] = [];
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, content] of Object.entries(files)) {
|
||||
// Validate extraction path is within project directory
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
const dirPath = extractPath.split('/').slice(0, -1).join('/');
|
||||
if (dirPath) {
|
||||
await this.fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Write the file (this will overwrite existing files)
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
extractedFiles.push(relativePath);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
|
||||
}
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: source instanceof File
|
||||
? `Import project from ${source.name}`
|
||||
: `Import project from files`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id: finalProjectId,
|
||||
name: finalProjectName,
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up on error (only if this was a new project creation)
|
||||
if (!projectExists) {
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy method for backward compatibility
|
||||
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||
// Generate a project ID based on the zip file name or use custom ID
|
||||
const baseName = zipFile.name.replace(/\.zip$/i, '');
|
||||
@@ -198,66 +398,12 @@ export class ProjectsManager {
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Initialize git repository if there's no .git directory
|
||||
try {
|
||||
await this.fs.stat(`${projectPath}/.git`);
|
||||
|
||||
// If git exists and we're overwriting, stage the new files
|
||||
if (overwrite) {
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
} catch {
|
||||
// Ignore git add errors for files that might be gitignored
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make commit for the overwrite
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: `Overwrite project from ${zipFile.name}`,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// No .git directory found, initialize new repository
|
||||
await this.git.init({
|
||||
dir: projectPath,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: `Import project from ${zipFile.name}`,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: `Import project from ${zipFile.name}`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id,
|
||||
@@ -278,6 +424,106 @@ export class ProjectsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import project directly from files object (bypasses ZIP creation)
|
||||
* Used by bulk import to avoid unnecessary ZIP repackaging
|
||||
*/
|
||||
async importProjectFromFiles(
|
||||
projectId: string,
|
||||
files: { [path: string]: Uint8Array },
|
||||
overwrite = false,
|
||||
projectName?: string
|
||||
): Promise<Project> {
|
||||
const projectPath = `${this.dir}/${projectId}`;
|
||||
const projectExists = await this.projectExists(projectId);
|
||||
|
||||
// Check if project with this ID already exists when not overwriting
|
||||
if (projectExists && !overwrite) {
|
||||
throw new Error(`Project with ID "${projectId}" already exists`);
|
||||
}
|
||||
|
||||
// Determine project name
|
||||
const finalProjectName = projectName || this.formatProjectName(projectId);
|
||||
|
||||
try {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
|
||||
// If overwriting, delete existing files except .ai directory and .git directory
|
||||
if (projectExists && overwrite) {
|
||||
const existingFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of existingFiles) {
|
||||
// Preserve .ai directory and .git directory
|
||||
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/${file}`);
|
||||
} catch {
|
||||
// Ignore deletion errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract all files with security validation
|
||||
const extractedFiles: string[] = [];
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, content] of Object.entries(files)) {
|
||||
// Validate the extraction path is within the project directory
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
const dirPath = extractPath.split('/').slice(0, -1).join('/');
|
||||
if (dirPath) {
|
||||
await this.fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Write the file (this will overwrite existing files)
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
extractedFiles.push(relativePath);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project directory:`, skippedFiles);
|
||||
}
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: `Import project from files`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id: projectId,
|
||||
name: finalProjectName,
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up on error (only if this was a new project creation)
|
||||
if (!projectExists) {
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
||||
const id = customId || await this.generateUniqueProjectId(name);
|
||||
|
||||
@@ -646,4 +892,54 @@ export class ProjectsManager {
|
||||
|
||||
return '/' + normalized.join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract files from a ZIP archive for a specific project path
|
||||
* Used by bulk import to extract files from a specific directory within a ZIP
|
||||
*/
|
||||
async extractFilesFromZip(zip: JSZip, projectPath: string): Promise<{ [path: string]: Uint8Array }> {
|
||||
const files: { [path: string]: Uint8Array } = {};
|
||||
const skippedFiles: string[] = [];
|
||||
const securitySkippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||
if (zipEntry.dir) continue;
|
||||
|
||||
// Check if this file is within the specified project path
|
||||
if (!relativePath.startsWith(projectPath + '/')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the relative path within the project
|
||||
const fileRelativePath = relativePath.substring(projectPath.length + 1);
|
||||
|
||||
// Skip empty paths (shouldn't happen due to the dir check above, but just in case)
|
||||
if (!fileRelativePath) continue;
|
||||
|
||||
// Validate extraction path is safe (zip slip protection)
|
||||
// Check for directory traversal attempts in the original path
|
||||
if (fileRelativePath.includes('../') || fileRelativePath.includes('..\\') || fileRelativePath.startsWith('/') || fileRelativePath.startsWith('\\')) {
|
||||
securitySkippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = await zipEntry.async('uint8array');
|
||||
files[fileRelativePath] = content;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to extract file ${relativePath}:`, error);
|
||||
skippedFiles.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
if (securitySkippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${securitySkippedFiles.length} files due to resolving to paths outside of project directory:`, securitySkippedFiles);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to extraction errors:`, skippedFiles);
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
}
|
||||
+37
-145
@@ -5,6 +5,7 @@ interface PackageLock {
|
||||
[key: string]: {
|
||||
name?: string;
|
||||
version: string;
|
||||
peerDependencies?: { [key: string]: string };
|
||||
} | undefined;
|
||||
};
|
||||
}
|
||||
@@ -61,6 +62,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
});
|
||||
|
||||
// Legacy (Internet Explorer) "behavior" syntax
|
||||
build.onResolve({ filter: /^#default#/, namespace: "esm" }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
external: true,
|
||||
};
|
||||
});
|
||||
|
||||
// Handle bare imports like "react"
|
||||
build.onResolve({ filter: /^[^./].*/ }, (args) => {
|
||||
const packageName = args.path.startsWith("@")
|
||||
@@ -69,8 +78,13 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
|
||||
// Handle transitive dependency versions
|
||||
const keys: string[] = [];
|
||||
let importerPackage: string | undefined;
|
||||
try {
|
||||
const importerPackage = extractPackageName(args.importer);
|
||||
const { pathname } = new URL(args.importer);
|
||||
if (/\.css$/.test(pathname)) {
|
||||
return; // CSS imports don't have external dependencies
|
||||
}
|
||||
importerPackage = extractPackageName(args.importer);
|
||||
keys.push(
|
||||
`node_modules/${importerPackage}/node_modules/${packageName}`,
|
||||
);
|
||||
@@ -89,22 +103,15 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
.find((info) => info);
|
||||
|
||||
const packagePath = args.path.slice(packageName.length);
|
||||
const version = packageInfo?.version;
|
||||
const version = packageInfo?.version
|
||||
|| packageLock.packages[`node_modules/${importerPackage}`]?.peerDependencies?.[packageName];
|
||||
|
||||
if (!version) return;
|
||||
const name = packageInfo?.name ?? packageName;
|
||||
const specifier = version
|
||||
? `${name}@${version}${packagePath}`
|
||||
: `${name}${packagePath}`;
|
||||
|
||||
const name = packageInfo.name ?? packageName;
|
||||
const specifier = `${name}@${version}${packagePath}`;
|
||||
|
||||
// Handle JSR packages with correct ESM.sh JSR format
|
||||
let url: URL;
|
||||
if (packageName.startsWith("@jsr/")) {
|
||||
// Convert @jsr/scope__package to jsr/@scope/package format for ESM.sh
|
||||
const jsrName = packageName.slice(5).replace("__", "/");
|
||||
url = new URL(`https://esm.sh/jsr/@${jsrName}@${version}${packagePath}`);
|
||||
} else {
|
||||
url = new URL(`https://esm.sh/*${specifier}`);
|
||||
}
|
||||
const url = new URL(`https://esm.sh/*${specifier}`);
|
||||
|
||||
if (target) {
|
||||
url.searchParams.set("target", target);
|
||||
@@ -118,109 +125,20 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
|
||||
// Handle relative or absolute imports inside esm.sh modules
|
||||
build.onResolve({ filter: /.*/, namespace: "esm" }, async (args) => {
|
||||
// Check if this is a bare package import (not a relative path)
|
||||
// Note: CSS assets and some other relative imports don't use ./ prefix
|
||||
const isLikelyAsset = /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|ico|webp|avif)$/i.test(args.path);
|
||||
const isRelativePath = args.path.startsWith("./") || args.path.startsWith("../") || args.path.startsWith("/") || isLikelyAsset;
|
||||
|
||||
if (!isRelativePath) {
|
||||
try {
|
||||
// This is a bare import like "@emotion/is-prop-valid" - treat it as a new package
|
||||
const packageName = args.path.startsWith("@")
|
||||
? args.path.split("/").slice(0, 2).join("/")
|
||||
: args.path.split("/")[0];
|
||||
|
||||
// Handle transitive dependency versions
|
||||
const keys: string[] = [];
|
||||
try {
|
||||
const importerPackage = extractPackageName(args.importer);
|
||||
keys.push(
|
||||
`node_modules/${importerPackage}/node_modules/${packageName}`,
|
||||
);
|
||||
} catch {
|
||||
// fallthrough
|
||||
}
|
||||
|
||||
if (packageName.startsWith("@jsr/")) {
|
||||
keys.push(`node_modules/@${packageName.slice(5).replace("__", "/")}`);
|
||||
}
|
||||
|
||||
keys.push(`node_modules/${packageName}`);
|
||||
|
||||
const packageInfo = keys
|
||||
.map((key) => packageLock.packages[key])
|
||||
.find((info) => info);
|
||||
|
||||
const packagePath = args.path.slice(packageName.length);
|
||||
const version = packageInfo?.version;
|
||||
|
||||
if (version) {
|
||||
const name = packageInfo.name ?? packageName;
|
||||
const specifier = `${name}@${version}${packagePath}`;
|
||||
|
||||
// Handle JSR packages with correct ESM.sh JSR format
|
||||
let url: URL;
|
||||
if (packageName.startsWith("@jsr/")) {
|
||||
// Convert @jsr/scope__package to jsr/@scope/package format for ESM.sh
|
||||
const jsrName = packageName.slice(5).replace("__", "/");
|
||||
url = new URL(`https://esm.sh/jsr/@${jsrName}@${version}${packagePath}`);
|
||||
} else {
|
||||
url = new URL(`https://esm.sh/*${specifier}`);
|
||||
}
|
||||
|
||||
if (target) {
|
||||
url.searchParams.set("target", target);
|
||||
}
|
||||
|
||||
return {
|
||||
path: url.toString(),
|
||||
namespace: "esm",
|
||||
};
|
||||
} else {
|
||||
// If we can't find the version in package lock, let ESM.sh resolve it
|
||||
// This handles transitive dependencies that might not be in our package-lock
|
||||
let url: URL;
|
||||
if (packageName.startsWith("@jsr/")) {
|
||||
// Convert @jsr/scope__package to jsr/@scope/package format for ESM.sh
|
||||
const jsrName = packageName.slice(5).replace("__", "/");
|
||||
url = new URL(`https://esm.sh/jsr/@${jsrName}${packagePath}`);
|
||||
} else {
|
||||
url = new URL(`https://esm.sh/${args.path}`);
|
||||
}
|
||||
|
||||
if (target) {
|
||||
url.searchParams.set("target", target);
|
||||
}
|
||||
|
||||
return {
|
||||
path: url.toString(),
|
||||
namespace: "esm",
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// If package resolution fails, fall through to URL resolution
|
||||
}
|
||||
}
|
||||
|
||||
let fullURL: URL;
|
||||
|
||||
try {
|
||||
fullURL = new URL(args.path);
|
||||
} catch {
|
||||
try {
|
||||
// Handle ESM.sh internal paths like /@jsr/package__name@version/...
|
||||
if (args.path.startsWith("/")) {
|
||||
fullURL = new URL(`https://esm.sh${args.path}`);
|
||||
} else {
|
||||
// When resolving relative paths, it's important the baseURL is *after* any redirects.
|
||||
// For example, `https://esm.sh/@fontsource/[email protected]` redirects to `https://esm.sh/@fontsource/[email protected]/index.css`
|
||||
// and this changes the outcome of resolving paths like `./font.woff2` and `../font.woff2`
|
||||
const baseURL = args.path.startsWith("./")
|
||||
? await getRedirectedURL(args.importer)
|
||||
: args.importer;
|
||||
// When resolving relative paths, it's important the baseURL is *after* any redirects.
|
||||
// For example, `https://esm.sh/@fontsource/[email protected]` redirects to `https://esm.sh/@fontsource/[email protected]/index.css`
|
||||
// and this changes the outcome of resolving paths like `./font.woff2` and `../font.woff2`
|
||||
const baseURL = args.path.startsWith("./")
|
||||
? await getRedirectedURL(args.importer)
|
||||
: args.importer;
|
||||
|
||||
fullURL = new URL(args.path, baseURL);
|
||||
}
|
||||
fullURL = new URL(args.path, baseURL);
|
||||
} catch {
|
||||
return {
|
||||
errors: [{ text: `Could not resolve ${args.path}` }],
|
||||
@@ -228,6 +146,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
// Skip static assets
|
||||
if (/\.(woff2?|ttf|otf|eot)$/.test(fullURL.pathname)) {
|
||||
return {
|
||||
path: fullURL.toString(),
|
||||
external: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
path: fullURL.toString(),
|
||||
namespace: "esm",
|
||||
@@ -243,40 +169,6 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
// Special handling for JSR packages when specific version isn't available
|
||||
if (args.path.includes('esm.sh/jsr/') && res.status === 404) {
|
||||
// Try without version (let ESM.sh pick the latest available version)
|
||||
const urlWithoutVersion = args.path.replace(/@[\d.]+(\?|$)/, '$1');
|
||||
|
||||
const fallbackRes = await fetch(urlWithoutVersion);
|
||||
|
||||
if (fallbackRes.ok) {
|
||||
if (fallbackRes.redirected) {
|
||||
redirectedURLs.set(args.path, fallbackRes.url);
|
||||
}
|
||||
|
||||
let loader: Loader | undefined;
|
||||
const contentType = fallbackRes.headers.get("Content-Type")?.split(";")[0];
|
||||
|
||||
if (contentType) {
|
||||
if (contentType === "application/javascript") {
|
||||
loader = "js";
|
||||
} else if (contentType === "text/css") {
|
||||
loader = "css";
|
||||
} else {
|
||||
loader = "text";
|
||||
}
|
||||
}
|
||||
|
||||
const contents = await fallbackRes.text();
|
||||
|
||||
return {
|
||||
contents,
|
||||
loader,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Failed to fetch ${args.path}`);
|
||||
}
|
||||
|
||||
|
||||
+31
-10
@@ -1,4 +1,4 @@
|
||||
import path from "path-browserify";
|
||||
import { join, dirname, extname } from "path-browserify";
|
||||
|
||||
import type { Loader, Plugin } from "esbuild-wasm";
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
@@ -8,27 +8,37 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
name: "fs",
|
||||
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^data:/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
external: true,
|
||||
};
|
||||
});
|
||||
|
||||
build.onResolve({ filter: /.*/ }, async (args) => {
|
||||
let resolved: string;
|
||||
|
||||
if (args.path.startsWith("@/")) {
|
||||
resolved = path.join(cwd, args.path.slice(2));
|
||||
resolved = join(cwd, args.path.slice(2));
|
||||
} else if (args.kind === "entry-point") {
|
||||
resolved = path.join(cwd, args.path);
|
||||
resolved = join(cwd, args.path);
|
||||
} else if (args.importer) {
|
||||
resolved = path.join(path.dirname(args.importer), args.path);
|
||||
resolved = join(dirname(args.importer), args.path);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// Vite query parameters https://vite.dev/guide/assets
|
||||
const [cleaned, query] = resolved.split("?");
|
||||
|
||||
try {
|
||||
resolved = await tryFileVariants(fs, resolved);
|
||||
resolved = await tryFileVariants(fs, cleaned);
|
||||
} catch {
|
||||
return; // Let other plugins handle this
|
||||
}
|
||||
|
||||
return {
|
||||
path: resolved,
|
||||
path: resolved + (typeof query === "string" ? "?" + query : ""),
|
||||
namespace: "fs",
|
||||
};
|
||||
});
|
||||
@@ -36,14 +46,25 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
build.onLoad(
|
||||
{ filter: /.*/, namespace: "fs" },
|
||||
async (args) => {
|
||||
const ext = path.extname(args.path).slice(1);
|
||||
const [path, query] = args.path.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
|
||||
// https://vite.dev/guide/assets.html#importing-asset-as-string
|
||||
if (params.has("raw")) {
|
||||
return {
|
||||
contents: await fs.readFile(path, "utf8"),
|
||||
loader: "text",
|
||||
};
|
||||
}
|
||||
|
||||
const ext = extname(path).slice(1);
|
||||
|
||||
if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return {
|
||||
contents: await fs.readFile(args.path, "utf8"),
|
||||
contents: await fs.readFile(path, "utf8"),
|
||||
loader: ext as Loader,
|
||||
};
|
||||
},
|
||||
@@ -56,7 +77,7 @@ async function tryFileVariants(
|
||||
fs: JSRuntimeFS,
|
||||
basePath: string,
|
||||
): Promise<string> {
|
||||
const extensions = [".ts", ".tsx", ".js", ".jsx", ".css", ".json"];
|
||||
const extensions = [".ts", ".tsx", ".js", ".jsx", ".css"];
|
||||
const stat = await statSafe(fs, basePath);
|
||||
|
||||
// If it's a file, check if it exists
|
||||
@@ -67,7 +88,7 @@ async function tryFileVariants(
|
||||
// If it's a directory, try index files
|
||||
if (stat.isDirectory()) {
|
||||
for (const ext of extensions) {
|
||||
const indexFile = path.join(basePath, "index" + ext);
|
||||
const indexFile = join(basePath, "index" + ext);
|
||||
const indexStat = await statSafe(fs, indexFile);
|
||||
if (indexStat.isFile()) {
|
||||
return indexFile;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { buildProject } from './index';
|
||||
import { copyFiles } from '../copyFiles';
|
||||
import { esmPlugin } from './esmPlugin';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock esbuild
|
||||
@@ -258,32 +257,4 @@ describe('buildProject', () => {
|
||||
// Should try to copy public files but directory is empty
|
||||
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
|
||||
});
|
||||
});
|
||||
|
||||
describe('esmPlugin JSR package handling', () => {
|
||||
it('should generate correct URLs for JSR packages', () => {
|
||||
const packageLock = {
|
||||
packages: {
|
||||
'node_modules/@jsr/nostrify__nostrify': {
|
||||
version: '0.46.11',
|
||||
name: '@jsr/nostrify__nostrify'
|
||||
},
|
||||
'node_modules/@nostrify/nostrify': {
|
||||
version: '0.46.11',
|
||||
name: '@jsr/nostrify__nostrify'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const plugin = esmPlugin(packageLock, 'esnext');
|
||||
|
||||
// Test the plugin setup to ensure it handles JSR packages correctly
|
||||
expect(plugin.name).toBe('esm');
|
||||
expect(plugin.setup).toBeDefined();
|
||||
|
||||
// The actual URL generation is tested through the resolve handlers
|
||||
// which are difficult to test directly, but the fix ensures:
|
||||
// - @jsr/[email protected] -> https://esm.sh/jsr/nostrify/[email protected]
|
||||
// - Regular packages still use -> https://esm.sh/*package@version
|
||||
});
|
||||
});
|
||||
+11
-6
@@ -1,6 +1,7 @@
|
||||
import { getEsbuild } from "@/lib/esbuild";
|
||||
import { copyFiles } from "@/lib/copyFiles";
|
||||
|
||||
import { shakespearePlugin } from "./shakespearePlugin";
|
||||
import { esmPlugin } from "./esmPlugin";
|
||||
import { fsPlugin } from "./fsPlugin";
|
||||
|
||||
@@ -49,6 +50,7 @@ async function bundle(
|
||||
outdir: "/",
|
||||
jsx: "automatic",
|
||||
plugins: [
|
||||
shakespearePlugin(), // Takes precedence over esmPlugin
|
||||
fsPlugin(fs, `${projectPath}/src`),
|
||||
esmPlugin(JSON.parse(packageLockText), target),
|
||||
],
|
||||
@@ -71,7 +73,7 @@ async function bundle(
|
||||
}
|
||||
|
||||
// Update index.html with proper script and link tags
|
||||
updateIndexHtml(doc);
|
||||
updateIndexHtml(doc, dist);
|
||||
|
||||
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
|
||||
dist["index.html"] = new TextEncoder().encode(updatedHtml);
|
||||
@@ -154,7 +156,7 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
function updateIndexHtml(doc: Document): void {
|
||||
function updateIndexHtml(doc: Document, dist: Record<string, Uint8Array>): void {
|
||||
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
|
||||
|
||||
if (!entrypoint) {
|
||||
@@ -163,8 +165,11 @@ function updateIndexHtml(doc: Document): void {
|
||||
|
||||
entrypoint.setAttribute("src", "/main.js");
|
||||
|
||||
const style = doc.createElement("link");
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
style.setAttribute("href", "/main.css");
|
||||
doc.head.appendChild(style);
|
||||
const css = dist["main.css"];
|
||||
if (css) {
|
||||
const style = doc.createElement("style");
|
||||
style.setAttribute("type", "text/tailwindcss");
|
||||
style.textContent = new TextDecoder().decode(css);
|
||||
doc.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import type { Plugin } from "esbuild-wasm";
|
||||
|
||||
/**
|
||||
* Shakespeare plugin for dependency polyfills and workarounds.
|
||||
* This plugin handles specific dependencies that need custom implementations
|
||||
* or dummy APIs to work correctly in the browser environment.
|
||||
*/
|
||||
export function shakespearePlugin(): Plugin {
|
||||
return {
|
||||
name: "shakespeare",
|
||||
|
||||
setup(build) {
|
||||
// Handle "sonner" imports with a dummy API
|
||||
build.onResolve({ filter: /^sonner$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-sonner",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy sonner implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-sonner" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of sonner toast library
|
||||
|
||||
// Toast function that does nothing
|
||||
const toast = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock]:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
// Add common toast methods
|
||||
toast.success = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Success:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.error = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Error:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.info = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Info:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.warning = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Warning:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.loading = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Loading:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.promise = (promise, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Promise:', promise, options);
|
||||
return promise;
|
||||
};
|
||||
|
||||
toast.dismiss = (id) => {
|
||||
console.log('[Shakespeare Sonner Mock] Dismiss:', id);
|
||||
};
|
||||
|
||||
// Toaster component (dummy React component)
|
||||
const Toaster = (props) => {
|
||||
console.log('[Shakespeare Sonner Mock] Toaster component rendered:', props);
|
||||
return null;
|
||||
};
|
||||
|
||||
// Export both named and default exports to match sonner API
|
||||
export { toast, Toaster };
|
||||
export default toast;
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle "next-themes" imports with a dummy API
|
||||
build.onResolve({ filter: /^next-themes$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-next-themes",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy next-themes implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-next-themes" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of next-themes
|
||||
|
||||
// useTheme hook that returns system theme
|
||||
const useTheme = () => {
|
||||
return { theme: "system" };
|
||||
};
|
||||
|
||||
// ThemeProvider component (dummy React component)
|
||||
const ThemeProvider = ({ children, ...props }) => {
|
||||
console.log('[Shakespeare next-themes Mock] ThemeProvider rendered:', props);
|
||||
return children;
|
||||
};
|
||||
|
||||
// Export both named and default exports to match next-themes API
|
||||
export { useTheme, ThemeProvider };
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle "virtual:pwa-register/react" imports with a dummy API
|
||||
build.onResolve({ filter: /^virtual:pwa-register\/react$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-pwa-register",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy PWA register implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-pwa-register" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of virtual:pwa-register/react
|
||||
|
||||
// useRegisterSW hook that returns dummy functions
|
||||
const useRegisterSW = (options = {}) => {
|
||||
console.log('[Shakespeare PWA Mock] useRegisterSW called:', options);
|
||||
|
||||
return {
|
||||
needRefresh: [false, () => {}],
|
||||
offlineReady: [false, () => {}],
|
||||
updateServiceWorker: (reloadPage) => {
|
||||
console.log('[Shakespeare PWA Mock] updateServiceWorker called:', reloadPage);
|
||||
if (reloadPage) {
|
||||
window.location.reload();
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
// Export the hook
|
||||
export { useRegisterSW };
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Add more dependency polyfills here as needed
|
||||
// Example structure for future dependencies:
|
||||
// build.onResolve({ filter: /^some-other-package$/ }, (args) => {
|
||||
// return {
|
||||
// path: args.path,
|
||||
// namespace: "shakespeare-other-package",
|
||||
// };
|
||||
// });
|
||||
//
|
||||
// build.onLoad({ filter: /.*/, namespace: "shakespeare-other-package" }, () => {
|
||||
// return {
|
||||
// contents: `// Custom implementation for some-other-package`,
|
||||
// loader: "js",
|
||||
// };
|
||||
// });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { GitAddCommand } from './add';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
import type { Git } from '../../git';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn().mockResolvedValue('mock content'),
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
readdir: vi.fn().mockResolvedValue([]),
|
||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}),
|
||||
lstat: vi.fn().mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
||||
rename: vi.fn().mockResolvedValue(undefined),
|
||||
readlink: vi.fn().mockResolvedValue('mock link'),
|
||||
symlink: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
|
||||
// Mock Git
|
||||
const createMockGit = (): Git => ({
|
||||
statusMatrix: vi.fn(),
|
||||
add: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
} as unknown as Git);
|
||||
|
||||
describe('GitAddCommand', () => {
|
||||
let addCommand: GitAddCommand;
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockGit: Git;
|
||||
const testCwd = '/test';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockGit = createMockGit();
|
||||
addCommand = new GitAddCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(addCommand.name).toBe('add');
|
||||
expect(addCommand.description).toBe('Add file contents to the index');
|
||||
expect(addCommand.usage).toBe('git add [--all | -A] [--] [<pathspec>...]');
|
||||
});
|
||||
|
||||
it('should return error when not in a git repository', async () => {
|
||||
// Mock stat to throw error for .git directory
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await addCommand.execute(['file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should return error when no files specified', async () => {
|
||||
const result = await addCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Nothing specified, nothing added');
|
||||
expect(result.stderr).toContain('Maybe you wanted to say \'git add .\'?');
|
||||
});
|
||||
|
||||
it('should add all modified files with --all flag', async () => {
|
||||
// Mock status matrix with modified and untracked files
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file (not staged)
|
||||
['untracked.txt', 0, 2, 0], // Untracked file
|
||||
['unchanged.txt', 1, 1, 1], // Unchanged file
|
||||
['staged.txt', 1, 2, 2], // Already staged file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(''); // Git add is silent on success
|
||||
|
||||
// Should add modified and untracked files, but not unchanged or already staged
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'modified.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'untracked.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should handle deleted files with --all flag', async () => {
|
||||
// Mock status matrix with deleted file
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['deleted.txt', 1, 0, 1], // Deleted file (not staged)
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
// Should remove the deleted file
|
||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'deleted.txt',
|
||||
});
|
||||
expect(mockGit.remove).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should add specific file', async () => {
|
||||
const result = await addCommand.execute(['file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle git add . (current directory)', async () => {
|
||||
// Mock status matrix with various files
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['file1.txt', 1, 2, 1], // Modified file
|
||||
['file2.txt', 0, 2, 0], // Untracked file
|
||||
['deleted.txt', 1, 0, 1], // Deleted file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['.']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
// Should add modified and untracked files
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file1.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file2.txt',
|
||||
});
|
||||
|
||||
// Should remove deleted file
|
||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'deleted.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await addCommand.execute(['/absolute/path/file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
});
|
||||
|
||||
it('should handle non-existent files', async () => {
|
||||
// Mock stat to throw error for non-existent file
|
||||
vi.mocked(mockFS.stat).mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
if (path.includes('nonexistent')) {
|
||||
throw new Error('ENOENT');
|
||||
}
|
||||
return Promise.resolve({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
});
|
||||
|
||||
// Mock git.remove to also throw error (file doesn't exist in git either)
|
||||
vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found'));
|
||||
|
||||
const result = await addCommand.execute(['nonexistent.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files');
|
||||
});
|
||||
|
||||
it('should handle -A flag (same as --all)', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['-A']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'modified.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle mixed options and paths', async () => {
|
||||
// Mock status matrix for --all to work
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all', 'specific.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
// When --all is specified, it should ignore specific paths and add all files
|
||||
expect(mockGit.statusMatrix).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle double dash separator', async () => {
|
||||
const result = await addCommand.execute(['--', 'file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should continue with other files if one fails', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['good.txt', 1, 2, 1], // This should succeed
|
||||
['bad.txt', 1, 2, 1], // This will fail
|
||||
]);
|
||||
|
||||
// Mock git.add to fail for bad.txt but succeed for good.txt
|
||||
vi.mocked(mockGit.add).mockImplementation(({ filepath }) => {
|
||||
if (filepath === 'bad.txt') {
|
||||
throw new Error('Permission denied');
|
||||
}
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0); // Should still succeed overall
|
||||
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
+20
-39
@@ -77,27 +77,22 @@ export class GitAddCommand implements GitSubcommand {
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
let addedCount = 0;
|
||||
let removedCount = 0;
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
try {
|
||||
if (workdirStatus === 0 && headStatus === 1) {
|
||||
// File was deleted
|
||||
// File was deleted in working directory
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
removedCount++;
|
||||
} else if (workdirStatus === 1) {
|
||||
// File exists (new or modified)
|
||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||
// File exists and has changes that aren't staged yet
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
addedCount++;
|
||||
}
|
||||
} catch {
|
||||
// Continue with other files if one fails
|
||||
@@ -105,19 +100,8 @@ export class GitAddCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
const messages: string[] = [];
|
||||
if (addedCount > 0) {
|
||||
messages.push(`Added ${addedCount} file${addedCount !== 1 ? 's' : ''}`);
|
||||
}
|
||||
if (removedCount > 0) {
|
||||
messages.push(`Removed ${removedCount} file${removedCount !== 1 ? 's' : ''}`);
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(messages.join(', ') + '\n');
|
||||
// Git add is typically silent on success, like real git
|
||||
return createSuccessResult('');
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to add all files: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
@@ -133,24 +117,24 @@ export class GitAddCommand implements GitSubcommand {
|
||||
if (path === '.') {
|
||||
// Add current directory (all files in it)
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
try {
|
||||
if (workdirStatus === 0 && headStatus === 1) {
|
||||
// File was deleted
|
||||
// File was deleted in working directory
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
addedFiles.push(filepath);
|
||||
} else if (workdirStatus === 1) {
|
||||
// File exists
|
||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||
// File exists and has changes that aren't staged yet
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
@@ -179,7 +163,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
} else {
|
||||
// Add single file
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: path,
|
||||
});
|
||||
@@ -189,7 +173,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
// Check if it's a deleted file
|
||||
try {
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: path,
|
||||
});
|
||||
@@ -208,11 +192,8 @@ export class GitAddCommand implements GitSubcommand {
|
||||
return createErrorResult(errors.join('\n'));
|
||||
}
|
||||
|
||||
if (addedFiles.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(`Added ${addedFiles.length} file${addedFiles.length !== 1 ? 's' : ''}\n`);
|
||||
// Git add is typically silent on success, like real git
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
private async addDirectory(dirPath: string, addedFiles: string[]): Promise<void> {
|
||||
@@ -231,7 +212,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
} else {
|
||||
try {
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: entryPath,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { GitStatusCommand } from './status';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
import type { Git } from '../../git';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn().mockResolvedValue('mock content'),
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
readdir: vi.fn().mockResolvedValue([]),
|
||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}),
|
||||
lstat: vi.fn().mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
||||
rename: vi.fn().mockResolvedValue(undefined),
|
||||
readlink: vi.fn().mockResolvedValue('mock link'),
|
||||
symlink: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
|
||||
// Mock Git
|
||||
const createMockGit = (): Git => ({
|
||||
statusMatrix: vi.fn(),
|
||||
currentBranch: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
} as unknown as Git);
|
||||
|
||||
describe('GitStatusCommand', () => {
|
||||
let statusCommand: GitStatusCommand;
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockGit: Git;
|
||||
const testCwd = '/test';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockGit = createMockGit();
|
||||
statusCommand = new GitStatusCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(statusCommand.name).toBe('status');
|
||||
expect(statusCommand.description).toBe('Show the working tree status');
|
||||
expect(statusCommand.usage).toBe('git status [--porcelain] [--short]');
|
||||
});
|
||||
|
||||
it('should return error when not in a git repository', async () => {
|
||||
// Mock stat to throw error for .git directory
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should show clean status when no changes', async () => {
|
||||
// Mock git status matrix with no changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('nothing to commit, working tree clean');
|
||||
});
|
||||
|
||||
it('should show untracked files correctly', async () => {
|
||||
// Mock git status matrix with untracked file
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
// Untracked: headStatus=0, stageStatus=0, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['newfile.txt', 0, 2, 0]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Untracked files:');
|
||||
expect(result.stdout).toContain('newfile.txt');
|
||||
});
|
||||
|
||||
it('should show staged files correctly', async () => {
|
||||
// Mock git status matrix with staged file
|
||||
// Staged new file: headStatus=0, stageStatus=2, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['newfile.txt', 0, 2, 2]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes to be committed:');
|
||||
expect(result.stdout).toContain('new file: newfile.txt');
|
||||
});
|
||||
|
||||
it('should show modified files correctly', async () => {
|
||||
// Mock git status matrix with modified file
|
||||
// Modified file: headStatus=1, stageStatus=1, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['existing.txt', 1, 2, 1]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('modified: existing.txt');
|
||||
});
|
||||
|
||||
it('should show deleted files correctly', async () => {
|
||||
// Mock git status matrix with deleted file
|
||||
// Deleted file: headStatus=1, stageStatus=1, workdirStatus=0
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['deleted.txt', 1, 0, 1]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('deleted: deleted.txt');
|
||||
});
|
||||
|
||||
it('should format porcelain output correctly', async () => {
|
||||
// Mock git status matrix with various changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['untracked.txt', 0, 2, 0], // Untracked
|
||||
['staged.txt', 0, 2, 2], // Staged new file
|
||||
['modified.txt', 1, 2, 1], // Modified
|
||||
['deleted.txt', 1, 0, 1], // Deleted
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute(['--porcelain']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('?? untracked.txt');
|
||||
expect(result.stdout).toContain('A staged.txt');
|
||||
expect(result.stdout).toContain(' M modified.txt');
|
||||
expect(result.stdout).toContain(' D deleted.txt');
|
||||
});
|
||||
|
||||
it('should handle short format', async () => {
|
||||
// Mock git status matrix with changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['untracked.txt', 0, 2, 0], // Untracked
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute(['--short']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('?? untracked.txt');
|
||||
});
|
||||
|
||||
it('should handle complex status matrix correctly', async () => {
|
||||
// Mock git status matrix with a complex scenario
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['file1.txt', 1, 2, 2], // Modified and staged
|
||||
['file2.txt', 0, 2, 0], // Untracked
|
||||
['file3.txt', 1, 0, 0], // Deleted (staged)
|
||||
['file4.txt', 1, 2, 1], // Modified (not staged)
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('feature-branch');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch feature-branch');
|
||||
expect(result.stdout).toContain('Changes to be committed:');
|
||||
expect(result.stdout).toContain('modified: file1.txt');
|
||||
expect(result.stdout).toContain('deleted: file3.txt');
|
||||
expect(result.stdout).toContain('Untracked files:');
|
||||
expect(result.stdout).toContain('file2.txt');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('modified: file4.txt');
|
||||
});
|
||||
|
||||
it('should handle detached HEAD state', async () => {
|
||||
// Mock git status matrix with no current branch
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue(undefined);
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD detached at unknown');
|
||||
expect(result.stdout).toContain('nothing to commit, working tree clean');
|
||||
});
|
||||
});
|
||||
@@ -39,7 +39,6 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
@@ -78,22 +77,26 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
let indexStatus = ' ';
|
||||
let workingStatus = ' ';
|
||||
|
||||
// Determine index status (staged changes)
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
indexStatus = 'A'; // Added
|
||||
// Determine index status (staged changes - comparing HEAD to stage)
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
indexStatus = 'A'; // Added to stage
|
||||
} else if (headStatus === 1 && stageStatus === 0) {
|
||||
indexStatus = 'D'; // Deleted
|
||||
} else if (headStatus === 1 && stageStatus === 1 && headStatus !== stageStatus) {
|
||||
indexStatus = 'M'; // Modified
|
||||
indexStatus = 'D'; // Deleted from stage
|
||||
} else if (headStatus === 1 && stageStatus === 2) {
|
||||
indexStatus = 'M'; // Modified in stage
|
||||
}
|
||||
|
||||
// Determine working directory status
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) {
|
||||
workingStatus = '?'; // Untracked
|
||||
// Determine working directory status (comparing stage to working dir)
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||
// Untracked files show as ?? in porcelain format
|
||||
indexStatus = '?';
|
||||
workingStatus = '?';
|
||||
} else if (stageStatus === 2 && workdirStatus === 0) {
|
||||
workingStatus = 'D'; // Deleted in working dir
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
workingStatus = 'D'; // Deleted
|
||||
} else if (stageStatus !== workdirStatus) {
|
||||
workingStatus = 'M'; // Modified
|
||||
workingStatus = 'D'; // Deleted in working dir (was same as HEAD)
|
||||
} else if (stageStatus !== workdirStatus && workdirStatus === 2) {
|
||||
workingStatus = 'M'; // Modified in working dir
|
||||
}
|
||||
|
||||
// Only show files with changes
|
||||
@@ -112,7 +115,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
if (currentBranch) {
|
||||
lines.push(`On branch ${currentBranch}`);
|
||||
} else {
|
||||
lines.push('On branch main');
|
||||
lines.push('HEAD detached at unknown');
|
||||
}
|
||||
|
||||
// Categorize changes
|
||||
@@ -122,24 +125,26 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
const deleted: string[] = [];
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
// Staged changes (index differs from HEAD)
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
// Staged changes (stage differs from HEAD)
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
staged.push(`\tnew file: ${filepath}`);
|
||||
} else if (headStatus === 1 && stageStatus === 0) {
|
||||
staged.push(`\tdeleted: ${filepath}`);
|
||||
} else if (headStatus !== stageStatus && headStatus === 1 && stageStatus === 1) {
|
||||
} else if (headStatus === 1 && stageStatus === 2) {
|
||||
staged.push(`\tmodified: ${filepath}`);
|
||||
}
|
||||
|
||||
// Working directory changes (working dir differs from index)
|
||||
if (stageStatus === 1 && workdirStatus === 0) {
|
||||
// Working directory changes (working dir differs from stage)
|
||||
if (stageStatus === 2 && workdirStatus === 0) {
|
||||
deleted.push(`\tdeleted: ${filepath}`);
|
||||
} else if (stageStatus !== workdirStatus && stageStatus === 1 && workdirStatus === 1) {
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
deleted.push(`\tdeleted: ${filepath}`);
|
||||
} else if (stageStatus !== workdirStatus && workdirStatus === 2) {
|
||||
modified.push(`\tmodified: ${filepath}`);
|
||||
}
|
||||
|
||||
// Untracked files
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) {
|
||||
// Untracked files (not in HEAD, not in stage, but in working dir)
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||
untracked.push(`\t${filepath}`);
|
||||
}
|
||||
}
|
||||
@@ -148,7 +153,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
if (staged.length > 0) {
|
||||
lines.push('');
|
||||
lines.push('Changes to be committed:');
|
||||
lines.push(' (use "git reset HEAD <file>..." to unstage)');
|
||||
lines.push(' (use "git restore --staged <file>..." to unstage)');
|
||||
lines.push('');
|
||||
lines.push(...staged);
|
||||
}
|
||||
@@ -158,7 +163,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
lines.push('');
|
||||
lines.push('Changes not staged for commit:');
|
||||
lines.push(' (use "git add <file>..." to update what will be committed)');
|
||||
lines.push(' (use "git checkout -- <file>..." to discard changes in working directory)');
|
||||
lines.push(' (use "git restore <file>..." to discard changes in working directory)');
|
||||
lines.push('');
|
||||
lines.push(...modified);
|
||||
lines.push(...deleted);
|
||||
|
||||
+1
-2
@@ -911,7 +911,6 @@ export class Git {
|
||||
const gitRelays = new Set<string>([
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
'wss://relay.nostr.band/', // General purpose relay as fallback
|
||||
]);
|
||||
|
||||
@@ -1313,6 +1312,7 @@ export class Git {
|
||||
dir: options.dir,
|
||||
ref: `refs/heads/${currentBranch}`,
|
||||
value: upstreamCommit,
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Update the working directory
|
||||
@@ -1395,7 +1395,6 @@ export class Git {
|
||||
relayUrls.push(
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
'wss://relay.nostr.band/'
|
||||
);
|
||||
}
|
||||
|
||||
@@ -81,9 +81,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Export files and manage local data',
|
||||
emailUpdates: 'Email Updates',
|
||||
emailUpdatesDescription: 'Subscribe to Shakespeare updates and resources',
|
||||
emailUpdatesDescriptionLong: 'Stay updated with the latest Shakespeare features, tutorials, and resources.',
|
||||
aboutShakespeareSettings: 'About Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Information about Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'New Project',
|
||||
@@ -207,7 +204,6 @@ const resources = {
|
||||
aboutShakespeare: 'About Shakespeare',
|
||||
aboutShakespeareDescription: 'Information about Shakespeare',
|
||||
sourceCode: 'Source Code',
|
||||
viewOnGitLab: 'View on GitLab',
|
||||
description: 'Description',
|
||||
license: 'License',
|
||||
loadingLicense: 'Loading license...',
|
||||
@@ -394,9 +390,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Exporte arquivos e gerencie dados locais',
|
||||
emailUpdates: 'Atualizações por Email',
|
||||
emailUpdatesDescription: 'Inscreva-se para receber atualizações e recursos do Shakespeare',
|
||||
emailUpdatesDescriptionLong: 'Mantenha-se atualizado com os recursos mais recentes do Shakespeare, tutoriais e recursos. Enviamos apenas atualizações ocasionais e você pode cancelar a inscrição a qualquer momento.',
|
||||
aboutShakespeareSettings: 'Sobre o Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Informações sobre o Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Novo Projeto',
|
||||
@@ -561,7 +554,6 @@ const resources = {
|
||||
aboutShakespeare: 'Sobre o Shakespeare',
|
||||
aboutShakespeareDescription: 'Informações sobre o Shakespeare.',
|
||||
sourceCode: 'Código-fonte',
|
||||
viewOnGitLab: 'Ver no GitLab',
|
||||
description: 'Descrição',
|
||||
license: 'Licença',
|
||||
loadingLicense: 'Carregando licença...',
|
||||
@@ -707,9 +699,6 @@ const resources = {
|
||||
dataSettingsDescription: '导出文件和管理本地数据',
|
||||
emailUpdates: '邮件更新',
|
||||
emailUpdatesDescription: '订阅Shakespeare更新和资源',
|
||||
emailUpdatesDescriptionLong: '及时了解最新的Shakespeare功能、教程和资源。我们只会偶尔发送更新,您可以随时取消订阅。',
|
||||
aboutShakespeareSettings: '关于Shakespeare',
|
||||
aboutShakespeareSettingsDescription: '关于Shakespeare的信息',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: '新项目',
|
||||
@@ -874,7 +863,6 @@ const resources = {
|
||||
aboutShakespeare: '关于Shakespeare',
|
||||
aboutShakespeareDescription: '关于Shakespeare的信息。',
|
||||
sourceCode: '源代码',
|
||||
viewOnGitLab: '在GitLab上查看',
|
||||
description: '描述',
|
||||
license: '许可证',
|
||||
loadingLicense: '加载许可证中...',
|
||||
@@ -1020,9 +1008,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Fitar da fayiloli da sarrafa bayanan gida',
|
||||
emailUpdates: 'Sabuntawar Imel',
|
||||
emailUpdatesDescription: 'Yi rajista don karbar sabuntawar Shakespeare da albarkatu',
|
||||
emailUpdatesDescriptionLong: 'Kasance da sabuntawa game da sabbin fasalolin Shakespeare, koyarwa, da albarkatu. Muna aika sabuntawa lokaci-lokaci kawai kuma kuna iya dakatar da rajista koyaushe.',
|
||||
aboutShakespeareSettings: 'Game da Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Bayani game da Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Sabon Aikin',
|
||||
@@ -1187,7 +1172,6 @@ const resources = {
|
||||
aboutShakespeare: 'Game da Shakespeare',
|
||||
aboutShakespeareDescription: 'Bayani game da Shakespeare.',
|
||||
sourceCode: 'Lambar Tushe',
|
||||
viewOnGitLab: 'Duba akan GitLab',
|
||||
description: 'Bayanin',
|
||||
license: 'Lasisi',
|
||||
loadingLicense: 'Ana lodin lasisi...',
|
||||
@@ -1333,9 +1317,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Gbe awọn faili jade ati ṣakoso data agbegbe',
|
||||
emailUpdates: 'Awọn Imudojuiwọn Imeeli',
|
||||
emailUpdatesDescription: 'Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo',
|
||||
emailUpdatesDescriptionLong: 'Wa pẹlu imudojuiwọn pẹlu awọn ẹya Shakespeare tuntun, awọn ikẹkọ, ati awọn ohun elo. A nfi awọn imudojuiwọn lọọrọọ nikan ranṣẹ ati pe o le da forukọsilẹ duro nigbakugba.',
|
||||
aboutShakespeareSettings: 'Nipa Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Alaye nipa Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Iṣẹ akanṣe Tuntun',
|
||||
@@ -1500,7 +1481,6 @@ const resources = {
|
||||
aboutShakespeare: 'Nipa Shakespeare',
|
||||
aboutShakespeareDescription: 'Alaye nipa Shakespeare.',
|
||||
sourceCode: 'Koodu Orisun',
|
||||
viewOnGitLab: 'Wo lori GitLab',
|
||||
description: 'Apejuwe',
|
||||
license: 'Iwe-aṣẹ',
|
||||
loadingLicense: 'N gbe iwe-aṣẹ...',
|
||||
@@ -1641,9 +1621,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Bupụta faịlụ na jikwaa data mpaghara',
|
||||
emailUpdates: 'Nmelite Email',
|
||||
emailUpdatesDescription: 'Debanye aha maka nmelite Shakespeare na akụrụngwa',
|
||||
emailUpdatesDescriptionLong: 'Nọrọ na-emelite na atụmatụ Shakespeare ọhụrụ, nkuzi, na akụrụngwa. Anyị na-eziga naanị nmelite mgbe ụfọdụ ma ị nwere ike ịkwụsị ndebanye aha mgbe ọ bụla.',
|
||||
aboutShakespeareSettings: 'Gbasara Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Ozi gbasara Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Ọrụ Ọhụrụ',
|
||||
@@ -1808,7 +1785,6 @@ const resources = {
|
||||
aboutShakespeare: 'Gbasara Shakespeare',
|
||||
aboutShakespeareDescription: 'Ozi gbasara Shakespeare.',
|
||||
sourceCode: 'Koodu Isi',
|
||||
viewOnGitLab: 'Lee na GitLab',
|
||||
description: 'Nkọwa',
|
||||
license: 'Ikike',
|
||||
loadingLicense: 'Na-ebu ikike...',
|
||||
|
||||
@@ -195,6 +195,25 @@ describe('NpmAddPackageTool', () => {
|
||||
}
|
||||
};
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2));
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
// Should not fetch from registry when no version specified and package already installed
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package lodash is already installed in dependencies with version ^4.17.21.');
|
||||
});
|
||||
|
||||
it('should handle package already installed with specific version', async () => {
|
||||
const packageJson = {
|
||||
name: 'test-project',
|
||||
version: '1.0.0',
|
||||
dependencies: {
|
||||
'lodash': '^4.17.21'
|
||||
}
|
||||
};
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2));
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
@@ -208,10 +227,10 @@ describe('NpmAddPackageTool', () => {
|
||||
})
|
||||
});
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
const result = await tool.execute({ name: 'lodash', version: '4.17.21' });
|
||||
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package [email protected] is already installed');
|
||||
expect(result).toContain('ℹ️ Package [email protected] is already installed in dependencies.');
|
||||
});
|
||||
|
||||
it('should handle missing package.json', async () => {
|
||||
|
||||
@@ -88,6 +88,16 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
throw new Error(`❌ Invalid package.json format. Could not parse JSON.`);
|
||||
}
|
||||
|
||||
// Check if package already exists
|
||||
const dependencyKey = dev ? 'devDependencies' : 'dependencies';
|
||||
const otherKey = dev ? 'dependencies' : 'devDependencies';
|
||||
|
||||
// If no version is specified and package is already installed, it's a no-op
|
||||
if (!version && packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
return `ℹ️ Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.`;
|
||||
}
|
||||
|
||||
// Determine version to use and fetch package metadata
|
||||
let targetVersion = version;
|
||||
let packageMetadata: NpmRegistryResponse;
|
||||
@@ -107,10 +117,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
}
|
||||
}
|
||||
|
||||
// Check if package already exists
|
||||
const dependencyKey = dev ? 'devDependencies' : 'dependencies';
|
||||
const otherKey = dev ? 'dependencies' : 'devDependencies';
|
||||
|
||||
// Check if package already exists with the specific version
|
||||
if (packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
if (currentVersion === `^${targetVersion}`) {
|
||||
|
||||
+50
-58
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react';
|
||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { EmailSubscription } from '@/components/EmailSubscription';
|
||||
|
||||
export function AboutSettings() {
|
||||
const { t } = useTranslation();
|
||||
@@ -78,64 +78,56 @@ export function AboutSettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Project Information */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
{t('sourceCode')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<Button
|
||||
variant="outline"
|
||||
asChild
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<a
|
||||
href="https://gitlab.com/soapbox-pub/act2"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
{t('viewOnGitLab')}
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-6 max-w-xl">
|
||||
{/* Email Updates */}
|
||||
<EmailSubscription />
|
||||
|
||||
{/* License */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<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" />
|
||||
{t('license')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground py-4">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('loadingLicense')}</span>
|
||||
<div className="space-y-3">
|
||||
{/* Project Information */}
|
||||
<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" 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" />
|
||||
{t('license')}
|
||||
</div>
|
||||
) : error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{t('failedToLoadLicense')}: {error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : license ? (
|
||||
<div className="prose text-sm" dangerouslySetInnerHTML={{ __html: license }} />
|
||||
) : null}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground py-4">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('loadingLicense')}</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{t('failedToLoadLicense')}: {error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : license ? (
|
||||
<div
|
||||
className="prose text-sm dark:prose-invert mx-auto"
|
||||
dangerouslySetInnerHTML={{ __html: license }}
|
||||
/>
|
||||
) : null}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+55
-2
@@ -4,11 +4,12 @@ import { useTranslation } from 'react-i18next';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { GitBranch, Loader2, AlertCircle } from 'lucide-react';
|
||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
import { ProjectImportDialog } from '@/components/ProjectImportDialog';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
|
||||
export default function Clone() {
|
||||
const { t } = useTranslation();
|
||||
@@ -20,6 +21,7 @@ export default function Clone() {
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const autoCloneInitiatedRef = useRef(false);
|
||||
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||
|
||||
useSeoMeta({
|
||||
title: `${t('importRepository')} - Shakespeare`,
|
||||
@@ -171,6 +173,28 @@ export default function Clone() {
|
||||
}
|
||||
}, [handleClone, searchParams]);
|
||||
|
||||
const handleImportZip = async (
|
||||
data: { file: File; projectId?: string },
|
||||
overwrite: boolean
|
||||
) => {
|
||||
try {
|
||||
// Single project import from ZIP file
|
||||
const project = await projectsManager.importProjectFromZip(data.file, data.projectId, overwrite);
|
||||
|
||||
// Show success toast
|
||||
toast({
|
||||
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
|
||||
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
|
||||
});
|
||||
|
||||
// Navigate to the imported project
|
||||
navigate(`/project/${project.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to import project:', error);
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AppLayout title={t('importRepository')}>
|
||||
<div className="max-w-2xl mx-auto">
|
||||
@@ -226,7 +250,36 @@ export default function Clone() {
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Import ZIP File Link */}
|
||||
<div className="mt-8 text-center">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="text-muted-foreground hover:text-primary hover:bg-transparent">
|
||||
<MoreHorizontal className="h-5 w-5" />
|
||||
<span className="sr-only">More options</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center">
|
||||
<DropdownMenuItem
|
||||
className="flex items-center gap-2 w-full"
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ZIP Import Dialog */}
|
||||
<ProjectImportDialog
|
||||
mode="single"
|
||||
onImport={handleImportZip}
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield, Upload } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
@@ -10,6 +11,8 @@ import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { ProjectImportDialog } from '@/components/ProjectImportDialog';
|
||||
import {
|
||||
isPersistentStorageSupported,
|
||||
isPersistentStorageGranted,
|
||||
@@ -39,10 +42,13 @@ export function DataSettings() {
|
||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||
const [isBulkImportOpen, setIsBulkImportOpen] = useState(false);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const projectsManager = useProjectsManager();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Format bytes to human readable format
|
||||
const formatBytes = (bytes: number): string => {
|
||||
@@ -217,6 +223,67 @@ export function DataSettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkImport = async (
|
||||
data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] },
|
||||
overwrite: boolean
|
||||
) => {
|
||||
try {
|
||||
let successCount = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
// Handle both single and bulk import data
|
||||
if ('projects' in data) {
|
||||
// Bulk import
|
||||
for (const project of data.projects) {
|
||||
try {
|
||||
// Import the project directly using files (bypasses ZIP creation)
|
||||
await projectsManager.importProject(
|
||||
{ files: project.files },
|
||||
{ projectId: project.id, overwrite, projectName: project.id }
|
||||
);
|
||||
successCount++;
|
||||
} catch (error) {
|
||||
console.error(`Failed to import project ${project.id}:`, error);
|
||||
errors.push(`${project.id}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single import (shouldn't happen in bulk mode, but handle gracefully)
|
||||
throw new Error('Single import not supported in bulk import mode');
|
||||
}
|
||||
|
||||
// Show success/error toast and refresh project list
|
||||
if (successCount > 0) {
|
||||
// Refresh projects list to show newly imported projects
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
|
||||
toast({
|
||||
title: `${successCount} Project${successCount !== 1 ? 's' : ''} Imported Successfully`,
|
||||
description: errors.length > 0
|
||||
? `${errors.length} project${errors.length !== 1 ? 's' : ''} failed to import.`
|
||||
: `All projects have been imported and are ready to use.`,
|
||||
variant: errors.length > 0 ? "destructive" : "default",
|
||||
});
|
||||
}
|
||||
|
||||
if (errors.length > 0 && successCount === 0) {
|
||||
toast({
|
||||
title: "Import Failed",
|
||||
description: `Failed to import projects: ${errors.slice(0, 3).join(', ')}${errors.length > 3 ? '...' : ''}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Bulk import failed:', error);
|
||||
toast({
|
||||
title: "Import Failed",
|
||||
description: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||
variant: "destructive",
|
||||
});
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearAllData = async () => {
|
||||
setIsClearing(true);
|
||||
try {
|
||||
@@ -391,6 +458,28 @@ export function DataSettings() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Import Projects */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Import Projects
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Import multiple projects from a ZIP file exported from Shakespeare. You can choose which projects to import and handle conflicts with existing projects.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button
|
||||
onClick={() => setIsBulkImportOpen(true)}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-2" />
|
||||
Import Projects
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Clear All Data */}
|
||||
<Card className="border-destructive/20">
|
||||
<CardHeader>
|
||||
@@ -459,6 +548,14 @@ export function DataSettings() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Bulk Project Import Dialog */}
|
||||
<ProjectImportDialog
|
||||
mode="bulk"
|
||||
onImport={handleBulkImport}
|
||||
open={isBulkImportOpen}
|
||||
onOpenChange={setIsBulkImportOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,292 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ArrowLeft, Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSettings() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0');
|
||||
const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`;
|
||||
const tag = '8982396';
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Submit to Mailchimp
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = url.href;
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = tag;
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = honeypot;
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={() => navigate('/settings')}
|
||||
className="w-full"
|
||||
>
|
||||
Back to Settings
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">
|
||||
Stay Updated with Shakespeare
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default EmailSettings;
|
||||
+4
-1
@@ -21,6 +21,7 @@ import { ModelSelector } from '@/components/ModelSelector';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useTranslation();
|
||||
@@ -267,7 +268,9 @@ export default function Index() {
|
||||
<AppLayout headerContent={headerContent}>
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="text-center mb-8 md:mb-12">
|
||||
<div className="text-4xl md:text-6xl mb-4 md:mb-6">🎭</div>
|
||||
<div className="mb-4 md:mb-6">
|
||||
<ShakespeareLogo className="w-20 h-20 md:w-24 md:h-24 mx-auto" />
|
||||
</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')}
|
||||
</h1>
|
||||
|
||||
@@ -92,15 +92,13 @@ export function NostrSettings() {
|
||||
{isLoading ? (
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
{/* Loading skeleton for accounts */}
|
||||
{[...Array(2)].map((_, i) => (
|
||||
<div key={i} className="flex items-center gap-3 p-3 border-b last:border-b-0">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-8 rounded" />
|
||||
<div className="flex items-center gap-3 p-3 border-b last:border-b-0">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
))}
|
||||
<Skeleton className="h-8 w-8 rounded" />
|
||||
</div>
|
||||
{/* Add account button skeleton */}
|
||||
<div className="flex items-center gap-3 p-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
|
||||
@@ -18,7 +18,7 @@ import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
import { clearConsoleMessages } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -29,6 +29,7 @@ export function ProjectView() {
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
||||
|
||||
const projectsManager = useProjectsManager();
|
||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||
@@ -46,8 +47,9 @@ export function ProjectView() {
|
||||
try {
|
||||
const projectData = await projectsManager.getProject(projectId);
|
||||
setProject(projectData);
|
||||
// Clear console messages when switching projects
|
||||
// Clear console messages and error state when switching projects
|
||||
clearConsoleMessages();
|
||||
setConsoleError(null);
|
||||
} catch (error) {
|
||||
console.error('Failed to load project:', error);
|
||||
} finally {
|
||||
@@ -79,6 +81,16 @@ export function ProjectView() {
|
||||
}
|
||||
}, [isPreviewable, mobileView, activeTab]);
|
||||
|
||||
// Global console error listener (always active regardless of current tab)
|
||||
useEffect(() => {
|
||||
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||
setConsoleError(error);
|
||||
};
|
||||
|
||||
addErrorListener(handleConsoleError);
|
||||
return () => removeErrorListener(handleConsoleError);
|
||||
}, []);
|
||||
|
||||
const handleNewChat = () => {
|
||||
// Reset to chat view on mobile when starting new chat
|
||||
if (isMobile) {
|
||||
@@ -100,6 +112,10 @@ export function ProjectView() {
|
||||
// when isAILoading becomes true after user interaction
|
||||
};
|
||||
|
||||
const handleDismissConsoleError = () => {
|
||||
setConsoleError(null);
|
||||
};
|
||||
|
||||
const handleProjectDeleted = async () => {
|
||||
setProject(null);
|
||||
navigate('/');
|
||||
@@ -212,6 +228,8 @@ export function ProjectView() {
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={build.isPending}
|
||||
consoleError={consoleError}
|
||||
onDismissConsoleError={handleDismissConsoleError}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
interface SettingsItem {
|
||||
@@ -48,13 +48,6 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
Reference in new issue
Block a user