Unify login/signup into single AuthDialog with 'Join' button

LoginArea now shows a single 'Join' button instead of separate 'Log in'
and 'Sign Up' buttons. The button opens a unified AuthDialog ported from
espy with steps: welcome \u2192 generate \u2192 secure \u2192 profile \u2192 login \u2192 connect.

The welcome step lets the user choose 'Create new account' or 'I already
have an account', so no functionality is lost \u2014 extension login,
nostrconnect QR flow, bunker URI, and secret-key file upload are all
preserved. Styling uses the template's neutral shadcn look rather than
espy's gradients, and copy is generic (no product branding).

Deletes LoginDialog.tsx and SignupDialog.tsx; updates AGENTS.md to
describe the new single-button behavior.
This commit is contained in:
Alex Gleason committed 2026-04-26 20:16:14 -05:00
1 parent 83c0ed42af
commit fc34ae02d4
5 files changed
+849 -913

No files matched your search

+3 -3
View File
@@ -17,7 +17,7 @@ This project is a Nostr client application built with React 19.x, TailwindCSS 3.
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/components/auth/`: Authentication-related components (LoginArea, AuthDialog, AccountSwitcher)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
@@ -663,9 +663,9 @@ function MyComponent() {
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
The `LoginArea` component handles all the login-related UI and interactions, including displaying the unified auth dialog (signup, login with extension/nsec/remote signer) and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
`LoginArea` displays a single "Join" button when the user is logged out, and changes to an account switcher once the user is logged in. The "Join" button opens an `AuthDialog` that lets the user either create a new account or log in with an existing one. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
**Important**: Social applications should include a profile menu button in the main interface (typically in headers/navigation) to provide access to account settings, profile editing, and logout functionality. Don't only show `LoginArea` in logged-out states.
+832
View File
@@ -0,0 +1,832 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
Download,
Upload,
Eye,
EyeOff,
Key,
Copy,
Check,
ChevronDown,
ChevronUp,
Loader2,
ExternalLink,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { QRCodeCanvas } from '@/components/ui/qrcode';
import { toast } from '@/hooks/useToast';
import {
useLoginActions,
generateNostrConnectParams,
generateNostrConnectURI,
type NostrConnectParams,
} from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
import { useIsMobile } from '@/hooks/useIsMobile';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
interface AuthDialogProps {
isOpen: boolean;
onClose: () => void;
}
type Step = 'welcome' | 'generate' | 'secure' | 'profile' | 'login' | 'connect';
const validateNsec = (nsec: string) => /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
const validateBunkerUri = (uri: string) => uri.startsWith('bunker://');
/** Check if running on an actual mobile device (not just a small screen). */
function isMobileDevice(): boolean {
if (typeof navigator === 'undefined') return false;
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
}
/** Download an nsec to a text file — same behavior as the previous SignupDialog. */
function downloadNsecFile(nsec: string) {
const decoded = nip19.decode(nsec);
if (decoded.type !== 'nsec') throw new Error('Invalid nsec key');
const pubkey = getPublicKey(decoded.data);
const npub = nip19.npubEncode(pubkey);
const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`;
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<Step>('welcome');
// Signup state
const [nsec, setNsec] = useState('');
const [showKey, setShowKey] = useState(false);
const [isGenerating, setIsGenerating] = useState(false);
const [profileData, setProfileData] = useState({ name: '', about: '', picture: '' });
// Login state
const [loginNsec, setLoginNsec] = useState('');
const [isLoggingIn, setIsLoggingIn] = useState(false);
const [loginError, setLoginError] = useState('');
const [showMoreOptions, setShowMoreOptions] = useState(false);
// Nostrconnect / bunker state
const [nostrConnectParams, setNostrConnectParams] = useState<NostrConnectParams | null>(null);
const [nostrConnectUri, setNostrConnectUri] = useState('');
const [isWaitingForConnect, setIsWaitingForConnect] = useState(false);
const [connectError, setConnectError] = useState<string | null>(null);
const [uriCopied, setUriCopied] = useState(false);
const [showBunkerInput, setShowBunkerInput] = useState(false);
const [bunkerUri, setBunkerUri] = useState('');
const login = useLoginActions();
// Stable ref so the nostrconnect effect doesn't restart on every render.
const loginRef = useRef(login);
loginRef.current = login;
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const avatarFileInputRef = useRef<HTMLInputElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const isMobile = useIsMobile();
const hasExtension = typeof window !== 'undefined' && 'nostr' in window;
// Reset state when the dialog closes.
useEffect(() => {
if (!isOpen) {
setStep('welcome');
setNsec('');
setLoginNsec('');
setShowKey(false);
setIsGenerating(false);
setIsLoggingIn(false);
setLoginError('');
setShowMoreOptions(false);
setProfileData({ name: '', about: '', picture: '' });
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
setUriCopied(false);
setShowBunkerInput(false);
setBunkerUri('');
abortControllerRef.current?.abort();
abortControllerRef.current = null;
}
}, [isOpen]);
// Generate a nostrconnect session (QR code data).
const generateConnectSession = useCallback(() => {
const relayUrls = login.getRelayUrls();
const params = generateNostrConnectParams(relayUrls);
const uri = generateNostrConnectURI(params, {
callback: isMobileDevice() ? `${window.location.origin}/remoteloginsuccess` : undefined,
});
setNostrConnectParams(params);
setNostrConnectUri(uri);
setConnectError(null);
}, [login]);
// Start listening for a nostrconnect response once params are set.
useEffect(() => {
if (!nostrConnectParams || isWaitingForConnect) return;
let cancelled = false;
const startListening = async () => {
setIsWaitingForConnect(true);
abortControllerRef.current = new AbortController();
try {
await loginRef.current.nostrconnect(
nostrConnectParams,
abortControllerRef.current.signal,
);
if (!cancelled) onClose();
} catch (error) {
if (cancelled) return;
if (error instanceof Error && error.name === 'AbortError') return;
console.error('Nostrconnect failed:', error);
setConnectError(error instanceof Error ? error.message : String(error));
setIsWaitingForConnect(false);
}
};
startListening();
return () => {
cancelled = true;
};
// NOTE: isWaitingForConnect is intentionally excluded from deps. Including
// it would cancel the first run the moment it sets the flag to true and
// spawn a duplicate listener.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [nostrConnectParams, onClose]);
const handleConnectRetry = useCallback(() => {
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
setTimeout(() => generateConnectSession(), 0);
}, [generateConnectSession]);
const handleCopyUri = async () => {
await navigator.clipboard.writeText(nostrConnectUri);
setUriCopied(true);
setTimeout(() => setUriCopied(false), 2000);
};
const handleOpenSignerApp = () => {
if (!nostrConnectUri) return;
window.location.href = nostrConnectUri;
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim() || !validateBunkerUri(bunkerUri)) return;
setIsLoggingIn(true);
try {
await login.bunker(bunkerUri);
onClose();
} catch {
setConnectError('Failed to connect. Check the bunker URI.');
setIsLoggingIn(false);
}
};
const goToConnect = () => {
setStep('connect');
if (!nostrConnectParams && !connectError) {
generateConnectSession();
}
};
// Signup: generate a key with a brief spinner for feedback.
const generateKey = () => {
setIsGenerating(true);
setTimeout(() => {
const sk = generateSecretKey();
setNsec(nip19.nsecEncode(sk));
setStep('secure');
setIsGenerating(false);
}, 750);
};
// Signup: download the nsec to a file and move on to the profile step.
const downloadAndProceed = () => {
try {
downloadNsecFile(nsec);
login.nsec(nsec);
setStep('profile');
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
};
// Login: submit the entered nsec.
const handleLogin = () => {
if (!loginNsec.trim()) {
setLoginError('Enter your secret key.');
return;
}
if (!validateNsec(loginNsec)) {
setLoginError('Invalid secret key. Must start with nsec1.');
return;
}
setIsLoggingIn(true);
setLoginError('');
// Timeout gives the UI a chance to repaint before the synchronous login.
setTimeout(() => {
try {
login.nsec(loginNsec);
onClose();
} catch {
setLoginError("Couldn't log in with this key.");
setIsLoggingIn(false);
}
}, 50);
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
const content = event.target?.result as string;
if (content && validateNsec(content.trim())) {
setLoginNsec(content.trim());
} else {
setLoginError('File does not contain a valid secret key.');
}
};
reader.onerror = () => setLoginError('Failed to read file.');
reader.readAsText(file);
};
const handleExtensionLogin = async () => {
if (!hasExtension) return;
setIsLoggingIn(true);
try {
await login.extension();
onClose();
} catch (e) {
setLoginError(e instanceof Error ? e.message : 'Extension login failed.');
setIsLoggingIn(false);
}
};
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
if (!file.type.startsWith('image/')) {
toast({ title: 'Please select an image.', variant: 'destructive' });
return;
}
if (file.size > 5 * 1024 * 1024) {
toast({ title: 'Image too large (max 5MB).', variant: 'destructive' });
return;
}
try {
const tags = await uploadFile(file);
const url = tags[0]?.[1];
if (url) setProfileData((prev) => ({ ...prev, picture: url }));
} catch {
toast({ title: 'Upload failed.', variant: 'destructive' });
}
};
const finishSignup = async (skipProfile = false) => {
try {
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
const metadata: Record<string, string> = {};
if (profileData.name) metadata.name = profileData.name;
if (profileData.about) metadata.about = profileData.about;
if (profileData.picture) metadata.picture = profileData.picture;
await publishEvent({ kind: 0, content: JSON.stringify(metadata) });
}
} catch {
toast({
title: 'Profile setup failed',
description: 'Your account was created but the profile could not be saved. You can update it later.',
variant: 'destructive',
});
} finally {
onClose();
}
};
const getTitle = () => {
switch (step) {
case 'welcome':
return 'Welcome';
case 'generate':
return 'Create account';
case 'secure':
return 'Save your key';
case 'profile':
return 'Your profile';
case 'login':
return 'Log in';
case 'connect':
return 'Connect signer';
}
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-0 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
{getTitle()}
</DialogTitle>
</DialogHeader>
<div className="px-6 pb-6 pt-4 space-y-5">
{/* Welcome step — the unified entry point. */}
{step === 'welcome' && (
<div className="space-y-5 text-center">
<div className="flex size-32 text-6xl bg-primary/10 rounded-full items-center justify-center mx-auto">
🔑
</div>
<p className="text-sm text-muted-foreground">
Join with a new Nostr account, or log in with one you already have.
</p>
<div className="space-y-2">
<Button onClick={() => setStep('generate')} className="w-full h-12">
Create new account
</Button>
<Button
variant="outline"
onClick={() => setStep('login')}
className="w-full h-12"
>
I already have an account
</Button>
</div>
</div>
)}
{/* Generate step. */}
{step === 'generate' && (
<div className="space-y-5 text-center">
<div className="relative w-20 h-20 mx-auto">
{isGenerating ? (
<div className="absolute inset-0 flex items-center justify-center">
<Loader2 className="w-12 h-12 text-primary animate-spin" />
</div>
) : (
<div className="absolute inset-0 rounded-full bg-primary/10 flex items-center justify-center">
<Key className="w-8 h-8 text-primary" />
</div>
)}
</div>
<div className="space-y-1">
<p className="font-medium">
{isGenerating ? 'Creating your key…' : 'Your key is your identity'}
</p>
<p className="text-sm text-muted-foreground">
{isGenerating
? 'This only takes a moment.'
: "We'll generate a secret key just for you. Keep it safe — it's the only way to log in."}
</p>
</div>
{!isGenerating && (
<Button onClick={generateKey} className="w-full h-12">
Generate key
</Button>
)}
<button
onClick={() => setStep('welcome')}
className="text-sm text-muted-foreground hover:text-foreground"
>
Back
</button>
</div>
)}
{/* Secure step — show + download nsec. */}
{step === 'secure' && (
<div className="space-y-4">
<div className="flex size-14 bg-primary/10 rounded-full items-center justify-center mx-auto">
<Key className="w-7 h-7 text-primary" />
</div>
<p className="text-sm text-muted-foreground text-center">
Store your key somewhere safe. You'll need it to log in again.
</p>
<div className="relative">
<Input
type={showKey ? 'text' : 'password'}
value={nsec}
readOnly
className="pr-10 font-mono"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowKey(!showKey)}
>
{showKey ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)}
</Button>
</div>
<div className="p-3 rounded-lg bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800">
<p className="text-xs text-amber-900 dark:text-amber-300">
This key is your only way to access your account. If you lose it, you lose the account.
</p>
</div>
<Button onClick={downloadAndProceed} className="w-full h-12">
<Download className="w-4 h-4 mr-2" />
Download &amp; continue
</Button>
</div>
)}
{/* Profile step — optional metadata. */}
{step === 'profile' && (
<div className="space-y-4">
<p className="text-sm text-muted-foreground text-center">
Tell others a bit about yourself (optional).
</p>
<div className={`space-y-4 ${isPublishing ? 'opacity-50 pointer-events-none' : ''}`}>
<div className="space-y-1.5">
<label htmlFor="profile-name" className="text-sm font-medium">
Display name
</label>
<Input
id="profile-name"
value={profileData.name}
onChange={(e) =>
setProfileData((prev) => ({ ...prev, name: e.target.value }))
}
placeholder="Your name"
/>
</div>
<div className="space-y-1.5">
<label htmlFor="profile-about" className="text-sm font-medium">
Bio
</label>
<Textarea
id="profile-about"
value={profileData.about}
onChange={(e) =>
setProfileData((prev) => ({ ...prev, about: e.target.value }))
}
placeholder="A little about you…"
className="resize-none"
rows={3}
/>
</div>
<div className="space-y-1.5">
<label htmlFor="profile-picture" className="text-sm font-medium">
Avatar
</label>
<div className="flex gap-2">
<Input
id="profile-picture"
value={profileData.picture}
onChange={(e) =>
setProfileData((prev) => ({ ...prev, picture: e.target.value }))
}
placeholder="https://…"
className="flex-1"
/>
<input
type="file"
accept="image/*"
className="hidden"
ref={avatarFileInputRef}
onChange={handleAvatarUpload}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading}
title="Upload avatar"
>
{isUploading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Upload className="w-4 h-4" />
)}
</Button>
</div>
</div>
</div>
<div className="space-y-2">
<Button
onClick={() => finishSignup(false)}
disabled={isPublishing}
className="w-full h-12"
>
{isPublishing ? 'Saving…' : 'Finish'}
</Button>
<Button
variant="ghost"
onClick={() => finishSignup(true)}
disabled={isPublishing}
className="w-full"
>
Skip for now
</Button>
</div>
</div>
)}
{/* Login step. */}
{step === 'login' && (
<div className="space-y-4">
{hasExtension ? (
<>
<Button
onClick={handleExtensionLogin}
disabled={isLoggingIn}
className="w-full h-12"
>
{isLoggingIn ? 'Logging in…' : 'Log in with extension'}
</Button>
<Button
variant="outline"
onClick={goToConnect}
className="w-full h-12"
>
Use remote signer
</Button>
<Collapsible open={showMoreOptions} onOpenChange={setShowMoreOptions}>
<CollapsibleTrigger className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground py-2">
<span>Use secret key</span>
<ChevronDown
className={`w-4 h-4 transition-transform ${
showMoreOptions ? 'rotate-180' : ''
}`}
/>
</CollapsibleTrigger>
<CollapsibleContent className="space-y-3 pt-1">
<NsecLoginForm
loginNsec={loginNsec}
setLoginNsec={setLoginNsec}
loginError={loginError}
setLoginError={setLoginError}
isLoggingIn={isLoggingIn}
onSubmit={handleLogin}
onFileChange={handleFileUpload}
fileInputRef={fileInputRef}
/>
</CollapsibleContent>
</Collapsible>
</>
) : (
<>
<NsecLoginForm
loginNsec={loginNsec}
setLoginNsec={setLoginNsec}
loginError={loginError}
setLoginError={setLoginError}
isLoggingIn={isLoggingIn}
onSubmit={handleLogin}
onFileChange={handleFileUpload}
fileInputRef={fileInputRef}
/>
<Button
variant="outline"
onClick={goToConnect}
className="w-full"
>
Use remote signer
</Button>
</>
)}
<button
onClick={() => setStep('welcome')}
className="w-full text-sm text-muted-foreground hover:text-foreground"
>
Back
</button>
</div>
)}
{/* Connect step — nostrconnect QR + bunker URI fallback. */}
{step === 'connect' && (
<div className="space-y-4">
<p className="text-sm text-muted-foreground text-center">
{isMobile ? 'Open your signer app to connect.' : 'Scan with your signer app.'}
</p>
<div className="flex flex-col items-center space-y-4">
{connectError ? (
<div className="flex flex-col items-center space-y-3 py-4">
<p className="text-sm text-destructive text-center">{connectError}</p>
<Button variant="outline" onClick={handleConnectRetry}>
Try again
</Button>
</div>
) : nostrConnectUri ? (
<>
{!isMobile && (
<div className="p-4 bg-white rounded-xl">
<QRCodeCanvas value={nostrConnectUri} size={180} level="M" />
</div>
)}
{isMobile && (
<Button onClick={handleOpenSignerApp} className="w-full h-12">
<ExternalLink className="w-5 h-5 mr-2" />
Open signer app
</Button>
)}
<Button
variant="outline"
size={isMobile ? 'default' : 'sm'}
className={isMobile ? 'w-full gap-2' : 'gap-2'}
onClick={handleCopyUri}
>
{uriCopied ? (
<>
<Check className="w-4 h-4" />
Copied
</>
) : (
<>
<Copy className="w-4 h-4" />
Copy URI
</>
)}
</Button>
</>
) : (
<div className="flex items-center justify-center h-[100px]">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
)}
</div>
{/* Manual bunker URI fallback. */}
<Collapsible open={showBunkerInput} onOpenChange={setShowBunkerInput}>
<CollapsibleTrigger className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground py-2">
<span>Enter bunker URI manually</span>
{showBunkerInput ? (
<ChevronUp className="w-4 h-4" />
) : (
<ChevronDown className="w-4 h-4" />
)}
</CollapsibleTrigger>
<CollapsibleContent className="space-y-3 pt-2">
<Input
value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)}
placeholder="bunker://…"
className="text-base md:text-sm"
/>
{bunkerUri && !validateBunkerUri(bunkerUri) && (
<Alert variant="destructive">
<AlertDescription>Invalid bunker URI format.</AlertDescription>
</Alert>
)}
<Button
variant="outline"
onClick={handleBunkerLogin}
disabled={
isLoggingIn || !bunkerUri.trim() || !validateBunkerUri(bunkerUri)
}
className="w-full"
>
{isLoggingIn ? 'Connecting…' : 'Connect'}
</Button>
</CollapsibleContent>
</Collapsible>
<button
onClick={() => setStep('login')}
className="w-full text-sm text-muted-foreground hover:text-foreground"
>
Back
</button>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
};
/** Shared nsec input + submit + file-upload block used in the login step. */
interface NsecLoginFormProps {
loginNsec: string;
setLoginNsec: (v: string) => void;
loginError: string;
setLoginError: (v: string) => void;
isLoggingIn: boolean;
onSubmit: () => void;
onFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
fileInputRef: React.RefObject<HTMLInputElement | null>;
}
const NsecLoginForm: React.FC<NsecLoginFormProps> = ({
loginNsec,
setLoginNsec,
loginError,
setLoginError,
isLoggingIn,
onSubmit,
onFileChange,
fileInputRef,
}) => (
<form
onSubmit={(e) => {
e.preventDefault();
onSubmit();
}}
className="space-y-3"
>
<Input
type="password"
value={loginNsec}
onChange={(e) => {
setLoginNsec(e.target.value);
if (loginError) setLoginError('');
}}
placeholder="nsec1…"
autoComplete="off"
className={loginError ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
{loginError && <p className="text-sm text-destructive">{loginError}</p>}
<div className="flex gap-2">
<Button
type="submit"
disabled={isLoggingIn || !loginNsec.trim()}
className="flex-1"
>
{isLoggingIn ? 'Logging in…' : 'Log in'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={onFileChange}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() => fileInputRef.current?.click()}
>
<Upload className="w-4 h-4" />
</Button>
</div>
</form>
);
export default AuthDialog;
+14 -38
View File
@@ -1,10 +1,6 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import AuthDialog from './AuthDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
@@ -15,45 +11,25 @@ export interface LoginAreaProps {
export function LoginArea({ className }: LoginAreaProps) {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
const handleLogin = () => {
setLoginDialogOpen(false);
setSignupDialogOpen(false);
};
const [authDialogOpen, setAuthDialogOpen] = useState(false);
return (
<div className={cn("inline-flex items-center justify-center", className)}>
<div className={cn('inline-flex items-center justify-center', className)}>
{currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
<AccountSwitcher onAddAccountClick={() => setAuthDialogOpen(true)} />
) : (
<div className="flex gap-3 justify-center">
<Button
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
>
<span>Sign up</span>
</Button>
</div>
<Button
onClick={() => setAuthDialogOpen(true)}
className="flex items-center gap-2 px-5 py-2 rounded-full bg-primary text-primary-foreground font-medium transition-all hover:bg-primary/90 animate-scale-in"
>
<span className="truncate">Join</span>
</Button>
)}
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
/>
<SignupDialog
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
<AuthDialog
isOpen={authDialogOpen}
onClose={() => setAuthDialogOpen(false)}
/>
</div>
);
}
}
-511
View File
@@ -1,511 +0,0 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect, useCallback } from 'react';
import { Upload, AlertTriangle, ChevronDown, ChevronUp, Loader2, Copy, Check, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Collapsible, CollapsibleContent } from '@/components/ui/collapsible';
import { QRCodeCanvas } from '@/components/ui/qrcode';
import {
useLoginActions,
generateNostrConnectParams,
generateNostrConnectURI,
type NostrConnectParams,
} from '@/hooks/useLoginActions';
import { DialogTitle } from '@radix-ui/react-dialog';
import { useIsMobile } from '@/hooks/useIsMobile';
interface LoginDialogProps {
isOpen: boolean;
onClose: () => void;
onLogin: () => void;
}
const validateNsec = (nsec: string) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
/** Check if running on actual mobile device (not just small screen) */
function isMobileDevice(): boolean {
if (typeof navigator === 'undefined') return false;
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
}
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [nostrConnectParams, setNostrConnectParams] = useState<NostrConnectParams | null>(null);
const [nostrConnectUri, setNostrConnectUri] = useState<string>('');
const [isWaitingForConnect, setIsWaitingForConnect] = useState(false);
const [connectError, setConnectError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [showBunkerInput, setShowBunkerInput] = useState(false);
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
file?: string;
extension?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const login = useLoginActions();
// Check if on mobile device
const isMobile = useIsMobile();
// Check if extension is available
const hasExtension = 'nostr' in window;
// Generate nostrconnect params (sync) - just creates the QR code data
const generateConnectSession = useCallback(() => {
const relayUrls = login.getRelayUrls();
const params = generateNostrConnectParams(relayUrls);
const uri = generateNostrConnectURI(params, {
callback: isMobileDevice() ? `${window.location.origin}/remoteloginsuccess` : undefined,
});
setNostrConnectParams(params);
setNostrConnectUri(uri);
setConnectError(null);
}, [login]);
// Start listening for connection (async) - runs after params are set
useEffect(() => {
if (!nostrConnectParams || isWaitingForConnect) return;
const startListening = async () => {
setIsWaitingForConnect(true);
abortControllerRef.current = new AbortController();
try {
await login.nostrconnect(nostrConnectParams, abortControllerRef.current.signal);
onLogin();
onClose();
} catch (error) {
console.error('Nostrconnect failed:', error);
// Don't show error if it was aborted (dialog closed)
if (error instanceof Error && error.name !== 'AbortError') {
setConnectError(error.message);
}
setIsWaitingForConnect(false);
}
};
startListening();
}, [nostrConnectParams, login, onLogin, onClose, isWaitingForConnect]);
// Clean up on close
useEffect(() => {
if (!isOpen) {
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
setNsec('');
setBunkerUri('');
setErrors({});
setIsLoading(false);
setIsFileLoading(false);
setShowBunkerInput(false);
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}, [isOpen]);
// Retry connection with new params
const handleRetry = useCallback(() => {
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
// Generate new session after state clears
setTimeout(() => generateConnectSession(), 0);
}, [generateConnectSession]);
const handleCopyUri = async () => {
await navigator.clipboard.writeText(nostrConnectUri);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
// Open the nostrconnect URI in the system - this will launch a signer app like Amber if installed
const handleOpenSignerApp = () => {
if (!nostrConnectUri) return;
window.location.href = nostrConnectUri;
};
const handleExtensionLogin = async () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
onLogin();
onClose();
} catch (e: unknown) {
const error = e as Error;
console.error('Extension login failed:', error);
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
} finally {
setIsLoading(false);
}
};
const executeLogin = (key: string) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
onLogin();
onClose();
// Clear the URI from memory
setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} finally {
setIsLoading(false);
}
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
} else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
} else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
};
reader.readAsText(file);
};
const [isMoreOptionsOpen, setIsMoreOptionsOpen] = useState(false);
const renderTabs = () => (
<Tabs
defaultValue="key"
className="w-full"
onValueChange={(value) => {
if (value === 'remote' && !nostrConnectParams && !connectError) {
generateConnectSession();
}
}}
>
<TabsList className="grid w-full grid-cols-2 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="key" className="flex items-center gap-2">
<span>Secret Key</span>
</TabsTrigger>
<TabsTrigger value="remote" className="flex items-center gap-2">
<span>Remote Signer</span>
</TabsTrigger>
</TabsList>
<TabsContent value='key' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleKeyLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<div className="flex space-x-2">
<Button
type="submit"
size="lg"
disabled={isLoading || !nsec.trim()}
className="flex-1"
>
{isLoading ? 'Verifying...' : 'Log in'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
type="button"
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</form>
</TabsContent>
<TabsContent value='remote' className='space-y-4'>
{/* Nostrconnect Section */}
<div className='flex flex-col items-center space-y-4'>
{connectError ? (
<div className='flex flex-col items-center space-y-4 py-4'>
<p className='text-sm text-red-500 text-center'>{connectError}</p>
<Button variant='outline' onClick={handleRetry}>
Retry
</Button>
</div>
) : nostrConnectUri ? (
<>
{/* QR Code - only show on desktop */}
{!isMobile && (
<div className='p-4 bg-white dark:bg-white rounded-xl'>
<QRCodeCanvas
value={nostrConnectUri}
size={180}
level='M'
/>
</div>
)}
{/* Status message */}
<div className='flex items-center gap-2 text-sm text-muted-foreground'>
<span>{isMobile ? 'Tap to open your signer app' : 'Scan with your signer app'}</span>
</div>
{/* Open Signer App button - primary action on mobile */}
{isMobile && (
<Button
className='w-full gap-2 py-6 rounded-full'
onClick={handleOpenSignerApp}
>
<ExternalLink className='w-5 h-5' />
Open Signer App
</Button>
)}
{/* Copy button */}
<Button
variant='outline'
size={isMobile ? 'default' : 'sm'}
className={isMobile ? 'w-full gap-2 rounded-full' : 'gap-2'}
onClick={handleCopyUri}
>
{copied ? (
<>
<Check className='w-4 h-4' />
Copied!
</>
) : (
<>
<Copy className='w-4 h-4' />
Copy URI
</>
)}
</Button>
</>
) : (
<div className='flex items-center justify-center h-[100px]'>
<Loader2 className='w-8 h-8 animate-spin text-muted-foreground' />
</div>
)}
</div>
{/* Manual URI input section - collapsible */}
<div className='pt-4 border-t border-gray-200 dark:border-gray-700'>
<button
type='button'
onClick={() => setShowBunkerInput(!showBunkerInput)}
className='flex items-center justify-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2'
>
<span>Enter bunker URI manually</span>
{showBunkerInput ? (
<ChevronUp className='w-4 h-4' />
) : (
<ChevronDown className='w-4 h-4' />
)}
</button>
{showBunkerInput && (
<div className='space-y-3 mt-3'>
<div className='space-y-2'>
<Input
id='connectBunkerUri'
value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary text-base md:text-sm'
placeholder='bunker://'
/>
{bunkerUri && !validateBunkerUri(bunkerUri) && (
<p className='text-red-500 text-xs'>Invalid bunker URI format</p>
)}
</div>
<Button
className='w-full rounded-full py-4'
variant='outline'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim() || !validateBunkerUri(bunkerUri)}
>
{isLoading ? 'Connecting...' : 'Connect'}
</Button>
</div>
)}
</div>
</TabsContent>
</Tabs>
);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
Log in
</DialogTitle>
</DialogHeader>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
<div className='px-6 pb-6 space-y-4 overflow-y-auto'>
{/* Extension Login Button - shown if extension is available */}
{hasExtension && (
<div className="space-y-3">
{errors.extension && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{errors.extension}</AlertDescription>
</Alert>
)}
<Button
className="w-full h-12 px-9"
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Log in with Extension'}
</Button>
</div>
)}
{/* Tabs - wrapped in collapsible if extension is available, otherwise shown directly */}
{hasExtension ? (
<Collapsible className="space-y-4" open={isMoreOptionsOpen} onOpenChange={setIsMoreOptionsOpen}>
<button
type="button"
onClick={() => setIsMoreOptionsOpen(!isMoreOptionsOpen)}
className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors py-2"
>
<span>More Options</span>
<ChevronDown className={`w-4 h-4 transition-transform ${isMoreOptionsOpen ? 'rotate-180' : ''}`} />
</button>
<CollapsibleContent>
{renderTabs()}
</CollapsibleContent>
</Collapsible>
) : (
renderTabs()
)}
</div>
</DialogContent>
</Dialog>
);
};
export default LoginDialog;
-361
View File
@@ -1,361 +0,0 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState, useEffect, useRef } from 'react';
import { Download, Upload, Eye, EyeOff } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'profile'>('generate');
const [nsec, setNsec] = useState('');
const [showKey, setShowKey] = useState(false);
const [profileData, setProfileData] = useState({
name: '',
about: '',
picture: ''
});
const login = useLoginActions();
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const avatarFileInputRef = useRef<HTMLInputElement>(null);
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
const sk = generateSecretKey();
setNsec(nip19.nsecEncode(sk));
setStep('download');
};
const downloadKey = () => {
try {
// Create a blob with the key text
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const decoded = nip19.decode(nsec);
if (decoded.type !== 'nsec') {
throw new Error('Invalid nsec key');
}
const pubkey = getPublicKey(decoded.data);
const npub = nip19.npubEncode(pubkey);
const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`;
// Create a temporary link element and trigger download
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Clean up immediately
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Continue to profile step
login.nsec(nsec);
setStep('profile');
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
};
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
// Reset file input
e.target.value = '';
// Validate file type
if (!file.type.startsWith('image/')) {
toast({
title: 'Invalid file type',
description: 'Please select an image file for your avatar.',
variant: 'destructive',
});
return;
}
// Validate file size (max 5MB)
if (file.size > 5 * 1024 * 1024) {
toast({
title: 'File too large',
description: 'Avatar image must be smaller than 5MB.',
variant: 'destructive',
});
return;
}
try {
const tags = await uploadFile(file);
// Get the URL from the first tag
const url = tags[0]?.[1];
if (url) {
setProfileData(prev => ({ ...prev, picture: url }));
}
} catch {
toast({
title: 'Upload failed',
description: 'Failed to upload avatar. Please try again.',
variant: 'destructive',
});
}
};
const finishSignup = async (skipProfile = false) => {
try {
// Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
const metadata: Record<string, string> = {};
if (profileData.name) metadata.name = profileData.name;
if (profileData.about) metadata.about = profileData.about;
if (profileData.picture) metadata.picture = profileData.picture;
await publishEvent({
kind: 0,
content: JSON.stringify(metadata),
});
}
} catch {
toast({
title: 'Profile Setup Failed',
description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive',
});
} finally {
onClose();
}
};
const getTitle = () => {
if (step === 'generate') return 'Sign up';
if (step === 'download') return 'Secret Key';
if (step === 'profile') return 'Create Your Profile';
};
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
setStep('generate');
setNsec('');
setShowKey(false);
setProfileData({ name: '', about: '', picture: '' });
}
}, [isOpen]);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
{getTitle()}
</DialogTitle>
</DialogHeader>
<div className='px-6 pb-6 space-y-4 overflow-y-auto flex-1'>
{/* Generate Step */}
{step === 'generate' && (
<div className='text-center space-y-6'>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
<Button className="w-full h-12 px-9" onClick={generateKey}>
Generate key
</Button>
</div>
)}
{/* Download Step */}
{step === 'download' && (
<div className='space-y-4'>
<div className="flex size-16 text-4xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
<div className="relative">
<Input
type={showKey ? "text" : "password"}
value={nsec}
readOnly
className="pr-10 font-mono"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowKey(!showKey)}
>
{showKey ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)}
</Button>
</div>
<Button
className="w-full h-12 px-9"
onClick={downloadKey}
>
<Download className="size-4" />
Download key
</Button>
<div className='mx-auto max-w-sm'>
<div className='p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800'>
<div className='flex items-center gap-2 mb-1'>
<span className='text-xs font-semibold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-amber-900 dark:text-amber-300'>
This key is your primary and only means of accessing your account. Store it safely and securely. Please download your key to continue.
</p>
</div>
</div>
</div>
)}
{/* Profile Step */}
{step === 'profile' && (
<div className='text-center space-y-4'>
{/* Publishing status indicator */}
{isPublishing && (
<div className='p-4 rounded-lg bg-muted border'>
<div className='flex items-center justify-center gap-3'>
<div className='w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium'>
Publishing your profile...
</span>
</div>
</div>
)}
{/* Profile form */}
<div className={`space-y-4 text-left ${isPublishing ? 'opacity-50 pointer-events-none' : ''}`}>
<div className='space-y-2'>
<label htmlFor='profile-name' className='text-sm font-medium'>
Display Name
</label>
<Input
id='profile-name'
value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name'
disabled={isPublishing}
/>
</div>
<div className='space-y-2'>
<label htmlFor='profile-about' className='text-sm font-medium'>
Bio
</label>
<Textarea
id='profile-about'
value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...'
className='resize-none'
rows={3}
disabled={isPublishing}
/>
</div>
<div className='space-y-2'>
<label htmlFor='profile-picture' className='text-sm font-medium'>
Avatar
</label>
<div className='flex gap-2'>
<Input
id='profile-picture'
value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg'
className='flex-1'
disabled={isPublishing}
/>
<input
type='file'
accept='image/*'
className='hidden'
ref={avatarFileInputRef}
onChange={handleAvatarUpload}
/>
<Button
type='button'
variant='outline'
size='icon'
onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing}
title='Upload avatar image'
>
{isUploading ? (
<div className='w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin' />
) : (
<Upload className='w-4 h-4' />
)}
</Button>
</div>
</div>
</div>
{/* Action buttons */}
<div className='space-y-3'>
<Button
className='w-full'
onClick={() => finishSignup(false)}
disabled={isPublishing || isUploading}
>
{isPublishing ? (
<>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Creating Profile...
</>
) : (
'Create profile'
)}
</Button>
<Button
variant='outline'
className='w-full'
onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
>
{isPublishing ? (
'Setting up account...'
) : (
'Skip for now'
)}
</Button>
</div>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
};
export default SignupDialog;