cleanup + shakespeare-like manual zap modal

This commit is contained in:
Chad Curtis 2025-07-14 01:16:31 +00:00
parent 0bc03017bb
commit 8183e3cc5a
3 changed files with 129 additions and 89 deletions

View File

@ -1,4 +1,4 @@
import { useState, useEffect } from 'react'; import { useState } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, Settings, CheckCircle } from 'lucide-react'; import { Wallet, Plus, Trash2, Zap, Globe, Settings, CheckCircle } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
@ -46,17 +46,6 @@ export function WalletModal({ children, className }: WalletModalProps) {
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected); const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const { toast } = useToast(); const { toast } = useToast();
// Debug logging for wallet modal status
useEffect(() => {
console.debug('WalletModal status:', {
hasWebLN,
hasNWC,
connectionsCount: connections.length,
connectionsDetails: connections.map(c => ({ alias: c.alias, isConnected: c.isConnected })),
isDetecting
});
}, [hasWebLN, hasNWC, connections, isDetecting]);
const handleAddConnection = async () => { const handleAddConnection = async () => {
if (!connectionUri.trim()) { if (!connectionUri.trim()) {
toast({ toast({
@ -67,30 +56,13 @@ export function WalletModal({ children, className }: WalletModalProps) {
return; return;
} }
console.debug('WalletModal: Before adding connection', {
currentConnections: connections.length,
hasNWC
});
setIsConnecting(true); setIsConnecting(true);
try { try {
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined); const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
if (success) { if (success) {
console.debug('WalletModal: Connection added successfully', {
newConnections: connections.length,
hasNWC
});
setConnectionUri(''); setConnectionUri('');
setAlias(''); setAlias('');
setAddDialogOpen(false); setAddDialogOpen(false);
// Force a small delay to check state after React updates
setTimeout(() => {
console.debug('WalletModal: Post-add state check', {
connectionsLength: connections.length,
hasNWC
});
}, 100);
} }
} finally { } finally {
setIsConnecting(false); setIsConnecting(false);
@ -98,20 +70,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
}; };
const handleRemoveConnection = (connectionString: string) => { const handleRemoveConnection = (connectionString: string) => {
console.debug('WalletModal: Before removing connection', {
currentConnections: connections.length,
hasNWC
});
removeConnection(connectionString); removeConnection(connectionString);
// Force a small delay to check state after React updates
setTimeout(() => {
console.debug('WalletModal: Post-remove state check', {
connectionsLength: connections.length,
hasNWC
});
}, 100);
}; };
const handleSetActive = (connectionString: string) => { const handleSetActive = (connectionString: string) => {

View File

@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react'; import { useState, useEffect, useRef } from 'react';
import { Zap, Copy, Sparkle, Sparkles, Star, Rocket } from 'lucide-react'; import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
Dialog, Dialog,
@ -11,15 +11,18 @@ import {
DialogTrigger, DialogTrigger,
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'; import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor'; import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast'; import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps'; import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet'; import { useWallet } from '@/hooks/useWallet';
import QRCode from 'qrcode';
import type { Event } from 'nostr-tools'; import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
interface ZapDialogProps { interface ZapDialogProps {
target: Event; target: Event;
@ -44,8 +47,9 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false)); const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const [amount, setAmount] = useState<number | string>(100); const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>(''); const [comment, setComment] = useState<string>('');
const [copied, setCopied] = useState(false);
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const qrCodeRef = useRef<HTMLCanvasElement>(null);
useEffect(() => { useEffect(() => {
if (target) { if (target) {
@ -60,18 +64,45 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
} }
}, [open, hasWebLN, detectWebLN]); }, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => { useEffect(() => {
if (invoice && qrCodeRef.current) { const generateQR = async () => {
QRCode.toCanvas(qrCodeRef.current, invoice, { width: 256 }); if (!invoice) return;
}
try {
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
width: 256,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
setQrCodeUrl(url);
} catch (err) {
console.error('Failed to generate QR code:', err);
}
};
generateQR();
}, [invoice]); }, [invoice]);
const handleCopy = () => { const handleCopy = async () => {
if (invoice) { if (invoice) {
navigator.clipboard.writeText(invoice); await navigator.clipboard.writeText(invoice);
setCopied(true);
toast({ toast({
title: 'Copied to clipboard!', title: 'Invoice copied',
description: 'Lightning invoice copied to clipboard',
}); });
setTimeout(() => setCopied(false), 2000);
}
};
const openInWallet = () => {
if (invoice) {
const lightningUrl = `lightning:${invoice}`;
window.open(lightningUrl, '_blank');
} }
}; };
@ -79,6 +110,8 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
if (open) { if (open) {
setAmount(100); setAmount(100);
setInvoice(null); setInvoice(null);
setCopied(false);
setQrCodeUrl('');
} }
}, [open, setInvoice]); }, [open, setInvoice]);
@ -100,26 +133,101 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
</DialogTrigger> </DialogTrigger>
<DialogContent className="sm:max-w-[425px]" data-testid="zap-modal"> <DialogContent className="sm:max-w-[425px]" data-testid="zap-modal">
<DialogHeader> <DialogHeader>
<DialogTitle>{invoice ? 'Manual Zap' : 'Send a Zap'}</DialogTitle> <DialogTitle>{invoice ? 'Lightning Payment' : 'Send a Zap'}</DialogTitle>
<DialogDescription asChild> <DialogDescription>
{invoice ? ( {invoice ? (
<div>Scan the QR code with a lightning-enabled wallet or copy the invoice below.</div> 'Scan the QR code or copy the invoice to pay with any Lightning wallet'
) : ( ) : (
<> <>
<div>Zaps are small Bitcoin payments that support the creator of this item.</div> Zaps are small Bitcoin payments that support the creator of this item.
<div className="mt-2">If you enjoyed this, consider sending a zap!</div> {' '}If you enjoyed this, consider sending a zap!
</> </>
)} )}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
{invoice ? ( {invoice ? (
<div className="flex flex-col items-center gap-4 py-4"> <div className="space-y-6">
<canvas ref={qrCodeRef} /> {/* Payment amount display */}
<div className="flex w-full items-center gap-2"> <div className="text-center">
<Input value={invoice} readOnly className="flex-1" /> <div className="text-2xl font-bold">{amount} sats</div>
<Button onClick={handleCopy} variant="outline" size="icon"> <div className="text-sm text-muted-foreground">Lightning Network Payment</div>
<Copy className="h-4 w-4" /> </div>
<Separator />
{/* QR Code */}
<div className="flex justify-center">
<Card className="p-4">
<CardContent className="p-0">
{qrCodeUrl ? (
<img
src={qrCodeUrl}
alt="Lightning Invoice QR Code"
className="w-64 h-64"
/>
) : (
<div className="w-64 h-64 bg-muted animate-pulse rounded" />
)}
</CardContent>
</Card>
</div>
{/* Invoice input */}
<div className="space-y-2">
<Label htmlFor="invoice">Lightning Invoice</Label>
<div className="flex gap-2">
<Input
id="invoice"
value={invoice}
readOnly
className="font-mono text-xs"
onClick={(e) => e.currentTarget.select()}
/>
<Button
variant="outline"
size="icon"
onClick={handleCopy}
className="shrink-0"
>
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
{/* Payment buttons */}
<div className="space-y-3">
{hasWebLN && (
<Button
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}}
disabled={isZapping}
className="w-full"
size="lg"
>
<Zap className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : "Pay with WebLN"}
</Button>
)}
<Button
variant="outline"
onClick={openInWallet}
className="w-full"
size="lg"
>
<ExternalLink className="h-4 w-4 mr-2" />
Open in Lightning Wallet
</Button> </Button>
<div className="text-xs text-muted-foreground text-center">
Scan the QR code or copy the invoice to pay with any Lightning wallet
</div>
</div> </div>
</div> </div>
) : ( ) : (

View File

@ -12,32 +12,6 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react'; import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify'; import type { NostrEvent } from '@nostrify/nostrify';
// NWC utility functions
function parseNWCUri(uri: string): NWCConnection | null {
try {
const url = new URL(uri);
if (url.protocol !== 'nostr+walletconnect:') {
return null;
}
const walletPubkey = url.pathname.replace('//', '');
const secret = url.searchParams.get('secret');
const relayParam = url.searchParams.getAll('relay');
if (!walletPubkey || !secret || relayParam.length === 0) {
return null;
}
return {
connectionString: uri,
alias: 'Parsed NWC',
isConnected: false,
};
} catch {
return null;
}
}
export function useZaps( export function useZaps(
target: Event | Event[], target: Event | Event[],
webln: WebLNProvider | null, webln: WebLNProvider | null,
@ -327,6 +301,5 @@ export function useZaps(
isZapping, isZapping,
invoice, invoice,
setInvoice, setInvoice,
parseNWCUri,
}; };
} }