mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Merge remote-tracking branch 'origin/main' into electron
This commit is contained in:
28 files changed
+5982
-649
No files matched your search
@@ -119,6 +119,30 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
|
||||
|
||||
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
|
||||
|
||||
### Gift Card Redemption
|
||||
|
||||
Shakespeare supports automatic gift card redemption via URL parameters. Users can click shareable gift card links to instantly redeem AI credits.
|
||||
|
||||
**URL Format:**
|
||||
```
|
||||
/giftcard#baseURL=<providerBaseURL>&code=<giftcardCode>
|
||||
```
|
||||
|
||||
**Flow:**
|
||||
1. User clicks gift card link (e.g., from email or social media)
|
||||
2. Shakespeare displays a dialog showing the credit amount
|
||||
3. URL is rewritten to `/` for privacy (removes gift card code from history)
|
||||
4. If user is not logged in or provider is not configured, a multi-step wizard guides them through setup
|
||||
5. User can switch between Nostr accounts before redeeming
|
||||
6. Credits are added to the user's account via NIP-98 authenticated API call
|
||||
|
||||
**Components:**
|
||||
- `GiftCardRedeemDialog`: Main dialog handling the entire redemption flow
|
||||
- Integrates with existing login/signup dialogs and provider configuration
|
||||
- Automatically matches provider baseURL against configured providers and presets
|
||||
|
||||
See `GIFTCARD_REDEMPTION.md` for detailed documentation.
|
||||
|
||||
## AI Message Format
|
||||
|
||||
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
|
||||
|
||||
@@ -10,6 +10,7 @@ https://shakespeare.diy
|
||||
|
||||
- **Use any AI provider** OpenAI, Anthropic, OpenRouter, xAI, ZAI, Deepseek, and more
|
||||
- **Buy credits anonymously** with Nostr and Lightning ⚡
|
||||
- **Redeem gift cards** with shareable links for instant credits
|
||||
- **Runs entirely in the browser** No backend required
|
||||
- **Desktop app available** Run as a native Electron application on macOS, Windows, and Linux
|
||||
|
||||
@@ -55,6 +56,13 @@ npm run electron:build
|
||||
```
|
||||
|
||||
For detailed instructions, see [electron/QUICKSTART.md](electron/QUICKSTART.md).
|
||||
## Mirrors
|
||||
|
||||
Shakespeare is available on the following URLs:
|
||||
|
||||
- [shakespeare.diy](https://shakespeare.diy)
|
||||
- [shakespeare.soapbox.dev](https://shakespeare.soapbox.dev)
|
||||
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
|
||||
|
||||
## Alternatives
|
||||
|
||||
|
||||
Generated
+3892
-408
File diff suppressed because it is too large.
Load diff
@@ -111,6 +111,7 @@
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"workbox-window": "^7.3.0",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -144,6 +145,7 @@
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-pwa": "^1.1.0",
|
||||
"vitest": "^3.1.4"
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
// Shakespeare Service Worker
|
||||
// Simple passthrough fetch handler
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
console.log('[ServiceWorker] Install');
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
console.log('[ServiceWorker] Activate');
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
// Passthrough: just fetch the request normally
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Favicon Proxy Service
|
||||
*
|
||||
* Proxies favicon requests to DuckDuckGo's favicon service.
|
||||
* This allows fetching favicons for any domain without CORS issues.
|
||||
*
|
||||
* Usage: GET /favicon?url=https://example.com
|
||||
* Returns: The favicon image for the specified domain
|
||||
*/
|
||||
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const requestUrl = new URL(request.url);
|
||||
const targetUrl = requestUrl.searchParams.get('url');
|
||||
|
||||
if (!targetUrl) {
|
||||
return new Response('Missing url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(targetUrl);
|
||||
} catch {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// AI-provider-specific hacks
|
||||
let hostname = url.hostname;
|
||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||
hostname = 'ollama.com';
|
||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||
hostname = 'gemini.google.com';
|
||||
} else if (url.host === 'api.z.ai') {
|
||||
hostname = 'docs.z.ai';
|
||||
}
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
return fetchFavicon(hostname);
|
||||
},
|
||||
};
|
||||
|
||||
function fetchFavicon(hostname: string): Promise<Response> {
|
||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||
}
|
||||
+5
-1
@@ -23,6 +23,8 @@ import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { ElectronFSAdapter } from '@/lib/ElectronFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -89,7 +91,7 @@ const defaultConfig: AppConfig = {
|
||||
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
|
||||
esmUrl: "https://esm.shakespeare.diy",
|
||||
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
|
||||
faviconUrl: "https://external-content.duckduckgo.com/ip3/{hostname}.ico",
|
||||
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
|
||||
previewDomain: "local-shakespeare.dev",
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
|
||||
@@ -144,6 +146,8 @@ export function App() {
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
|
||||
@@ -34,6 +34,7 @@ export function AppRouter() {
|
||||
<URLFragmentHandler />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/giftcard" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Check, Sparkles, ArrowRight, AlertCircle } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Check, Sparkles, ArrowRight, AlertCircle, ExternalLink } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
@@ -14,6 +15,7 @@ interface AddProviderDialogProps {
|
||||
|
||||
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
|
||||
const scrollableContentRef = useRef<HTMLDivElement>(null);
|
||||
const [agreedToTerms, setAgreedToTerms] = useState(false);
|
||||
|
||||
const { settings, setProvider } = useAISettings();
|
||||
|
||||
@@ -25,27 +27,26 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
existingProvider.nostr === provider.nostr &&
|
||||
existingProvider.proxy === provider.proxy;
|
||||
|
||||
// Get provider name from presets or fallback to id
|
||||
const getProviderName = () => {
|
||||
const preset = AI_PROVIDER_PRESETS.find(
|
||||
p => p.id === provider.id && p.baseURL === provider.baseURL
|
||||
);
|
||||
return preset?.name || provider.id;
|
||||
};
|
||||
|
||||
const providerName = getProviderName();
|
||||
// Get provider preset if available
|
||||
const preset = AI_PROVIDER_PRESETS.find(
|
||||
p => p.id === provider.id && p.baseURL === provider.baseURL
|
||||
);
|
||||
const providerName = preset?.name || provider.id;
|
||||
|
||||
const handleAddProvider = () => {
|
||||
setProvider(provider);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// Scroll to top when dialog opens
|
||||
// Reset agreed to terms when dialog opens or provider changes
|
||||
useEffect(() => {
|
||||
if (open && scrollableContentRef.current) {
|
||||
scrollableContentRef.current.scrollTop = 0;
|
||||
if (open) {
|
||||
setAgreedToTerms(false);
|
||||
if (scrollableContentRef.current) {
|
||||
scrollableContentRef.current.scrollTop = 0;
|
||||
}
|
||||
}
|
||||
}, [open]);
|
||||
}, [open, provider.id]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -164,8 +165,40 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Terms of Service Agreement */}
|
||||
{preset?.tosURL && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Checkbox
|
||||
id="agree-provider-terms"
|
||||
checked={agreedToTerms}
|
||||
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-provider-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
I agree to {providerName}'s{' '}
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline hover:no-underline inline-flex items-center gap-1"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Terms of Service
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button onClick={handleAddProvider}>
|
||||
<Button
|
||||
onClick={handleAddProvider}
|
||||
disabled={preset?.tosURL ? !agreedToTerms : false}
|
||||
>
|
||||
Add Provider
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
+761
-144
@@ -1,15 +1,15 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import QRCode from 'qrcode';
|
||||
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft } from 'lucide-react';
|
||||
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
@@ -50,6 +50,35 @@ interface AddCreditsRequest {
|
||||
redirect_url?: string;
|
||||
}
|
||||
|
||||
interface Giftcard {
|
||||
object: 'giftcard';
|
||||
id: string;
|
||||
code: string;
|
||||
amount: number;
|
||||
redeemed: boolean;
|
||||
created_at?: number;
|
||||
}
|
||||
|
||||
interface GiftcardsResponse {
|
||||
object: 'list';
|
||||
data: Giftcard[];
|
||||
has_more: boolean;
|
||||
}
|
||||
|
||||
interface CreateGiftcardRequest {
|
||||
amount: number;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
interface RedeemGiftcardRequest {
|
||||
code: string;
|
||||
}
|
||||
|
||||
interface GiftcardRedemption {
|
||||
object: 'giftcard_redemption';
|
||||
amount: number;
|
||||
}
|
||||
|
||||
const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
|
||||
|
||||
interface LightningPaymentProps {
|
||||
@@ -192,6 +221,11 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
|
||||
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
|
||||
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
|
||||
const [giftcardAmount, setGiftcardAmount] = useState<number>(10);
|
||||
const [giftcardQuantity, setGiftcardQuantity] = useState<number>(1);
|
||||
const [redeemCode, setRedeemCode] = useState<string>('');
|
||||
const [copiedCode, setCopiedCode] = useState<string | null>(null);
|
||||
const [isPrintingQRCodes, setIsPrintingQRCodes] = useState(false);
|
||||
|
||||
// Query for payment history
|
||||
const { data: payments, isLoading: isLoadingPayments } = useQuery({
|
||||
@@ -206,6 +240,19 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
// Query for gift cards
|
||||
const { data: giftcards, isLoading: isLoadingGiftcards } = useQuery({
|
||||
queryKey: ['ai-giftcards', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
queryFn: async (): Promise<Giftcard[]> => {
|
||||
const ai = createAIClient(provider, user, config.corsProxy);
|
||||
const data = await ai.get('/credits/giftcards?limit=50') as GiftcardsResponse;
|
||||
return data.data;
|
||||
},
|
||||
enabled: open,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
// Mutation for adding credits
|
||||
const addCreditsMutation = useMutation({
|
||||
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
|
||||
@@ -316,6 +363,77 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
},
|
||||
});
|
||||
|
||||
// Mutation for creating gift cards
|
||||
const createGiftcardMutation = useMutation({
|
||||
mutationFn: async (request: CreateGiftcardRequest): Promise<Giftcard[]> => {
|
||||
const ai = createAIClient(provider, user, config.corsProxy);
|
||||
const response = await ai.post('/credits/giftcards', {
|
||||
body: request,
|
||||
}) as GiftcardsResponse;
|
||||
return response.data;
|
||||
},
|
||||
onSuccess: (giftcards) => {
|
||||
toast({
|
||||
title: 'Gift Cards created!',
|
||||
description: `Successfully created ${giftcards.length} gift card${giftcards.length > 1 ? 's' : ''}.`,
|
||||
});
|
||||
|
||||
// Refresh gift cards list
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['ai-giftcards', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
});
|
||||
|
||||
// Refresh credits balance
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
});
|
||||
|
||||
// Reset form
|
||||
setGiftcardAmount(10);
|
||||
setGiftcardQuantity(1);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const errorMessage = error?.message || 'Failed to create gift cards';
|
||||
toast({
|
||||
title: 'Creation failed',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Mutation for redeeming gift cards
|
||||
const redeemGiftcardMutation = useMutation({
|
||||
mutationFn: async (request: RedeemGiftcardRequest): Promise<GiftcardRedemption> => {
|
||||
const ai = createAIClient(provider, user, config.corsProxy);
|
||||
return await ai.post('/credits/giftcards/redeem', {
|
||||
body: request,
|
||||
}) as GiftcardRedemption;
|
||||
},
|
||||
onSuccess: (redemption) => {
|
||||
toast({
|
||||
title: 'Gift Card redeemed!',
|
||||
description: `${formatCurrency(redemption.amount)} has been added to your account.`,
|
||||
});
|
||||
|
||||
// Refresh credits balance
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
});
|
||||
|
||||
// Reset redeem code
|
||||
setRedeemCode('');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const errorMessage = error?.message || 'Failed to redeem gift card';
|
||||
toast({
|
||||
title: 'Redemption failed',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleAddCredits = () => {
|
||||
if (amount <= 0) {
|
||||
toast({
|
||||
@@ -338,6 +456,292 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
addCreditsMutation.mutate(request);
|
||||
};
|
||||
|
||||
const handleCreateGiftcard = () => {
|
||||
if (giftcardAmount <= 0) {
|
||||
toast({
|
||||
title: 'Invalid amount',
|
||||
description: 'Please enter a valid amount.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (giftcardQuantity <= 0 || giftcardQuantity > 100) {
|
||||
toast({
|
||||
title: 'Invalid quantity',
|
||||
description: 'Quantity must be between 1 and 100.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
createGiftcardMutation.mutate({
|
||||
amount: giftcardAmount,
|
||||
quantity: giftcardQuantity,
|
||||
});
|
||||
};
|
||||
|
||||
const handleRedeemGiftcard = () => {
|
||||
const trimmedCode = redeemCode.trim();
|
||||
if (!trimmedCode) {
|
||||
toast({
|
||||
title: 'Invalid code',
|
||||
description: 'Please enter a gift card code.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
redeemGiftcardMutation.mutate({ code: trimmedCode });
|
||||
};
|
||||
|
||||
const handleCopyCode = (code: string) => {
|
||||
navigator.clipboard.writeText(code);
|
||||
setCopiedCode(code);
|
||||
setTimeout(() => setCopiedCode(null), 2000);
|
||||
};
|
||||
|
||||
const handlePrintGiftcards = async () => {
|
||||
if (!giftcards || giftcards.length === 0) return;
|
||||
|
||||
// Filter only active (non-redeemed) gift cards
|
||||
const activeGiftcards = giftcards.filter(gc => !gc.redeemed);
|
||||
if (activeGiftcards.length === 0) {
|
||||
toast({
|
||||
title: 'No active gift cards',
|
||||
description: 'You have no active gift cards to print.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPrintingQRCodes(true);
|
||||
|
||||
try {
|
||||
// Generate QR codes for all active gift cards
|
||||
const qrCodePromises = activeGiftcards.map(async (giftcard) => {
|
||||
const url = `${window.location.origin}/giftcard#baseURL=${encodeURIComponent(provider.baseURL)}&code=${encodeURIComponent(giftcard.code)}`;
|
||||
const qrDataUrl = await QRCode.toDataURL(url, {
|
||||
width: 256,
|
||||
margin: 2,
|
||||
color: {
|
||||
dark: '#000000',
|
||||
light: '#ffffff',
|
||||
},
|
||||
});
|
||||
return {
|
||||
...giftcard,
|
||||
qrDataUrl,
|
||||
};
|
||||
});
|
||||
|
||||
const giftcardsWithQR = await Promise.all(qrCodePromises);
|
||||
|
||||
// Create a new window for printing
|
||||
const printWindow = window.open('', '_blank');
|
||||
if (!printWindow) {
|
||||
throw new Error('Failed to open print window. Please allow popups for this site.');
|
||||
}
|
||||
|
||||
// Generate the print HTML
|
||||
const printHTML = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Shakespeare AI Gift Cards</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
padding: 20px;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 20px;
|
||||
max-width: 8.5in;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.card {
|
||||
border: 2px solid #000;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
page-break-inside: avoid;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 15px;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.qr-code {
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
margin: 0 auto 15px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.amount {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
color: #000;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.code {
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 14px;
|
||||
background: #f5f5f5;
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
word-break: break-all;
|
||||
color: #000;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.footer {
|
||||
margin-top: 10px;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
@media print {
|
||||
body {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.grid {
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.card {
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="grid">
|
||||
${giftcardsWithQR.map(gc => `
|
||||
<div class="card">
|
||||
<div class="card-title">Shakespeare AI Gift Card</div>
|
||||
<img src="${gc.qrDataUrl}" alt="QR Code" class="qr-code" />
|
||||
<div class="amount">${formatCurrency(gc.amount)}</div>
|
||||
<div class="code">${gc.code}</div>
|
||||
<div class="footer">Scan to redeem</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
printWindow.document.write(printHTML);
|
||||
printWindow.document.close();
|
||||
|
||||
// Wait for images to load before printing
|
||||
printWindow.onload = () => {
|
||||
setTimeout(() => {
|
||||
printWindow.print();
|
||||
}, 250);
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to generate QR codes:', error);
|
||||
toast({
|
||||
title: 'Print failed',
|
||||
description: error instanceof Error ? error.message : 'Failed to generate QR codes for printing',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsPrintingQRCodes(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadCSV = () => {
|
||||
if (!giftcards || giftcards.length === 0) return;
|
||||
|
||||
// Filter only active (non-redeemed) gift cards
|
||||
const activeGiftcards = giftcards.filter(gc => !gc.redeemed);
|
||||
if (activeGiftcards.length === 0) {
|
||||
toast({
|
||||
title: 'No active gift cards',
|
||||
description: 'You have no active gift cards to download.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create CSV header
|
||||
const headers = ['Code', 'Amount', 'Status', 'Created Date', 'Redemption URL'];
|
||||
|
||||
// Create CSV rows
|
||||
const rows = activeGiftcards.map(gc => {
|
||||
const url = `${window.location.origin}/giftcard#baseURL=${encodeURIComponent(provider.baseURL)}&code=${encodeURIComponent(gc.code)}`;
|
||||
const createdDate = gc.created_at
|
||||
? new Date(gc.created_at * 1000).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})
|
||||
: 'N/A';
|
||||
|
||||
return [
|
||||
gc.code,
|
||||
Number(gc.amount).toFixed(2),
|
||||
gc.redeemed ? 'Redeemed' : 'Active',
|
||||
createdDate,
|
||||
url
|
||||
];
|
||||
});
|
||||
|
||||
// Combine headers and rows
|
||||
const csvContent = [
|
||||
headers.join(','),
|
||||
...rows.map(row => row.map(cell => `"${cell}"`).join(','))
|
||||
].join('\n');
|
||||
|
||||
// Create blob and download
|
||||
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
||||
const link = document.createElement('a');
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
link.setAttribute('href', url);
|
||||
link.setAttribute('download', `shakespeare-giftcards-${new Date().toISOString().split('T')[0]}.csv`);
|
||||
link.style.visibility = 'hidden';
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
toast({
|
||||
title: 'CSV downloaded',
|
||||
description: `Downloaded ${activeGiftcards.length} gift card${activeGiftcards.length > 1 ? 's' : ''}.`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to generate CSV:', error);
|
||||
toast({
|
||||
title: 'Download failed',
|
||||
description: error instanceof Error ? error.message : 'Failed to generate CSV file',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
@@ -433,160 +837,373 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{/* Add Credits Form - Fixed size section */}
|
||||
<div className="flex-shrink-0 space-y-4 px-1 -mx-1">
|
||||
<div className="space-y-3">
|
||||
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
|
||||
<div className="space-y-3">
|
||||
<Input
|
||||
id="amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(Number(e.target.value))}
|
||||
placeholder="Enter amount"
|
||||
className="text-center text-lg font-medium"
|
||||
/>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{PRESET_AMOUNTS.map((preset) => (
|
||||
<Button
|
||||
key={preset}
|
||||
variant={amount === preset ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setAmount(preset)}
|
||||
className="text-xs"
|
||||
>
|
||||
${preset}
|
||||
</Button>
|
||||
))}
|
||||
<div className="flex-1 overflow-y-auto px-1 -mx-1">
|
||||
<Accordion type="multiple" defaultValue={["add"]} className="w-full">
|
||||
{/* Buy Credits Accordion */}
|
||||
<AccordionItem value="add">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<DollarSign className="h-4 w-4" />
|
||||
Buy Credits
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium">Payment Method</Label>
|
||||
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="stripe" className="flex items-center gap-2">
|
||||
<CreditCard className="h-4 w-4" />
|
||||
Credit Card
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="lightning" className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4" />
|
||||
Lightning
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleAddCredits}
|
||||
disabled={amount <= 0 || addCreditsMutation.isPending}
|
||||
className="w-full h-12 text-base font-medium"
|
||||
size="lg"
|
||||
>
|
||||
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
|
||||
{amount > 0 && ` - ${formatCurrency(amount)}`}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-shrink-0 px-1 -mx-1 py-4">
|
||||
<Separator />
|
||||
</div>
|
||||
|
||||
{/* Transaction History - Flexible section */}
|
||||
<div className="flex-1 min-h-0 flex flex-col px-1 -mx-1">
|
||||
<div className="flex-shrink-0 mb-4">
|
||||
<h3 className="text-base font-semibold">Recent Transactions</h3>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{isLoadingPayments ? (
|
||||
<div className="p-3 border rounded-lg space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-4 rounded" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-16 ml-auto" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-32" />
|
||||
</div>
|
||||
) : !payments || payments.length === 0 ? (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<CreditCard className="h-10 w-10 mx-auto mb-3 opacity-50" />
|
||||
<p className="text-sm">No transactions yet</p>
|
||||
<p className="text-xs">Your payment history will appear here</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 pb-2">
|
||||
{payments.map((payment) => (
|
||||
<div
|
||||
key={payment.id}
|
||||
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
{getStatusIcon(payment.status)}
|
||||
<span className="text-sm font-medium truncate">
|
||||
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
|
||||
</span>
|
||||
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
|
||||
{payment.status}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
|
||||
{payment.fee > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
+{formatCurrency(payment.fee)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-3 pt-2">
|
||||
<div className="space-y-3">
|
||||
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
|
||||
<div className="space-y-3">
|
||||
<Input
|
||||
id="amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(Number(e.target.value))}
|
||||
placeholder="Enter amount"
|
||||
className="text-center text-lg font-medium"
|
||||
/>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{PRESET_AMOUNTS.map((preset) => (
|
||||
<Button
|
||||
key={preset}
|
||||
variant={amount === preset ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setAmount(preset)}
|
||||
className="text-xs"
|
||||
>
|
||||
${preset}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{formatDate(payment.created_at)}</span>
|
||||
{payment.status === 'pending' && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => checkPaymentMutation.mutate(payment.id)}
|
||||
disabled={refreshingPayments.has(payment.id)}
|
||||
className="h-6 px-2 text-xs"
|
||||
title="Refresh payment status"
|
||||
>
|
||||
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
{payment.url && (
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium">Payment Method</Label>
|
||||
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="stripe" className="flex items-center gap-2">
|
||||
<CreditCard className="h-4 w-4" />
|
||||
Credit Card
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="lightning" className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4" />
|
||||
Lightning
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleAddCredits}
|
||||
disabled={amount <= 0 || addCreditsMutation.isPending}
|
||||
className="w-full h-12 text-base font-medium"
|
||||
size="lg"
|
||||
>
|
||||
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
|
||||
{amount > 0 && ` - ${formatCurrency(amount)}`}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* Transaction History Accordion */}
|
||||
<AccordionItem value="history">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<History className="h-4 w-4" />
|
||||
Recent Transactions
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="pt-2">
|
||||
{isLoadingPayments ? (
|
||||
<div className="p-3 border rounded-lg space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-4 rounded" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-16 ml-auto" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-32" />
|
||||
</div>
|
||||
) : !payments || payments.length === 0 ? (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
<CreditCard className="h-10 w-10 mx-auto mb-3 opacity-50" />
|
||||
<p className="text-sm">No transactions yet</p>
|
||||
<p className="text-xs">Your payment history will appear here</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{payments.map((payment) => (
|
||||
<div
|
||||
key={payment.id}
|
||||
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
{getStatusIcon(payment.status)}
|
||||
<span className="text-sm font-medium truncate">
|
||||
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
|
||||
</span>
|
||||
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
|
||||
{payment.status}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
|
||||
{payment.fee > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
+{formatCurrency(payment.fee)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{formatDate(payment.created_at)}</span>
|
||||
{payment.status === 'pending' && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => checkPaymentMutation.mutate(payment.id)}
|
||||
disabled={refreshingPayments.has(payment.id)}
|
||||
className="h-6 px-2 text-xs"
|
||||
title="Refresh payment status"
|
||||
>
|
||||
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
{payment.url && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (payment.method === 'lightning') {
|
||||
setLightningInvoice(payment.url);
|
||||
} else {
|
||||
window.open(payment.url, '_blank');
|
||||
}
|
||||
}}
|
||||
className="h-6 px-2 text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3 mr-1" />
|
||||
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* Redeem Gift Card Accordion */}
|
||||
<AccordionItem value="redeem">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Redeem Gift Card
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-3 pt-2">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="redeem-code"
|
||||
type="text"
|
||||
value={redeemCode}
|
||||
onChange={(e) => setRedeemCode(e.target.value)}
|
||||
placeholder="Enter gift card code"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleRedeemGiftcard}
|
||||
disabled={!redeemCode.trim() || redeemGiftcardMutation.isPending}
|
||||
size="lg"
|
||||
>
|
||||
{redeemGiftcardMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Redeem
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* Create Gift Card Accordion */}
|
||||
<AccordionItem value="create">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Gift className="h-4 w-4" />
|
||||
Create Gift Card
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-3 pt-2">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="giftcard-amount" className="text-xs text-muted-foreground">Amount (USD)</Label>
|
||||
<Input
|
||||
id="giftcard-amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={giftcardAmount}
|
||||
onChange={(e) => setGiftcardAmount(Number(e.target.value))}
|
||||
placeholder="Amount"
|
||||
className="text-center"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="giftcard-quantity" className="text-xs text-muted-foreground">Quantity</Label>
|
||||
<Input
|
||||
id="giftcard-quantity"
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
value={giftcardQuantity}
|
||||
onChange={(e) => setGiftcardQuantity(Number(e.target.value))}
|
||||
placeholder="Qty"
|
||||
className="text-center"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{PRESET_AMOUNTS.map((preset) => (
|
||||
<Button
|
||||
key={preset}
|
||||
variant={giftcardAmount === preset ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setGiftcardAmount(preset)}
|
||||
className="text-xs"
|
||||
>
|
||||
${preset}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleCreateGiftcard}
|
||||
disabled={giftcardAmount <= 0 || giftcardQuantity <= 0 || createGiftcardMutation.isPending}
|
||||
className="w-full h-12 text-base font-medium"
|
||||
size="lg"
|
||||
>
|
||||
{createGiftcardMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Create {giftcardQuantity > 1 ? `${giftcardQuantity} ` : ''}Gift Card{giftcardQuantity > 1 ? 's' : ''}
|
||||
{giftcardAmount > 0 && giftcardQuantity > 0 && ` - ${formatCurrency(giftcardAmount * giftcardQuantity)}`}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* Your Gift Cards Accordion */}
|
||||
<AccordionItem value="list" className="border-b-0">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCard className="h-4 w-4" />
|
||||
Your Gift Cards
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pb-0">
|
||||
<div className="pt-2 space-y-3">
|
||||
{giftcards && giftcards.filter(gc => !gc.redeemed).length > 0 && (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button
|
||||
onClick={handlePrintGiftcards}
|
||||
disabled={isPrintingQRCodes}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
{isPrintingQRCodes ? (
|
||||
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Printer className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
Print QR Codes
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleDownloadCSV}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Download CSV
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{isLoadingGiftcards ? (
|
||||
<div className="p-3 border rounded-lg space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-4 rounded" />
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<Skeleton className="h-4 w-16 ml-auto" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-48" />
|
||||
</div>
|
||||
) : !giftcards || giftcards.length === 0 ? (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
<Gift className="h-10 w-10 mx-auto mb-3 opacity-50" />
|
||||
<p className="text-sm">No gift cards yet</p>
|
||||
<p className="text-xs">Create gift cards to share with others</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{giftcards.map((giftcard) => (
|
||||
<div
|
||||
key={giftcard.id}
|
||||
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<Gift className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="text-sm font-medium truncate">
|
||||
Gift Card
|
||||
</span>
|
||||
<Badge variant={giftcard.redeemed ? "secondary" : "default"} className="text-xs flex-shrink-0">
|
||||
{giftcard.redeemed ? 'Redeemed' : 'Active'}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<p className="text-sm font-medium">{formatCurrency(giftcard.amount)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<code className="text-xs bg-muted px-2 py-1 rounded font-mono">
|
||||
{giftcard.code}
|
||||
</code>
|
||||
<div className="relative">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (payment.method === 'lightning') {
|
||||
setLightningInvoice(payment.url);
|
||||
} else {
|
||||
window.open(payment.url, '_blank');
|
||||
}
|
||||
}}
|
||||
onClick={() => handleCopyCode(giftcard.code)}
|
||||
className="h-6 px-2 text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3 mr-1" />
|
||||
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
)}
|
||||
{copiedCode === giftcard.code && (
|
||||
<div className="absolute -top-8 right-0 bg-foreground text-background text-xs px-2 py-1 rounded shadow-lg z-10 animate-in fade-in-0 duration-200 whitespace-nowrap">
|
||||
Copied!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{giftcard.created_at && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Created {formatDate(giftcard.created_at)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GiftCardRedeemDialog } from './GiftCardRedeemDialog';
|
||||
|
||||
// Mock fetch
|
||||
global.fetch = vi.fn();
|
||||
|
||||
describe('GiftCardRedeemDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders loading state initially', async () => {
|
||||
// Mock the gift card check endpoint
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockImplementation(() =>
|
||||
new Promise(() => {}) // Never resolves to keep it loading
|
||||
);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show loading skeleton
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error for invalid gift card', async () => {
|
||||
// Mock the gift card check endpoint to return an error
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => ({
|
||||
error: {
|
||||
message: 'No giftcard found with code "INVALID-CODE"',
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="INVALID-CODE"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for error message to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Invalid Gift Card')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows already redeemed message for redeemed gift card', async () => {
|
||||
// Mock the gift card check endpoint to return a redeemed gift card
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 25.0,
|
||||
redeemed: true,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for redeemed message to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Already Redeemed')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows gift card amount for valid unredeemed gift card', async () => {
|
||||
// Mock the gift card check endpoint to return a valid gift card
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 25.0,
|
||||
redeemed: false,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for gift card amount to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/You've got \$25\.00!/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows provider name when matching preset is found', async () => {
|
||||
// Mock the gift card check endpoint
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 10.0,
|
||||
redeemed: false,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for provider name to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Shakespeare AI')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,410 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { Gift, Check, LogIn, Settings as SettingsIcon } from 'lucide-react';
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import { AccountSwitcher } from '@/components/auth/AccountSwitcher';
|
||||
import SimpleLoginDialog from '@/components/auth/SimpleLoginDialog';
|
||||
import SimpleSignupDialog from '@/components/auth/SimpleSignupDialog';
|
||||
import { AddProviderDialog } from '@/components/AddProviderDialog';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface GiftCardRedeemDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
baseURL: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
interface Giftcard {
|
||||
object: 'giftcard';
|
||||
id: string;
|
||||
code: string;
|
||||
amount: number;
|
||||
redeemed: boolean;
|
||||
created_at?: number;
|
||||
}
|
||||
|
||||
interface GiftcardRedemption {
|
||||
object: 'giftcard_redemption';
|
||||
amount: number;
|
||||
}
|
||||
|
||||
type Step = 'preview' | 'login' | 'provider';
|
||||
|
||||
/**
|
||||
* Gift Card Redemption Dialog
|
||||
*
|
||||
* This component handles the complete gift card redemption flow, including:
|
||||
* - Fetching gift card details from the provider API
|
||||
* - Multi-step wizard for login and provider setup
|
||||
* - Account switching before redemption
|
||||
* - Automatic provider matching against presets
|
||||
*
|
||||
* Flow:
|
||||
* 1. Check if gift card is valid (unauthenticated API call)
|
||||
* 2. Determine required steps based on user state:
|
||||
* - Not logged in? → Show login step
|
||||
* - Provider not configured? → Show provider setup step
|
||||
* - Ready to redeem? → Show preview with account switcher
|
||||
* 3. Redeem gift card and add credits to user's account
|
||||
* 4. Navigate to AI Settings to show new balance
|
||||
*
|
||||
* @param open - Whether the dialog is open
|
||||
* @param onOpenChange - Callback when dialog open state changes
|
||||
* @param baseURL - Provider base URL (e.g., https://ai.shakespeare.diy/v1)
|
||||
* @param code - Gift card code to redeem (e.g., XXXX-XXXX-XXXX-XXXX)
|
||||
*/
|
||||
export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: GiftCardRedeemDialogProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { settings } = useAISettings();
|
||||
const { config } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [currentStep, setCurrentStep] = useState<Step>('preview');
|
||||
const [showLoginDialog, setShowLoginDialog] = useState(false);
|
||||
const [showSignupDialog, setShowSignupDialog] = useState(false);
|
||||
const [showAddProviderDialog, setShowAddProviderDialog] = useState(false);
|
||||
|
||||
// Find matching provider by baseURL
|
||||
const matchingProvider = settings.providers.find(p => p.baseURL === baseURL);
|
||||
const matchingPreset = AI_PROVIDER_PRESETS.find(p => p.baseURL === baseURL);
|
||||
|
||||
// Query gift card details without authentication
|
||||
const { data: giftcard, isLoading: isLoadingGiftcard, error: giftcardError } = useQuery({
|
||||
queryKey: ['giftcard-check', baseURL, code],
|
||||
queryFn: async (): Promise<Giftcard> => {
|
||||
const response = await fetch(`${baseURL}/credits/giftcards/check/${code}`);
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error?.message || 'Failed to fetch gift card details');
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
enabled: open && !!baseURL && !!code,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
// Mutation for redeeming gift card
|
||||
const redeemMutation = useMutation({
|
||||
mutationFn: async (): Promise<GiftcardRedemption> => {
|
||||
if (!matchingProvider) {
|
||||
throw new Error('Provider not configured');
|
||||
}
|
||||
const ai = createAIClient(matchingProvider, user, config.corsProxy);
|
||||
return await ai.post('/credits/giftcards/redeem', {
|
||||
body: { code },
|
||||
}) as GiftcardRedemption;
|
||||
},
|
||||
onSuccess: (redemption) => {
|
||||
toast({
|
||||
title: '🎉 Gift card redeemed!',
|
||||
description: `${formatCurrency(redemption.amount)} has been added to your account.`,
|
||||
});
|
||||
onOpenChange(false);
|
||||
// Navigate to AI settings to show the new credits
|
||||
navigate('/settings/ai');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Redemption failed',
|
||||
description: error.message || 'Failed to redeem gift card',
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Determine current step based on conditions
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
// Check if user is logged in and provider is configured
|
||||
const hasUser = !!user;
|
||||
const hasProvider = !!matchingProvider;
|
||||
|
||||
if (hasUser && hasProvider) {
|
||||
setCurrentStep('preview');
|
||||
} else if (!hasUser) {
|
||||
setCurrentStep('login');
|
||||
} else if (!hasProvider) {
|
||||
setCurrentStep('provider');
|
||||
}
|
||||
}, [open, user, matchingProvider]);
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(amount);
|
||||
};
|
||||
|
||||
const handleRedeem = () => {
|
||||
// Check prerequisites
|
||||
if (!user) {
|
||||
setCurrentStep('login');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!matchingProvider) {
|
||||
setCurrentStep('provider');
|
||||
return;
|
||||
}
|
||||
|
||||
// All good, redeem the gift card
|
||||
redeemMutation.mutate();
|
||||
};
|
||||
|
||||
const handleLoginSuccess = () => {
|
||||
setShowLoginDialog(false);
|
||||
setShowSignupDialog(false);
|
||||
|
||||
// After login, check if provider is configured
|
||||
if (matchingProvider) {
|
||||
setCurrentStep('preview');
|
||||
} else {
|
||||
setCurrentStep('provider');
|
||||
}
|
||||
};
|
||||
|
||||
const handleProviderAdded = () => {
|
||||
setShowAddProviderDialog(false);
|
||||
setCurrentStep('preview');
|
||||
};
|
||||
|
||||
const handleNext = () => {
|
||||
if (currentStep === 'login') {
|
||||
// User needs to log in
|
||||
setShowSignupDialog(true);
|
||||
} else if (currentStep === 'provider') {
|
||||
// User needs to add provider
|
||||
setShowAddProviderDialog(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddAccountClick = () => {
|
||||
setShowLoginDialog(true);
|
||||
};
|
||||
|
||||
// Error state
|
||||
if (giftcardError) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8">
|
||||
<div className="mb-4">
|
||||
<Gift className="h-16 w-16 mx-auto text-muted-foreground opacity-50" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold mb-2">Invalid Gift Card</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{giftcardError instanceof Error ? giftcardError.message : 'This gift card could not be found.'}
|
||||
</p>
|
||||
<Button onClick={() => onOpenChange(false)} className="mt-6">
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (isLoadingGiftcard) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8 space-y-4">
|
||||
<Skeleton className="h-16 w-16 rounded-full mx-auto" />
|
||||
<Skeleton className="h-8 w-48 mx-auto" />
|
||||
<Skeleton className="h-4 w-64 mx-auto" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Already redeemed
|
||||
if (giftcard?.redeemed) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8">
|
||||
<div className="mb-4">
|
||||
<Check className="h-16 w-16 mx-auto text-green-500" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold mb-2">Already Redeemed</h2>
|
||||
<p className="text-muted-foreground">
|
||||
This gift card has already been redeemed.
|
||||
</p>
|
||||
<Button onClick={() => onOpenChange(false)} className="mt-6">
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8 space-y-6">
|
||||
{/* Animated gift icon */}
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="h-24 w-24 rounded-full bg-primary/10 animate-pulse" />
|
||||
</div>
|
||||
<div className="relative flex items-center justify-center">
|
||||
<Gift className="h-16 w-16 text-primary animate-bounce" style={{ animationDuration: '2s' }} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Title and amount */}
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
You've got {giftcard && formatCurrency(giftcard.amount)}!
|
||||
</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{currentStep === 'preview' && 'Ready to add these credits to your account?'}
|
||||
{currentStep === 'login' && 'First, let\'s get you logged in to redeem your credits'}
|
||||
{currentStep === 'provider' && `Add ${matchingPreset?.name || 'the provider'} to redeem your credits`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Provider info */}
|
||||
{matchingPreset && (
|
||||
<div className="bg-muted/50 rounded-lg p-4 text-sm">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<span className="text-muted-foreground">Provider:</span>
|
||||
<span className="font-medium">{matchingPreset.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Account preview (only show on preview step) */}
|
||||
{currentStep === 'preview' && user && (
|
||||
<div className="border rounded-lg p-4">
|
||||
<p className="text-xs text-muted-foreground mb-3 text-left">Redeeming to account:</p>
|
||||
<AccountSwitcher onAddAccountClick={handleAddAccountClick} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="space-y-3">
|
||||
{currentStep === 'preview' ? (
|
||||
<Button
|
||||
onClick={handleRedeem}
|
||||
disabled={redeemMutation.isPending}
|
||||
size="lg"
|
||||
className="w-full text-lg h-14 font-semibold"
|
||||
>
|
||||
{redeemMutation.isPending ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2" />
|
||||
Redeeming...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Gift className="h-5 w-5 mr-2" />
|
||||
Redeem Now
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleNext}
|
||||
size="lg"
|
||||
className="w-full text-lg h-14 font-semibold"
|
||||
>
|
||||
{currentStep === 'login' ? (
|
||||
<>
|
||||
<LogIn className="h-5 w-5 mr-2" />
|
||||
Log In to Continue
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<SettingsIcon className="h-5 w-5 mr-2" />
|
||||
Add Provider
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="w-full"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Progress indicator */}
|
||||
{currentStep !== 'preview' && (
|
||||
<div className="flex items-center justify-center gap-2 pt-2">
|
||||
<div className={`h-2 w-2 rounded-full ${currentStep === 'login' ? 'bg-primary' : 'bg-muted'}`} />
|
||||
<div className={`h-2 w-2 rounded-full ${currentStep === 'provider' ? 'bg-primary' : 'bg-muted'}`} />
|
||||
<div className={`h-2 w-2 rounded-full bg-muted`} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Login/Signup Dialogs */}
|
||||
<SimpleLoginDialog
|
||||
isOpen={showLoginDialog}
|
||||
onClose={() => setShowLoginDialog(false)}
|
||||
onLogin={handleLoginSuccess}
|
||||
onSignup={() => {
|
||||
setShowLoginDialog(false);
|
||||
setShowSignupDialog(true);
|
||||
}}
|
||||
/>
|
||||
|
||||
<SimpleSignupDialog
|
||||
isOpen={showSignupDialog}
|
||||
onClose={() => setShowSignupDialog(false)}
|
||||
onComplete={handleLoginSuccess}
|
||||
onLogin={() => {
|
||||
setShowSignupDialog(false);
|
||||
setShowLoginDialog(true);
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Add Provider Dialog */}
|
||||
{matchingPreset && (
|
||||
<AddProviderDialog
|
||||
open={showAddProviderDialog}
|
||||
onOpenChange={(open) => {
|
||||
setShowAddProviderDialog(open);
|
||||
if (!open) {
|
||||
// Check if provider was added when dialog closes
|
||||
const wasAdded = settings.providers.some(p => p.baseURL === baseURL);
|
||||
if (wasAdded) {
|
||||
handleProviderAdded();
|
||||
}
|
||||
}
|
||||
}}
|
||||
provider={{
|
||||
id: matchingPreset.id,
|
||||
baseURL: matchingPreset.baseURL,
|
||||
nostr: matchingPreset.nostr,
|
||||
proxy: matchingPreset.proxy,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { WifiOff, Wifi } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useOffline } from '@/hooks/useOffline';
|
||||
|
||||
/**
|
||||
* Component that displays an indicator when the app is offline
|
||||
*/
|
||||
export function OfflineIndicator() {
|
||||
const { isOffline, isOnline } = useOffline();
|
||||
const [showOnlineNotification, setShowOnlineNotification] = useState(false);
|
||||
const [wasOffline, setWasOffline] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOffline) {
|
||||
setWasOffline(true);
|
||||
}
|
||||
|
||||
if (isOnline && wasOffline) {
|
||||
// Show "back online" notification briefly
|
||||
setShowOnlineNotification(true);
|
||||
const timer = setTimeout(() => {
|
||||
setShowOnlineNotification(false);
|
||||
setWasOffline(false);
|
||||
}, 3000);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [isOffline, isOnline, wasOffline]);
|
||||
|
||||
if (!isOffline && !showOnlineNotification) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 z-50 animate-in slide-in-from-bottom-4">
|
||||
{isOffline ? (
|
||||
<Alert variant="destructive" className="shadow-lg border-2">
|
||||
<WifiOff className="h-4 w-4" />
|
||||
<AlertDescription className="font-medium">
|
||||
You're offline. Some features may be limited.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<Alert className="shadow-lg border-2 border-green-500 bg-green-50 dark:bg-green-950">
|
||||
<Wifi className="h-4 w-4 text-green-600 dark:text-green-400" />
|
||||
<AlertDescription className="font-medium text-green-600 dark:text-green-400">
|
||||
You're back online!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRegisterSW } from 'virtual:pwa-register/react';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Component that prompts users to update when a new service worker is available
|
||||
*/
|
||||
export function PWAUpdatePrompt() {
|
||||
const [showPrompt, setShowPrompt] = useState(false);
|
||||
const [isUpdating, setIsUpdating] = useState(false);
|
||||
|
||||
const {
|
||||
offlineReady: [offlineReady],
|
||||
needRefresh: [needRefresh],
|
||||
updateServiceWorker,
|
||||
} = useRegisterSW({
|
||||
onRegisteredSW(swUrl, registration) {
|
||||
console.log('[PWA] Service worker registered:', swUrl);
|
||||
|
||||
// Check for updates periodically (every hour)
|
||||
if (registration) {
|
||||
setInterval(() => {
|
||||
registration.update();
|
||||
}, 60 * 60 * 1000);
|
||||
}
|
||||
},
|
||||
onRegisterError(error) {
|
||||
console.error('[PWA] Service worker registration error:', error);
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (offlineReady) {
|
||||
console.log('[PWA] App ready to work offline');
|
||||
}
|
||||
}, [offlineReady]);
|
||||
|
||||
useEffect(() => {
|
||||
if (needRefresh) {
|
||||
setShowPrompt(true);
|
||||
}
|
||||
}, [needRefresh]);
|
||||
|
||||
const handleUpdate = () => {
|
||||
setIsUpdating(true);
|
||||
updateServiceWorker(true);
|
||||
};
|
||||
|
||||
if (!showPrompt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 md:top-4 md:right-4 md:bottom-auto md:left-auto md:translate-x-0 z-50 animate-in slide-in-from-bottom-4 md:slide-in-from-top-4 duration-500 max-w-full truncate">
|
||||
<button
|
||||
onClick={handleUpdate}
|
||||
disabled={isUpdating}
|
||||
className="group relative flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate"
|
||||
>
|
||||
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
|
||||
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
|
||||
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -31,7 +31,7 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
return (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
|
||||
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-muted/50 transition-all w-full text-foreground'>
|
||||
<Avatar className='w-10 h-10'>
|
||||
<AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
|
||||
<AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
/**
|
||||
* Hook to detect offline status and provide cache management utilities
|
||||
*/
|
||||
export function useOffline() {
|
||||
const [isOnline, setIsOnline] = useState(navigator.onLine);
|
||||
const [serviceWorkerRegistration, setServiceWorkerRegistration] = useState<ServiceWorkerRegistration | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const handleOnline = () => setIsOnline(true);
|
||||
const handleOffline = () => setIsOnline(false);
|
||||
|
||||
window.addEventListener('online', handleOnline);
|
||||
window.addEventListener('offline', handleOffline);
|
||||
|
||||
// Get service worker registration
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
setServiceWorkerRegistration(registration);
|
||||
}).catch((error) => {
|
||||
console.error('[ServiceWorker] Failed to get registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('online', handleOnline);
|
||||
window.removeEventListener('offline', handleOffline);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const clearCache = async () => {
|
||||
if ('caches' in window) {
|
||||
const cacheNames = await caches.keys();
|
||||
await Promise.all(
|
||||
cacheNames
|
||||
.filter(name => name.startsWith('workbox-') || name.includes('shakespeare'))
|
||||
.map(name => caches.delete(name))
|
||||
);
|
||||
console.log('[Cache] Cleared all caches');
|
||||
}
|
||||
};
|
||||
|
||||
const updateServiceWorker = async () => {
|
||||
if (serviceWorkerRegistration) {
|
||||
await serviceWorkerRegistration.update();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isOnline,
|
||||
isOffline: !isOnline,
|
||||
serviceWorkerRegistration,
|
||||
clearCache,
|
||||
updateServiceWorker,
|
||||
};
|
||||
}
|
||||
@@ -13,7 +13,7 @@ export class LightningFSAdapter implements JSRuntimeFS {
|
||||
async readFile(path: string, options: string): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBuffer>>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
return this.lightningFS.readFile(path, encoding);
|
||||
|
||||
@@ -88,6 +88,14 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
tosURL: "https://ai.google.dev/gemini-api/terms",
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: "vercel",
|
||||
name: "Vercel",
|
||||
baseURL: "https://api.v0.dev/v1",
|
||||
apiKeysURL: "https://vercel.com/account/tokens",
|
||||
tosURL: "https://vercel.com/legal/terms",
|
||||
proxy: true,
|
||||
},
|
||||
];
|
||||
|
||||
// Helper function to get a specific preset by ID
|
||||
|
||||
@@ -228,6 +228,8 @@ const resources = {
|
||||
// About Settings
|
||||
aboutShakespeare: 'About Shakespeare',
|
||||
aboutShakespeareDescription: 'Information about Shakespeare',
|
||||
mirrors: 'Mirrors',
|
||||
mirrorsDescription: 'Shakespeare is available at multiple mirror URLs for redundancy and accessibility.',
|
||||
sourceCode: 'Source Code',
|
||||
description: 'Description',
|
||||
license: 'License',
|
||||
@@ -236,6 +238,13 @@ const resources = {
|
||||
|
||||
// Data Settings
|
||||
dataSettingsDescriptionLong: 'Export files and manage local data.',
|
||||
offlineCache: 'Offline Cache',
|
||||
offlineCacheDescription: 'Shakespeare caches files locally to enable offline functionality. Clear the cache to free up space or troubleshoot issues.',
|
||||
cacheSize: 'Cache size',
|
||||
clearCache: 'Clear Cache',
|
||||
cacheClearedSuccessfully: 'Cache Cleared',
|
||||
cacheClearedDescription: 'Offline cache has been cleared successfully.',
|
||||
failedToClearCache: 'Failed to Clear Cache',
|
||||
exportFiles: 'Export Files',
|
||||
exportFilesDescription: 'Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally.',
|
||||
exportAllFiles: 'Export All Files',
|
||||
@@ -563,6 +572,13 @@ const resources = {
|
||||
|
||||
// Data Settings
|
||||
dataSettingsDescriptionLong: 'Exporte arquivos e gerencie dados locais.',
|
||||
offlineCache: 'Cache Offline',
|
||||
offlineCacheDescription: 'O Shakespeare armazena arquivos localmente para permitir funcionalidade offline. Limpe o cache para liberar espaço ou solucionar problemas.',
|
||||
cacheSize: 'Tamanho do cache',
|
||||
clearCache: 'Limpar Cache',
|
||||
cacheClearedSuccessfully: 'Cache Limpo',
|
||||
cacheClearedDescription: 'O cache offline foi limpo com sucesso.',
|
||||
failedToClearCache: 'Falha ao Limpar Cache',
|
||||
exportFiles: 'Exportar Arquivos',
|
||||
exportFilesDescription: 'Baixe todos os seus projetos e arquivos como um arquivo ZIP. Isso inclui todos os arquivos de projeto, configurações e dados armazenados localmente.',
|
||||
exportAllFiles: 'Exportar Todos os Arquivos',
|
||||
@@ -605,6 +621,8 @@ const resources = {
|
||||
// About Settings
|
||||
aboutShakespeare: 'Sobre o Shakespeare',
|
||||
aboutShakespeareDescription: 'Informações sobre o Shakespeare.',
|
||||
mirrors: 'Espelhos',
|
||||
mirrorsDescription: 'Shakespeare está disponível em vários URLs espelhados para redundância e acessibilidade.',
|
||||
sourceCode: 'Código-fonte',
|
||||
description: 'Descrição',
|
||||
license: 'Licença',
|
||||
@@ -899,6 +917,13 @@ const resources = {
|
||||
|
||||
// Data Settings
|
||||
dataSettingsDescriptionLong: '导出文件和管理本地数据。',
|
||||
offlineCache: '离线缓存',
|
||||
offlineCacheDescription: 'Shakespeare在本地缓存文件以启用离线功能。清除缓存以释放空间或解决问题。',
|
||||
cacheSize: '缓存大小',
|
||||
clearCache: '清除缓存',
|
||||
cacheClearedSuccessfully: '缓存已清除',
|
||||
cacheClearedDescription: '离线缓存已成功清除。',
|
||||
failedToClearCache: '清除缓存失败',
|
||||
exportFiles: '导出文件',
|
||||
exportFilesDescription: '将您的所有项目和文件下载为ZIP存档。这包括所有项目文件、设置和本地存储的数据。',
|
||||
exportAllFiles: '导出所有文件',
|
||||
@@ -941,6 +966,8 @@ const resources = {
|
||||
// About Settings
|
||||
aboutShakespeare: '关于Shakespeare',
|
||||
aboutShakespeareDescription: '关于Shakespeare的信息。',
|
||||
mirrors: '镜像',
|
||||
mirrorsDescription: 'Shakespeare可通过多个镜像URL访问,以确保冗余和可访问性。',
|
||||
sourceCode: '源代码',
|
||||
description: '描述',
|
||||
license: '许可证',
|
||||
@@ -1274,6 +1301,8 @@ const resources = {
|
||||
// About Settings
|
||||
aboutShakespeare: 'Game da Shakespeare',
|
||||
aboutShakespeareDescription: 'Bayani game da Shakespeare.',
|
||||
mirrors: 'Madubai',
|
||||
mirrorsDescription: 'Shakespeare yana samuwa a URLs masu yawa don inganci da samun dama.',
|
||||
sourceCode: 'Lambar Tushe',
|
||||
description: 'Bayanin',
|
||||
license: 'Lasisi',
|
||||
@@ -1607,6 +1636,8 @@ const resources = {
|
||||
// About Settings
|
||||
aboutShakespeare: 'Nipa Shakespeare',
|
||||
aboutShakespeareDescription: 'Alaye nipa Shakespeare.',
|
||||
mirrors: 'Awọn Digi',
|
||||
mirrorsDescription: 'Shakespeare wa ni awọn URL digi pupọ fun aredundan ati iraye si.',
|
||||
sourceCode: 'Koodu Orisun',
|
||||
description: 'Apejuwe',
|
||||
license: 'Iwe-aṣẹ',
|
||||
@@ -1935,6 +1966,8 @@ const resources = {
|
||||
// About Settings
|
||||
aboutShakespeare: 'Gbasara Shakespeare',
|
||||
aboutShakespeareDescription: 'Ozi gbasara Shakespeare.',
|
||||
mirrors: 'Enyo',
|
||||
mirrorsDescription: 'Shakespeare dị na ọtụtụ URL enyo maka nnọchi na nnweta.',
|
||||
sourceCode: 'Koodu Isi',
|
||||
description: 'Nkọwa',
|
||||
license: 'Ikike',
|
||||
|
||||
+1
-15
@@ -15,18 +15,4 @@ import '@fontsource-variable/inter';
|
||||
// Prism syntax highlighting
|
||||
import 'prismjs/themes/prism.css';
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
|
||||
// Register service worker (skip in Electron - doesn't work with file:// protocol)
|
||||
if ('serviceWorker' in navigator && !globalThis.electron) {
|
||||
window.addEventListener('load', () => {
|
||||
navigator.serviceWorker
|
||||
.register('/sw.js')
|
||||
.then((registration) => {
|
||||
console.log('[ServiceWorker] Registered:', registration);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('[ServiceWorker] Registration failed:', error);
|
||||
});
|
||||
});
|
||||
}
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
@@ -37,26 +37,6 @@ import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
|
||||
/** A few provider-specific icon hacks */
|
||||
function getProviderIconUrl(provider: { id: string; baseURL: string }): string {
|
||||
if (provider.id === 'ollama' && provider.baseURL === 'http://localhost:11434/v1') {
|
||||
return 'https://ollama.com/';
|
||||
} else if (provider.baseURL === 'https://generativelanguage.googleapis.com/v1beta/openai') {
|
||||
return 'https://gemini.google.com/';
|
||||
} else if (provider.baseURL === 'https://api.z.ai/api/paas/v4') {
|
||||
return 'https://docs.z.ai/';
|
||||
}
|
||||
try {
|
||||
// Strip .ai and .api subdomains for a better chance at finding a favicon
|
||||
const urlObj = new URL(provider.baseURL);
|
||||
urlObj.hostname = urlObj.hostname.replace(/^(ai\.|api\.)/, '');
|
||||
return urlObj.toString();
|
||||
} catch {
|
||||
// Fallback to baseURL
|
||||
return provider.baseURL;
|
||||
}
|
||||
}
|
||||
|
||||
interface SortableProviderItemProps {
|
||||
provider: AIProvider;
|
||||
preset?: PresetProvider;
|
||||
@@ -103,7 +83,7 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
|
||||
)}
|
||||
{provider.baseURL ? (
|
||||
<ExternalFavicon
|
||||
url={getProviderIconUrl(provider)}
|
||||
url={provider.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
/>
|
||||
@@ -390,7 +370,7 @@ export function AISettings() {
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={getProviderIconUrl(preset)}
|
||||
url={preset.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
/>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code } from 'lucide-react';
|
||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code, Globe } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
@@ -83,6 +83,53 @@ export function AboutSettings() {
|
||||
<EmailSubscription />
|
||||
|
||||
<div className="space-y-3">
|
||||
{/* Mirrors */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="mirrors" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="h-5 w-5" />
|
||||
{t('mirrors')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<p className="text-sm text-muted-foreground mb-3">{t('mirrorsDescription')}</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-10 flex items-center gap-2 justify-start"
|
||||
asChild
|
||||
>
|
||||
<a href="https://shakespeare.diy" target="_blank" rel="noopener noreferrer">
|
||||
<span className="font-mono text-sm">shakespeare.diy</span>
|
||||
<ExternalLink className="ml-auto h-4 w-4" />
|
||||
</a>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-10 flex items-center gap-2 justify-start"
|
||||
asChild
|
||||
>
|
||||
<a href="https://shakespeare.soapbox.dev" target="_blank" rel="noopener noreferrer">
|
||||
<span className="font-mono text-sm">shakespeare.soapbox.dev</span>
|
||||
<ExternalLink className="ml-auto h-4 w-4" />
|
||||
</a>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-10 flex items-center gap-2 justify-start"
|
||||
asChild
|
||||
>
|
||||
<a href="https://shakespeare-b0b9c8.gitlab.io" target="_blank" rel="noopener noreferrer">
|
||||
<span className="font-mono text-sm">shakespeare-b0b9c8.gitlab.io</span>
|
||||
<ExternalLink className="ml-auto h-4 w-4" />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Project Information */}
|
||||
<Button
|
||||
variant="outline"
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import Index from './Index';
|
||||
|
||||
// Mock fetch
|
||||
global.fetch = vi.fn();
|
||||
|
||||
// Mock useLocation and useNavigate
|
||||
const mockNavigate = vi.fn();
|
||||
const mockLocation = { pathname: '/', hash: '', search: '', state: null, key: 'default' };
|
||||
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom');
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mockNavigate,
|
||||
useLocation: () => mockLocation,
|
||||
};
|
||||
});
|
||||
|
||||
describe('Index - Gift Card URL Handling', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockNavigate.mockClear();
|
||||
mockLocation.pathname = '/';
|
||||
mockLocation.hash = '';
|
||||
});
|
||||
|
||||
it('opens gift card dialog when navigating to /giftcard with hash parameters', async () => {
|
||||
// Mock the gift card check endpoint
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 25.0,
|
||||
redeemed: false,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
// Set location to /giftcard with hash
|
||||
mockLocation.pathname = '/giftcard';
|
||||
mockLocation.hash = '#baseURL=https://ai.shakespeare.diy/v1&code=TEST-CODE-1234-5678';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<Index />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for gift card dialog to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/You've got \$25\.00!/)).toBeInTheDocument();
|
||||
}, { timeout: 3000 });
|
||||
|
||||
// Verify URL was rewritten to '/'
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
|
||||
});
|
||||
|
||||
it('redirects to home when /giftcard has no hash parameters', async () => {
|
||||
// Set location to /giftcard without hash
|
||||
mockLocation.pathname = '/giftcard';
|
||||
mockLocation.hash = '';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<Index />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should redirect to home page
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
|
||||
});
|
||||
});
|
||||
|
||||
it('redirects to home when /giftcard has incomplete hash parameters', async () => {
|
||||
// Set location to /giftcard with incomplete hash
|
||||
mockLocation.pathname = '/giftcard';
|
||||
mockLocation.hash = '#baseURL=https://ai.shakespeare.diy/v1';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<Index />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should redirect to home page
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
+41
-1
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useAIProjectId } from '@/hooks/useAIProjectId';
|
||||
@@ -11,6 +11,7 @@ import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Act1Dialog } from '@/components/Act1Dialog';
|
||||
import { GiftCardRedeemDialog } from '@/components/GiftCardRedeemDialog';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
@@ -32,7 +33,11 @@ export default function Index() {
|
||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [showAct1Dialog, setShowAct1Dialog] = useState(false);
|
||||
const [showGiftCardDialog, setShowGiftCardDialog] = useState(false);
|
||||
const [giftCardBaseURL, setGiftCardBaseURL] = useState('');
|
||||
const [giftCardCode, setGiftCardCode] = useState('');
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { fs } = useFS();
|
||||
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
|
||||
@@ -75,6 +80,31 @@ export default function Index() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Handle gift card redemption from URL
|
||||
useEffect(() => {
|
||||
// Check if we're on the /giftcard route
|
||||
if (location.pathname === '/giftcard') {
|
||||
// Parse hash parameters
|
||||
const hash = location.hash.slice(1); // Remove the '#'
|
||||
const params = new URLSearchParams(hash);
|
||||
const baseURL = params.get('baseURL');
|
||||
const code = params.get('code');
|
||||
|
||||
if (baseURL && code) {
|
||||
// Store the gift card details
|
||||
setGiftCardBaseURL(baseURL);
|
||||
setGiftCardCode(code);
|
||||
setShowGiftCardDialog(true);
|
||||
|
||||
// Rewrite URL to '/' for privacy
|
||||
navigate('/', { replace: true });
|
||||
} else {
|
||||
// Invalid gift card URL, just navigate to home
|
||||
navigate('/', { replace: true });
|
||||
}
|
||||
}
|
||||
}, [location, navigate]);
|
||||
|
||||
// Sync prompt with local storage
|
||||
const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newPrompt = e.target.value;
|
||||
@@ -399,6 +429,16 @@ export default function Index() {
|
||||
open={showAct1Dialog}
|
||||
onOpenChange={setShowAct1Dialog}
|
||||
/>
|
||||
|
||||
{/* Gift Card Redeem Dialog */}
|
||||
{giftCardBaseURL && giftCardCode && (
|
||||
<GiftCardRedeemDialog
|
||||
open={showGiftCardDialog}
|
||||
onOpenChange={setShowGiftCardDialog}
|
||||
baseURL={giftCardBaseURL}
|
||||
code={giftCardCode}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useOffline } from '@/hooks/useOffline';
|
||||
import {
|
||||
isPersistentStorageSupported,
|
||||
isPersistentStorageGranted,
|
||||
@@ -43,6 +44,7 @@ export function StorageSettings() {
|
||||
const { fs } = useFS();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const { clearCache } = useOffline();
|
||||
|
||||
// Format bytes to human readable format
|
||||
const formatBytes = (bytes: number): string => {
|
||||
@@ -223,6 +225,9 @@ export function StorageSettings() {
|
||||
// Clear localStorage
|
||||
localStorage.clear();
|
||||
|
||||
// Clear caches
|
||||
await clearCache();
|
||||
|
||||
// Clear IndexedDB databases
|
||||
const databases = await indexedDB.databases();
|
||||
const deletePromises = databases.map(db => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Settings, ArrowLeft } from "lucide-react";
|
||||
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
@@ -9,12 +9,17 @@ import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/
|
||||
import { useIsMobile } from "@/hooks/useIsMobile";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
import { useOffline } from "@/hooks/useOffline";
|
||||
import { useToast } from "@/hooks/useToast";
|
||||
|
||||
export function SystemSettings() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const { serviceWorkerRegistration, updateServiceWorker, clearCache } = useOffline();
|
||||
|
||||
const [projectTemplateInput, setProjectTemplateInput] = useState(config.projectTemplate);
|
||||
const [esmUrlInput, setEsmUrlInput] = useState(config.esmUrl);
|
||||
const [corsProxyInput, setCorsProxyInput] = useState(config.corsProxy);
|
||||
@@ -25,6 +30,94 @@ export function SystemSettings() {
|
||||
const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig);
|
||||
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
|
||||
|
||||
// Service Worker state
|
||||
const [swState, setSwState] = useState<string>('');
|
||||
const [isUpdatingSW, setIsUpdatingSW] = useState(false);
|
||||
const [isUnregisteringSW, setIsUnregisteringSW] = useState(false);
|
||||
const [isClearingCache, setIsClearingCache] = useState(false);
|
||||
|
||||
// Monitor Service Worker state
|
||||
useEffect(() => {
|
||||
if (serviceWorkerRegistration?.active) {
|
||||
setSwState(serviceWorkerRegistration.active.state);
|
||||
|
||||
const handleStateChange = () => {
|
||||
if (serviceWorkerRegistration.active) {
|
||||
setSwState(serviceWorkerRegistration.active.state);
|
||||
}
|
||||
};
|
||||
|
||||
serviceWorkerRegistration.active.addEventListener('statechange', handleStateChange);
|
||||
|
||||
return () => {
|
||||
serviceWorkerRegistration.active?.removeEventListener('statechange', handleStateChange);
|
||||
};
|
||||
}
|
||||
}, [serviceWorkerRegistration]);
|
||||
|
||||
const handleUpdateSW = async () => {
|
||||
setIsUpdatingSW(true);
|
||||
try {
|
||||
await updateServiceWorker();
|
||||
toast({
|
||||
title: "Service Worker Updated",
|
||||
description: "The service worker has been updated successfully.",
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Update Failed",
|
||||
description: error instanceof Error ? error.message : "Failed to update service worker",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsUpdatingSW(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUnregisterSW = async () => {
|
||||
setIsUnregisteringSW(true);
|
||||
try {
|
||||
if (serviceWorkerRegistration) {
|
||||
const success = await serviceWorkerRegistration.unregister();
|
||||
if (success) {
|
||||
toast({
|
||||
title: "Service Worker Unregistered",
|
||||
description: "The service worker has been unregistered. Refresh the page to complete the process.",
|
||||
});
|
||||
} else {
|
||||
throw new Error("Failed to unregister service worker");
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Unregister Failed",
|
||||
description: error instanceof Error ? error.message : "Failed to unregister service worker",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsUnregisteringSW(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearCache = async () => {
|
||||
setIsClearingCache(true);
|
||||
try {
|
||||
await clearCache();
|
||||
toast({
|
||||
title: "Cache Cleared",
|
||||
description: "All service worker caches have been cleared.",
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Clear Cache Failed",
|
||||
description: error instanceof Error ? error.message : "Failed to clear cache",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsClearingCache(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
@@ -63,6 +156,109 @@ export function SystemSettings() {
|
||||
)}
|
||||
|
||||
<div className="space-y-3 max-w-xl">
|
||||
{/* Service Worker Configuration */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="service-worker" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<h4 className="text-sm font-medium">Service Worker</h4>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-4">
|
||||
{serviceWorkerRegistration ? (
|
||||
<>
|
||||
{/* Service Worker Status */}
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm space-y-1">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Status:</span>
|
||||
<span className="font-medium capitalize">{swState || 'Unknown'}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Scope:</span>
|
||||
<span className="font-mono text-xs">{serviceWorkerRegistration.scope}</span>
|
||||
</div>
|
||||
{serviceWorkerRegistration.active && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Script URL:</span>
|
||||
<span className="font-mono text-xs truncate max-w-[200px]" title={serviceWorkerRegistration.active.scriptURL}>
|
||||
{serviceWorkerRegistration.active.scriptURL.split('/').pop()}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Service Worker Controls */}
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<Button
|
||||
onClick={handleUpdateSW}
|
||||
disabled={isUpdatingSW}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{isUpdatingSW ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Updating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Update
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleClearCache}
|
||||
disabled={isClearingCache}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{isClearingCache ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Clearing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Clear Cache
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleUnregisterSW}
|
||||
disabled={isUnregisteringSW}
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{isUnregisteringSW ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Unregistering...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<XCircle className="h-4 w-4" />
|
||||
Unregister
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
No service worker is currently registered. Service workers are automatically registered when you load the application.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Project Template Configuration */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="project-template" className="border rounded-lg">
|
||||
@@ -134,7 +330,7 @@ export function SystemSettings() {
|
||||
<Input
|
||||
id="favicon-url"
|
||||
type="url"
|
||||
placeholder="https://external-content.duckduckgo.com/ip3/{hostname}.ico"
|
||||
placeholder="https://favicon.shakespeare.diy/?url={href}"
|
||||
value={faviconUrlInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
|
||||
Vendored
+1
@@ -1,4 +1,5 @@
|
||||
/// <reference types="vite/client" />
|
||||
/// <reference types="vite-plugin-pwa/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_GITHUB_OAUTH_CLIENT_ID?: string;
|
||||
|
||||
+14
-20
@@ -3,6 +3,7 @@ import path from "node:path";
|
||||
|
||||
import react from "@vitejs/plugin-react-swc";
|
||||
import { defineConfig } from "vitest/config";
|
||||
import { VitePWA } from 'vite-plugin-pwa';
|
||||
|
||||
function getVersion(): string {
|
||||
try {
|
||||
@@ -27,29 +28,22 @@ export default defineConfig(() => ({
|
||||
},
|
||||
plugins: [
|
||||
react(),
|
||||
VitePWA({
|
||||
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3'],
|
||||
manifest: false, // Use existing manifest.webmanifest from public folder
|
||||
workbox: {
|
||||
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
||||
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024, // 10 MB
|
||||
cleanupOutdatedCaches: true,
|
||||
},
|
||||
devOptions: {
|
||||
enabled: false,
|
||||
type: 'module'
|
||||
}
|
||||
})
|
||||
],
|
||||
build: {
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks(id) {
|
||||
if (id.includes('node_modules')) {
|
||||
// get the path after "node_modules/"
|
||||
const parts = id.toString().split('node_modules/')[1].split('/');
|
||||
|
||||
// handle scoped packages (@scope/name)
|
||||
const pkgName = parts[0].startsWith('@')
|
||||
? `${parts[0]}/${parts[1]}`
|
||||
: parts[0];
|
||||
|
||||
return `npm/${pkgName.replace('@', '')}`;
|
||||
}
|
||||
if (id.includes('/src/')) {
|
||||
return 'app';
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
|
||||
Reference in new issue
Block a user