mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2474609a5a | ||
|
|
ea5932490a | ||
|
|
3db5148780 | ||
|
|
a0bd6729ae | ||
|
|
05c0ec92f7 |
No files matched your search
@@ -36,7 +36,6 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
||||||
- `useNWC`: Nostr Wallet Connect connection management
|
- `useNWC`: Nostr Wallet Connect connection management
|
||||||
- `useNWCContext`: Access NWC context provider
|
- `useNWCContext`: Access NWC context provider
|
||||||
- `usePush`: Push notifications via Nostr RPC
|
|
||||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||||
- `/src/lib/`: Utility functions and shared logic
|
- `/src/lib/`: Utility functions and shared logic
|
||||||
- `/src/contexts/`: React context providers (AppContext, NWCContext)
|
- `/src/contexts/`: React context providers (AppContext, NWCContext)
|
||||||
@@ -843,48 +842,6 @@ const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
|||||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Push Notifications
|
|
||||||
|
|
||||||
The project includes `usePush` hook for managing push notifications via Nostr RPC. This enables users to receive browser notifications for Nostr events.
|
|
||||||
|
|
||||||
#### Basic Usage
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { usePush } from '@/hooks/usePush';
|
|
||||||
|
|
||||||
function NotificationButton({ authorPubkey }: { authorPubkey: string }) {
|
|
||||||
const { subscribeToAuthor, isLoading, error } = usePush();
|
|
||||||
|
|
||||||
const handleEnableNotifications = async () => {
|
|
||||||
try {
|
|
||||||
await subscribeToAuthor(authorPubkey);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to enable notifications:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button onClick={handleEnableNotifications} disabled={isLoading}>
|
|
||||||
{isLoading ? 'Enabling...' : 'Enable Notifications'}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Available Methods
|
|
||||||
|
|
||||||
- **`subscribeToAuthor`**: Get notifications for new posts from a specific user
|
|
||||||
- **`subscribeToMentions`**: Get notifications when mentioned in posts
|
|
||||||
- **`subscribeToHashtag`**: Get notifications for posts with specific hashtags
|
|
||||||
- **`registerSubscription`**: Create custom notification subscriptions
|
|
||||||
- **`deleteSubscription`**: Remove notification subscriptions
|
|
||||||
|
|
||||||
#### Requirements
|
|
||||||
|
|
||||||
- User must be logged in with NIP-44 encryption support
|
|
||||||
- Browser must support push notifications
|
|
||||||
- VAPID public key is included by default
|
|
||||||
|
|
||||||
### Rendering Rich Text Content
|
### Rendering Rich Text Content
|
||||||
|
|
||||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||||
|
|||||||
@@ -57,6 +57,11 @@ export function LoginArea({ className }: LoginAreaProps) {
|
|||||||
<SignupDialog
|
<SignupDialog
|
||||||
isOpen={signupDialogOpen}
|
isOpen={signupDialogOpen}
|
||||||
onClose={() => setSignupDialogOpen(false)}
|
onClose={() => setSignupDialogOpen(false)}
|
||||||
|
onLogin={handleLogin}
|
||||||
|
onOpenLogin={() => {
|
||||||
|
setSignupDialogOpen(false);
|
||||||
|
setLoginDialogOpen(true);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
// 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 React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
|
import { Download, CheckCircle, User, Upload } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
@@ -19,17 +19,17 @@ interface SignupDialogProps {
|
|||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onComplete?: () => void;
|
onComplete?: () => void;
|
||||||
|
onLogin?: () => void;
|
||||||
|
onOpenLogin?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const sanitizeFilename = (filename: string) => {
|
const sanitizeFilename = (filename: string) => {
|
||||||
return filename.replace(/[^a-z0-9_.-]/gi, '_');
|
return filename.replace(/[^a-z0-9_.-]/gi, '_');
|
||||||
}
|
}
|
||||||
|
|
||||||
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete }) => {
|
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete, onLogin, onOpenLogin }) => {
|
||||||
const [step, setStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
|
const [step, setStep] = useState<'key' | 'keygen' | 'download' | 'profile' | 'done'>('key');
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [nsec, setNsec] = useState('');
|
const [nsec, setNsec] = useState('');
|
||||||
const [showSparkles, setShowSparkles] = useState(false);
|
|
||||||
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
|
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
|
||||||
const [profileData, setProfileData] = useState({
|
const [profileData, setProfileData] = useState({
|
||||||
name: '',
|
name: '',
|
||||||
@@ -41,10 +41,8 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
|||||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||||
const avatarFileInputRef = useRef<HTMLInputElement>(null);
|
const avatarFileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
// Generate a proper nsec key using nostr-tools
|
const handleGenerateKey = () => {
|
||||||
const generateKey = () => {
|
setStep('keygen');
|
||||||
setIsLoading(true);
|
|
||||||
setShowSparkles(true);
|
|
||||||
|
|
||||||
// Add a dramatic pause for the key generation effect
|
// Add a dramatic pause for the key generation effect
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -66,13 +64,18 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
|||||||
description: 'Failed to generate key. Please try again.',
|
description: 'Failed to generate key. Please try again.',
|
||||||
variant: 'destructive',
|
variant: 'destructive',
|
||||||
});
|
});
|
||||||
} finally {
|
setStep('key');
|
||||||
setIsLoading(false);
|
|
||||||
setShowSparkles(false);
|
|
||||||
}
|
}
|
||||||
}, 2000);
|
}, 2000);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleHasKey = () => {
|
||||||
|
onClose();
|
||||||
|
if (onOpenLogin) {
|
||||||
|
onOpenLogin();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const downloadKey = () => {
|
const downloadKey = () => {
|
||||||
try {
|
try {
|
||||||
// Create a blob with the key text
|
// Create a blob with the key text
|
||||||
@@ -110,8 +113,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const finishKeySetup = () => {
|
const finishKeySetup = () => {
|
||||||
try {
|
try {
|
||||||
login.nsec(nsec);
|
login.nsec(nsec);
|
||||||
@@ -242,302 +243,154 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getTitle = () => {
|
const getTitle = () => {
|
||||||
if (step === 'welcome') return (
|
if (step === 'key') return 'Sign up';
|
||||||
<span className="flex items-center justify-center gap-2">
|
if (step === 'keygen') return 'Generating Your Key';
|
||||||
Create Your Account
|
if (step === 'download') return 'Secret Key';
|
||||||
</span>
|
if (step === 'profile') return 'Create Your Profile';
|
||||||
);
|
return 'Welcome!';
|
||||||
if (step === 'generate') return (
|
|
||||||
<span className="flex items-center justify-center gap-2">
|
|
||||||
Generating Your Key
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
if (step === 'download') return (
|
|
||||||
<span className="flex items-center justify-center gap-2">
|
|
||||||
Secret Key
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
if (step === 'profile') return (
|
|
||||||
<span className="flex items-center justify-center gap-2">
|
|
||||||
Create Your Profile
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
<span className="flex items-center justify-center gap-2">
|
|
||||||
Welcome!
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Reset state when dialog opens
|
// Reset state when dialog opens
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
setStep('welcome');
|
setStep('key');
|
||||||
setIsLoading(false);
|
|
||||||
setNsec('');
|
setNsec('');
|
||||||
setShowSparkles(false);
|
|
||||||
setKeySecured('none');
|
setKeySecured('none');
|
||||||
setProfileData({ name: '', about: '', picture: '' });
|
setProfileData({ name: '', about: '', picture: '' });
|
||||||
}
|
}
|
||||||
}, [isOpen]);
|
}, [isOpen]);
|
||||||
|
|
||||||
// Add sparkle animation effect
|
|
||||||
useEffect(() => {
|
|
||||||
if (showSparkles) {
|
|
||||||
const interval = setInterval(() => {
|
|
||||||
// This will trigger re-renders for sparkle animation
|
|
||||||
}, 100);
|
|
||||||
return () => clearInterval(interval);
|
|
||||||
}
|
|
||||||
}, [showSparkles]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
<DialogContent
|
<DialogContent
|
||||||
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
|
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
|
||||||
>
|
>
|
||||||
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
|
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
|
||||||
<DialogTitle className={cn('font-semibold text-center text-lg')}>
|
<DialogTitle className={cn('font-semibold text-left text-lg')}>
|
||||||
{getTitle()}
|
{getTitle()}
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
|
|
||||||
{/* Welcome Step - New engaging introduction */}
|
|
||||||
{step === 'welcome' && (
|
|
||||||
<div className='text-center space-y-4'>
|
|
||||||
{/* Hero illustration */}
|
|
||||||
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50'>
|
|
||||||
<div className='flex justify-center items-center space-x-4 mb-3'>
|
|
||||||
<div className='relative'>
|
|
||||||
<UserPlus className='w-12 h-12 text-blue-600' />
|
|
||||||
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' />
|
|
||||||
</div>
|
|
||||||
<Globe className='w-16 h-16 text-blue-700 animate-spin-slow' />
|
|
||||||
<div className='relative'>
|
|
||||||
<FileText className='w-12 h-12 text-blue-600' />
|
|
||||||
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse' style={{animationDelay: '0.3s'}} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Benefits */}
|
<div className='px-6 pt-2 pb-6 space-y-6 flex-1'>
|
||||||
<div className='grid grid-cols-1 gap-2 text-sm'>
|
{/* Initial Key Step - Soapbox style */}
|
||||||
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
|
{step === 'key' && (
|
||||||
<Shield className='w-4 h-4' />
|
<div className='flex flex-col items-center space-y-6'>
|
||||||
Decentralized and censorship-resistant
|
<p className='text-center font-semibold'>
|
||||||
</div>
|
You need a key to continue
|
||||||
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
|
</p>
|
||||||
<User className='w-4 h-4' />
|
|
||||||
You are in control of your data
|
<div className='rounded-full bg-gray-100 p-8 dark:bg-gray-800'>
|
||||||
</div>
|
<div className='text-8xl'>
|
||||||
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
|
🔑
|
||||||
<Globe className='w-4 h-4' />
|
|
||||||
Join a global network
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='space-y-3'>
|
<div className='flex flex-col items-center space-y-3 w-full'>
|
||||||
<Button
|
<Button
|
||||||
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
|
className='bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-6 rounded-2xl'
|
||||||
onClick={() => setStep('generate')}
|
size='lg'
|
||||||
|
onClick={handleGenerateKey}
|
||||||
>
|
>
|
||||||
<LogIn className='w-5 h-5 mr-2' />
|
Generate key
|
||||||
Get Started
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant='ghost'
|
||||||
|
className='text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 rounded-2xl'
|
||||||
|
onClick={handleHasKey}
|
||||||
|
>
|
||||||
|
I already have a key
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Generate Step - Enhanced with animations */}
|
{/* Key Generation Step */}
|
||||||
{step === 'generate' && (
|
{step === 'keygen' && (
|
||||||
<div className='text-center space-y-4'>
|
<div className='text-center space-y-4'>
|
||||||
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-purple-100 dark:from-blue-950/50 dark:to-purple-950/50 overflow-hidden'>
|
<div className='space-y-2'>
|
||||||
{/* Animated background elements */}
|
<p className='text-lg font-semibold'>
|
||||||
{showSparkles && (
|
Generating your secret key...
|
||||||
<div className='absolute inset-0'>
|
</p>
|
||||||
{[...Array(12)].map((_, i) => (
|
<p className='text-sm text-muted-foreground'>
|
||||||
<Sparkles
|
Creating your secure key
|
||||||
key={i}
|
</p>
|
||||||
className={`absolute w-4 h-4 text-yellow-400 animate-ping`}
|
|
||||||
style={{
|
|
||||||
left: `${Math.random() * 80 + 10}%`,
|
|
||||||
top: `${Math.random() * 80 + 10}%`,
|
|
||||||
animationDelay: `${Math.random() * 2}s`
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className='relative z-10'>
|
|
||||||
{isLoading ? (
|
|
||||||
<div className='space-y-3'>
|
|
||||||
<div className='relative'>
|
|
||||||
<Key className='w-20 h-20 text-primary mx-auto animate-pulse' />
|
|
||||||
<div className='absolute inset-0 flex items-center justify-center'>
|
|
||||||
<div className='w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin'></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className='space-y-2'>
|
|
||||||
<p className='text-lg font-semibold text-primary flex items-center justify-center gap-2'>
|
|
||||||
<Sparkles className='w-5 h-5' />
|
|
||||||
Generating your secret key...
|
|
||||||
</p>
|
|
||||||
<p className='text-sm text-muted-foreground'>
|
|
||||||
Creating your secure key
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className='space-y-3'>
|
|
||||||
<Key className='w-20 h-20 text-primary mx-auto' />
|
|
||||||
<div className='space-y-2'>
|
|
||||||
<p className='text-lg font-semibold'>
|
|
||||||
Ready to generate your secret key?
|
|
||||||
</p>
|
|
||||||
<p className='text-sm text-muted-foreground px-5'>
|
|
||||||
This key will be your password to access applications within the Nostr network.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!isLoading && (
|
<div className='flex justify-center'>
|
||||||
<Button
|
<div className='w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin'></div>
|
||||||
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
|
</div>
|
||||||
onClick={generateKey}
|
|
||||||
disabled={isLoading}
|
|
||||||
>
|
|
||||||
<Sparkles className='w-5 h-5 mr-2' />
|
|
||||||
Generate My Secret Key
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Download Step - Whimsical and magical */}
|
{/* Download Step */}
|
||||||
{step === 'download' && (
|
{step === 'download' && (
|
||||||
<div className='text-center space-y-4'>
|
<div className='text-center space-y-4'>
|
||||||
{/* Key reveal */}
|
<div className='space-y-2'>
|
||||||
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
|
<p className='text-lg font-semibold'>
|
||||||
{/* Sparkles */}
|
Your secret key has been generated!
|
||||||
<div className='absolute inset-0 pointer-events-none'>
|
</p>
|
||||||
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
|
<p className='text-sm text-muted-foreground'>
|
||||||
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
|
Please download and save your key securely.
|
||||||
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
|
</p>
|
||||||
<Sparkles className='absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '1.5s'}} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='relative z-10 flex justify-center items-center mb-3'>
|
|
||||||
<div className='relative'>
|
|
||||||
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg animate-pulse'>
|
|
||||||
<Key className='w-8 h-8 text-indigo-800' />
|
|
||||||
</div>
|
|
||||||
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
|
|
||||||
<Sparkles className='w-3 h-3 text-white' />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='relative z-10 space-y-2'>
|
|
||||||
<p className='text-base font-semibold'>
|
|
||||||
Your secret key has been generated!
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{/* Warning */}
|
|
||||||
<div className='relative mx-auto max-w-sm'>
|
|
||||||
<div className='p-3 bg-gradient-to-r from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-950/40 dark:via-yellow-950/20 dark:to-amber-950/40 rounded-lg border-2 border-amber-300 dark:border-amber-700 shadow-md'>
|
|
||||||
<div className='flex items-center gap-2 mb-1'>
|
|
||||||
<FileText className='w-3 h-3 text-amber-700' />
|
|
||||||
<span className='text-xs font-bold text-amber-800 dark:text-amber-200'>
|
|
||||||
Important Warning
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<p className='text-xs text-red-700 dark:text-amber-300 italic'>
|
|
||||||
This key is your primary and only means of accessing your account. Store it safely and securely.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Key vault */}
|
|
||||||
|
|
||||||
|
|
||||||
{/* Security options */}
|
|
||||||
<div className='space-y-3'>
|
<div className='space-y-3'>
|
||||||
|
<Card className={`cursor-pointer transition-all duration-200 ${
|
||||||
|
keySecured === 'downloaded'
|
||||||
<div className='grid grid-cols-1 gap-2'>
|
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
|
||||||
{/* Download Option */}
|
: 'hover:bg-primary/5 hover:border-primary/20'
|
||||||
<Card className={`cursor-pointer transition-all duration-200 ${
|
}`}>
|
||||||
keySecured === 'downloaded'
|
<CardContent className='p-3'>
|
||||||
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
|
<Button
|
||||||
: 'hover:bg-primary/5 hover:border-primary/20'
|
variant="ghost"
|
||||||
}`}>
|
className='w-full h-auto p-0 justify-start hover:bg-transparent'
|
||||||
<CardContent className='p-3'>
|
onClick={downloadKey}
|
||||||
<Button
|
>
|
||||||
variant="ghost"
|
<div className='flex items-center gap-3 w-full'>
|
||||||
className='w-full h-auto p-0 justify-start hover:bg-transparent'
|
<div className={`p-1.5 rounded-lg ${
|
||||||
onClick={downloadKey}
|
keySecured === 'downloaded'
|
||||||
>
|
? 'bg-green-100 dark:bg-green-900'
|
||||||
<div className='flex items-center gap-3 w-full'>
|
: 'bg-primary/10'
|
||||||
<div className={`p-1.5 rounded-lg ${
|
}`}>
|
||||||
keySecured === 'downloaded'
|
{keySecured === 'downloaded' ? (
|
||||||
? 'bg-green-100 dark:bg-green-900'
|
<CheckCircle className='w-4 h-4 text-green-600' />
|
||||||
: 'bg-primary/10'
|
) : (
|
||||||
}`}>
|
<Download className='w-4 h-4 text-primary' />
|
||||||
{keySecured === 'downloaded' ? (
|
)}
|
||||||
<CheckCircle className='w-4 h-4 text-green-600' />
|
|
||||||
) : (
|
|
||||||
<Download className='w-4 h-4 text-primary' />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className='flex-1 text-left'>
|
|
||||||
<div className='font-medium text-sm'>
|
|
||||||
Download as File
|
|
||||||
</div>
|
|
||||||
<div className='text-xs text-muted-foreground'>
|
|
||||||
Save as nostr-nsec-key.txt file
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{keySecured === 'downloaded' && (
|
|
||||||
<div className='text-xs font-medium text-green-600'>
|
|
||||||
✓ Downloaded
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</Button>
|
<div className='flex-1 text-left'>
|
||||||
</CardContent>
|
<div className='font-medium text-sm'>
|
||||||
</Card>
|
Download as File
|
||||||
|
</div>
|
||||||
|
<div className='text-xs text-muted-foreground'>
|
||||||
|
Save as nostr-nsec-key.txt file
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{keySecured === 'downloaded' && (
|
||||||
|
<div className='text-xs font-medium text-green-600'>
|
||||||
|
✓ Downloaded
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Continue button */}
|
|
||||||
<Button
|
<Button
|
||||||
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
|
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
|
||||||
keySecured === 'downloaded'
|
keySecured === 'downloaded'
|
||||||
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105'
|
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 hover:scale-105'
|
||||||
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'
|
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'
|
||||||
}`}
|
}`}
|
||||||
onClick={finishKeySetup}
|
onClick={finishKeySetup}
|
||||||
disabled={keySecured !== 'downloaded'}
|
disabled={keySecured !== 'downloaded'}
|
||||||
>
|
>
|
||||||
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
|
|
||||||
<span className="text-center leading-tight">
|
<span className="text-center leading-tight">
|
||||||
{keySecured === 'none' ? (
|
{keySecured === 'none' ? (
|
||||||
<>
|
'Please download your key first'
|
||||||
Please download your key first
|
|
||||||
</>
|
|
||||||
) : (
|
) : (
|
||||||
<>
|
'My Key is Safe - Continue'
|
||||||
<span className="hidden sm:inline">My Key is Safe - Continue</span>
|
|
||||||
<span className="sm:hidden">Key Secured - Continue</span>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
</Button>
|
</Button>
|
||||||
@@ -545,38 +398,16 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Profile Step - Optional profile setup */}
|
{/* Profile Setup Step */}
|
||||||
{step === 'profile' && (
|
{step === 'profile' && (
|
||||||
<div className='text-center space-y-4'>
|
<div className='text-center space-y-4'>
|
||||||
{/* Profile setup illustration */}
|
<div className='space-y-2'>
|
||||||
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
|
<p className='text-lg font-semibold'>
|
||||||
{/* Sparkles */}
|
Almost there! Let's set up your profile
|
||||||
<div className='absolute inset-0 pointer-events-none'>
|
</p>
|
||||||
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
|
<p className='text-sm text-muted-foreground'>
|
||||||
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
|
Your profile is your identity on Nostr.
|
||||||
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
|
</p>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='relative z-10 flex justify-center items-center mb-3'>
|
|
||||||
<div className='relative'>
|
|
||||||
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg'>
|
|
||||||
<User className='w-8 h-8 text-blue-800' />
|
|
||||||
</div>
|
|
||||||
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
|
|
||||||
<Sparkles className='w-3 h-3 text-white' />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='relative z-10 space-y-2'>
|
|
||||||
<p className='text-base font-semibold'>
|
|
||||||
Almost there! Let's set up your profile
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p className='text-sm text-muted-foreground'>
|
|
||||||
Your profile is your identity on Nostr.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Publishing status indicator */}
|
{/* Publishing status indicator */}
|
||||||
|
|||||||
@@ -1,615 +0,0 @@
|
|||||||
import { useState, useCallback } from 'react';
|
|
||||||
import { useNostr } from '@nostrify/react';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { nip19 } from 'nostr-tools';
|
|
||||||
|
|
||||||
// Your VAPID public key
|
|
||||||
const VAPID_PUBLIC_KEY = 'BIur4J9v796yU2ZUhaka6exwLAKUhAnDv0zJhrf_T1yuFs4jh4g8IaYygGAJ7u1KxZdu2Dwxh1ae5ob8yClHamc';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Push subscription configuration for Web Push API
|
|
||||||
*/
|
|
||||||
export interface PushSubscription {
|
|
||||||
endpoint: string;
|
|
||||||
p256dh_key: string;
|
|
||||||
auth_key: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Nostr event filter for push notifications
|
|
||||||
*/
|
|
||||||
export interface NotificationFilter {
|
|
||||||
kinds?: number[];
|
|
||||||
authors?: string[];
|
|
||||||
"#p"?: string[];
|
|
||||||
"#t"?: string[];
|
|
||||||
since?: number;
|
|
||||||
until?: number;
|
|
||||||
limit?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Notification content configuration
|
|
||||||
*/
|
|
||||||
export interface NotificationConfig {
|
|
||||||
title: string;
|
|
||||||
body: string;
|
|
||||||
icon?: string;
|
|
||||||
badge?: string;
|
|
||||||
data?: Record<string, unknown>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Complete subscription object for push notifications
|
|
||||||
*/
|
|
||||||
export interface PushNotificationSubscription {
|
|
||||||
subscription_id: string;
|
|
||||||
domain: string;
|
|
||||||
filter: NotificationFilter;
|
|
||||||
notification: NotificationConfig;
|
|
||||||
push_subscription: PushSubscription;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* RPC request structure for push notification server
|
|
||||||
*/
|
|
||||||
interface RPCRequest {
|
|
||||||
method: 'register_subscription' | 'update_subscription' | 'delete_subscription' | 'list_subscriptions' | 'get_subscription';
|
|
||||||
params: Record<string, unknown>;
|
|
||||||
request_id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook for managing push notifications via Nostr RPC
|
|
||||||
* Sends encrypted RPC events to a push notification worker
|
|
||||||
*/
|
|
||||||
export function usePush(workerPubkey?: string) {
|
|
||||||
const { nostr } = useNostr();
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { toast } = useToast();
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// Default worker pubkey - your actual push notification server
|
|
||||||
const defaultWorkerPubkey = workerPubkey || '7c3be2769c76eecd6c6e27276722dfae0d8ad201825253452153b90093c41654';
|
|
||||||
|
|
||||||
const clearError = useCallback(() => {
|
|
||||||
setError(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Send an encrypted RPC request to the push notification worker
|
|
||||||
*/
|
|
||||||
const sendRPCRequest = useCallback(async (
|
|
||||||
method: RPCRequest['method'],
|
|
||||||
params: Record<string, unknown>
|
|
||||||
): Promise<void> => {
|
|
||||||
if (!user?.signer) {
|
|
||||||
throw new Error('User must be logged in to manage push notifications');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!user.signer.nip44) {
|
|
||||||
throw new Error('Signer must support NIP-44 encryption for push notifications');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decode worker pubkey if it's in npub format
|
|
||||||
let workerHex = defaultWorkerPubkey;
|
|
||||||
if (defaultWorkerPubkey.startsWith('npub1')) {
|
|
||||||
const decoded = nip19.decode(defaultWorkerPubkey);
|
|
||||||
if (decoded.type !== 'npub') {
|
|
||||||
throw new Error('Invalid worker pubkey format');
|
|
||||||
}
|
|
||||||
workerHex = decoded.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestId = `req_${crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`;
|
|
||||||
|
|
||||||
const request: RPCRequest = {
|
|
||||||
method,
|
|
||||||
params,
|
|
||||||
request_id: requestId,
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Encrypt the request using NIP-44
|
|
||||||
const payload = JSON.stringify(request);
|
|
||||||
console.log('Encrypting RPC request payload:', payload);
|
|
||||||
|
|
||||||
const encryptedRequest = await user.signer.nip44.encrypt(workerHex, payload);
|
|
||||||
console.log('Encrypted request:', encryptedRequest);
|
|
||||||
|
|
||||||
// Create unsigned RPC event (kind 25742)
|
|
||||||
const unsignedEvent = {
|
|
||||||
kind: 25742,
|
|
||||||
content: encryptedRequest,
|
|
||||||
tags: [
|
|
||||||
['p', workerHex],
|
|
||||||
['rpc', requestId],
|
|
||||||
['method', method],
|
|
||||||
],
|
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
|
||||||
};
|
|
||||||
|
|
||||||
console.log('Signing RPC event:', unsignedEvent);
|
|
||||||
console.log('Target worker pubkey:', workerHex);
|
|
||||||
|
|
||||||
// Sign the event using the user's signer
|
|
||||||
const signedEvent = await user.signer.signEvent(unsignedEvent);
|
|
||||||
console.log('Signed RPC event:', signedEvent);
|
|
||||||
|
|
||||||
// Send the signed RPC event
|
|
||||||
const result = await nostr.event(signedEvent);
|
|
||||||
console.log('RPC event sent result:', result);
|
|
||||||
|
|
||||||
return;
|
|
||||||
} catch (err) {
|
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
|
|
||||||
console.error('RPC send error:', err);
|
|
||||||
throw new Error(`Failed to send push notification request: ${errorMessage}`);
|
|
||||||
}
|
|
||||||
}, [user, nostr, defaultWorkerPubkey]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register a new push notification subscription
|
|
||||||
*/
|
|
||||||
const registerSubscription = useCallback(async (
|
|
||||||
subscriptionId: string,
|
|
||||||
domain: string,
|
|
||||||
filter: NotificationFilter,
|
|
||||||
notification: NotificationConfig,
|
|
||||||
pushSubscription: PushSubscription
|
|
||||||
): Promise<void> => {
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sendRPCRequest('register_subscription', {
|
|
||||||
subscription_id: subscriptionId,
|
|
||||||
domain,
|
|
||||||
filter,
|
|
||||||
notification,
|
|
||||||
push_subscription: pushSubscription,
|
|
||||||
});
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Push notifications enabled',
|
|
||||||
description: 'You will now receive push notifications for this content.',
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to register subscription';
|
|
||||||
setError(errorMessage);
|
|
||||||
toast({
|
|
||||||
title: 'Failed to enable notifications',
|
|
||||||
description: errorMessage,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [sendRPCRequest, toast]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update an existing push notification subscription
|
|
||||||
*/
|
|
||||||
const updateSubscription = useCallback(async (
|
|
||||||
subscriptionId: string,
|
|
||||||
domain: string,
|
|
||||||
updates: Partial<Pick<PushNotificationSubscription, 'filter' | 'notification' | 'push_subscription'> & { is_active: boolean }>
|
|
||||||
): Promise<void> => {
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sendRPCRequest('update_subscription', {
|
|
||||||
subscription_id: subscriptionId,
|
|
||||||
domain,
|
|
||||||
updates,
|
|
||||||
});
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Subscription updated',
|
|
||||||
description: 'Your push notification settings have been updated.',
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to update subscription';
|
|
||||||
setError(errorMessage);
|
|
||||||
toast({
|
|
||||||
title: 'Failed to update notifications',
|
|
||||||
description: errorMessage,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [sendRPCRequest, toast]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Delete a push notification subscription
|
|
||||||
*/
|
|
||||||
const deleteSubscription = useCallback(async (
|
|
||||||
subscriptionId: string,
|
|
||||||
domain: string
|
|
||||||
): Promise<void> => {
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sendRPCRequest('delete_subscription', {
|
|
||||||
subscription_id: subscriptionId,
|
|
||||||
domain,
|
|
||||||
});
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Push notifications disabled',
|
|
||||||
description: 'You will no longer receive push notifications for this content.',
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to delete subscription';
|
|
||||||
setError(errorMessage);
|
|
||||||
toast({
|
|
||||||
title: 'Failed to disable notifications',
|
|
||||||
description: errorMessage,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [sendRPCRequest, toast]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* List all subscriptions for a domain
|
|
||||||
*/
|
|
||||||
const listSubscriptions = useCallback(async (domain: string): Promise<void> => {
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sendRPCRequest('list_subscriptions', { domain });
|
|
||||||
// Note: This is a fire-and-forget operation - the worker logs the results
|
|
||||||
// In a full implementation, you might want to listen for response events
|
|
||||||
} catch (err) {
|
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to list subscriptions';
|
|
||||||
setError(errorMessage);
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [sendRPCRequest]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a specific subscription
|
|
||||||
*/
|
|
||||||
const getSubscription = useCallback(async (subscriptionId: string): Promise<void> => {
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sendRPCRequest('get_subscription', { subscription_id: subscriptionId });
|
|
||||||
// Note: This is a fire-and-forget operation - the worker logs the results
|
|
||||||
// In a full implementation, you might want to listen for response events
|
|
||||||
} catch (err) {
|
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get subscription';
|
|
||||||
setError(errorMessage);
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [sendRPCRequest]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Request browser permission for push notifications
|
|
||||||
*/
|
|
||||||
const requestNotificationPermission = useCallback(async (): Promise<NotificationPermission> => {
|
|
||||||
if (!('Notification' in window)) {
|
|
||||||
throw new Error('This browser does not support push notifications');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Notification.permission === 'granted') {
|
|
||||||
return 'granted';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Notification.permission === 'denied') {
|
|
||||||
throw new Error('Push notifications are blocked. Please enable them in your browser settings.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const permission = await Notification.requestPermission();
|
|
||||||
if (permission !== 'granted') {
|
|
||||||
throw new Error('Push notification permission was denied');
|
|
||||||
}
|
|
||||||
|
|
||||||
return permission;
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert npub to hex format for use in filters
|
|
||||||
*/
|
|
||||||
const convertNpubToHex = useCallback((pubkey: string): string => {
|
|
||||||
if (pubkey.startsWith('npub1')) {
|
|
||||||
try {
|
|
||||||
const decoded = nip19.decode(pubkey);
|
|
||||||
if (decoded.type !== 'npub') {
|
|
||||||
throw new Error('Invalid npub format');
|
|
||||||
}
|
|
||||||
return decoded.data;
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Failed to decode npub: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// If it's already hex format, return as-is
|
|
||||||
return pubkey;
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert VAPID key from base64url string to Uint8Array (matches working implementation)
|
|
||||||
*/
|
|
||||||
const convertVapidKey = useCallback((key: string): Uint8Array => {
|
|
||||||
try {
|
|
||||||
// Add padding if needed
|
|
||||||
const padding = '='.repeat((4 - (key.length % 4)) % 4);
|
|
||||||
const base64 = (key + padding).replace(/-/g, '+').replace(/_/g, '/');
|
|
||||||
|
|
||||||
// Decode base64 to binary string
|
|
||||||
const rawData = window.atob(base64);
|
|
||||||
|
|
||||||
// Convert binary string to Uint8Array
|
|
||||||
const outputArray = new Uint8Array(rawData.length);
|
|
||||||
for (let i = 0; i < rawData.length; ++i) {
|
|
||||||
outputArray[i] = rawData.charCodeAt(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('VAPID key converted:', {
|
|
||||||
originalLength: key.length,
|
|
||||||
base64Length: base64.length,
|
|
||||||
outputLength: outputArray.length,
|
|
||||||
firstBytes: Array.from(outputArray.slice(0, 10))
|
|
||||||
});
|
|
||||||
|
|
||||||
return outputArray;
|
|
||||||
} catch (err) {
|
|
||||||
throw new Error(`Invalid VAPID key format: ${err instanceof Error ? err.message : String(err)}`);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Subscribe to browser push notifications and get subscription details
|
|
||||||
*/
|
|
||||||
const subscribeToPush = useCallback(async (vapidPublicKey: string = VAPID_PUBLIC_KEY): Promise<PushSubscription> => {
|
|
||||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
|
||||||
throw new Error('Push notifications are not supported in this browser');
|
|
||||||
}
|
|
||||||
|
|
||||||
await requestNotificationPermission();
|
|
||||||
|
|
||||||
// Register service worker and wait for it to be ready
|
|
||||||
const registration = await navigator.serviceWorker.ready;
|
|
||||||
console.log('Service worker ready:', registration);
|
|
||||||
console.log('Service worker scope:', registration.scope);
|
|
||||||
console.log('Service worker active:', !!registration.active);
|
|
||||||
|
|
||||||
// Check if already subscribed
|
|
||||||
const existingSubscription = await registration.pushManager.getSubscription();
|
|
||||||
console.log('Existing subscription:', existingSubscription);
|
|
||||||
|
|
||||||
// Convert VAPID key to proper format
|
|
||||||
console.log('VAPID public key (base64):', vapidPublicKey);
|
|
||||||
const applicationServerKey = convertVapidKey(vapidPublicKey);
|
|
||||||
console.log('VAPID key converted to Uint8Array, length:', applicationServerKey.length);
|
|
||||||
|
|
||||||
let subscription;
|
|
||||||
try {
|
|
||||||
console.log('Attempting to subscribe to push manager...');
|
|
||||||
|
|
||||||
// Subscribe to push notifications
|
|
||||||
subscription = await registration.pushManager.subscribe({
|
|
||||||
userVisibleOnly: true,
|
|
||||||
applicationServerKey,
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Push subscription successful:', subscription);
|
|
||||||
} catch (pushError: any) {
|
|
||||||
console.error('Push subscription failed with error:', pushError);
|
|
||||||
console.error('Error name:', pushError.name);
|
|
||||||
console.error('Error message:', pushError.message);
|
|
||||||
|
|
||||||
// Provide specific error messages based on error type
|
|
||||||
if (pushError.name === 'InvalidStateError') {
|
|
||||||
throw new Error('Push subscription failed: Invalid state (possibly already subscribed)');
|
|
||||||
} else if (pushError.name === 'NotAllowedError') {
|
|
||||||
throw new Error('Push subscription failed: Permission denied by user');
|
|
||||||
} else if (pushError.name === 'NotSupportedError') {
|
|
||||||
throw new Error('Push subscription failed: Push not supported by this browser/service');
|
|
||||||
} else if (pushError.name === 'AbortError') {
|
|
||||||
throw new Error('Push subscription failed: Request was aborted (VAPID key mismatch?)');
|
|
||||||
} else {
|
|
||||||
throw new Error(`Push subscription failed: ${pushError.name} - ${pushError.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract keys safely
|
|
||||||
const subscriptionJson = subscription.toJSON();
|
|
||||||
const keys = subscriptionJson.keys;
|
|
||||||
|
|
||||||
if (!keys?.p256dh || !keys?.auth) {
|
|
||||||
throw new Error('Invalid subscription keys received');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert to our format
|
|
||||||
return {
|
|
||||||
endpoint: subscription.endpoint,
|
|
||||||
p256dh_key: keys.p256dh,
|
|
||||||
auth_key: keys.auth,
|
|
||||||
};
|
|
||||||
}, [requestNotificationPermission, convertVapidKey]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper function to create a subscription for following an author
|
|
||||||
*/
|
|
||||||
const subscribeToAuthor = useCallback(async (
|
|
||||||
authorPubkey: string,
|
|
||||||
vapidPublicKey: string = VAPID_PUBLIC_KEY,
|
|
||||||
domain: string = window.location.hostname,
|
|
||||||
customNotification?: Partial<NotificationConfig>
|
|
||||||
): Promise<void> => {
|
|
||||||
const pushSubscription = await subscribeToPush(vapidPublicKey);
|
|
||||||
|
|
||||||
// Convert npub to hex format for the filter
|
|
||||||
const authorHex = convertNpubToHex(authorPubkey);
|
|
||||||
|
|
||||||
const subscriptionId = `follow-${authorHex.slice(0, 16)}-${Date.now()}`;
|
|
||||||
|
|
||||||
const filter: NotificationFilter = {
|
|
||||||
kinds: [1], // Text notes
|
|
||||||
authors: [authorHex], // Use hex format
|
|
||||||
limit: 50,
|
|
||||||
};
|
|
||||||
|
|
||||||
const notification: NotificationConfig = {
|
|
||||||
title: '{{author_name}} posted something!',
|
|
||||||
body: '{{content}}',
|
|
||||||
icon: '/icon-192x192.png',
|
|
||||||
badge: '/badge-72x72.png',
|
|
||||||
data: {
|
|
||||||
type: 'new_post',
|
|
||||||
author: authorHex, // Store hex format in data as well
|
|
||||||
},
|
|
||||||
...customNotification,
|
|
||||||
};
|
|
||||||
|
|
||||||
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
|
|
||||||
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper function to create a subscription for mentions
|
|
||||||
*/
|
|
||||||
const subscribeToMentions = useCallback(async (
|
|
||||||
userPubkey: string,
|
|
||||||
vapidPublicKey: string = VAPID_PUBLIC_KEY,
|
|
||||||
domain: string = window.location.hostname,
|
|
||||||
customNotification?: Partial<NotificationConfig>
|
|
||||||
): Promise<void> => {
|
|
||||||
const pushSubscription = await subscribeToPush(vapidPublicKey);
|
|
||||||
|
|
||||||
// Convert npub to hex format for the filter
|
|
||||||
const userHex = convertNpubToHex(userPubkey);
|
|
||||||
|
|
||||||
const subscriptionId = `mentions-${userHex.slice(0, 16)}-${Date.now()}`;
|
|
||||||
|
|
||||||
const filter: NotificationFilter = {
|
|
||||||
kinds: [1], // Text notes
|
|
||||||
"#p": [userHex], // Mentions of the user (use hex format)
|
|
||||||
limit: 50,
|
|
||||||
};
|
|
||||||
|
|
||||||
const notification: NotificationConfig = {
|
|
||||||
title: '{{author_name}} mentioned you!',
|
|
||||||
body: '{{content}}',
|
|
||||||
icon: '/icon-192x192.png',
|
|
||||||
badge: '/badge-72x72.png',
|
|
||||||
data: {
|
|
||||||
type: 'mention',
|
|
||||||
user: userHex, // Store hex format in data as well
|
|
||||||
},
|
|
||||||
...customNotification,
|
|
||||||
};
|
|
||||||
|
|
||||||
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
|
|
||||||
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper function to create a subscription for hashtags
|
|
||||||
*/
|
|
||||||
const subscribeToHashtag = useCallback(async (
|
|
||||||
hashtag: string,
|
|
||||||
vapidPublicKey: string = VAPID_PUBLIC_KEY,
|
|
||||||
domain: string = window.location.hostname,
|
|
||||||
customNotification?: Partial<NotificationConfig>
|
|
||||||
): Promise<void> => {
|
|
||||||
const pushSubscription = await subscribeToPush(vapidPublicKey);
|
|
||||||
|
|
||||||
const subscriptionId = `hashtag-${hashtag}-${Date.now()}`;
|
|
||||||
|
|
||||||
const filter: NotificationFilter = {
|
|
||||||
kinds: [1], // Text notes
|
|
||||||
"#t": [hashtag], // Posts with the hashtag
|
|
||||||
limit: 50,
|
|
||||||
};
|
|
||||||
|
|
||||||
const notification: NotificationConfig = {
|
|
||||||
title: `{{author_name}} posted about #${hashtag}`,
|
|
||||||
body: `{{content}}`,
|
|
||||||
icon: '/icon-192x192.png',
|
|
||||||
badge: '/badge-72x72.png',
|
|
||||||
data: {
|
|
||||||
type: 'hashtag',
|
|
||||||
hashtag,
|
|
||||||
},
|
|
||||||
...customNotification,
|
|
||||||
};
|
|
||||||
|
|
||||||
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
|
|
||||||
}, [subscribeToPush, registerSubscription]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
// Core RPC methods
|
|
||||||
registerSubscription,
|
|
||||||
updateSubscription,
|
|
||||||
deleteSubscription,
|
|
||||||
listSubscriptions,
|
|
||||||
getSubscription,
|
|
||||||
|
|
||||||
// Browser push notification helpers
|
|
||||||
requestNotificationPermission,
|
|
||||||
subscribeToPush,
|
|
||||||
|
|
||||||
// Convenience methods for common use cases
|
|
||||||
subscribeToAuthor,
|
|
||||||
subscribeToMentions,
|
|
||||||
subscribeToHashtag,
|
|
||||||
|
|
||||||
// State
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
clearError,
|
|
||||||
|
|
||||||
// Config
|
|
||||||
workerPubkey: defaultWorkerPubkey,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Example usage:
|
|
||||||
*
|
|
||||||
* ```tsx
|
|
||||||
* import { usePush } from '@/hooks/usePush';
|
|
||||||
*
|
|
||||||
* function MyComponent() {
|
|
||||||
* const {
|
|
||||||
* subscribeToAuthor,
|
|
||||||
* subscribeToMentions,
|
|
||||||
* isLoading,
|
|
||||||
* error
|
|
||||||
* } = usePush('npub1yourpushworkerpubkey');
|
|
||||||
*
|
|
||||||
* const handleFollowNotifications = async (authorPubkey: string) => {
|
|
||||||
* try {
|
|
||||||
* await subscribeToAuthor(authorPubkey, 'myapp.com');
|
|
||||||
* } catch (error) {
|
|
||||||
* console.error('Failed to enable notifications:', error);
|
|
||||||
* }
|
|
||||||
* };
|
|
||||||
*
|
|
||||||
* return (
|
|
||||||
* <Button
|
|
||||||
* onClick={() => handleFollowNotifications('npub1author...')}
|
|
||||||
* disabled={isLoading}
|
|
||||||
* >
|
|
||||||
* {isLoading ? 'Enabling...' : 'Enable Notifications'}
|
|
||||||
* </Button>
|
|
||||||
* );
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
Reference in new issue
Block a user