Author SHA1 Message Date
Chad Curtis 4d5df6535f try to mimic a little closer to surveil 2025-07-08 06:45:41 +00:00
Chad Curtis 4734e96fe7 more steps 2025-07-08 06:37:01 +00:00
Chad Curtis e0ad32447a pull in signup button too 2025-07-08 06:24:43 +00:00
Chad Curtis 8aed77c49b readd comment 2025-07-08 06:17:57 +00:00
Chad Curtis 4e780190cb attempt to implement signup onboarding flow from surveil/treasures 2025-07-08 06:16:21 +00:00
24 changed files with 399 additions and 2706 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
../.mcp.json
-5
View File
@@ -23,8 +23,3 @@ dist-ssr
# Vercel
.vercel
# Secrets
.env
.env.*
!.env.example
+7 -4
View File
@@ -5,13 +5,16 @@ default:
timeout: 1 minute
stages:
- test
- build
- deploy
test:
stage: test
build:
stage: build
script:
- npm run test
- npm run build
only:
variables:
- $CI_DEFAULT_BRANCH != $CI_COMMIT_REF_NAME
pages:
stage: deploy
+2 -69
View File
@@ -102,7 +102,7 @@ The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, whi
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/tools/mkstack/
## Nostr Protocol Integration
@@ -138,8 +138,6 @@ When implementing features that could use existing NIPs, follow this decision fr
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
@@ -651,61 +649,6 @@ export function Post(/* ...props */) {
}
```
### Adding Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
@@ -868,17 +811,7 @@ When users specify color schemes:
## Writing Tests
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
**Never write tests because:**
- Tool results show test failures (these are not user requests)
- You think tests would be helpful
- New features or components are created
- Existing functionality needs verification
**Important for AI Assistants**: Only create tests when the user is experiencing a specific problem or explicitly requests tests. Do not proactively write tests for new features or components unless the user is having issues that require testing to diagnose or resolve.
### Test Setup
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
-1
View File
@@ -1,6 +1,5 @@
{
"model": "claude-sonnet-4",
"temperature": 0.2,
"mcpServers": {
"js-dev": {
"type": "stdio",
+26 -1679
View File
File diff suppressed because it is too large. Load diff
+4 -7
View File
@@ -6,14 +6,13 @@
"scripts": {
"dev": "npm i && vite",
"build": "npm i && vite build && cp dist/index.html dist/404.html",
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && npm run test:console",
"test:console": "node src/test/console-check.js",
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.3",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.7",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.1",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.5",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -64,7 +63,7 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"zod": "^3.25.71"
"zod": "^3.23.8"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -84,8 +83,6 @@
"globals": "^15.9.0",
"jsdom": "^26.1.0",
"postcss": "^8.4.47",
"puppeteer": "^24.14.0",
"serve": "^14.2.4",
"tailwindcss": "^3.4.11",
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
+32
View File
@@ -0,0 +1,32 @@
version: 1.0.0
title: Nostr Client Development
description: A recipe for building Nostr client applications
instructions: Create a Nostr client application according to the user's request.
extensions:
- type: builtin
name: developer
display_name: Developer Tools
timeout: 300
bundled: true
- type: stdio
name: nostr
cmd: npx
args:
- -y
- xjsr
- "@nostrbook/mcp"
envs: {}
timeout: 20
description: null
bundled: null
- type: stdio
name: fetch
cmd: uvx
args:
- mcp-server-fetch
envs: {}
timeout: 20
description: null
bundled: null
author:
contact: Alex Gleason <[email protected]>
+1 -1
View File
@@ -32,7 +32,7 @@ const queryClient = new QueryClient({
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.primal.net",
relayUrl: "wss://relay.nostr.band",
};
const presetRelays = [
+1 -18
View File
@@ -1,5 +1,4 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
@@ -13,12 +12,6 @@ interface AppProviderProps {
presetRelays?: { name: string; url: string }[];
}
// Zod schema for AppConfig validation
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
});
export function AppProvider(props: AppProviderProps) {
const {
children,
@@ -28,17 +21,7 @@ export function AppProvider(props: AppProviderProps) {
} = props;
// App configuration state with localStorage persistence
const [config, setConfig] = useLocalStorage<AppConfig>(
storageKey,
defaultConfig,
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.parse(parsed);
}
}
);
const [config, setConfig] = useLocalStorage<AppConfig>(storageKey, defaultConfig);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
+1 -1
View File
@@ -28,7 +28,7 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
}
return (
<DropdownMenu modal={false}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
<Avatar className='w-10 h-10'>
+4 -10
View File
@@ -5,7 +5,7 @@ import { useState } from 'react';
import { User } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
@@ -17,11 +17,9 @@ 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);
};
return (
@@ -39,16 +37,12 @@ export function LoginArea({ className }: LoginAreaProps) {
)}
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
/>
</div>
);
}
+108 -130
View File
@@ -1,7 +1,4 @@
// 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 } from 'react';
import React, { useRef, useState, useEffect } from 'react';
import { Shield, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import { Input } from '@/components/ui/input.tsx';
@@ -14,20 +11,32 @@ import {
} from '@/components/ui/dialog.tsx';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useToast } from '@/hooks/useToast';
import SignupFlow from './SignupFlow';
interface LoginDialogProps {
isOpen: boolean;
onClose: () => void;
onLogin: () => void;
onSignup?: () => void;
}
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [view, setView] = useState<'login' | 'signup'>('login');
const fileInputRef = useRef<HTMLInputElement>(null);
const login = useLoginActions();
const { toast } = useToast();
useEffect(() => {
if (isOpen) {
setView('login');
setIsLoading(false);
setNsec('');
setBunkerUri('');
}
}, [isOpen]);
const handleExtensionLogin = () => {
setIsLoading(true);
@@ -40,6 +49,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
onClose();
} catch (error) {
console.error('Extension login failed:', error);
toast({ title: 'Login Failed', description: (error as Error).message, variant: 'destructive' });
} finally {
setIsLoading(false);
}
@@ -48,13 +58,13 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const handleKeyLogin = () => {
if (!nsec.trim()) return;
setIsLoading(true);
try {
login.nsec(nsec);
onLogin();
onClose();
} catch (error) {
console.error('Nsec login failed:', error);
toast({ title: 'Login Failed', description: 'Invalid nsec key.', variant: 'destructive' });
} finally {
setIsLoading(false);
}
@@ -63,13 +73,13 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const handleBunkerLogin = () => {
if (!bunkerUri.trim() || !bunkerUri.startsWith('bunker://')) return;
setIsLoading(true);
try {
login.bunker(bunkerUri);
onLogin();
onClose();
} catch (error) {
console.error('Bunker login failed:', error);
toast({ title: 'Bunker Login Failed', description: 'Could not connect to bunker.', variant: 'destructive' });
} finally {
setIsLoading(false);
}
@@ -78,7 +88,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
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;
@@ -87,131 +96,100 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
const renderLoginView = () => (
<>
<DialogHeader className='px-6 pt-6 pb-0 relative'>
<DialogTitle className='text-xl font-semibold text-center'>Log in</DialogTitle>
<DialogDescription className='text-center text-muted-foreground mt-2'>
Access your account securely with your preferred method
</DialogDescription>
</DialogHeader>
<div className='px-6 py-8 space-y-6'>
<div className='text-center'>
<p className='text-sm text-muted-foreground'>New to Nostr?</p>
<Button variant='link' className='text-primary' onClick={() => setView('signup')}>
Create an account
</Button>
</div>
<div className='relative'>
<div className='absolute inset-0 flex items-center' aria-hidden='true'>
<div className='w-full border-t border-border' />
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-2 bg-background text-muted-foreground'>Or log in with</span>
</div>
</div>
<Tabs defaultValue={'nostr' in window ? 'extension' : 'key'} className='w-full'>
<TabsList className='grid grid-cols-3 mb-6'>
<TabsTrigger value='extension'>Extension</TabsTrigger>
<TabsTrigger value='key'>Nsec</TabsTrigger>
<TabsTrigger value='bunker'>Bunker</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-4'>
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<Button className='w-full rounded-full py-6' onClick={handleExtensionLogin} disabled={isLoading}>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Enter your nsec
</label>
<Input id='nsec' value={nsec} onChange={(e) => setNsec(e.target.value)} className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary' placeholder='nsec1...' />
</div>
<div className='text-center'>
<p className='text-sm mb-2 text-gray-600 dark:text-gray-400'>Or upload a key file</p>
<input type='file' accept='.txt' className='hidden' ref={fileInputRef} onChange={handleFileUpload} />
<Button variant='outline' className='w-full dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700' onClick={() => fileInputRef.current?.click()}>
<Upload className='w-4 h-4 mr-2' />
Upload Nsec File
</Button>
</div>
<Button className='w-full rounded-full py-6 mt-4' onClick={handleKeyLogin} disabled={isLoading || !nsec.trim()}>
{isLoading ? 'Verifying...' : 'Login with Nsec'}
</Button>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
</label>
<Input id='bunkerUri' value={bunkerUri} onChange={(e) => setBunkerUri(e.target.value)} className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary' placeholder='bunker://' />
{bunkerUri && !bunkerUri.startsWith('bunker://') && (<p className='text-red-500 text-xs'>URI must start with bunker://</p>)}
</div>
<Button className='w-full rounded-full py-6' onClick={handleBunkerLogin} disabled={isLoading || !bunkerUri.trim() || !bunkerUri.startsWith('bunker://')}>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</TabsContent>
</Tabs>
</div>
</>
);
const renderSignupView = () => (
<>
<DialogHeader>
<DialogTitle>Create Account</DialogTitle>
<DialogDescription>Create a new Nostr account.</DialogDescription>
</DialogHeader>
<div className='px-6 py-8'>
<SignupFlow onBack={() => setView('login')} onClose={onClose} />
</div>
</>
);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
<DialogHeader className='px-6 pt-6 pb-0 relative'>
<DialogTitle className='text-xl font-semibold text-center'>Log in</DialogTitle>
<DialogDescription className='text-center text-muted-foreground mt-2'>
Access your account securely with your preferred method
</DialogDescription>
</DialogHeader>
<div className='px-6 py-8 space-y-6'>
<Tabs defaultValue={'nostr' in window ? 'extension' : 'key'} className='w-full'>
<TabsList className='grid grid-cols-3 mb-6'>
<TabsTrigger value='extension'>Extension</TabsTrigger>
<TabsTrigger value='key'>Nsec</TabsTrigger>
<TabsTrigger value='bunker'>Bunker</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-4'>
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<Button
className='w-full rounded-full py-6'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Enter your nsec
</label>
<Input
type='password'
id='nsec'
value={nsec}
onChange={(e) => setNsec(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
placeholder='nsec1...'
/>
</div>
<div className='text-center'>
<p className='text-sm mb-2 text-gray-600 dark:text-gray-400'>Or upload a key file</p>
<input
type='file'
accept='.txt'
className='hidden'
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant='outline'
className='w-full dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700'
onClick={() => fileInputRef.current?.click()}
>
<Upload className='w-4 h-4 mr-2' />
Upload Nsec File
</Button>
</div>
<Button
className='w-full rounded-full py-6 mt-4'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Login with Nsec'}
</Button>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
</label>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
placeholder='bunker://'
/>
{bunkerUri && !bunkerUri.startsWith('bunker://') && (
<p className='text-red-500 text-xs'>URI must start with bunker://</p>
)}
</div>
<Button
className='w-full rounded-full py-6'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim() || !bunkerUri.startsWith('bunker://')}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</TabsContent>
</Tabs>
<div className='text-center text-sm'>
<p className='text-gray-600 dark:text-gray-400'>
Don't have an account?{' '}
<button
onClick={handleSignupClick}
className='text-primary hover:underline font-medium'
>
Sign up
</button>
</p>
</div>
</div>
{view === 'login' ? renderLoginView() : renderSignupView()}
</DialogContent>
</Dialog>
);
-167
View File
@@ -1,167 +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 } from 'react';
import { Download, Key } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { toast } from '@/hooks/useToast.ts';
import { useLoginActions } from '@/hooks/useLoginActions';
import { generateSecretKey, nip19 } from 'nostr-tools';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'done'>('generate');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const login = useLoginActions();
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
setIsLoading(true);
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
} catch (error) {
console.error('Failed to generate key:', error);
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const downloadKey = () => {
// Create a blob with the key text
const blob = new Blob([nsec], { type: 'text/plain' });
const url = globalThis.URL.createObjectURL(blob);
// Create a temporary link element and trigger download
const a = document.createElement('a');
a.href = url;
a.download = 'nsec.txt';
document.body.appendChild(a);
a.click();
// Clean up
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
toast({
title: 'Key downloaded',
description: 'Your key has been downloaded. Keep it safe!',
});
};
const finishSignup = () => {
login.nsec(nsec);
setStep('done');
onClose();
toast({
title: 'Account created',
description: 'You are now logged in.',
});
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
<DialogHeader className='px-6 pt-6 pb-0 relative'>
<DialogTitle className='text-xl font-semibold text-center'>
{step === 'generate' && 'Create Your Account'}
{step === 'download' && 'Download Your Key'}
{step === 'done' && 'Setting Up Your Account'}
</DialogTitle>
<DialogDescription className='text-center text-muted-foreground mt-2'>
{step === 'generate' && 'Generate a secure key for your account'}
{step === 'download' && "Keep your key safe - you'll need it to log in"}
{step === 'done' && 'Finalizing your account setup'}
</DialogDescription>
</DialogHeader>
<div className='px-6 py-8 space-y-6'>
{step === 'generate' && (
<div className='text-center space-y-6'>
<div className='p-4 rounded-lg bg-gray-50 dark:bg-gray-800 flex items-center justify-center'>
<Key className='w-16 h-16 text-primary' />
</div>
<p className='text-sm text-gray-600 dark:text-gray-300'>
We'll generate a secure key for your account. You'll need this key to log in later.
</p>
<Button
className='w-full rounded-full py-6'
onClick={generateKey}
disabled={isLoading}
>
{isLoading ? 'Generating key...' : 'Generate my key'}
</Button>
</div>
)}
{step === 'download' && (
<div className='space-y-6'>
<div className='p-4 rounded-lg border bg-gray-50 dark:bg-gray-800 overflow-auto'>
<code className='text-xs break-all'>{nsec}</code>
</div>
<div className='text-sm text-gray-600 dark:text-gray-300 space-y-2'>
<p className='font-medium text-red-500'>Important:</p>
<ul className='list-disc pl-5 space-y-1'>
<li>This is your only way to access your account</li>
<li>Store it somewhere safe</li>
<li>Never share this key with anyone</li>
</ul>
</div>
<div className='flex flex-col space-y-3'>
<Button
variant='outline'
className='w-full'
onClick={downloadKey}
>
<Download className='w-4 h-4 mr-2' />
Download Key
</Button>
<Button
className='w-full rounded-full py-6'
onClick={finishSignup}
>
I've saved my key, continue
</Button>
</div>
</div>
)}
{step === 'done' && (
<div className='flex justify-center items-center py-8'>
<div className='animate-spin rounded-full h-12 w-12 border-b-2 border-primary'></div>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
};
export default SignupDialog;
+212
View File
@@ -0,0 +1,212 @@
import React, { useState, useEffect } from 'react';
import { Download, KeyRound, Lock, CheckCircle, Copy, ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { useToast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { generateSecretKey, nip19 } from 'nostr-tools';
interface SignupFlowProps {
onBack: () => void;
onClose: () => void;
}
const SignupFlow: React.FC<SignupFlowProps> = ({ onBack, onClose }) => {
const [signupStep, setSignupStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [keySecured, setKeySecured] = useState<'none' | 'copied' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({ name: '', about: '' });
const { toast } = useToast();
const login = useLoginActions();
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
useEffect(() => {
setSignupStep('welcome');
setIsLoading(false);
setNsec('');
setKeySecured('none');
setProfileData({ name: '', about: '' });
}, []);
const generateKey = () => {
setIsLoading(true);
setTimeout(() => {
try {
const sk = generateSecretKey();
setNsec(nip19.nsecEncode(sk));
setSignupStep('download');
toast({ title: 'New key generated', description: 'Keep it safe.' });
} catch {
toast({ title: 'Error', description: 'Failed to generate key. Please try again.', variant: 'destructive' });
} finally {
setIsLoading(false);
}
}, 1000);
};
const downloadKey = () => {
try {
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const filename = 'secret-key.txt';
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);
setKeySecured('downloaded');
toast({ title: 'Key Secured', description: 'Your key has been safely stored.' });
} catch {
toast({ title: 'Download failed', description: 'Could not download the key file. Please copy it manually.', variant: 'destructive' });
}
};
const copyKey = () => {
navigator.clipboard.writeText(nsec);
setKeySecured('copied');
toast({ title: 'Copied to clipboard', description: 'Your key has been copied.' });
};
const finishKeySetup = () => {
try {
login.nsec(nsec);
setSignupStep('profile');
} catch {
toast({ title: 'Login Failed', description: 'Failed to login with the generated key. Please try again.', variant: 'destructive' });
}
};
const finishSignup = async (skipProfile = false) => {
try {
if (!skipProfile && (profileData.name || profileData.about)) {
const metadata: Record<string, string> = {};
if (profileData.name) metadata.name = profileData.name;
if (profileData.about) metadata.about = profileData.about;
await publishEvent({ kind: 0, content: JSON.stringify(metadata) });
toast({ title: 'Profile Created', description: 'Your profile has been created.' });
}
setSignupStep('done');
setTimeout(() => {
onClose();
toast({ title: 'Welcome!', description: 'You are now logged in.' });
}, 2000);
} catch {
toast({ title: 'Profile Setup Failed', description: 'Your account was created but profile setup failed. You can update it later.', variant: 'destructive' });
setSignupStep('done');
setTimeout(() => {
onClose();
toast({ title: 'Welcome!', description: 'You are now logged in.' });
}, 2000);
}
};
return (
<div className='space-y-4'>
{signupStep === 'welcome' && (
<div className='text-center space-y-4'>
<div className='flex justify-center items-center h-24'>
<KeyRound className='w-16 h-16 text-primary' />
</div>
<p>Your key is your identity. It's how you log in and how others see you.</p>
<Button className='w-full' onClick={() => setSignupStep('generate')}>
<ArrowRight className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
)}
{signupStep === 'generate' && (
<div className='text-center space-y-4'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative flex justify-center items-center h-24'>
<KeyRound className='w-20 h-20 mx-auto animate-pulse text-primary' />
</div>
<p className='text-lg font-semibold'>Generating your key...</p>
</div>
) : (
<div className='space-y-3'>
<div className='flex justify-center items-center h-24'>
<KeyRound className='w-16 h-16 mx-auto text-primary' />
</div>
<p className='text-lg font-semibold'>Ready to generate your key?</p>
</div>
)}
{!isLoading && (<Button className='w-full' onClick={generateKey} disabled={isLoading}>Generate My Key</Button>)}
</div>
)}
{signupStep === 'download' && (
<div className='space-y-4'>
<div className='relative p-3 bg-muted rounded-xl border'>
<div className='flex items-center gap-2 mb-2'><Lock className='w-4 h-4' /><span className='text-sm font-medium'>Your Secret Key</span></div>
<div className='p-2 bg-background rounded-lg border'><code className='text-xs break-all font-mono'>{nsec}</code></div>
</div>
<div className='space-y-3'>
<p className='text-sm font-medium text-center'>Choose how to secure your key:</p>
<div className='grid grid-cols-1 gap-2'>
<Card className={`cursor-pointer transition-all duration-200 ${keySecured === 'copied' ? 'ring-2 ring-primary' : 'hover:bg-muted'}`}>
<CardContent className='p-3'>
<Button variant="ghost" className='w-full h-auto p-0 justify-start' onClick={copyKey}>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${keySecured === 'copied' ? 'bg-primary/20' : 'bg-muted'}`}>
{keySecured === 'copied' ? (<CheckCircle className='w-4 h-4 text-primary' />) : (<Copy className='w-4 h-4' />)}
</div>
<div className='flex-1 text-left'><div className='font-medium text-sm'>Copy to Clipboard</div></div>
{keySecured === 'copied' && (<div className='text-xs font-medium text-primary'>✓ Copied</div>)}
</div>
</Button>
</CardContent>
</Card>
<Card className={`cursor-pointer transition-all duration-200 ${keySecured === 'downloaded' ? 'ring-2 ring-primary' : 'hover:bg-muted'}`}>
<CardContent className='p-3'>
<Button variant="ghost" className='w-full h-auto p-0 justify-start' onClick={downloadKey}>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${keySecured === 'downloaded' ? 'bg-primary/20' : 'bg-muted'}`}>
{keySecured === 'downloaded' ? (<CheckCircle className='w-4 h-4 text-primary' />) : (<Download className='w-4 h-4' />)}
</div>
<div className='flex-1 text-left'><div className='font-medium text-sm'>Download as File</div></div>
{keySecured === 'downloaded' && (<div className='text-xs font-medium text-primary'>✓ Downloaded</div>)}
</div>
</Button>
</CardContent>
</Card>
</div>
<Button className='w-full' onClick={finishKeySetup} disabled={keySecured === 'none'}><Lock className='w-4 h-4 mr-2' />Continue</Button>
</div>
</div>
)}
{signupStep === 'profile' && (
<div className='space-y-4'>
<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...' rows={3} disabled={isPublishing} />
</div>
</div>
<div className='space-y-3'>
<Button className='w-full' onClick={() => finishSignup(false)} disabled={isPublishing}>{isPublishing ? 'Creating Profile...' : 'Create Profile & Finish'}</Button>
<Button variant='outline' className='w-full' onClick={() => finishSignup(true)} disabled={isPublishing}>Skip for now</Button>
</div>
</div>
)}
{signupStep === 'done' && (
<div className='flex justify-center items-center py-8'>
<div className='animate-spin rounded-full h-12 w-12 border-b-2 border-primary'></div>
</div>
)}
<Button variant='link' onClick={onBack}>Back to login</Button>
</div>
);
};
export default SignupFlow;
-153
View File
@@ -1,153 +0,0 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { useComments } from '@/hooks/useComments';
import { CommentForm } from './CommentForm';
import { NoteContent } from '@/components/NoteContent';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { genUserName } from '@/lib/genUserName';
interface CommentProps {
root: NostrEvent | URL;
comment: NostrEvent;
depth?: number;
maxDepth?: number;
limit?: number;
}
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
const [showReplyForm, setShowReplyForm] = useState(false);
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
const author = useAuthor(comment.pubkey);
const { data: commentsData } = useComments(root, limit);
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(comment.pubkey)
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
// Get direct replies to this comment
const replies = commentsData?.getDirectReplies(comment.id) || [];
const hasReplies = replies.length > 0;
return (
<div className={`space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`}>
<Card className="bg-card/50">
<CardContent className="p-4">
<div className="space-y-3">
{/* Comment Header */}
<div className="flex items-start justify-between">
<div className="flex items-center space-x-3">
<Link to={`/${nip19.npubEncode(comment.pubkey)}`}>
<Avatar className="h-8 w-8 hover:ring-2 hover:ring-primary/30 transition-all cursor-pointer">
<AvatarImage src={metadata?.picture} />
<AvatarFallback className="text-xs">
{displayName.charAt(0)}
</AvatarFallback>
</Avatar>
</Link>
<div>
<Link
to={`/${nip19.npubEncode(comment.pubkey)}`}
className="font-medium text-sm hover:text-primary transition-colors"
>
{displayName}
</Link>
<p className="text-xs text-muted-foreground">{timeAgo}</p>
</div>
</div>
</div>
{/* Comment Content */}
<div className="text-sm">
<NoteContent event={comment} className="text-sm" />
</div>
{/* Comment Actions */}
<div className="flex items-center justify-between pt-2">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => setShowReplyForm(!showReplyForm)}
className="h-8 px-2 text-xs"
>
<MessageSquare className="h-3 w-3 mr-1" />
Reply
</Button>
{hasReplies && (
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 px-2 text-xs">
{showReplies ? (
<ChevronDown className="h-3 w-3 mr-1" />
) : (
<ChevronRight className="h-3 w-3 mr-1" />
)}
{replies.length} {replies.length === 1 ? 'reply' : 'replies'}
</Button>
</CollapsibleTrigger>
</Collapsible>
)}
</div>
{/* Comment menu */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-xs"
aria-label="Comment options"
>
<MoreHorizontal className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
</DropdownMenu>
</div>
</div>
</CardContent>
</Card>
{/* Reply Form */}
{showReplyForm && (
<div className="ml-6">
<CommentForm
root={root}
reply={comment}
onSuccess={() => setShowReplyForm(false)}
placeholder="Write a reply..."
compact
/>
</div>
)}
{/* Replies */}
{hasReplies && (
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
<CollapsibleContent className="space-y-3">
{replies.map((reply) => (
<Comment
key={reply.id}
root={root}
comment={reply}
depth={depth + 1}
maxDepth={maxDepth}
limit={limit}
/>
))}
</CollapsibleContent>
</Collapsible>
)}
</div>
);
}
-90
View File
@@ -1,90 +0,0 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { usePostComment } from '@/hooks/usePostComment';
import { LoginArea } from '@/components/auth/LoginArea';
import { NostrEvent } from '@nostrify/nostrify';
import { MessageSquare, Send } from 'lucide-react';
interface CommentFormProps {
root: NostrEvent | URL;
reply?: NostrEvent | URL;
onSuccess?: () => void;
placeholder?: string;
compact?: boolean;
}
export function CommentForm({
root,
reply,
onSuccess,
placeholder = "Write a comment...",
compact = false
}: CommentFormProps) {
const [content, setContent] = useState('');
const { user } = useCurrentUser();
const { mutate: postComment, isPending } = usePostComment();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim() || !user) return;
postComment(
{ content: content.trim(), root, reply },
{
onSuccess: () => {
setContent('');
onSuccess?.();
},
}
);
};
if (!user) {
return (
<Card className={compact ? "border-dashed" : ""}>
<CardContent className={compact ? "p-4" : "p-6"}>
<div className="text-center space-y-4">
<div className="flex items-center justify-center space-x-2 text-muted-foreground">
<MessageSquare className="h-5 w-5" />
<span>Sign in to {reply ? 'reply' : 'comment'}</span>
</div>
<LoginArea />
</div>
</CardContent>
</Card>
);
}
return (
<Card className={compact ? "border-dashed" : ""}>
<CardContent className={compact ? "p-4" : "p-6"}>
<form onSubmit={handleSubmit} className="space-y-4">
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={placeholder}
className={compact ? "min-h-[80px]" : "min-h-[100px]"}
disabled={isPending}
/>
<div className="flex justify-between items-center">
<span className="text-sm text-muted-foreground">
{reply ? 'Replying to comment' : 'Adding to the discussion'}
</span>
<Button
type="submit"
disabled={!content.trim() || isPending}
size={compact ? "sm" : "default"}
>
<Send className="h-4 w-4 mr-2" />
{isPending ? 'Posting...' : (reply ? 'Reply' : 'Comment')}
</Button>
</div>
</form>
</CardContent>
</Card>
);
}
-100
View File
@@ -1,100 +0,0 @@
import { useComments } from '@/hooks/useComments';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { NostrEvent } from '@nostrify/nostrify';
import { CommentForm } from './CommentForm';
import { Comment } from './Comment';
interface CommentsSectionProps {
root: NostrEvent | URL;
title?: string;
emptyStateMessage?: string;
emptyStateSubtitle?: string;
className?: string;
limit?: number;
}
export function CommentsSection({
root,
title = "Comments",
emptyStateMessage = "No comments yet",
emptyStateSubtitle = "Be the first to share your thoughts!",
className,
limit = 500,
}: CommentsSectionProps) {
const { data: commentsData, isLoading, error } = useComments(root, limit);
const comments = commentsData?.topLevelComments || [];
if (error) {
return (
<Card className="rounded-none sm:rounded-lg mx-0 sm:mx-0">
<CardContent className="px-2 py-6 sm:p-6">
<div className="text-center text-muted-foreground">
<MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p>Failed to load comments</p>
</div>
</CardContent>
</Card>
);
}
return (
<Card className={cn("rounded-none sm:rounded-lg mx-0 sm:mx-0", className)}>
<CardHeader className="px-2 pt-6 pb-4 sm:p-6">
<CardTitle className="flex items-center space-x-2">
<MessageSquare className="h-5 w-5" />
<span>{title}</span>
{!isLoading && (
<span className="text-sm font-normal text-muted-foreground">
({comments.length})
</span>
)}
</CardTitle>
</CardHeader>
<CardContent className="px-2 pb-6 pt-4 sm:p-6 sm:pt-0 space-y-6">
{/* Comment Form */}
<CommentForm root={root} />
{/* Comments List */}
{isLoading ? (
<div className="space-y-4">
{[...Array(3)].map((_, i) => (
<Card key={i} className="bg-card/50">
<CardContent className="p-4">
<div className="space-y-3">
<div className="flex items-center space-x-3">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
<Skeleton className="h-16 w-full" />
</div>
</CardContent>
</Card>
))}
</div>
) : comments.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-30" />
<p className="text-lg font-medium mb-2">{emptyStateMessage}</p>
<p className="text-sm">{emptyStateSubtitle}</p>
</div>
) : (
<div className="space-y-4">
{comments.map((comment) => (
<Comment
key={comment.id}
root={root}
comment={comment}
/>
))}
</div>
)}
</CardContent>
</Card>
);
}
+1 -1
View File
@@ -24,7 +24,7 @@ const AvatarImage = React.forwardRef<
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full object-cover", className)}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
-98
View File
@@ -1,98 +0,0 @@
import { NKinds, NostrEvent, NostrFilter } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
export function useComments(root: NostrEvent | URL, limit?: number) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
queryFn: async (c) => {
const filter: NostrFilter = { kinds: [1111] };
if (root instanceof URL) {
filter['#I'] = [root.toString()];
} else if (NKinds.addressable(root.kind)) {
const d = root.tags.find(([name]) => name === 'd')?.[1] ?? '';
filter['#A'] = [`${root.kind}:${root.pubkey}:${d}`];
} else if (NKinds.replaceable(root.kind)) {
filter['#A'] = [`${root.kind}:${root.pubkey}:`];
} else {
filter['#E'] = [root.id];
}
if (typeof limit === 'number') {
filter.limit = limit;
}
// Query for all kind 1111 comments that reference this addressable event regardless of depth
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const events = await nostr.query([filter], { signal });
// Helper function to get tag value
const getTagValue = (event: NostrEvent, tagName: string): string | undefined => {
const tag = event.tags.find(([name]) => name === tagName);
return tag?.[1];
};
// Filter top-level comments (those with lowercase tag matching the root)
const topLevelComments = events.filter(comment => {
if (root instanceof URL) {
return getTagValue(comment, 'i') === root.toString();
} else if (NKinds.addressable(root.kind)) {
const d = getTagValue(root, 'd') ?? '';
return getTagValue(comment, 'a') === `${root.kind}:${root.pubkey}:${d}`;
} else if (NKinds.replaceable(root.kind)) {
return getTagValue(comment, 'a') === `${root.kind}:${root.pubkey}:`;
} else {
return getTagValue(comment, 'e') === root.id;
}
});
// Helper function to get all descendants of a comment
const getDescendants = (parentId: string): NostrEvent[] => {
const directReplies = events.filter(comment => {
const eTag = getTagValue(comment, 'e');
return eTag === parentId;
});
const allDescendants = [...directReplies];
// Recursively get descendants of each direct reply
for (const reply of directReplies) {
allDescendants.push(...getDescendants(reply.id));
}
return allDescendants;
};
// Create a map of comment ID to its descendants
const commentDescendants = new Map<string, NostrEvent[]>();
for (const comment of events) {
commentDescendants.set(comment.id, getDescendants(comment.id));
}
// Sort top-level comments by creation time (newest first)
const sortedTopLevel = topLevelComments.sort((a, b) => b.created_at - a.created_at);
return {
allComments: events,
topLevelComments: sortedTopLevel,
getDescendants: (commentId: string) => {
const descendants = commentDescendants.get(commentId) || [];
// Sort descendants by creation time (oldest first for threaded display)
return descendants.sort((a, b) => a.created_at - b.created_at);
},
getDirectReplies: (commentId: string) => {
const directReplies = events.filter(comment => {
const eTag = getTagValue(comment, 'e');
return eTag === commentId;
});
// Sort direct replies by creation time (oldest first for threaded display)
return directReplies.sort((a, b) => a.created_at - b.created_at);
}
};
},
enabled: !!root,
});
}
-92
View File
@@ -1,92 +0,0 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { NKinds, type NostrEvent } from '@nostrify/nostrify';
interface PostCommentParams {
root: NostrEvent | URL; // The root event to comment on
reply?: NostrEvent | URL; // Optional reply to another comment
content: string;
}
/** Post a NIP-22 (kind 1111) comment on an event. */
export function usePostComment() {
const { mutateAsync: publishEvent } = useNostrPublish();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ root, reply, content }: PostCommentParams) => {
const tags: string[][] = [];
// d-tag identifiers
const dRoot = root instanceof URL ? '' : root.tags.find(([name]) => name === 'd')?.[1] ?? '';
const dReply = reply instanceof URL ? '' : reply?.tags.find(([name]) => name === 'd')?.[1] ?? '';
// Root event tags
if (root instanceof URL) {
tags.push(['I', root.toString()]);
} else if (NKinds.addressable(root.kind)) {
tags.push(['A', `${root.kind}:${root.pubkey}:${dRoot}`]);
} else if (NKinds.replaceable(root.kind)) {
tags.push(['A', `${root.kind}:${root.pubkey}:`]);
} else {
tags.push(['E', root.id]);
}
if (root instanceof URL) {
tags.push(['K', root.hostname]);
} else {
tags.push(['K', root.kind.toString()]);
tags.push(['P', root.pubkey]);
}
// Reply event tags
if (reply) {
if (reply instanceof URL) {
tags.push(['i', reply.toString()]);
} else if (NKinds.addressable(reply.kind)) {
tags.push(['a', `${reply.kind}:${reply.pubkey}:${dReply}`]);
} else if (NKinds.replaceable(reply.kind)) {
tags.push(['a', `${reply.kind}:${reply.pubkey}:`]);
} else {
tags.push(['e', reply.id]);
}
if (reply instanceof URL) {
tags.push(['k', reply.hostname]);
} else {
tags.push(['k', reply.kind.toString()]);
tags.push(['p', reply.pubkey]);
}
} else {
// If this is a top-level comment, use the root event's tags
if (root instanceof URL) {
tags.push(['i', root.toString()]);
} else if (NKinds.addressable(root.kind)) {
tags.push(['a', `${root.kind}:${root.pubkey}:${dRoot}`]);
} else if (NKinds.replaceable(root.kind)) {
tags.push(['a', `${root.kind}:${root.pubkey}:`]);
} else {
tags.push(['e', root.id]);
}
if (root instanceof URL) {
tags.push(['k', root.hostname]);
} else {
tags.push(['k', root.kind.toString()]);
tags.push(['p', root.pubkey]);
}
}
const event = await publishEvent({
kind: 1111,
content,
tags,
});
return event;
},
onSuccess: (_, { root }) => {
// Invalidate and refetch comments
queryClient.invalidateQueries({
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
});
},
});
}
-75
View File
@@ -1,75 +0,0 @@
#!/usr/bin/env node
import puppeteer from 'puppeteer';
const SITE_URL = process.env.DEPLOY_URL;
if (!SITE_URL) {
console.error('❌ DEPLOY_URL environment variable is required');
process.exit(1);
}
async function checkConsole() {
console.log(`🔍 Checking ${SITE_URL} for console errors...`);
const browser = await puppeteer.launch({ headless: true });
try {
const page = await browser.newPage();
const errors = [];
const warnings = [];
page.on('console', (msg) => {
const text = msg.text();
const type = msg.type();
if (type === 'error') {
errors.push(text);
} else if (type === 'warn') {
warnings.push(text);
}
});
page.on('pageerror', (error) => {
errors.push(`Page error: ${error.message}`);
});
await page.goto(SITE_URL, {
waitUntil: 'networkidle0',
timeout: 15000
});
// Allow time for any async errors
await new Promise(resolve => setTimeout(resolve, 1000));
// Filter out common non-critical issues
const filteredErrors = errors.filter(error =>
!error.includes('404') &&
!error.includes('manifest.webmanifest') &&
!error.includes('favicon.ico') &&
!error.includes('net::ERR_ABORTED')
);
if (filteredErrors.length > 0) {
console.error('❌ Console errors found:');
filteredErrors.forEach(err => console.error(` - ${err}`));
process.exit(1);
}
if (warnings.length > 0) {
console.warn('⚠️ Console warnings (non-blocking):');
warnings.forEach(warn => console.warn(` - ${warn}`));
}
console.log('✅ No critical console errors found!');
} finally {
await browser.close();
}
}
checkConsole().catch(error => {
console.error('❌ Console check failed:', error.message);
process.exit(1);
});
-3
View File
@@ -19,9 +19,6 @@ export default defineConfig(() => ({
onConsoleLog(log) {
return !log.includes("React Router Future Flag Warning");
},
env: {
DEBUG_PRINT_LIMIT: '0', // Suppress DOM output that exceeds AI context windows
},
},
resolve: {
alias: {