Author SHA1 Message Date
P. Reis 206a9977a3 Merge branch 'main' into fix-kind-0-photo
Conflicts:
	src/hooks/useAuthor.ts
	src/hooks/useLoggedInAccounts.ts
2025-04-23 17:16:11 -03:00
P. Reis 339acb2bc8 fix: increase timeout to 3 seconds 2025-04-23 17:11:12 -03:00
159 changed files with 3972 additions and 26487 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
CONTEXT.md
+1
View File
@@ -0,0 +1 @@
../CONTEXT.md
-56
View File
@@ -1,56 +0,0 @@
name: Deploy to GitHub Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["main"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
# Single deploy job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
- name: Install dependencies and build
run: |
npm install
npm run build
cp dist/index.html dist/404.html
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: dist
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
-30
View File
@@ -1,30 +0,0 @@
name: Test
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
- name: Clean install dependencies
run: |
rm -rf node_modules package-lock.json
npm install
- name: Run tests
run: npm run test
-11
View File
@@ -7,13 +7,10 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
.ai/
yarn.lock
# Editor directories and files
.idea
@@ -23,11 +20,3 @@ yarn.lock
*.njsproj
*.sln
*.sw?
# Vercel
.vercel
# Secrets
.env
.env.*
!.env.example
-27
View File
@@ -1,27 +0,0 @@
image: node:22
default:
interruptible: true
timeout: 1 minute
stages:
- test
- deploy
test:
stage: test
script:
- npm run test
pages:
stage: deploy
script:
- npm run build
- rm -rf public
- mv dist public
artifacts:
paths:
- public
only:
variables:
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
+1
View File
@@ -0,0 +1 @@
CONTEXT.md
+16
View File
@@ -0,0 +1,16 @@
# jsr registry should not be edited or removed
.npmrc
# vite client types are needed
src/vite-env.d.ts
# tsconfig is stable and working correctly, so should not be edited
tsconfig.json
tsconfig.app.json
tsconfig.node.json
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
postcss.config.js
# vite config is stable and usually should not need to be edited
vite.config.ts
+1 -6
View File
@@ -1,14 +1,9 @@
{
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
"args": ["-y", "xjsr", "@nostrbook/mcp"]
}
}
}
+1
View File
@@ -0,0 +1 @@
@jsr:registry=https://npm.jsr.io
+1 -6
View File
@@ -1,14 +1,9 @@
{
"servers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
"args": ["-y", "xjsr", "@nostrbook/mcp"]
}
}
}
-1143
View File
File diff suppressed because it is too large. Load diff
Symlink
+1
View File
@@ -0,0 +1 @@
CONTEXT.md
+198
View File
@@ -0,0 +1,198 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/hooks/`: Custom hooks including `useNostr` and `useNostrQuery`
- `/src/pages/`: Page components used by React Router
- `/src/lib/`: Utility functions and shared logic
- `/public/`: Static assets
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea />
</div>
);
}
```
The `LoginArea` component displays a "Log in" button when the user is logged out, and changes to an account switcher once the user is logged in. It handles all the login-related UI and interactions internally, including displaying login dialogs and switching between accounts.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to multiple Nostr relays for network redundancy
## Build & Deployment
- Build for production: `npm run build`
- Development build: `npm run build:dev`
## Testing Your Changes
Whenever you modify code, you should test your changes after you're finished by running:
```bash
npm run ci
```
This command will typecheck the code and attempt to build it.
Your task is not considered finished until this test passes without errors.
+4 -235
View File
@@ -1,238 +1,7 @@
# MKStack
# mkstack
**The Complete Framework for Building Nostr Clients with AI**
> NOTE: This README is from a template and should be replaced with your project description.
MKStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, MKStack provides everything you need to create decentralized apps on the Nostr protocol.
## Created with mkstack
## 🚀 Quick Start
Build your Nostr app in 3 simple steps:
### 1. Install & Create
```bash
npm install -g @getstacks/stacks
stacks mkstack
```
### 2. Build with AI
```bash
stacks agent
# Tell Dork AI what you want: "Build a group chat application"
```
### 3. Deploy Instantly
```bash
npm run deploy
# ✅ App deployed to NostrDeploy.com!
```
## ✨ What Makes MKStack Special
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Wallet Connect (NIP-47)
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
## 🛠 Technology Stack
- **React 18.x**: Stable version with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: 48+ unstyled, accessible UI components built with Radix UI
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: Client-side routing with BrowserRouter
- **TanStack Query**: Data fetching, caching, and state management
- **TypeScript**: Type-safe JavaScript development
## 🎯 Real-World Examples
### Built with One Prompt
Each of these applications was created with just a single prompt to Dork AI:
- **Group Chat Application**: `"Build me a group chat application"`
- [Live Demo](https://groupchat-74z9j26wq-mks-projects-1f1254c4.vercel.app/)
- **Decentralized Goodreads**: `"Build a decentralized goodreads alternative. Use OpenLibrary API for book data."`
- [Live Demo](https://bookstr123-87phkwjcy-mks-projects-1f1254c4.vercel.app/)
- **Chess Game**: `"Build a chess game with NIP 64"`
- [Live Demo](https://chess-l0d7ms7m3-mks-projects-1f1254c4.vercel.app/chess)
### Production Apps
Real Nostr applications built using MKStack:
- **[Chorus](https://chorus.community/)**: Facebook-style groups on Nostr with built-in eCash wallet
- **[Blobbi](https://www.blobbi.pet/)**: Digital pet companions that live forever on the decentralized web
- **[Treasures](https://treasures.to/)**: Decentralized geocaching adventure powered by Nostr
[Browse more apps made with MKStack →](https://nostrhub.io/apps/t/mkstack/)
## 🔧 Core Features
### Authentication & Users
- `LoginArea` component with account switching
- `useCurrentUser` hook for authentication state
- `useAuthor` hook for fetching user profiles
- NIP-07 browser signing support
- Multi-account management
### Nostr Protocol Support
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47)
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
### Data Management
- `useNostr` hook for querying and publishing
- `useNostrPublish` hook with automatic client tagging
- Event validation and filtering
- Infinite scroll with TanStack Query
- Multi-relay support
### UI Components
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
- `NoteContent` component for rich text rendering
- `EditProfileForm` for profile management
- `RelaySelector` for relay switching
- `CommentsSection` for threaded discussions
- Light/dark theme system
### Media & Files
- `useUploadFile` hook with Blossom server integration
- NIP-94 compatible file metadata
- Image and video support
- File attachment to events
### Advanced Features
- NIP-19 identifier routing (`npub1`, `note1`, `nevent1`, `naddr1`)
- Cryptographic operations (encryption/decryption)
- Lightning payments and zaps
- Real-time event subscriptions
- Responsive design with mobile support
## 🤖 AI Development with Dork
MKStack includes Dork, a built-in AI agent that understands your codebase and Nostr protocols:
### Supported AI Providers
Configure your AI provider with `stacks configure`:
- **OpenRouter** ([openrouter.ai](https://openrouter.ai/)): Enter your API key from settings
- **Routstr** ([routstr.com](https://www.routstr.com/)): Use Cashu tokens for payment
- **PayPerQ** ([ppq.ai](https://ppq.ai/)): OpenAI-compatible API
### How Dork Works
- **Context-Aware**: Understands your entire codebase and project structure
- **Nostr Expert**: Built-in knowledge of 50+ NIPs and best practices
- **Instant Implementation**: Makes changes directly to your code following React/TypeScript best practices
Example prompts:
```bash
"Add user profiles with avatars and bio"
"Implement NIP-17 private messaging"
"Add a dark mode toggle"
"Create a marketplace with NIP-15"
```
## 📁 Project Structure
```
src/
├── components/ # UI components
│ ├── ui/ # shadcn/ui components (48+ available)
│ ├── auth/ # Authentication components
│ └── comments/ # Comment system components
├── hooks/ # Custom React hooks
│ ├── useNostr # Core Nostr integration
│ ├── useAuthor # User profile data
│ ├── useCurrentUser # Authentication state
│ ├── useNostrPublish # Event publishing
│ ├── useUploadFile # File uploads
│ └── useZaps # Lightning payments
├── pages/ # Page components
├── lib/ # Utility functions
├── contexts/ # React context providers
└── test/ # Testing utilities
```
## 🎨 UI Components
MKStack includes 48+ shadcn/ui components:
**Layout**: Card, Separator, Sheet, Sidebar, ScrollArea, Resizable
**Navigation**: Breadcrumb, NavigationMenu, Menubar, Tabs, Pagination
**Forms**: Button, Input, Textarea, Select, Checkbox, RadioGroup, Switch, Slider
**Feedback**: Alert, AlertDialog, Toast, Progress, Skeleton
**Overlay**: Dialog, Popover, HoverCard, Tooltip, ContextMenu, DropdownMenu
**Data Display**: Table, Avatar, Badge, Calendar, Chart, Carousel
**And many more...
## 🔐 Security & Best Practices
- **Never use `any` type**: Always use proper TypeScript types
- **Event validation**: Filter events through validator functions for custom kinds
- **Efficient queries**: Minimize separate queries to avoid rate limiting
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
- **Secure authentication**: Use signer interface, never request private keys directly
## 📱 Responsive Design
- Mobile-first approach with Tailwind breakpoints
- `useIsMobile` hook for responsive behavior
- Touch-friendly interactions
- Optimized for all screen sizes
## 🧪 Testing
- Vitest with jsdom environment
- React Testing Library with jest-dom matchers
- `TestApp` component provides all necessary context providers
- Mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
## 🚀 Deployment
Built-in deployment to NostrDeploy.com:
```bash
npm run deploy
```
Your app goes live instantly with:
- Automatic builds
- CDN distribution
- HTTPS support
- Custom domains available
## 📚 Documentation
For detailed documentation on building Nostr applications with MKStack:
- [Tutorial](https://soapbox.pub/blog/mkstack-tutorial)
- [Nostr Protocol Documentation](https://nostr.com)
- [shadcn/ui Components](https://ui.shadcn.com)
## 🤝 Contributing
MKStack is open source and welcomes contributions. The framework is designed to be:
- **Extensible**: Easy to add new NIPs and features
- **Maintainable**: Clean architecture with TypeScript
- **Testable**: Comprehensive testing setup included
- **Documented**: Clear patterns and examples
## 📄 License
Open source - build amazing Nostr applications and help grow the decentralized web!
---
**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack)
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
mkstack is a starter template for building Nostr web clients in TypeScript, using React, Tailwind, shadcn/ui, Vite, and Nostrify.
Symlink
+1
View File
@@ -0,0 +1 @@
CONTEXT.md
-299
View File
@@ -1,299 +0,0 @@
### AI Integration with Shakespeare API
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
```tsx
import { useShakespeare, type ChatMessage, type Model } from '@/hooks/useShakespeare';
const {
sendChatMessage,
sendStreamingMessage,
getAvailableModels,
isLoading,
error,
isAuthenticated
} = useShakespeare();
```
#### Model Selector Component
```tsx
function ModelSelector({ onModelSelect }: { onModelSelect: (modelId: string) => void }) {
const { getAvailableModels, isLoading } = useShakespeare();
const [models, setModels] = useState<Model[]>([]);
const [selectedModel, setSelectedModel] = useState<string>('');
useEffect(() => {
const fetchModels = async () => {
try {
const response = await getAvailableModels();
// Sort models by total cost (cheapest first)
const sortedModels = response.data.sort((a, b) => {
const costA = parseFloat(a.pricing.prompt) + parseFloat(a.pricing.completion);
const costB = parseFloat(b.pricing.prompt) + parseFloat(b.pricing.completion);
return costA - costB;
});
setModels(sortedModels);
// Select the cheapest model by default
if (sortedModels.length > 0) {
const cheapestModel = sortedModels[0];
setSelectedModel(cheapestModel.id);
onModelSelect(cheapestModel.id);
}
} catch (err) {
console.error('Failed to fetch models:', err);
}
};
fetchModels();
}, [getAvailableModels, onModelSelect]);
const handleModelChange = (modelId: string) => {
setSelectedModel(modelId);
onModelSelect(modelId);
};
return (
<div>
<label htmlFor="model-select">Choose Model:</label>
<select
id="model-select"
value={selectedModel}
onChange={(e) => handleModelChange(e.target.value)}
disabled={isLoading}
>
<option value="">Select a model...</option>
{models.map((model, index) => {
const totalCost = parseFloat(model.pricing.prompt) + parseFloat(model.pricing.completion);
const isCheapest = index === 0;
return (
<option key={model.id} value={model.id}>
{model.name} - {isCheapest ? "Cheapest" : `$${totalCost.toFixed(6)}/token`}
</option>
);
})}
</select>
</div>
);
}
```
#### Basic Chat Example
```tsx
function AIChat() {
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState('');
const [selectedModel, setSelectedModel] = useState<string>('');
const handleSend = async () => {
if (!input.trim() || !selectedModel) return;
const newMessages = [...messages, { role: 'user', content: input }];
setMessages(newMessages);
setInput('');
try {
const response = await sendChatMessage(newMessages, selectedModel);
setMessages(prev => [...prev, {
role: 'assistant',
content: response.choices[0].message.content as string
}]);
} catch (err) {
console.error('Chat error:', err);
}
};
if (!isAuthenticated) return <div>Please log in to use AI</div>;
return (
<div className="max-w-2xl mx-auto p-4">
{error && <div className="text-red-500 mb-4">{error}</div>}
{/* Model Selection */}
<div className="mb-4">
<ModelSelector onModelSelect={setSelectedModel} />
</div>
<div className="space-y-2 mb-4">
{messages.map((msg, i) => (
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
</div>
<div className="flex gap-2">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
className="flex-1 p-2 border rounded"
disabled={isLoading || !selectedModel}
placeholder={!selectedModel ? "Select a model first..." : "Type your message..."}
/>
<button
onClick={handleSend}
disabled={isLoading || !selectedModel}
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
>
Send
</button>
</div>
</div>
);
}
```
#### Streaming Chat Example
```tsx
function StreamingChat() {
const { sendStreamingMessage } = useShakespeare();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [currentResponse, setCurrentResponse] = useState('');
const [selectedModel, setSelectedModel] = useState<string>('');
const handleStreaming = async (content: string) => {
if (!selectedModel) return;
setCurrentResponse('');
const newMessages = [...messages, { role: 'user', content }];
setMessages(newMessages);
try {
await sendStreamingMessage(newMessages, selectedModel, (chunk) => {
setCurrentResponse(prev => prev + chunk);
});
// Add the complete response to messages
if (currentResponse.trim()) {
setMessages(prev => [...prev, {
role: 'assistant',
content: currentResponse
}]);
}
} catch (err) {
console.error('Streaming error:', err);
} finally {
setCurrentResponse('');
}
};
return (
<div>
{/* Model selection UI */}
<div className="mb-4">
<ModelSelector onModelSelect={setSelectedModel} />
</div>
{/* Chat interface */}
{/* ... rest of your chat UI */}
</div>
);
}
```
#### Model Information
Models are dynamically fetched from the Shakespeare API and include:
- **Model ID**: Unique identifier for the model
- **Name**: Human-readable model name
- **Description**: Model capabilities and use cases
- **Context Window**: Maximum token limit for conversations
- **Pricing**: Cost per token for prompt and completion
- **Free Models**: Models with `pricing.prompt === "0"` and `pricing.completion === "0"`
#### Key Points
- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()`
- **Authentication Required**: User must be logged in with Nostr account
- **Free vs Premium**: Check pricing to determine if model requires credits
- **Error Handling**: Handle `isLoading` and `error` states appropriately
- **Model Selection**: Provide UI for users to choose between available models
## Implementation Patterns and Best Practices
### Streaming Response Handling
When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss:
```tsx
const handleStreamingResponse = async () => {
let streamedContent = ''; // ✅ Use local variable to accumulate content
try {
await sendStreamingMessage(messages, model, (chunk) => {
streamedContent += chunk; // ✅ Accumulate in local variable
setCurrentStreamingMessage(streamedContent); // Update UI
});
// ✅ Save accumulated content to persistent state
if (streamedContent.trim()) {
const assistantMessage: MessageDisplay = {
id: Date.now().toString(),
role: 'assistant',
content: streamedContent, // ✅ Use accumulated content
timestamp: new Date()
};
setMessages(prev => [...prev, assistantMessage]);
}
} finally {
setCurrentStreamingMessage(''); // ✅ Clear streaming state after saving
}
};
```
### Error Boundary Patterns
Always wrap AI components with error boundaries and provide user-friendly error messages for common failure scenarios:
```tsx
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { Alert, AlertDescription } from '@/components/ui/alert';
function AIChatWithErrorBoundary() {
return (
<ErrorBoundary
fallback={
<div className="p-4">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
Something went wrong with the AI chat. Please refresh the page and try again.
</AlertDescription>
</Alert>
</div>
}
>
<AIChat />
</ErrorBoundary>
);
}
// In your AI component, handle specific error types gracefully:
function useAIWithErrorHandling() {
const { sendChatMessage, error, clearError } = useShakespeare();
const sendMessage = async (messages: ChatMessage[], modelId: string) => {
try {
await sendChatMessage(messages, modelId);
} catch (err) {
// Handle specific error types with user-friendly messages
if (err.message.includes('401')) {
throw new Error('Authentication failed. Please log in again.');
} else if (err.message.includes('402')) {
throw new Error('Insufficient credits. Please add credits to use premium features.');
} else if (err.message.includes('network')) {
throw new Error('Network error. Please check your internet connection.');
}
throw err; // Re-throw for error boundary
}
};
return { sendMessage, error, clearError };
}
```
-460
View File
@@ -1,460 +0,0 @@
# Bitcoin Wallet System for AI Agents (NutStack)
This document explains the Bitcoin wallet system architecture and provides guidance for AI agents to extend, modify, and build upon the existing implementation.
## Overview
The Bitcoin wallet system provides on-chain Bitcoin transaction capabilities including:
- **Send/Receive**: On-chain Bitcoin transactions using Taproot addresses
- **UTXO Management**: View and manage unspent transaction outputs
- **UTXO Consolidation**: Combine multiple UTXOs into a single transaction
- **Transaction History**: View past Bitcoin transactions with status tracking
- **QR Code Support**: Scan Bitcoin addresses and npubs
The wallet requires nsec login for transaction signing.
## Architecture
### Component Hierarchy
```
WalletContainer (parent)
└── BitcoinWallet
├── WalletHeader (balance, mode toggle, address display)
├── PaymentCard (send/receive forms)
├── TransactionHistory (transaction list)
├── UTXOSelector (UTXO dropdown with consolidation)
├── ConsolidationModal (UTXO consolidation confirmation)
├── QRScanner (QR code scanning)
└── QRModal (address QR code display)
```
### Key Components
#### `BitcoinWallet.tsx`
Main Bitcoin wallet component that orchestrates all Bitcoin operations:
- Manages Bitcoin send/receive state
- Handles QR scan results
- Coordinates UTXO management
- Provides action buttons (Send, Receive, Scan, History)
**Key State:**
- `bitcoinAmount`: Amount to send (in sats)
- `bitcoinRecipient`: Recipient address or npub
- `pendingBitcoinRecipient`: Confirmed recipient after validation
- `showSendModal`, `showReceiveModal`, `showHistoryModal`: Drawer visibility
**Key Props:**
- `user`: Current user with pubkey
- `toast`: Toast notification function
- `generateQRCode`: QR code generation function
- `onRequestQRScanner`: Request QR scanner modal
- `onQRResult`: Handle QR scan results
#### `WalletHeader.tsx`
Displays wallet balance, mode toggle, and address management:
- **Balance Display**: Shows total Bitcoin balance with USD/sats toggle
- **Address Display**: Shows Bitcoin address with copy/QR buttons
- **UTXO Selector**: Displays UTXO count and consolidation option
- **Custody Badge**: Indicates "Self-Custody" for Bitcoin mode
#### `PaymentCard.tsx`
Transaction card for Bitcoin operations:
- **Bitcoin Send**: Two-step process (recipient → amount)
- **Bitcoin Receive**: Shows address with QR generation
- **Send Max**: Toggle for sending all available funds
**Bitcoin Send Flow:**
1. User enters recipient address or npub
2. System validates and converts npub to Bitcoin address if needed
3. User enters amount (or clicks "Send Max")
4. Transaction is created, signed, and broadcast
#### `TransactionHistory.tsx`
Transaction history display:
- **Bitcoin Transactions**: On-chain transactions with status
- **Transaction Types**: `sent`, `received`, `consolidate`
- **Status Display**: `confirmed`, `unconfirmed`, `pending`
**Bitcoin Transaction Format:**
```typescript
interface BitcoinTransaction {
id: string;
txid: string;
type: 'sent' | 'received' | 'consolidate';
amount: number; // in satoshis
fee?: number; // in satoshis
address: string;
confirmations: number;
blockHeight?: number;
timestamp: number;
status: 'confirmed' | 'unconfirmed' | 'pending';
}
```
#### `UTXOSelector.tsx`
UTXO management dropdown:
- Shows UTXO count and total balance
- Lists individual UTXOs with block information
- Consolidation button for combining UTXOs
- Formatting supports sats/USD display
#### `ConsolidationModal.tsx`
Confirmation modal for UTXO consolidation:
- Shows number of UTXOs to be consolidated
- Displays total value
- Explains benefits (reduced fees, simplified management)
- Handles consolidation execution
#### `QRScanner.tsx`
QR code scanning interface:
- Camera-based scanning using Html5Qrcode
- Paste from clipboard support
- Classifies scanned codes (Bitcoin address, npub, etc.)
- Handles camera permissions and errors
### Core Hooks
#### `useBitcoin.ts`
Main Bitcoin operations hook:
- **`useBitcoinBalance`**: Fetches UTXOs and calculates balance
- **`useBitcoinTransactionHistory`**: Fetches transaction history from Blockstream API
- **`useBitcoinOperations`**: Manages send/receive/consolidate operations
**Key Functions:**
```typescript
// Fetch UTXOs and balance
const { data: bitcoinBalanceData } = useBitcoinBalance(bitcoinAddress);
// Fetch transaction history
const { data: bitcoinTransactions } = useBitcoinTransactionHistory(bitcoinAddress);
// Get operations hook
const {
utxos,
isConsolidating,
bitcoinMaxAmount,
fetchBitcoinUtxos,
handleSendMax,
handleBitcoinSend,
handleBitcoinReceive,
handleConsolidateUtxos,
} = useBitcoinOperations(bitcoinAddress);
```
#### `useNsecAccess.ts`
Access to private key for transaction signing:
- **`hasNsecAccess`**: Checks if user logged in with nsec
- **`getPrivateKey`**: Returns private key in hex format
**Usage:**
```typescript
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
if (!hasNsecAccess) {
// Show error: nsec login required
return;
}
const privateKey = getPrivateKey();
// Use private key for transaction signing
```
#### `useQRCode.ts`
QR code generation and scanning:
- **`generateQRCode`**: Creates QR code from text
- **`startScanning`**: Starts camera scanner
- **`stopScanning`**: Stops scanner
- **`classifyQRCode`**: Classifies scanned text (Bitcoin address, npub, etc.)
**QR Code Types:**
- `bitcoin_address`: Bitcoin address (bc1..., 1..., 3...)
- `npub`: Nostr public key (npub1...)
- `unknown`: Unrecognized format
### Core Libraries
#### `bitcoin.ts`
Bitcoin utility functions:
- **Address Derivation**: `nostrPubkeyToBitcoinAddress()`, `npubToBitcoinAddress()`
- **Validation**: `isValidBitcoinAddress()`
- **UTXO Management**: `fetchUTXOs()`, `calculateMaxSendAmount()`
- **Transaction Building**: `createBitcoinTransaction()`, `broadcastTransaction()`
- **Fee Estimation**: `getFeeRates()`
**Key Functions:**
```typescript
// Convert Nostr pubkey to Bitcoin Taproot address
const address = nostrPubkeyToBitcoinAddress(user.pubkey);
// Fetch UTXOs from Blockstream API
const utxos = await fetchUTXOs(address);
// Get fee rates
const feeRates = await getFeeRates();
// Returns: { fastestFee, halfHourFee, hourFee, economyFee, minimumFee }
// Create and sign transaction
const { txHex, fee } = await createBitcoinTransaction(
privateKeyHex,
recipientAddress,
amountSats,
utxos,
feeRates.fastestFee,
sendMax // true for send max
);
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
```
#### `exchangeRateService.ts`
Exchange rate service for BTC/USD conversion:
- Fetches rates from Coinbase API
- 1-minute caching to reduce API calls
- Fallback to cached rate on API failure
- Methods: `getBtcUsdRate()`, `satsToUsd()`, `btcToUsd()`, `usdToBtc()`
## Key Features
### On-Chain Bitcoin Transactions
**Address Derivation:**
- Bitcoin addresses are derived from Nostr public keys
- Uses Taproot (P2TR) addresses (bc1p...)
- Supports conversion from npub format
**Transaction Flow:**
1. User enters recipient (Bitcoin address or npub)
2. System validates and converts npub if needed
3. User enters amount (or selects "Send Max")
4. System fetches UTXOs and fee rates
5. Transaction is built and signed
6. Transaction is broadcast to network
7. Balance is refreshed automatically
**Send Max:**
- Calculates maximum sendable amount (total - fees)
- No change output (sends all UTXOs)
- Useful for consolidating or emptying wallet
### UTXO Management
**UTXO Display:**
- Shows count and total value
- Lists individual UTXOs with block information
- Displays confirmation status
**UTXO Consolidation:**
- Combines multiple UTXOs into single transaction
- Sends all funds to own address (self-send)
- Reduces future transaction fees
- Requires nsec login for signing
**UTXO Selection:**
- Automatic selection for transactions
- Uses all available UTXOs for send max
- Optimizes for fee efficiency
### Transaction History
**Data Source:**
Blockstream API provides transaction history:
- Fetches transaction list from `/address/:address/txs`
- Fetches full transaction details for accurate sent/received detection
- Calculates transaction amounts and fees
**Transaction Detection:**
- **Received**: Address appears in outputs only
- **Sent**: Address appears in input prevouts
- **Consolidate**: Self-send where all outputs go to same address
**Display:**
- Transaction type with icon
- Amount with direction (sent/received)
- Fee information (for sent transactions)
- Confirmation count and status
- Block height and timestamp
### QR Code Integration
**QR Code Generation:**
- Bitcoin addresses for receiving payments
**QR Code Scanning:**
- Bitcoin addresses: Auto-fills recipient field
- npubs: Converts to Bitcoin address and auto-fills
**Supported Formats:**
- `bc1...` (Taproot addresses)
- `1...`, `3...` (Legacy addresses)
- `npub1...` (Nostr public keys)
## State Management
### Bitcoin State Flow
```
BitcoinWallet Component
├── Local State
│ ├── bitcoinAmount (send amount)
│ ├── bitcoinRecipient (recipient input)
│ ├── pendingBitcoinRecipient (validated recipient)
│ └── Modal visibility states
├── useBitcoinBalance Hook
│ ├── Fetches UTXOs from Blockstream API
│ ├── Calculates total balance
│ └── Auto-refreshes every 30 seconds
├── useBitcoinTransactionHistory Hook
│ ├── Fetches transaction history
│ └── Auto-refreshes every 30 seconds
└── useBitcoinOperations Hook
├── UTXO management
├── Send/receive operations
└── Consolidation handling
```
### React Query Integration
**Bitcoin Balance:**
```typescript
const { data: bitcoinBalanceData, refetch } = useBitcoinBalance(bitcoinAddress);
// Returns: { balance: number, utxos: UTXO[] }
```
**Transaction History:**
```typescript
const { data: bitcoinTransactions } = useBitcoinTransactionHistory(bitcoinAddress);
// Returns: BitcoinTransaction[]
```
**Auto-Refresh:**
- Balance: Refetches every 30 seconds
- Transactions: Refetches every 30 seconds
- Stale time: 10 seconds (data considered fresh for 10s)
## Extension Points
### Adding New Features
#### 1. Custom Fee Selection
To allow users to select fee rates:
**Add Fee Selector Component:**
```typescript
const [selectedFeeRate, setSelectedFeeRate] = useState<'fastest' | 'halfHour' | 'hour' | 'economy'>('fastest');
const feeRates = await getFeeRates();
const feeRate = feeRates[`${selectedFeeRate}Fee`];
```
**Update `PaymentCard.tsx`:**
```typescript
// Add fee selector dropdown
<Select value={selectedFeeRate} onValueChange={setSelectedFeeRate}>
<SelectItem value="fastest">Fastest ({feeRates.fastestFee} sat/vB)</SelectItem>
<SelectItem value="halfHour">Half Hour ({feeRates.halfHourFee} sat/vB)</SelectItem>
// ...
</Select>
```
#### 2. Transaction Labels/Notes
To add labels or notes to transactions:
**Extend Transaction History:**
```typescript
interface BitcoinTransaction {
// ... existing fields
label?: string;
notes?: string;
}
```
**Store Labels:**
- Use local storage or IndexedDB
- Key by transaction ID
- Display in transaction history
### Modifying Existing Features
#### Change Address Format
**Modify `bitcoin.ts`:**
```typescript
// Change from Taproot to P2WPKH (bc1q...)
export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string {
const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex');
const { address } = bitcoin.payments.p2wpkh({
pubkey: pubkeyBuffer,
network: bitcoin.networks.bitcoin,
});
return address || '';
}
```
#### Change Fee Estimation
**Modify `bitcoin.ts`:**
```typescript
// Use different API or estimation method
export async function getFeeRates() {
return {
fastestFee: 10,
halfHourFee: 5,
hourFee: 3,
economyFee: 1,
minimumFee: 1,
};
}
```
## Troubleshooting
### Common Issues
#### 1. "Nsec login required" error
**Cause**: User not logged in with nsec
**Solution**: Check `hasNsecAccess` before showing Bitcoin features
#### 2. Transaction fails to broadcast
**Cause**: Invalid transaction or network error
**Solution**: Validate transaction before broadcasting, retry on network errors
#### 3. UTXOs not updating
**Cause**: Blockstream API rate limiting or network issues
**Solution**: Implement retry logic, show error to user
#### 4. Balance incorrect
**Cause**: UTXOs not fetched or cached data stale
**Solution**: Force refresh balance, check Blockstream API response
## API Dependencies
### Blockstream API
- **Base URL**: `https://blockstream.info/api`
- **Endpoints**:
- `/address/:address/utxo` - Fetch UTXOs
- `/address/:address/txs` - Fetch transaction list
- `/tx/:txid` - Fetch full transaction details
- `/fee-estimates` - Get fee rates
- `/tx` - Broadcast transaction (POST)
### Coinbase API
- **Base URL**: `https://api.coinbase.com/v2/exchange-rates`
- **Endpoint**: `?currency=BTC` - Get BTC/USD exchange rate
## Dependencies
Required packages:
```json
{
"bitcoinjs-lib": "^7.x",
"@bitcoinerlab/secp256k1": "^1.x",
"ecpair": "^2.x",
"qrcode": "^1.x",
"html5-qrcode": "^2.x"
}
```
-784
View File
@@ -1,784 +0,0 @@
# Cashu Wallet Implementation Guide
This document provides comprehensive instructions for AI agents working on the Cashu/Lightning wallet implementation. It covers architecture, patterns, and best practices for extending and maintaining the wallet system.
## Table of Contents
1. [Architecture Overview](#architecture-overview)
2. [Component Structure](#component-structure)
3. [Hook Patterns](#hook-patterns)
4. [Wallet Modes](#wallet-modes)
5. [Mint Management](#mint-management)
6. [Transaction Operations](#transaction-operations)
7. [Integration Points](#integration-points)
8. [Extension Guidelines](#extension-guidelines)
9. [Best Practices](#best-practices)
## Architecture Overview
The Cashu wallet is built on a **layered architecture** with clear separation of concerns:
```
┌─────────────────────────────────────────────────┐
│ CashuWallet (Orchestrator) │
│ - Coordinates all operations │
│ - Manages UI state and modals │
│ - Routes between modes (tokens/lightning) │
└─────────────────────────────────────────────────┘
│
┌───────────┼──────────┐
│ │ │
┌───────▼─────┐ ┌───▼───────┐ ┌▼─────────────┐
│ WalletHeader│ │PaymentCard│ │Modals/Drawers│
│ - Balance │ │- Send/ │ │ - QRScanner │
│ - Mint │ │ Receive │ │ - History │
│ - Mode │ │- Lightning│ │ - Breakdown │
└─────────────┘ └───────────┘ └──────────────┘
│
│
┌───────▼───────────────────────────────────────┐
│ Domain Hooks │
│ - useMintManager (mint operations) │
│ - useTokenOperations (Cashu tokens) │
│ - useLightningOperations (Lightning) │
│ - useHistoryManager (transaction history) │
└───────────────────────────────────────────────┘
│
│
┌───────▼───────────────────────────────────────┐
│ Core Hooks │
│ - useCashu (coco manager instance) │
│ - useNpubCash (npub.cash API) │
│ - useLightningAddress (LNURL resolution) │
│ - useQRCode (QR generation/scanning) │
└───────────────────────────────────────────────┘
│
│
┌───────▼───────────────────────────────────────┐
│ coco-cashu-core Library │
│ - Proof management │
│ - Mint operations │
│ - Quote processing │
└───────────────────────────────────────────────┘
```
### Key Principles
1. **Separation of Concerns**: UI components are separated from business logic hooks
2. **Single Responsibility**: Each hook handles one specific domain (mints, tokens, lightning)
3. **State Management**: React state for UI reactivity, coco instance for wallet operations
4. **Error Handling**: Centralized error handling with toast notifications
5. **Type Safety**: Full TypeScript coverage with proper types from coco-cashu-core
## Component Structure
### Main Components
#### `CashuWallet.tsx` - Main Orchestrator
**Purpose**: Coordinates all wallet operations and manages global state.
**Key Responsibilities**:
- Initializes and manages the `coco` wallet manager instance
- Coordinates between mint management, token operations, and lightning operations
- Manages modal/drawer state (send, receive, history, QR scanner)
- Handles QR scan results and routes to appropriate handlers
- Integrates with npub.cash API for Lightning addresses
- Exposes wallet header props to parent `WalletContainer`
**Key Patterns**:
```typescript
// Core hooks initialized first
const { coco, balances, mints, ... } = useCashu();
const { ... } = useNpubCash();
// Domain hooks use core hooks
const { activeMintUrl, ... } = useMintManager({ coco, mints, ... });
const { sendAmount, ... } = useTokenOperations({ coco, activeMintUrl, ... });
// Combined handlers route to appropriate domain
const handleSend = async () => {
if (sendAmount && activeMintUrl) {
return tokenOps.handleTokenSend();
}
if (pendingLightningAddress) {
return lightningOps.handleLightningAddressPayment();
}
// ...
};
```
**State Management**:
- Uses refs to track initialization state (`hasFetchedUserInfoRef`, `hasSetMintFromUserInfoRef`)
- Persists active mint URL to localStorage
- Manages drawer open/close state with cleanup
#### `WalletHeader.tsx` - Balance and Controls
**Purpose**: Displays wallet balance, mode switching, and mint/address selectors.
**Key Features**:
- Toggle between sats and USD display
- Mode switching button (tokens → lightning → bitcoin → tokens)
- Mint selector dropdown (when mode is tokens/lightning)
- Lightning address display (when mode is lightning)
- Bitcoin address display (when mode is bitcoin)
- Seed phrase display (when mode is tokens)
**Key Patterns**:
- Uses `exchangeRateService` for BTC/USD conversion
- Conditional rendering based on `mode` prop
- Copy-to-clipboard functionality with visual feedback
- QR code generation for addresses
#### `PaymentCard.tsx` - Send/Receive Interface
**Purpose**: Unified interface for all send/receive operations.
**Modes Supported**:
- **Send**: Token send, Lightning invoice payment, Lightning address payment, Bitcoin send, reverse swap
- **Receive**: Token receive, Lightning invoice creation, Bitcoin address display
**Key Patterns**:
- Single component handles multiple operation types
- Uses `operation` prop ('send' | 'receive') to determine UI
- Uses `mode` prop ('tokens' | 'lightning' | 'bitcoin') for context
- Progressive disclosure: shows pending state (e.g., "Sending to: address") before amount input
- Input validation with error messages
**State Flow**:
```typescript
// Send flow
1. User enters invoice/address → detectAndHandleLightningInput()
2. Sets pending state (pendingInvoice, pendingLightningAddress)
3. Shows confirmation UI with amount
4. User confirms → handleConfirmInvoicePayment() or handleLightningAddressPayment()
// Receive flow
1. User enters amount → handleLightningReceive()
2. Creates mint quote → shows invoice modal
3. Waits for payment via mint-quote:redeemed event
```
#### `MintSelector.tsx` - Mint Dropdown
**Purpose**: Select and manage Cashu mints.
**Features**:
- Dropdown showing all trusted mints with balances
- Add new mint input
- Remove mint button (with confirmation modal)
- Active mint indicator
- Denomination breakdown button
**Key Patterns**:
- Uses `DropdownMenu` from shadcn/ui
- Filters mints to only show trusted mints
- Format balance with sats/USD toggle
- Inline input for adding mints
### Modal Components
#### `QRScanner.tsx`
- Camera-based QR code scanning
- Paste from clipboard support
- Classifies QR codes (invoice, address, token, etc.)
- Uses `html5-qrcode` library
#### `ProofBreakdownModal.tsx`
- Shows token denomination breakdown for a mint
- Displays total balance and count of each denomination
- Useful for debugging payment issues
#### `RemoveMintModal.tsx`
- Confirmation dialog for removing mints
- Warns about data loss
- Shows mint name/URL
#### `SeedPhraseModal.tsx`
- Input for restoring tokens from seed phrase
- Validates mnemonic format
- Shows active mint context
#### `TransactionHistory.tsx`
- Displays transaction history from coco
- Filters out unpaid quotes (only shows completed)
- Supports both Cashu and Bitcoin transactions
- Shows transaction type, amount, timestamp, mint info
## Hook Patterns
### Core Hooks
#### `useCashu.ts` - Wallet Manager
**Purpose**: Manages the `coco` wallet manager instance and core wallet state.
**Key Features**:
- Singleton pattern to prevent multiple initializations
- Mnemonic generation and validation
- Balance and mint state management
- Event listeners for automatic balance updates
- Repository access for direct proof operations
**Usage Pattern**:
```typescript
const {
coco, // Manager instance (null until initialized)
repositories, // Direct repository access
balances, // Reactive balance state
mints, // Reactive mint list
isInitialized, // Initialization status
isLoading, // Loading state
error, // Error state
mnemonic, // Current mnemonic
refreshMints // Refresh mint list
} = useCashu();
```
**Important Notes**:
- `coco` is `null` until wallet is initialized
- Always check `isInitialized` before using `coco`
- Balance updates automatically via event listeners
- Repositories provide direct access to proofs, mints, history
#### `useNpubCash.ts` - npub.cash Integration
**Purpose**: Integrates with npub.cash API for Lightning addresses and quote sync.
**Key Features**:
- NIP-98 authentication with Nostr signer
- User info fetching (mint URL, Lightning address)
- Quote synchronization with wallet
- Real-time quote updates via WebSocket
- Automatic mint addition for quotes
**Usage Pattern**:
```typescript
const {
setMint, // Set mint URL in npub.cash
getUserInfo, // Get user info (mint URL, name)
syncQuotesWithWallet, // Subscribe to quote updates
isLoggedIn, // Login status
isLoading, // Loading state
error // Error state
} = useNpubCash();
```
**Quote Sync Flow**:
1. On login, `syncQuotesWithWallet()` is called
2. Fetches all quotes from npub.cash
3. Adds mints if needed (auto-trusts)
4. Adds quotes to wallet via `coco.quotes.addMintQuote()`
5. Subscribes to real-time updates
6. On quote update, fetches newer quotes and syncs
#### `useLightningAddress.ts` - LNURL Resolution
**Purpose**: Resolves Lightning addresses to invoices using LNURL-pay protocol.
**Key Features**:
- Two-step LNURL-pay resolution
- Amount validation (min/max)
- Comment support
- Error handling with descriptive messages
**Usage Pattern**:
```typescript
const { getInvoice, isLoading, error } = useLightningAddress();
const invoice = await getInvoice({
lightningAddress: '[email protected]',
amountSats: 1000,
comment: 'Optional comment'
});
```
**Resolution Flow**:
1. Parse Lightning address → `https://domain/.well-known/lnurlp/username`
2. Fetch LNURL-pay info (min/max, callback URL)
3. Validate amount against bounds
4. Request invoice from callback URL with amount
5. Return BOLT11 invoice
### Domain Hooks
#### `useMintManager.ts` - Mint Operations
**Purpose**: Manages mint selection, adding, removing, and denomination display.
**Key Features**:
- Active mint selection with npub.cash sync
- Mint addition with auto-trust
- Mint removal with confirmation
- Denomination breakdown calculation
- Mint URL normalization
**Key Functions**:
- `handleSetActiveMint()` - Set active mint, optionally sync to npub.cash
- `handleAddMint()` - Add new mint with validation
- `handleRemoveMintClick()` - Show removal confirmation
- `handleConfirmRemoveMint()` - Remove mint and switch active mint
- `handleShowDenominations()` - Calculate and show token breakdown
**Important Patterns**:
```typescript
// Always check if mint exists before adding
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
if (isKnown) {
// Ensure trusted
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
if (!isTrusted) {
await coco.mint.trustMint(mintUrl);
}
} else {
// Add with trusted flag
await coco.mint.addMint(mintUrl, { trusted: true });
}
```
#### `useTokenOperations.ts` - Cashu Token Operations
**Purpose**: Handles sending and receiving Cashu tokens.
**Key Features**:
- Token send with amount validation
- Token receive with unknown mint handling
- QR code generation for sent tokens
- Automatic mint addition for unknown mints
**Key Functions**:
- `handleTokenSend()` - Send tokens, generate QR code
- `handleTokenReceive()` - Receive tokens, handle unknown mints
- `handleUnknownMintError()` - Add unknown mint and retry
**Error Handling**:
- Detects `UnknownMintError` from coco
- Extracts mint URL from error message
- Automatically adds and trusts the mint
- Retries the receive operation
#### `useLightningOperations.ts` - Lightning Operations
**Purpose**: Handles Lightning invoice creation, payment, and address resolution.
**Key Features**:
- Lightning invoice creation (mint quotes)
- Invoice payment (melt quotes)
- Lightning address payment flow
- Invoice amount decoding
- Real-time payment tracking
**Key Functions**:
- `handleLightningReceive()` - Create mint quote, show invoice modal
- `detectAndHandleLightningInput()` - Classify input (invoice vs address)
- `handleLightningAddressPayment()` - Resolve address, create invoice, pay
- `handleConfirmInvoicePayment()` - Pay pending invoice
**Payment Flow**:
```typescript
// Receive flow
1. User enters amount → handleLightningReceive()
2. coco.quotes.createMintQuote(mintUrl, amount)
3. Generate QR code for invoice
4. Show invoice modal
5. Listen for 'mint-quote:redeemed' event
6. On payment, close modal and show success
// Send flow (invoice)
1. User enters invoice → detectAndHandleLightningInput()
2. Decode amount from invoice
3. Set pendingInvoice state
4. User confirms → handleConfirmInvoicePayment()
5. coco.quotes.createMeltQuote() + payMeltQuote()
// Send flow (address)
1. User enters address → detectAndHandleLightningInput()
2. Set pendingLightningAddress state
3. User enters amount → handleLightningAddressPayment()
4. Resolve address to invoice → createMeltQuote() + payMeltQuote()
```
#### `useHistoryManager.ts` - Transaction History
**Purpose**: Manages transaction history loading and filtering.
**Key Features**:
- Paginated history loading
- Filters out unpaid quotes (only completed transactions)
- Auto-refresh on wallet events
- Event listeners for history updates
**Filtering Logic**:
- Mint quotes: only show `state === 'ISSUED'` (completed)
- Melt quotes: only show `state === 'PAID'` (completed)
- Send/Receive: show all (no state field)
**Event Listeners**:
- `history:updated` - General history updates
- `melt-quote:created` - Melt quote created (coco bug workaround)
- `melt-quote:paid` - Melt quote paid
- `mint-quote:redeemed` - Mint quote redeemed (invoice paid)
#### `useQRCode.ts` - QR Code Operations
**Purpose**: Generates QR codes and scans QR codes with camera.
**Key Features**:
- QR code generation with `qrcode` library
- Camera-based scanning with `html5-qrcode`
- QR code classification (invoice, address, token, npub, Bitcoin address)
- Paste from clipboard support
- Error handling for camera permissions
**Classification Logic**:
```typescript
// Lightning invoice: lnbc... or lightning:lnbc...
// Lightning address: [email protected] or lightning:[email protected]
// Cashu token: cashu...
// Bitcoin address: bc1..., 1..., 3...
// Nostr npub: npub1... or nostr:npub1...
```
## Wallet Modes
The wallet supports three modes, each with different UI and operations:
### Mode: 'tokens' (Cashu)
**Purpose**: Direct Cashu token operations.
**Features**:
- Mint selector for choosing active mint
- Send tokens (generates Cashu token)
- Receive tokens (redeems Cashu token)
- Seed phrase display
- Token denomination breakdown
**Operations**:
- Send: `coco.wallet.send(mintUrl, amount)` → generates token
- Receive: `coco.wallet.receive(token)` → redeems token
### Mode: 'lightning'
**Purpose**: Lightning Network operations via Cashu mints.
**Features**:
- Lightning address display (from npub.cash)
- Send: Pay Lightning invoices or addresses
- Receive: Create Lightning invoices (mint quotes)
- Mint selector for choosing active mint
- Reverse swap support (on-chain to Lightning)
**Operations**:
- Send: `createMeltQuote()` + `payMeltQuote()` to pay invoice
- Receive: `createMintQuote()` → generates Lightning invoice → wait for payment
### Mode: 'bitcoin'
**Purpose**: On-chain Bitcoin operations.
**Features**:
- Bitcoin address display (derived from Nostr pubkey)
- UTXO selector for managing UTXOs
- Send Bitcoin on-chain
- Receive Bitcoin on-chain
- Consolidation support
**Note**: Bitcoin mode is handled by `BitcoinWallet` component (not shown in attached files reference BITCOIN_WALLET.md for more information).
## Mint Management
### Mint Lifecycle
1. **Add Mint**: User enters URL → `coco.mint.addMint(url, { trusted: true })`
2. **Trust Mint**: Automatically trusted when added (or via `coco.mint.trustMint()`)
3. **Select Mint**: Set as active mint → `setActiveMintUrl(url)`
4. **Remove Mint**: Delete from repository → `repositories.mintRepository.deleteMint(url)`
### Mint States
- **Known**: Mint exists in repository (from `getAllMints()`)
- **Trusted**: Mint is trusted (from `isTrustedMint()`)
- **Active**: Currently selected mint (stored in state and localStorage)
### Mint Synchronization
- When user logs into npub.cash, mint URL is fetched and set as active
- When user manually selects a mint, it's synced to npub.cash (if logged in)
- Active mint URL is persisted to localStorage
## Transaction Operations
### Send Operations
#### Token Send
```typescript
const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
// Show QR code modal with token
```
#### Lightning Invoice Payment
```typescript
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
```
#### Lightning Address Payment
```typescript
// 1. Resolve address to invoice
const invoice = await getLightningInvoice({ lightningAddress, amountSats });
// 2. Pay invoice
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
```
### Receive Operations
#### Token Receive
```typescript
await coco.wallet.receive(token);
// Automatically handles unknown mints
```
#### Lightning Invoice Creation
```typescript
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// quote.request is the Lightning invoice
// Show QR code modal
// Listen for 'mint-quote:redeemed' event
```
## Integration Points
### npub.cash Integration
**Purpose**: Provides Lightning addresses and quote synchronization.
**Flow**:
1. User logs in with Nostr → `useNIP98` provides signer
2. `useNpubCash` creates `NPCClient` with JWT auth
3. On login, fetch user info → get mint URL and Lightning address
4. Set mint URL as active mint (if not already set)
5. Subscribe to quote updates → sync quotes to wallet
**Key Files**:
- `useNpubCash.ts` - API client and sync logic
- `useNIP98.ts` - NIP-98 authentication (not shown, but referenced)
### QR Code Integration
**Flow**:
1. User clicks scan button → opens `QRScanner` modal
2. Camera starts → `html5-qrcode` scans
3. QR code detected → `classifyQRCode()` classifies type
4. Result routed to appropriate handler:
- `lightning_invoice` → `handleQRResult()` → sets invoice
- `lightning_address` → `handleQRResult()` → sets address
- `cashu_token` → `handleQRResult()` → sets token input
- `bitcoin_address` → handled by BitcoinWallet
- `npub` → handled by BitcoinWallet
### Exchange Rate Service
**Purpose**: Provides BTC/USD conversion for balance display.
**Usage**:
```typescript
import { exchangeRateService } from '@/lib/exchangeRateService';
const rate = await exchangeRateService.getBtcUsdRate();
const usdAmount = await exchangeRateService.satsToUsd(sats);
```
**Features**:
- 1-minute cache to avoid excessive API calls
- Fallback to stale cache on error
- Coinbase API integration
## Extension Guidelines
### Error Handling Patterns
**Toast Notifications**:
```typescript
try {
await operation();
toast({
title: 'Success',
description: 'Operation completed successfully',
});
} catch (err) {
toast({
variant: 'destructive',
title: 'Error',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
```
**Unknown Mint Handling**:
```typescript
try {
await coco.wallet.receive(token);
} catch (err) {
if (isUnknownMintError(err)) {
const mintUrl = extractMintUrlFromError(err);
if (mintUrl) {
await coco.mint.addMint(mintUrl, { trusted: true });
await coco.wallet.receive(token); // Retry
}
}
}
```
## Best Practices
### State Management
1. **Use refs for initialization tracking**: Prevents duplicate requests
```typescript
const hasFetchedRef = useRef(false);
if (hasFetchedRef.current) return;
hasFetchedRef.current = true;
```
2. **Persist important state**: Use `useLocalStorage` for user preferences
```typescript
const [storedValue, setStoredValue] = useLocalStorage('key', defaultValue);
```
3. **Clean up state on unmount**: Reset state when drawers/modals close
```typescript
const handleClose = (open: boolean) => {
setModalOpen(open);
if (!open) {
// Reset all related state
setInput('');
setPending(null);
}
};
```
### Event Listeners
1. **Always unsubscribe**: Clean up event listeners in useEffect return
```typescript
useEffect(() => {
const unsubscribe = coco.on('event', handler);
return () => unsubscribe();
}, [coco]);
```
2. **Store unsubscribe functions**: Use refs for complex cleanup
```typescript
const unsubscribeRef = useRef<(() => void) | null>(null);
useEffect(() => {
unsubscribeRef.current = coco.on('event', handler);
return () => {
if (unsubscribeRef.current) {
unsubscribeRef.current();
}
};
}, [coco]);
```
### Type Safety
1. **Use types from coco-cashu-core**: Import types from the library
```typescript
import type { Manager, HistoryEntry, Mint } from 'coco-cashu-core';
```
2. **Validate inputs**: Check types and values before operations
```typescript
const amount = parseInt(input);
if (isNaN(amount) || amount <= 0) {
toast({ variant: 'destructive', title: 'Invalid amount' });
return;
}
```
## Common Patterns Reference
### Mint Check Pattern
```typescript
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
if (isKnown) {
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
if (!isTrusted) {
await coco.mint.trustMint(mintUrl);
}
} else {
await coco.mint.addMint(mintUrl, { trusted: true });
}
```
### Quote Sync Pattern
```typescript
// Group quotes by mint
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
// Process each mint
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
// Ensure mint exists and is trusted
// Add quotes
coco.quotes.addMintQuote(mintUrl, mintQuotes.map(q => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})));
}
```
## File Organization
```
src/
├── components/
│ └── wallet/
│ ├── CashuWallet.tsx # Main orchestrator
│ ├── WalletHeader.tsx # Balance and controls
│ ├── PaymentCard.tsx # Send/receive UI
│ ├── MintSelector.tsx # Mint dropdown
│ ├── TransactionHistory.tsx # History display
│ ├── ProofBreakdownModal.tsx # Token breakdown
│ ├── RemoveMintModal.tsx # Mint removal confirmation
│ ├── SeedPhraseModal.tsx # Seed phrase restore
│ └── QRScanner.tsx # QR code scanner
├── hooks/
│ └── wallet/
│ ├── useCashu.ts # Core wallet manager
│ ├── useMintManager.ts # Mint operations
│ ├── useTokenOperations.ts # Token send/receive
│ ├── useLightningOperations.ts # Lightning operations
│ ├── useLightningAddress.ts # LNURL resolution
│ ├── useNpubCash.ts # npub.cash API
│ ├── useQRCode.ts # QR code operations
│ ├── useHistoryManager.ts # Transaction history
│ └── useSeedPhraseRestore.ts # Seed phrase restore
└── lib/
├── bolt11Decoder.ts # Lightning invoice decoding
└── exchangeRateService.ts # BTC/USD exchange rates
```
## Additional Resources
- **coco-cashu-core**: Main Cashu library documentation
- **npubcash-sdk**: npub.cash API SDK documentation
- **LNURL-pay**: Lightning address protocol specification
- **BOLT11**: Lightning invoice format specification
-54
View File
@@ -1,54 +0,0 @@
# Adding Nostr 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"
/>
```
-438
View File
@@ -1,438 +0,0 @@
### Direct Messaging on Nostr
This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, - more - private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent - cache first - local storage.
## Quick Start
### 1. Enable Direct Messaging
The `DMProvider` is already added to your app, but **disabled by default**. To enable messaging, pass `enabled: true` in the config:
```tsx
import { DMProvider } from '@/contexts/DMContext';
import { PROTOCOL_MODE } from '@/lib/dmConstants';
function App() {
return (
<DMProvider config={{
enabled: true, // Enable the DM system
protocolMode: PROTOCOL_MODE.NIP17_ONLY
}}>
{/* Your app components */}
</DMProvider>
);
}
```
**Config Options:**
- `enabled` (boolean, default: `false`) - Enable/disable entire DM system. When false, no messages are loaded, stored, or processed.
- `protocolMode` (ProtocolMode, default: `PROTOCOL_MODE.NIP17_ONLY`) - Which protocols to support:
- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
- `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended)
- `PROTOCOL_MODE.BOTH` - Support both protocols (for backwards compatibility)
**Note**: The DM system uses domain-based IndexedDB naming (`nostr-dm-store-${hostname}`) to prevent conflicts between multiple apps on the same domain.
### 2. Send Messages
```tsx
import { useDMContext } from '@/contexts/DMContext';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
const { sendMessage } = useDMContext();
const [content, setContent] = useState('');
const handleSend = async () => {
await sendMessage({
recipientPubkey,
content,
protocol: MESSAGE_PROTOCOL.NIP17, // Uses NIP-44 encryption + gift wrapping
});
setContent('');
};
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
/>
<button type="submit">Send</button>
</form>
);
}
```
### 3. Display Conversations
```tsx
import { useDMContext } from '@/contexts/DMContext';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function ConversationList({ onSelectConversation }: { onSelectConversation: (pubkey: string) => void }) {
const { conversations, isLoading } = useDMContext();
if (isLoading) {
return <div>Loading conversations...</div>;
}
return (
<div className="space-y-2">
{conversations.map((conversation) => (
<ConversationItem
key={conversation.pubkey}
conversation={conversation}
onClick={() => onSelectConversation(conversation.pubkey)}
/>
))}
</div>
);
}
function ConversationItem({ conversation, onClick }: {
conversation: ConversationSummary;
onClick: () => void;
}) {
const author = useAuthor(conversation.pubkey);
const displayName = author.data?.metadata?.name || genUserName(conversation.pubkey);
const avatarUrl = author.data?.metadata?.picture;
return (
<button onClick={onClick} className="w-full p-3 hover:bg-accent rounded-lg">
<div className="flex items-center gap-3">
<Avatar>
<AvatarImage src={avatarUrl} />
<AvatarFallback>{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 text-left">
<div className="font-medium">{displayName}</div>
<div className="text-sm text-muted-foreground truncate">
{conversation.lastMessage?.decryptedContent || 'No messages yet'}
</div>
</div>
</div>
</button>
);
}
```
### 4. Display Messages in a Conversation
```tsx
import { useConversationMessages } from '@/contexts/DMContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
const { user } = useCurrentUser();
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(conversationPubkey);
return (
<div className="flex flex-col space-y-2">
{hasMoreMessages && (
<button onClick={loadEarlierMessages} className="text-sm text-muted-foreground">
Load earlier messages
</button>
)}
{messages.map((message) => {
const isFromMe = message.pubkey === user?.pubkey;
return (
<div
key={message.id}
className={cn(
"flex",
isFromMe ? "justify-end" : "justify-start"
)}
>
<div className={cn(
"max-w-[70%] rounded-lg px-4 py-2",
isFromMe ? "bg-primary text-primary-foreground" : "bg-muted"
)}>
{message.error ? (
<span className="text-red-500">🔒 {message.error}</span>
) : (
<p className="whitespace-pre-wrap break-words">
{message.decryptedContent}
</p>
)}
{message.isSending && (
<span className="text-xs opacity-50">Sending...</span>
)}
</div>
</div>
);
})}
</div>
);
}
```
## Using the Complete Messaging Interface
For a fully-featured messaging UI out of the box, use the `DMMessagingInterface` component:
```tsx
import { DMMessagingInterface } from "@/components/dm/DMMessagingInterface";
function MessagesPage() {
return (
<div className="container mx-auto p-4 h-screen">
<DMMessagingInterface />
</div>
);
}
```
The `DMMessagingInterface` component provides a complete messaging UI with:
- Conversation list with Active/Requests tabs
- Message thread view with pagination
- Compose area with file upload support
- Real-time message updates
- Mobile-responsive layout (shows one panel at a time on mobile)
It requires no props and works automatically when wrapped in `DMProvider`.
**For custom layouts**, see the "Building Custom Messaging UIs" section below for individual components (`DMConversationList`, `DMChatArea`, `DMStatusInfo`).
## Sending Files with Messages
```tsx
import { useDMContext, type FileAttachment } from '@/contexts/DMContext';
import { useUploadFile } from '@/hooks/useUploadFile';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
const { sendMessage } = useDMContext();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const [content, setContent] = useState('');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const handleSend = async () => {
let attachments: FileAttachment[] | undefined;
// Upload file if one is selected
if (selectedFile) {
const tags = await uploadFile(selectedFile);
attachments = [{
url: tags[0][1], // URL from first tag
mimeType: selectedFile.type,
size: selectedFile.size,
name: selectedFile.name,
tags: tags
}];
}
await sendMessage({
recipientPubkey,
content,
protocol: MESSAGE_PROTOCOL.NIP17,
attachments,
});
setContent('');
setSelectedFile(null);
};
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
/>
<input
type="file"
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
/>
{selectedFile && <div>Selected: {selectedFile.name}</div>}
<button type="submit" disabled={isUploading}>
{isUploading ? 'Uploading...' : 'Send'}
</button>
</form>
);
}
```
## Protocol Comparison
### NIP-04 (Legacy)
- **Encryption**: NIP-04 (simpler, older)
- **Metadata**: Sender and recipient visible to relays
- **Event Kind**: Kind 4
- **Use When**: Compatibility with older clients
### NIP-17 (Modern & Private)
- **Encryption**: NIP-44 (stronger)
- **Metadata**: Hidden via gift wrapping (NIP-59)
- **Event Kinds**: Kind 14 (text), Kind 15 (files)
- **Wrapped In**: Kind 1059 (Gift Wrap) with ephemeral keys
- **Use When**: Maximum privacy (recommended)
**Key Privacy Features of NIP-17:**
- Sender identity hidden (uses random ephemeral keys)
- Timestamps randomized (±2 days) to hide send time
- Dual gift wraps (recipient + sender) for message history
## Advanced Features
### Conversation Categorization
The system automatically categorizes conversations:
```tsx
const { conversations } = useDMContext();
// Filter by category
const knownConversations = conversations.filter(c => c.isKnown);
const requestConversations = conversations.filter(c => c.isRequest);
// isKnown = true if user has sent at least one message
// isRequest = true if only received messages, never replied
```
### Loading States
```tsx
const { isLoading, loadingPhase, scanProgress } = useDMContext();
// Check overall loading state
if (isLoading) {
console.log('Current phase:', loadingPhase);
// LOADING_PHASES.CACHE - Loading from local cache
// LOADING_PHASES.RELAYS - Querying relays
// LOADING_PHASES.SUBSCRIPTIONS - Setting up real-time updates
// LOADING_PHASES.READY - Fully loaded
}
// Display scan progress for large message histories
if (scanProgress.nip17) {
console.log(`NIP-17: ${scanProgress.nip17.current} messages - ${scanProgress.nip17.status}`);
}
```
### Clear Cache and Refresh
```tsx
import { useDMContext } from '@/contexts/DMContext';
function SettingsButton() {
const { clearCacheAndRefetch } = useDMContext();
const handleClearCache = async () => {
await clearCacheAndRefetch();
// Clears IndexedDB cache and reloads all messages from relays
};
return (
<button onClick={handleClearCache}>
Clear Message Cache
</button>
);
}
```
## Architecture Notes
### Data Flow
1. **Cache First**: Messages load instantly from encrypted IndexedDB cache
2. **Background Sync**: New messages fetched from relays in parallel
3. **Real-time Updates**: WebSocket subscriptions for live messages
4. **Optimistic UI**: Sent messages appear immediately, confirmed on relay response
### Storage
- **IndexedDB**: All messages stored locally with NIP-44 encryption
- **Per-User Storage**: Separate encrypted store for each logged-in user
- **Automatic Sync**: Debounced writes (15s) + immediate on new messages
### Performance
- **Parallel Queries**: NIP-04 and NIP-17 messages fetched simultaneously
- **Batched Loading**: Messages loaded in batches (1000/batch, 20k limit)
- **Pagination**: Conversation messages paginated (25/page)
- **Deduplication**: Automatic filtering of duplicate messages by ID
### Security
- **NIP-44 Encryption**: Modern authenticated encryption for all NIP-17 messages
- **Local Encryption**: IndexedDB storage encrypted with user's NIP-44 key
- **Ephemeral Keys**: Random keys for NIP-17 gift wraps (sender anonymity)
- **No Plaintext**: Decrypted content never persisted unencrypted
- **Domain Isolation**: IndexedDB databases are namespaced by hostname to prevent data conflicts
## Building Custom Messaging UIs
For advanced use cases, you can use the individual DM components to build custom layouts:
### Available Components
**`DMConversationList`** - Conversation sidebar with tabs
```tsx
import { DMConversationList } from '@/components/dm/DMConversationList';
<DMConversationList
selectedPubkey={selectedPubkey}
onSelectConversation={(pubkey) => setSelectedPubkey(pubkey)}
onStatusClick={() => setShowStatus(true)} // optional
className="h-full"
/>
```
**`DMChatArea`** - Message thread and compose area
```tsx
import { DMChatArea } from '@/components/dm/DMChatArea';
<DMChatArea
pubkey={selectedPubkey}
onBack={() => setSelectedPubkey(null)} // optional, for mobile back button
className="h-full"
/>
```
**`DMStatusInfo`** - Debug/status panel
```tsx
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
```
### Custom Layout Example
```tsx
import { useState } from 'react';
import { DMConversationList } from '@/components/dm/DMConversationList';
import { DMChatArea } from '@/components/dm/DMChatArea';
function CustomMessagingLayout() {
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
return (
<div className="flex h-screen">
{/* Custom sidebar */}
<aside className="w-64 border-r">
<DMConversationList
selectedPubkey={selectedPubkey}
onSelectConversation={setSelectedPubkey}
/>
</aside>
{/* Custom main area */}
<main className="flex-1">
{selectedPubkey ? (
<DMChatArea pubkey={selectedPubkey} />
) : (
<div className="flex items-center justify-center h-full">
<p>Select a conversation to start messaging</p>
</div>
)}
</main>
</div>
);
}
```
-72
View File
@@ -1,72 +0,0 @@
### Infinite Scroll for Nostr Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
```typescript
import { useNostr } from '@nostrify/react';
import { useInfiniteQuery } from '@tanstack/react-query';
export function useGlobalFeed() {
const { nostr } = useNostr();
return useInfiniteQuery({
queryKey: ['global-feed'],
queryFn: async ({ pageParam, signal }) => {
const filter = { kinds: [1], limit: 20 };
if (pageParam) filter.until = pageParam;
const events = await nostr.query([filter], {
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
});
return events;
},
getNextPageParam: (lastPage) => {
if (lastPage.length === 0) return undefined;
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
},
initialPageParam: undefined,
});
}
```
Example usage with intersection observer for automatic loading:
```tsx
import { useInView } from 'react-intersection-observer';
import { useMemo } from 'react';
function GlobalFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
// Remove duplicate events by ID
const posts = useMemo(() => {
const seen = new Set();
return data?.pages.flat().filter(event => {
if (!event.id || seen.has(event.id)) return false;
seen.add(event.id);
return true;
}) || [];
}, [data?.pages]);
return (
<div className="space-y-4">
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
{hasNextPage && (
<div ref={ref} className="py-4">
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
</div>
)}
</div>
);
}
```
-146
View File
@@ -1,146 +0,0 @@
# Custom ESLint Rules
This directory contains custom ESLint rules for the project.
## no-inline-script
This rule prevents the use of inline script tags in HTML files. Inline scripts can pose security risks and violate Content Security Policy (CSP) directives.
### Examples
❌ **Bad** - These will trigger the rule:
```html
<!-- Inline JavaScript code -->
<script>
console.log("This is inline JavaScript");
</script>
<!-- Inline JSON-LD structured data -->
<script type="application/ld+json">
{"@context": "https://schema.org", "@type": "Organization"}
</script>
```
✅ **Good** - These are fine:
```html
<!-- External script files -->
<script src="/js/app.js"></script>
<script type="module" src="/src/main.tsx"></script>
<!-- Empty script tags (no content) -->
<script id="data-container"></script>
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/no-inline-script": "error"
```
### Purpose
This rule helps maintain security best practices by:
- Preventing XSS vulnerabilities from inline scripts
- Enforcing Content Security Policy compliance
- Encouraging separation of concerns (HTML structure vs JavaScript logic)
- Making code easier to maintain and debug
## no-placeholder-comments
This rule detects and flags comments that start with "// In a real" (case-insensitive). These comments typically indicate placeholder implementations that should be replaced with real code.
### Examples
❌ **Bad** - These will trigger the rule:
```javascript
// In a real application, this would connect to a database
const data = [];
// in a real world scenario, this would be different
const config = {};
/* In a real implementation, we would handle errors */
const handleError = () => {};
```
✅ **Good** - These are fine:
```javascript
// This is a regular comment
const data = [];
// TODO: Implement database connection
const config = {};
// Note: In a real application, consider using a database
const handleError = () => {};
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/no-placeholder-comments": "error"
```
You can change the severity level to:
- `"off"` - Disable the rule
- `"warn"` - Show as warning
- `"error"` - Show as error (current setting)
### Purpose
This rule helps ensure that placeholder comments used during development are replaced with actual implementations before code is committed or deployed to production.
## require-webmanifest
This rule ensures that HTML files include a proper web manifest link tag and that the referenced manifest file exists. Web manifests are essential for Progressive Web Apps (PWAs) and provide metadata about the application.
### Examples
❌ **Bad** - These will trigger the rule:
```html
<!-- Missing manifest link entirely -->
<head>
<title>My App</title>
</head>
<!-- Manifest file doesn't exist -->
<head>
<link rel="manifest" href="/nonexistent-manifest.json">
</head>
<!-- Invalid manifest link (missing rel or href) -->
<head>
<link href="/manifest.json">
</head>
```
✅ **Good** - These are fine:
```html
<!-- Proper manifest link with existing file -->
<head>
<link rel="manifest" href="/manifest.json">
</head>
<!-- Alternative valid manifest link -->
<head>
<link rel="manifest" href="/public/site.webmanifest">
</head>
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/require-webmanifest": "error"
```
### Purpose
This rule helps ensure:
- PWA compliance by requiring a web manifest
- Proper manifest file structure and accessibility
- Better user experience on mobile devices
- App installation capabilities
- Consistent branding and metadata across platforms
-11
View File
@@ -1,11 +0,0 @@
import noInlineScript from './no-inline-script.js';
import noPlaceholderComments from './no-placeholder-comments.js';
import requireWebmanifest from './require-webmanifest.js';
export default {
rules: {
'no-inline-script': noInlineScript,
'no-placeholder-comments': noPlaceholderComments,
'require-webmanifest': requireWebmanifest,
},
};
-40
View File
@@ -1,40 +0,0 @@
/**
* Rule to prevent inline script tags in HTML files
*/
export default {
meta: {
type: 'problem',
docs: {
description: 'Prevent inline script tags in HTML files',
category: 'Security',
recommended: true,
},
fixable: null,
schema: [],
messages: {
noInlineScript: 'Inline script tags are not allowed. Move script content to external files.',
},
},
create(context) {
return {
// For HTML files, we need to check script tags
'ScriptTag'(node) {
// Check if this is an inline script (has content but no src attribute)
const hasContent = node.value && node.value.value && node.value.value.trim().length > 0;
const hasSrc = node.attributes && node.attributes.some(attr =>
attr.key && attr.key.value === 'src'
);
// If the script has content but no src attribute, it's an inline script
if (hasContent && !hasSrc) {
context.report({
node,
messageId: 'noInlineScript',
});
}
},
};
},
};
-45
View File
@@ -1,45 +0,0 @@
/**
* Custom ESLint rule to detect placeholder comments starting with "// In a real"
* These comments indicate incomplete implementations that should be replaced with real code.
*/
export default {
meta: {
type: "problem",
docs: {
description: "Disallow placeholder comments starting with '// In a real'",
category: "Best Practices",
recommended: true,
},
fixable: null,
schema: [],
messages: {
placeholderComment: "Placeholder comment detected: '{{comment}}'. This should be replaced with a real implementation.",
},
},
create(context) {
const sourceCode = context.getSourceCode();
return {
Program() {
const comments = sourceCode.getAllComments();
comments.forEach((comment) => {
const commentText = comment.value.trim();
// Check if comment starts with "In a real" (case-insensitive)
if (commentText.toLowerCase().startsWith("in a real")) {
context.report({
node: comment,
messageId: "placeholderComment",
data: {
comment: `// ${commentText}`,
},
});
}
});
},
};
},
};
-84
View File
@@ -1,84 +0,0 @@
import fs from 'fs';
import path from 'path';
export default {
meta: {
type: 'problem',
docs: {
description: 'Require web manifest file and proper HTML link tag',
category: 'Best Practices',
},
fixable: null,
schema: [],
messages: {
missingManifestFile: 'Web manifest file not found. Expected {{expectedPath}}',
missingManifestLink: 'Missing web manifest link tag in HTML head',
invalidManifestLink: 'Web manifest link tag has incorrect rel or href attribute',
},
},
create(context) {
const filename = context.getFilename();
// Only run this rule on HTML files
if (!filename.endsWith('.html')) {
return {};
}
return {
Program(node) {
const sourceCode = context.getSourceCode();
const htmlContent = sourceCode.getText();
// Check for manifest link tag in HTML
const manifestLinkRegex = /<link[^>]*rel=["']manifest["'][^>]*>/i;
const manifestMatch = htmlContent.match(manifestLinkRegex);
if (!manifestMatch) {
context.report({
node,
messageId: 'missingManifestLink',
});
return;
}
// Extract href from the manifest link
const hrefMatch = manifestMatch[0].match(/href=["']([^"']+)["']/i);
if (!hrefMatch) {
context.report({
node,
messageId: 'invalidManifestLink',
});
return;
}
const manifestPath = hrefMatch[1];
// Resolve the manifest file path relative to the project root
const htmlDir = path.dirname(filename);
let resolvedManifestPath;
if (manifestPath.startsWith('/')) {
// Absolute path - check in public directory first, then project root
const publicPath = path.resolve(htmlDir, 'public' + manifestPath);
const rootPath = path.resolve(htmlDir, '.' + manifestPath);
resolvedManifestPath = fs.existsSync(publicPath) ? publicPath : rootPath;
} else {
// Relative path
resolvedManifestPath = path.resolve(htmlDir, manifestPath);
}
// Check if the manifest file exists
if (!fs.existsSync(resolvedManifestPath)) {
context.report({
node,
messageId: 'missingManifestFile',
data: {
expectedPath: manifestPath,
},
});
}
},
};
},
};
+1 -47
View File
@@ -3,9 +3,6 @@ import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import htmlEslint from "@html-eslint/eslint-plugin";
import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist"] },
@@ -16,14 +13,9 @@ export default tseslint.config(
ecmaVersion: 2020,
globals: globals.browser,
},
linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
"custom": customRules,
},
rules: {
...reactHooks.configs.recommended.rules,
@@ -31,45 +23,7 @@ export default tseslint.config(
"warn",
{ allowConstantExport: true },
],
"@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true,
},
],
"custom/no-placeholder-comments": "error",
"no-warning-comments": [
"error",
{ terms: ["fixme"] },
],
},
},
{
files: ["**/*.html"],
plugins: {
"@html-eslint": htmlEslint,
"custom": customRules,
},
languageOptions: {
parser: htmlParser,
},
rules: {
"@html-eslint/require-title": "error",
"@html-eslint/require-meta-charset": "error",
"@html-eslint/require-meta-description": "error",
"@html-eslint/require-meta-viewport": "error",
"@html-eslint/require-open-graph-protocol": [
"error",
[
"og:type",
"og:title",
"og:description",
],
],
"custom/no-inline-script": "error",
"custom/require-webmanifest": "error",
"@typescript-eslint/no-unused-vars": "off",
},
}
);
+2 -8
View File
@@ -2,14 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<title>NutStack</title>
<meta name="description" content="A Bitcoin wallet powered by Nostr">
<meta property="og:type" content="website">
<meta property="og:title" content="NutStack">
<meta property="og:description" content="A Bitcoin wallet powered by Nostr">
<link rel="manifest" href="/manifest.webmanifest">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>mkstack</title>
</head>
<body>
<div id="root"></div>
+3056 -5630
View File
File diff suppressed because it is too large. Load diff
+12 -36
View File
@@ -4,18 +4,17 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"deploy": "npm i --silent && npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
"dev": "npm i && vite",
"build": "npm i && vite build",
"build:dev": "npm i && vite build --mode development",
"ci": "npm i && tsc --noEmit && vite build",
"lint": "npm i && eslint .",
"preview": "npm i && vite preview"
},
"dependencies": {
"@bitcoinerlab/secp256k1": "^1.2.0",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.44.0",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.1",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -43,67 +42,44 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@scure/bip39": "^2.0.0",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"@vulpemventures/secp256k1-zkp": "^3.2.1",
"bitcoinjs-lib": "^7.0.0",
"boltz-core": "^3.0.0",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"coco-cashu-core": "1.0.0-rc.17",
"coco-cashu-indexeddb": "1.0.0-rc.17",
"date-fns": "^3.6.0",
"ecpair": "^3.0.0",
"embla-carousel-react": "^8.3.0",
"idb": "^8.0.3",
"html5-qrcode": "^2.3.8",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"npubcash-sdk": "^0.2.0",
"qrcode": "^1.5.4",
"next-themes": "^0.3.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
"recharts": "^2.12.7",
"sonner": "^1.5.0",
"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",
"@html-eslint/eslint-plugin": "^0.41.0",
"@html-eslint/parser": "^0.41.0",
"@tailwindcss/typography": "^0.5.15",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
"@webbtc/webln-types": "^3.0.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"jsdom": "^26.1.0",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.11",
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
"vite": "^6.3.5",
"vitest": "^3.1.4"
"vite": "^5.4.1"
}
}
-1
View File
@@ -1 +0,0 @@
/* /index.html 200
-2
View File
@@ -1,2 +0,0 @@
User-agent: *
Allow: /
+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]>
+42
View File
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
-8
View File
@@ -1,8 +0,0 @@
import { render } from '@testing-library/react';
import { test } from 'vitest';
import App from './App';
test('App', () => {
render(<App />);
})
+20 -58
View File
@@ -1,26 +1,17 @@
// NOTE: This file should normally not be modified unless you are adding a new provider.
// To add new routes, edit the AppRouter.tsx file.
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import NostrProvider from '@/components/NostrProvider'
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { DMProvider, type DMConfig } from '@/contexts/DMContext';
import { AppConfig } from '@/contexts/AppContext';
import { PROTOCOL_MODE } from '@/lib/dmConstants';
import AppRouter from './AppRouter';
const head = createHead({
plugins: [
InferSeoMetaPlugin(),
],
});
// AI: do not modify this relay list
const defaultRelays = [
'wss://relay.damus.io',
'wss://relay.nostr.band',
'wss://ditto.pub/relay',
];
const queryClient = new QueryClient({
defaultOptions: {
@@ -32,51 +23,22 @@ const queryClient = new QueryClient({
},
});
const defaultConfig: AppConfig = {
theme: "system",
relayUrl: "wss://relay.ditto.pub",
};
const presetRelays = [
{ url: 'wss://relay.ditto.pub', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
const dmConfig: DMConfig = {
// Enable or disable DMs entirely
enabled: true, // Set to false to completely disable messaging functionality
// Choose one protocol mode:
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
// PROTOCOL_MODE.NIP04_OR_NIP17 - Allow users to choose between NIP-04 and NIP-17 (defaults to NIP-17)
protocolMode: PROTOCOL_MODE.NIP04_OR_NIP17,
};
// NOTE: This file should normally not be modified unless you are adding a new provider.
// To add new routes, edit the AppRouter.tsx file.
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider relays={defaultRelays}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NWCProvider>
<DMProvider config={dmConfig}>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</DMProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<AppRouter />
</TooltipProvider>
</QueryClientProvider>
</AppProvider>
</UnheadProvider>
</NostrProvider>
</NostrLoginProvider>
);
}
-9
View File
@@ -1,22 +1,13 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import Messages from "./pages/Messages";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { WalletContainer } from "./components/wallet/WalletContainer";
export function AppRouter() {
return (
<BrowserRouter>
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/messages" element={<Messages />} />
<Route path="/wallet" element={<WalletContainer />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
-105
View File
@@ -1,105 +0,0 @@
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';
interface AppProviderProps {
children: ReactNode;
/** Application storage key */
storageKey: string;
/** Default app configuration */
defaultConfig: AppConfig;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
}) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) {
const {
children,
storageKey,
defaultConfig,
presetRelays,
} = props;
// App configuration state with localStorage persistence
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
storageKey,
{},
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.partial().parse(parsed);
}
}
);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
setConfig(updater);
};
const config = { ...defaultConfig, ...rawConfig };
const appContextValue: AppContextType = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
useApplyTheme(config.theme);
return (
<AppContext.Provider value={appContextValue}>
{children}
</AppContext.Provider>
);
}
/**
* Hook to apply theme changes to the document root
*/
function useApplyTheme(theme: Theme) {
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
.matches
? 'dark'
: 'light';
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
// Handle system theme changes when theme is set to "system"
useEffect(() => {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [theme]);
}
-349
View File
@@ -1,349 +0,0 @@
import React, { useEffect, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Loader2, Upload } from 'lucide-react';
import { NSchema as n, type NostrMetadata } from '@nostrify/nostrify';
import { useQueryClient } from '@tanstack/react-query';
import { useUploadFile } from '@/hooks/useUploadFile';
export const EditProfileForm: React.FC = () => {
const queryClient = useQueryClient();
const { user, metadata } = useCurrentUser();
const { mutateAsync: publishEvent, isPending } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const { toast } = useToast();
// Initialize the form with default values
const form = useForm<NostrMetadata>({
resolver: zodResolver(n.metadata()),
defaultValues: {
name: '',
about: '',
picture: '',
banner: '',
website: '',
nip05: '',
bot: false,
},
});
// Update form values when user data is loaded
useEffect(() => {
if (metadata) {
form.reset({
name: metadata.name || '',
about: metadata.about || '',
picture: metadata.picture || '',
banner: metadata.banner || '',
website: metadata.website || '',
nip05: metadata.nip05 || '',
bot: metadata.bot || false,
});
}
}, [metadata, form]);
// Handle file uploads for profile picture and banner
const uploadPicture = async (file: File, field: 'picture' | 'banner') => {
try {
// The first tuple in the array contains the URL
const [[_, url]] = await uploadFile(file);
form.setValue(field, url);
toast({
title: 'Success',
description: `${field === 'picture' ? 'Profile picture' : 'Banner'} uploaded successfully`,
});
} catch (error) {
console.error(`Failed to upload ${field}:`, error);
toast({
title: 'Error',
description: `Failed to upload ${field === 'picture' ? 'profile picture' : 'banner'}. Please try again.`,
variant: 'destructive',
});
}
};
const onSubmit = async (values: NostrMetadata) => {
if (!user) {
toast({
title: 'Error',
description: 'You must be logged in to update your profile',
variant: 'destructive',
});
return;
}
try {
// Combine existing metadata with new values
const data = { ...metadata, ...values };
// Clean up empty values
for (const key in data) {
if (data[key] === '') {
delete data[key];
}
}
// Publish the metadata event (kind 0)
await publishEvent({
kind: 0,
content: JSON.stringify(data),
});
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['logins'] });
queryClient.invalidateQueries({ queryKey: ['author', user.pubkey] });
toast({
title: 'Success',
description: 'Your profile has been updated',
});
} catch (error) {
console.error('Failed to update profile:', error);
toast({
title: 'Error',
description: 'Failed to update your profile. Please try again.',
variant: 'destructive',
});
}
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Your name" {...field} />
</FormControl>
<FormDescription>
This is your display name that will be displayed to others.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="about"
render={({ field }) => (
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea
placeholder="Tell others about yourself"
className="resize-none"
{...field}
/>
</FormControl>
<FormDescription>
A short description about yourself.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField
control={form.control}
name="picture"
render={({ field }) => (
<ImageUploadField
field={field}
label="Profile Picture"
placeholder="https://example.com/profile.jpg"
description="URL to your profile picture. You can upload an image or provide a URL."
previewType="square"
onUpload={(file) => uploadPicture(file, 'picture')}
/>
)}
/>
<FormField
control={form.control}
name="banner"
render={({ field }) => (
<ImageUploadField
field={field}
label="Banner Image"
placeholder="https://example.com/banner.jpg"
description="URL to a wide banner image for your profile. You can upload an image or provide a URL."
previewType="wide"
onUpload={(file) => uploadPicture(file, 'banner')}
/>
)}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField
control={form.control}
name="website"
render={({ field }) => (
<FormItem>
<FormLabel>Website</FormLabel>
<FormControl>
<Input placeholder="https://yourwebsite.com" {...field} />
</FormControl>
<FormDescription>
Your personal website or social media link.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="nip05"
render={({ field }) => (
<FormItem>
<FormLabel>NIP-05 Identifier</FormLabel>
<FormControl>
<Input placeholder="[email protected]" {...field} />
</FormControl>
<FormDescription>
Your verified Nostr identifier.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="bot"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Bot Account</FormLabel>
<FormDescription>
Mark this account as automated or a bot.
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<Button
type="submit"
className="w-full md:w-auto"
disabled={isPending || isUploading}
>
{(isPending || isUploading) && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
Save Profile
</Button>
</form>
</Form>
);
};
// Reusable component for image upload fields
interface ImageUploadFieldProps {
field: {
value: string | undefined;
onChange: (value: string) => void;
name: string;
onBlur: () => void;
};
label: string;
placeholder: string;
description: string;
previewType: 'square' | 'wide';
onUpload: (file: File) => void;
}
const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
field,
label,
placeholder,
description,
previewType,
onUpload,
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
return (
<FormItem>
<FormLabel>{label}</FormLabel>
<div className="flex flex-col gap-2">
<FormControl>
<Input
placeholder={placeholder}
name={field.name}
value={field.value ?? ''}
onChange={e => field.onChange(e.target.value)}
onBlur={field.onBlur}
/>
</FormControl>
<div className="flex items-center gap-2">
<input
type="file"
ref={fileInputRef}
accept="image/*"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) {
onUpload(file);
}
}}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
<Upload className="h-4 w-4 mr-2" />
Upload Image
</Button>
{field.value && (
<div className={`h-10 ${previewType === 'square' ? 'w-10' : 'w-24'} rounded overflow-hidden`}>
<img
src={field.value}
alt={`${label} preview`}
className="h-full w-full object-cover"
/>
</div>
)}
</div>
</div>
<FormDescription>
{description}
</FormDescription>
<FormMessage />
</FormItem>
);
};
-113
View File
@@ -1,113 +0,0 @@
import { Component, ErrorInfo, ReactNode } from 'react';
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
}
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
return {
hasError: true,
error,
};
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
this.setState({
error,
errorInfo,
});
}
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<div className="max-w-md w-full space-y-4">
<div className="text-center">
<h2 className="text-2xl font-bold text-foreground mb-2">
Something went wrong
</h2>
<p className="text-muted-foreground">
An unexpected error occurred. The error has been reported.
</p>
</div>
<div className="bg-muted p-4 rounded-lg">
<details className="text-sm">
<summary className="cursor-pointer font-medium text-foreground">
Error details
</summary>
<div className="mt-2 space-y-2">
<div>
<strong className="text-foreground">Message:</strong>
<p className="text-muted-foreground mt-1">
{this.state.error?.message}
</p>
</div>
{this.state.error?.stack && (
<div>
<strong className="text-foreground">Stack trace:</strong>
<pre className="text-xs text-muted-foreground mt-1 overflow-auto max-h-32">
{this.state.error.stack}
</pre>
</div>
)}
</div>
</details>
</div>
<div className="flex gap-2">
<button
onClick={this.handleReset}
className="flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
>
Try again
</button>
<button
onClick={() => window.location.reload()}
className="flex-1 px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 transition-colors"
>
Reload page
</button>
</div>
</div>
</div>
);
}
return this.props.children;
}
}
+5 -31
View File
@@ -1,54 +1,28 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
import React, { useRef } from 'react';
interface NostrProviderProps {
children: React.ReactNode;
relays: string[];
}
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
const queryClient = useQueryClient();
const { children, relays } = props;
// Create NPool instance only once
const pool = useRef<NPool | undefined>(undefined);
// Use refs so the pool always has the latest data
const relayUrl = useRef<string>(config.relayUrl);
// Invalidate Nostr queries when relayUrl changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.invalidateQueries({ queryKey: ['nostr'] });
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
if (!pool.current) {
pool.current = new NPool({
open(url: string) {
return new NRelay1(url);
},
reqRouter(filters) {
return new Map([[relayUrl.current, filters]]);
return new Map(relays.map((url) => [url, filters]));
},
eventRouter(_event: NostrEvent) {
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
return [...allRelays];
return relays;
},
});
}
-136
View File
@@ -1,136 +0,0 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { NoteContent } from './NoteContent';
import type { NostrEvent } from '@nostrify/nostrify';
describe('NoteContent', () => {
it('linkifies URLs in kind 1 events', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'Check out this link: https://example.com',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
const link = screen.getByRole('link', { name: 'https://example.com' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://example.com');
expect(link).toHaveAttribute('target', '_blank');
});
it('linkifies URLs in kind 1111 events (comments)', () => {
const event: NostrEvent = {
id: 'test-comment-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1111,
tags: [
['a', '30040:pubkey:identifier'],
['k', '30040'],
['p', 'pubkey'],
],
content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just b a kind 1111: https://nostrbook.dev/kinds/1111',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
const link = screen.getByRole('link', { name: 'https://nostrbook.dev/kinds/1111' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://nostrbook.dev/kinds/1111');
expect(link).toHaveAttribute('target', '_blank');
});
it('handles text without URLs correctly', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1111,
tags: [],
content: 'This is just plain text without any links.',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
expect(screen.getByText('This is just plain text without any links.')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
it('renders hashtags as links', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'This is a post about #nostr and #bitcoin development.',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
expect(nostrHashtag).toBeInTheDocument();
expect(bitcoinHashtag).toBeInTheDocument();
expect(nostrHashtag).toHaveAttribute('href', '/t/nostr');
expect(bitcoinHashtag).toHaveAttribute('href', '/t/bitcoin');
});
it('generates deterministic names for users without metadata and styles them differently', () => {
// Use a valid npub for testing
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: `Mentioning nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0`,
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
// The mention should be rendered with a deterministic name
const mention = screen.getByRole('link');
expect(mention).toBeInTheDocument();
// Should have muted styling for generated names (gray instead of blue)
expect(mention).toHaveClass('text-gray-500');
expect(mention).not.toHaveClass('text-blue-500');
// The text should start with @ and contain a generated name (not a truncated npub)
const linkText = mention.textContent;
expect(linkText).not.toMatch(/^@npub1/); // Should not be a truncated npub
expect(linkText).toEqual("@Swift Falcon");
});
});
-137
View File
@@ -1,137 +0,0 @@
import { useMemo } from 'react';
import { type NostrEvent } from '@nostrify/nostrify';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { cn } from '@/lib/utils';
interface NoteContentProps {
event: NostrEvent;
className?: string;
}
/** Parses content of text note events so that URLs and hashtags are linkified. */
export function NoteContent({
event,
className,
}: NoteContentProps) {
// Process the content to render mentions, links, etc.
const content = useMemo(() => {
const text = event.content;
// Regex to find URLs, Nostr references, and hashtags
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
const parts: React.ReactNode[] = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
let keyCounter = 0;
while ((match = regex.exec(text)) !== null) {
const [fullMatch, url, nostrPrefix, nostrData, hashtag] = match;
const index = match.index;
// Add text before this match
if (index > lastIndex) {
parts.push(text.substring(lastIndex, index));
}
if (url) {
// Handle URLs
parts.push(
<a
key={`url-${keyCounter++}`}
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline"
>
{url}
</a>
);
} else if (nostrPrefix && nostrData) {
// Handle Nostr references
try {
const nostrId = `${nostrPrefix}${nostrData}`;
const decoded = nip19.decode(nostrId);
if (decoded.type === 'npub') {
const pubkey = decoded.data;
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else {
// For other types, just show as a link
parts.push(
<Link
key={`nostr-${keyCounter++}`}
to={`/${nostrId}`}
className="text-blue-500 hover:underline"
>
{fullMatch}
</Link>
);
}
} catch {
// If decoding fails, just render as text
parts.push(fullMatch);
}
} else if (hashtag) {
// Handle hashtags
const tag = hashtag.slice(1); // Remove the #
parts.push(
<Link
key={`hashtag-${keyCounter++}`}
to={`/t/${tag}`}
className="text-blue-500 hover:underline"
>
{hashtag}
</Link>
);
}
lastIndex = index + fullMatch.length;
}
// Add any remaining text
if (lastIndex < text.length) {
parts.push(text.substring(lastIndex));
}
// If no special content was found, just use the plain text
if (parts.length === 0) {
parts.push(text);
}
return parts;
}, [event]);
return (
<div className={cn("whitespace-pre-wrap break-words", className)}>
{content.length > 0 ? content : event.content}
</div>
);
}
// Helper component to display user mentions
function NostrMention({ pubkey }: { pubkey: string }) {
const author = useAuthor(pubkey);
const npub = nip19.npubEncode(pubkey);
const hasRealName = !!author.data?.metadata?.name;
const displayName = author.data?.metadata?.name ?? genUserName(pubkey);
return (
<Link
to={`/${npub}`}
className={cn(
"font-medium hover:underline",
hasRealName
? "text-blue-500"
: "text-gray-500 hover:text-gray-700"
)}
>
@{displayName}
</Link>
);
}
-174
View File
@@ -1,174 +0,0 @@
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext";
interface RelaySelectorProps {
className?: string;
}
export function RelaySelector(props: RelaySelectorProps) {
const { className } = props;
const { config, updateConfig, presetRelays = [] } = useAppContext();
const selectedRelay = config.relayUrl;
const setSelectedRelay = (relay: string) => {
updateConfig((current) => ({ ...current, relayUrl: relay }));
};
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
// Function to normalize relay URL by adding wss:// if no protocol is present
const normalizeRelayUrl = (url: string): string => {
const trimmed = url.trim();
if (!trimmed) return trimmed;
// Check if it already has a protocol
if (trimmed.includes('://')) {
return trimmed;
}
// Add wss:// prefix
return `wss://${trimmed}`;
};
// Handle adding a custom relay
const handleAddCustomRelay = (url: string) => {
setSelectedRelay?.(normalizeRelayUrl(url));
setOpen(false);
setInputValue("");
};
// Check if input value looks like a valid relay URL
const isValidRelayInput = (value: string): boolean => {
const trimmed = value.trim();
if (!trimmed) return false;
// Basic validation - should contain at least a domain-like structure
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className={cn("justify-between", className)}
>
<div className="flex items-center gap-2">
<Wifi className="h-4 w-4" />
<span className="truncate">
{selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..."
}
</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0">
<Command>
<CommandInput
placeholder="Search relays or type URL..."
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
<CommandEmpty>
{inputValue && isValidRelayInput(inputValue) ? (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
) : (
<div className="py-6 text-center text-sm text-muted-foreground">
{inputValue ? "Invalid relay URL" : "No relay found."}
</div>
)}
</CommandEmpty>
<CommandGroup>
{presetRelays
.filter((option) =>
!inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase())
)
.map((option) => (
<CommandItem
key={option.url}
value={option.url}
onSelect={(currentValue) => {
setSelectedRelay(normalizeRelayUrl(currentValue));
setOpen(false);
setInputValue("");
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
selectedRelay === option.url ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col">
<span className="font-medium">{option.name}</span>
<span className="text-xs text-muted-foreground">{option.url}</span>
</div>
</CommandItem>
))}
{inputValue && isValidRelayInput(inputValue) && (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer border-t"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
)}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
-12
View File
@@ -1,12 +0,0 @@
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
-429
View File
@@ -1,429 +0,0 @@
import { useState, forwardRef } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X, Coins } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useNWC } from '@/hooks/useNWCContext';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/wallet/useCashu';
import { useToast } from '@/hooks/useToast';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
import type { WebLNProvider } from "@webbtc/webln-types";
interface LightningWalletModalProps {
children?: React.ReactNode;
className?: string;
}
// Extracted AddWalletContent to prevent re-renders
const AddWalletContent = forwardRef<HTMLDivElement, {
alias: string;
setAlias: (value: string) => void;
connectionUri: string;
setConnectionUri: (value: string) => void;
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
<div className="space-y-4 px-4" ref={ref}>
<div>
<Label htmlFor="alias">Wallet Name (optional)</Label>
<Input
id="alias"
placeholder="My Lightning Wallet"
value={alias}
onChange={(e) => setAlias(e.target.value)}
/>
</div>
<div>
<Label htmlFor="connection-uri">Connection URI</Label>
<Textarea
id="connection-uri"
placeholder="nostr+walletconnect://..."
value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)}
rows={3}
/>
</div>
</div>
));
AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
webln: WebLNProvider | null;
hasNWC: boolean;
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
activeConnection: string | null;
cashuBalance: number;
isCashuInitialized: boolean;
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
}>(({
webln,
hasNWC,
connections,
connectionInfo,
activeConnection,
cashuBalance,
isCashuInitialized,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Primary Payment Method - Cashu */}
<div className="space-y-3">
<h3 className="font-medium">Primary Wallet</h3>
<div className="flex items-center justify-between p-3 border rounded-lg bg-muted/30">
<div className="flex items-center gap-3">
<Coins className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Cashu Wallet</p>
<p className="text-xs text-muted-foreground">
{isCashuInitialized
? `${cashuBalance.toLocaleString()} sats available`
: "Instant Bitcoin payments"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isCashuInitialized && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={isCashuInitialized ? "default" : "secondary"} className="text-xs">
{isCashuInitialized ? "Active" : "Not Set Up"}
</Badge>
</div>
</div>
</div>
<Separator />
{/* Lightning Fallback Methods */}
<div className="space-y-3">
<h3 className="font-medium">Other Options</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">WebLN</p>
<p className="text-xs text-muted-foreground">Browser extension</p>
</div>
</div>
<div className="flex items-center gap-2">
{webln && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={webln ? "default" : "secondary"} className="text-xs">
{webln ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
{/* NWC */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Nostr Wallet Connect</p>
<p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div>
</div>
</div>
<Separator />
{/* NWC Management */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Help */}
{!isCashuInitialized && !webln && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Set up your Cashu wallet for instant payments, or install a WebLN extension/connect NWC wallet for Lightning
</p>
</div>
</>
)}
</div>
));
WalletContent.displayName = 'WalletContent';
export function LightningWalletModal({ children, className }: LightningWalletModalProps) {
const [open, setOpen] = useState(false);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [connectionUri, setConnectionUri] = useState('');
const [alias, setAlias] = useState('');
const [isConnecting, setIsConnecting] = useState(false);
const isMobile = useIsMobile();
const {
connections,
activeConnection,
connectionInfo,
addConnection,
removeConnection,
setActiveConnection
} = useNWC();
const { webln } = useWallet();
const { balances, isInitialized: isCashuInitialized } = useCashu();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
const { toast } = useToast();
const handleAddConnection = async () => {
if (!connectionUri.trim()) {
toast({
title: 'Connection URI required',
description: 'Please enter a valid NWC connection URI.',
variant: 'destructive',
});
return;
}
setIsConnecting(true);
try {
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
if (success) {
setConnectionUri('');
setAlias('');
setAddDialogOpen(false);
}
} finally {
setIsConnecting(false);
}
};
const handleRemoveConnection = (connectionString: string) => {
removeConnection(connectionString);
};
const handleSetActive = (connectionString: string) => {
setActiveConnection(connectionString);
toast({
title: 'Active wallet changed',
description: 'The selected wallet is now active for zaps.',
});
};
const walletContentProps = {
webln,
hasNWC,
connections,
connectionInfo,
activeConnection,
cashuBalance,
isCashuInitialized,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
};
const addWalletDialog = (
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Connect NWC Wallet</DialogTitle>
<DialogDescription>
Enter your connection string from a compatible wallet.
</DialogDescription>
</DialogHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<DialogFooter className="px-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
if (isMobile) {
return (
<>
<Drawer open={open} onOpenChange={setOpen}>
<DrawerTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Payment Settings
</Button>
)}
</DrawerTrigger>
<DrawerContent className="h-full">
<DrawerHeader className="text-center relative">
<DrawerClose asChild>
<Button variant="ghost" size="sm" className="absolute right-4 top-4">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
<Wallet className="h-5 w-5" />
Payment Settings
</DrawerTitle>
<DrawerDescription>
Manage wallet methods for zaps
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
<WalletContent {...walletContentProps} />
</div>
</DrawerContent>
</Drawer>
{/* Render Add Wallet as a separate Drawer for mobile */}
<Drawer open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>Connect NWC Wallet</DrawerTitle>
<DrawerDescription>
Enter your connection string from a compatible wallet.
</DrawerDescription>
</DrawerHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<div className="p-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</div>
</DrawerContent>
</Drawer>
</>
);
}
return (
<>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Payment Settings
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Payment Settings
</DialogTitle>
<DialogDescription>
Manage wallet methods for zaps
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
</DialogContent>
</Dialog>
{addWalletDialog}
</>
);
}
-565
View File
@@ -1,565 +0,0 @@
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X, Coins } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/wallet/useCashu';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
import type { WebLNProvider } from "@webbtc/webln-types";
interface ZapButtonProps {
target: Event;
className?: string;
showCount?: boolean;
zapData?: { count: number; totalSats: number; isLoading?: boolean };
}
const presetAmounts = [
{ amount: 1, icon: Sparkle },
{ amount: 50, icon: Sparkles },
{ amount: 100, icon: Zap },
{ amount: 250, icon: Star },
{ amount: 1000, icon: Rocket },
];
interface ZapContentProps {
invoice: string | null;
amount: number | string;
comment: string;
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
webln: WebLNProvider | null;
canPayWithCashu: boolean;
cashuBalance: number;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
setAmount: (amount: number | string) => void;
setComment: (comment: string) => void;
inputRef: React.RefObject<HTMLInputElement>;
zap: (amount: number, comment: string) => void;
}
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
}, ref) => (
<div ref={ref}>
{invoice ? (
<div className="flex flex-col h-full min-h-0">
{/* Payment amount display */}
<div className="text-center pt-4">
<div className="text-2xl font-bold">{amount} sats</div>
</div>
<Separator className="my-4" />
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
{/* QR Code */}
<div className="flex justify-center">
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
<CardContent className="p-0 flex justify-center">
{qrCodeUrl ? (
<img
src={qrCodeUrl}
alt="Lightning Invoice QR Code"
className="w-full h-auto aspect-square max-w-full object-contain"
/>
) : (
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
)}
</CardContent>
</Card>
</div>
{/* Invoice input */}
<div className="space-y-2 mt-4">
<Label htmlFor="invoice">Lightning Invoice</Label>
<div className="flex gap-2 min-w-0">
<Input
id="invoice"
value={invoice}
readOnly
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
onClick={(e) => e.currentTarget.select()}
/>
<Button
variant="outline"
size="icon"
onClick={handleCopy}
className="shrink-0"
>
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
{/* Payment buttons */}
<div className="space-y-3 mt-4">
{/* Primary Lightning payment button - powered by Cashu when available */}
<Button
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}}
disabled={isZapping}
className="w-full"
size="lg"
>
{canPayWithCashu ? (
<>
<Coins className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : `Pay with Cashu (${cashuBalance.toLocaleString()} sats)`}
</>
) : (
<>
<Zap className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : "Pay with Lightning"}
</>
)}
</Button>
{/* WebLN fallback button */}
{webln && (
<Button
variant="outline"
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}}
disabled={isZapping}
className="w-full"
size="lg"
>
<Zap className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : "Pay with WebLN"}
</Button>
)}
<Button
variant="outline"
onClick={openInWallet}
className="w-full"
size="lg"
>
<ExternalLink className="h-4 w-4 mr-2" />
Open in Lightning Wallet
</Button>
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
{canPayWithCashu
? "Pay Lightning invoice using your Cashu token balance, or scan QR code manually."
: "Scan the QR code or copy the invoice to pay with any Lightning wallet."
}
</div>
</div>
</div>
</div>
) : (
<>
{/* Cashu balance indicator */}
{canPayWithCashu && (
<div className="text-center mb-4 p-3 bg-muted/30 rounded-lg mx-4">
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
<Coins className="h-4 w-4" />
<span>Pay with Cashu Balance: {cashuBalance.toLocaleString()} sats</span>
</div>
</div>
)}
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
<ToggleGroup
type="single"
value={String(amount)}
onValueChange={(value) => {
if (value) {
setAmount(parseInt(value, 10));
}
}}
className="grid grid-cols-5 gap-1 w-full"
>
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
<ToggleGroupItem
key={presetAmount}
value={String(presetAmount)}
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
disabled={canPayWithCashu && presetAmount > cashuBalance}
>
<Icon className="h-4 w-4 mb-1" />
<span className="truncate">{presetAmount}</span>
</ToggleGroupItem>
))}
</ToggleGroup>
<div className="flex items-center gap-2">
<div className="h-px flex-1 bg-muted" />
<span className="text-xs text-muted-foreground">OR</span>
<div className="h-px flex-1 bg-muted" />
</div>
<Input
ref={inputRef}
id="custom-amount"
type="number"
placeholder="Custom amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="w-full text-sm"
max={canPayWithCashu ? cashuBalance : undefined}
/>
<Textarea
id="custom-comment"
placeholder="Add a comment (optional)"
value={comment}
onChange={(e) => setComment(e.target.value)}
className="w-full resize-none text-sm"
rows={2}
/>
</div>
<div className="px-4 pb-4">
<Button
onClick={handleZap}
className="w-full"
disabled={isZapping || (canPayWithCashu && (typeof amount === 'string' ? parseInt(amount, 10) : amount) > cashuBalance)}
size="default"
>
{isZapping ? (
'Creating Lightning invoice...'
) : canPayWithCashu ? (
<>
<Coins className="h-4 w-4 mr-2" />
Zap {amount} sats (Cashu → Lightning)
</>
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Zap {amount} sats
</>
)}
</Button>
</div>
</>
)}
</div>
));
ZapContent.displayName = 'ZapContent';
export function ZapButton({
target,
className = "text-xs ml-1",
showCount = true,
zapData: externalZapData
}: ZapButtonProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target?.pubkey || '');
const { toast } = useToast();
const { webln, activeNWC } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>('');
const [copied, setCopied] = useState(false);
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
const inputRef = useRef<HTMLInputElement>(null);
const isMobile = useIsMobile();
// Check if Cashu wallet is available and has balance
const canPayWithCashu = isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
// Only fetch data if not provided externally
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
webln,
activeNWC
);
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
}
}, [target]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
const generateQR = async () => {
if (!invoice) {
setQrCodeUrl('');
return;
}
try {
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
width: 512,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
if (!isCancelled) {
setQrCodeUrl(url);
}
} catch (err) {
if (!isCancelled) {
console.error('Failed to generate QR code:', err);
}
}
};
generateQR();
return () => {
isCancelled = true;
};
}, [invoice]);
const handleCopy = async () => {
if (invoice) {
await navigator.clipboard.writeText(invoice);
setCopied(true);
toast({
title: 'Invoice copied',
description: 'Lightning invoice copied to clipboard',
});
setTimeout(() => setCopied(false), 2000);
}
};
const openInWallet = () => {
if (invoice) {
const lightningUrl = `lightning:${invoice}`;
window.open(lightningUrl, '_blank');
}
};
useEffect(() => {
if (open) {
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
} else {
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
}
}, [open, setInvoice]);
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
if (canPayWithCashu && finalAmount > cashuBalance) {
toast({
title: 'Insufficient Cashu balance',
description: `You only have ${cashuBalance} sats available.`,
variant: 'destructive',
});
return;
}
zap(finalAmount, comment);
};
const contentProps = {
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
};
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
return null;
}
if (isMobile) {
return (
<Drawer
open={open}
onOpenChange={setOpen}
dismissible={true}
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
activeSnapPoint={invoice ? 0.98 : 0.98}
modal={true}
shouldScaleBackground={false}
fadeFromIndex={0}
>
<DrawerTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
<div className="flex items-center gap-1">
<Zap className="h-4 w-4" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</div>
</DrawerTrigger>
<DrawerContent
key={invoice ? 'payment' : 'form'}
className={cn(
"transition-all duration-300",
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
)}
data-testid="zap-modal"
>
<DrawerHeader className="text-center relative">
{/* Back button when showing invoice */}
{invoice && (
<Button
variant="ghost"
size="sm"
onClick={() => {
setInvoice(null);
setQrCodeUrl('');
}}
className="absolute left-4 top-4 flex items-center gap-2"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{/* Close button */}
<DrawerClose asChild>
<Button
variant="ghost"
size="sm"
className="absolute right-4 top-4"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="text-lg break-words pt-2">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DrawerTitle>
<DrawerDescription className="text-sm break-words text-center">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
canPayWithCashu
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<ZapContent {...contentProps} />
</div>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
<div className="flex items-center gap-1">
<Zap className="h-4 w-4" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</div>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
<DialogHeader>
<DialogTitle className="text-lg break-words">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DialogTitle>
<DialogDescription className="text-sm text-center break-words">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
canPayWithCashu
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DialogDescription>
</DialogHeader>
<div className="overflow-y-auto">
<ZapContent {...contentProps} />
</div>
</DialogContent>
</Dialog>
);
}
-547
View File
@@ -1,547 +0,0 @@
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X, Coins } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/wallet/useCashu';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
import type { WebLNProvider } from "@webbtc/webln-types";
interface ZapDialogProps {
target: Event;
children?: React.ReactNode;
className?: string;
}
const presetAmounts = [
{ amount: 1, icon: Sparkle },
{ amount: 50, icon: Sparkles },
{ amount: 100, icon: Zap },
{ amount: 250, icon: Star },
{ amount: 1000, icon: Rocket },
];
interface ZapContentProps {
invoice: string | null;
amount: number | string;
comment: string;
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
webln: WebLNProvider | null;
// Cashu-related props
canPayWithCashu: boolean;
cashuBalance: number;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
setAmount: (amount: number | string) => void;
setComment: (comment: string) => void;
inputRef: React.RefObject<HTMLInputElement>;
zap: (amount: number, comment: string) => void;
}
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
}, ref) => (
<div ref={ref}>
{invoice ? (
<div className="flex flex-col h-full min-h-0">
{/* Payment amount display */}
<div className="text-center pt-4">
<div className="text-2xl font-bold">{amount} sats</div>
</div>
<Separator className="my-4" />
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
{/* QR Code */}
<div className="flex justify-center">
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
<CardContent className="p-0 flex justify-center">
{qrCodeUrl ? (
<img
src={qrCodeUrl}
alt="Lightning Invoice QR Code"
className="w-full h-auto aspect-square max-w-full object-contain"
/>
) : (
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
)}
</CardContent>
</Card>
</div>
{/* Invoice input */}
<div className="space-y-2 mt-4">
<Label htmlFor="invoice">Lightning Invoice</Label>
<div className="flex gap-2 min-w-0">
<Input
id="invoice"
value={invoice}
readOnly
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
onClick={(e) => e.currentTarget.select()}
/>
<Button
variant="outline"
size="icon"
onClick={handleCopy}
className="shrink-0"
>
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
{/* Payment buttons */}
<div className="space-y-3 mt-4">
{/* Primary Lightning payment button - powered by Cashu when available */}
<Button
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}}
disabled={isZapping}
className="w-full"
size="lg"
>
{canPayWithCashu ? (
<>
<Coins className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : `Pay with Cashu (${cashuBalance.toLocaleString()} sats)`}
</>
) : (
<>
<Zap className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : "Pay with Lightning"}
</>
)}
</Button>
{/* WebLN fallback button */}
{webln && (
<Button
variant="outline"
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}}
disabled={isZapping}
className="w-full"
size="lg"
>
<Zap className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : "Pay with WebLN"}
</Button>
)}
<Button
variant="outline"
onClick={openInWallet}
className="w-full"
size="lg"
>
<ExternalLink className="h-4 w-4 mr-2" />
Open in Lightning Wallet
</Button>
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
{canPayWithCashu
? "Pay Lightning invoice using your Cashu token balance, or scan QR code manually."
: "Scan the QR code or copy the invoice to pay with any Lightning wallet."
}
</div>
</div>
</div>
</div>
) : (
<>
{/* Cashu balance indicator */}
{canPayWithCashu && (
<div className="text-center mb-4 p-3 bg-muted/30 rounded-lg mx-4">
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
<Coins className="h-4 w-4" />
<span>Pay with Cashu Balance: {cashuBalance.toLocaleString()} sats</span>
</div>
</div>
)}
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
<ToggleGroup
type="single"
value={String(amount)}
onValueChange={(value) => {
if (value) {
setAmount(parseInt(value, 10));
}
}}
className="grid grid-cols-5 gap-1 w-full"
>
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
<ToggleGroupItem
key={presetAmount}
value={String(presetAmount)}
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
disabled={canPayWithCashu && presetAmount > cashuBalance}
>
<Icon className="h-4 w-4 mb-1" />
<span className="truncate">{presetAmount}</span>
</ToggleGroupItem>
))}
</ToggleGroup>
<div className="flex items-center gap-2">
<div className="h-px flex-1 bg-muted" />
<span className="text-xs text-muted-foreground">OR</span>
<div className="h-px flex-1 bg-muted" />
</div>
<Input
ref={inputRef}
id="custom-amount"
type="number"
placeholder="Custom amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="w-full text-sm"
max={canPayWithCashu ? cashuBalance : undefined}
/>
<Textarea
id="custom-comment"
placeholder="Add a comment (optional)"
value={comment}
onChange={(e) => setComment(e.target.value)}
className="w-full resize-none text-sm"
rows={2}
/>
</div>
<div className="px-4 pb-4">
<Button
onClick={handleZap}
className="w-full"
disabled={isZapping || (canPayWithCashu && (typeof amount === 'string' ? parseInt(amount, 10) : amount) > cashuBalance)}
size="default"
>
{isZapping ? (
'Creating Lightning invoice...'
) : canPayWithCashu ? (
<>
<Coins className="h-4 w-4 mr-2" />
Zap {amount} sats (Cashu → Lightning)
</>
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Zap {amount} sats
</>
)}
</Button>
</div>
</>
)}
</div>
));
ZapContent.displayName = 'ZapContent';
export function ZapDialog({ target, children, className }: ZapDialogProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>('');
const [copied, setCopied] = useState(false);
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
const inputRef = useRef<HTMLInputElement>(null);
const isMobile = useIsMobile();
// Check if Cashu wallet is available and has balance
const canPayWithCashu = isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
}
}, [target]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
const generateQR = async () => {
if (!invoice) {
setQrCodeUrl('');
return;
}
try {
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
width: 512,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
if (!isCancelled) {
setQrCodeUrl(url);
}
} catch (err) {
if (!isCancelled) {
console.error('Failed to generate QR code:', err);
}
}
};
generateQR();
return () => {
isCancelled = true;
};
}, [invoice]);
const handleCopy = async () => {
if (invoice) {
await navigator.clipboard.writeText(invoice);
setCopied(true);
toast({
title: 'Invoice copied',
description: 'Lightning invoice copied to clipboard',
});
setTimeout(() => setCopied(false), 2000);
}
};
const openInWallet = () => {
if (invoice) {
const lightningUrl = `lightning:${invoice}`;
window.open(lightningUrl, '_blank');
}
};
useEffect(() => {
if (open) {
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
} else {
// Clean up state when dialog closes
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
}
}, [open, setInvoice]);
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
// Validate the amount
if (isNaN(finalAmount) || finalAmount <= 0) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount greater than 0.',
variant: 'destructive',
});
return;
}
if (canPayWithCashu && finalAmount > cashuBalance) {
toast({
title: 'Insufficient Cashu balance',
description: `You only have ${cashuBalance} sats available.`,
variant: 'destructive',
});
return;
}
zap(finalAmount, comment);
};
const contentProps = {
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
};
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud06 && !author?.metadata?.lud16) {
return null;
}
if (isMobile) {
// Use drawer for entire mobile flow, make it full-screen when showing invoice
return (
<Drawer
open={open}
onOpenChange={(newOpen) => {
// Reset invoice when closing
if (!newOpen) {
setInvoice(null);
setQrCodeUrl('');
}
setOpen(newOpen);
}}
dismissible={true} // Always allow dismissal via drag
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
activeSnapPoint={invoice ? 0.98 : 0.98}
modal={true}
shouldScaleBackground={false}
fadeFromIndex={0}
>
<DrawerTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DrawerTrigger>
<DrawerContent
key={invoice ? 'payment' : 'form'}
className={cn(
"transition-all duration-300",
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
)}
data-testid="zap-modal"
>
<DrawerHeader className="text-center relative">
{/* Back button when showing invoice */}
{invoice && (
<Button
variant="ghost"
size="sm"
onClick={() => {
setInvoice(null);
setQrCodeUrl('');
}}
className="absolute left-4 top-4 flex items-center gap-2"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{/* Close button */}
<DrawerClose asChild>
<Button
variant="ghost"
size="sm"
className="absolute right-4 top-4"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="text-lg break-words pt-2">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DrawerTitle>
<DrawerDescription className="text-sm break-words text-center">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
canPayWithCashu
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<ZapContent {...contentProps} />
</div>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
<DialogHeader>
<DialogTitle className="text-lg break-words">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DialogTitle>
<DialogDescription className="text-sm text-center break-words">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
canPayWithCashu
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DialogDescription>
</DialogHeader>
<div className="overflow-y-auto">
<ZapContent {...contentProps} />
</div>
</DialogContent>
</Dialog>
);
}
+12 -30
View File
@@ -1,7 +1,8 @@
// 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 { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import React from 'react';
import { ChevronDown, LogOut, UserPlus } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -10,10 +11,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { LightningWalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
interface AccountSwitcherProps {
onAddAccountClick: () => void;
@@ -24,28 +22,21 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
if (!currentUser) return null;
const getDisplayName = (account: Account): string => {
return account.metadata.name ?? genUserName(account.pubkey);
}
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'>
<AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
<AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>
<AvatarImage src={currentUser.metadata.picture} alt={currentUser.metadata.name} />
<AvatarFallback>{currentUser.metadata.name?.charAt(0)}</AvatarFallback>
</Avatar>
<div className='flex-1 text-left hidden md:block truncate'>
<p className='font-medium text-sm truncate'>{getDisplayName(currentUser)}</p>
<div className='flex-1 text-left hidden md:block'>
<p className='font-medium text-sm'>{currentUser.metadata.name}</p>
</div>
<ChevronDown className='w-4 h-4 text-muted-foreground' />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
<RelaySelector className="w-full" />
<DropdownMenuSeparator />
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => (
<DropdownMenuItem
@@ -54,25 +45,16 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Avatar className='w-8 h-8'>
<AvatarImage src={user.metadata.picture} alt={getDisplayName(user)} />
<AvatarFallback>{getDisplayName(user)?.charAt(0) || <UserIcon />}</AvatarFallback>
<AvatarImage src={user.metadata.picture} alt={user.metadata.name} />
<AvatarFallback>{user.metadata.name?.charAt(0)}</AvatarFallback>
</Avatar>
<div className='flex-1 truncate'>
<p className='text-sm font-medium'>{getDisplayName(user)}</p>
<div className='flex-1'>
<p className='text-sm font-medium'>{user.metadata.name}</p>
</div>
{user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<LightningWalletModal>
<DropdownMenuItem
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
onSelect={(e) => e.preventDefault()}
>
<Wallet className='w-4 h-4' />
<span>Payment Settings</span>
</DropdownMenuItem>
</LightningWalletModal>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+14 -28
View File
@@ -1,20 +1,15 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import React, { 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';
export interface LoginAreaProps {
className?: string;
}
export function LoginArea({ className }: LoginAreaProps) {
export function LoginArea() {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
@@ -25,31 +20,22 @@ export function LoginArea({ className }: LoginAreaProps) {
};
return (
<div className={cn("inline-flex items-center justify-center", className)}>
<>
{currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
) : (
<div className="flex gap-3 justify-center">
<Button
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
>
<UserPlus className="w-4 h-4" />
<span>Sign Up</span>
</Button>
</div>
<Button
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span>Log in</span>
</Button>
)}
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
@@ -58,6 +44,6 @@ export function LoginArea({ className }: LoginAreaProps) {
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
/>
</div>
</>
);
}
+98 -255
View File
@@ -1,15 +1,19 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect } from 'react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import React, { useEffect, useRef, useState } from 'react';
import { Shield, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import { Input } from '@/components/ui/input.tsx';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
interface LoginDialogProps {
isOpen: boolean;
@@ -18,124 +22,54 @@ interface LoginDialogProps {
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
file?: string;
extension?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const login = useLoginActions();
// Reset all state when dialog opens/closes
useEffect(() => {
if (isOpen) {
// Reset state when dialog opens
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setErrors({});
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}, [isOpen]);
const handleExtensionLogin = async () => {
const handleExtensionLogin = () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
login.extension();
onLogin();
onClose();
} catch (e: unknown) {
const error = e as Error;
console.error('Bunker login failed:', error);
console.error('Nsec login failed:', error);
} catch (error) {
console.error('Extension login failed:', error);
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
} finally {
setIsLoading(false);
}
};
const executeLogin = (key: string) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
if (!nsec.trim()) return;
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
login.nsec(nsec);
onLogin();
onClose();
// Clear the URI from memory
setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} catch (error) {
console.error('Nsec login failed:', error);
} finally {
setIsLoading(false);
}
};
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);
} finally {
setIsLoading(false);
}
@@ -145,27 +79,10 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
} else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
} else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
setNsec(content.trim());
};
reader.readAsText(file);
};
@@ -177,139 +94,57 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
}
};
const defaultTab = 'nostr' in window ? 'extension' : 'key';
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<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")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
<DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
<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 pt-2 pb-4 space-y-4 overflow-y-auto flex-1 min-h-0'>
{/* Prominent Sign Up Section */}
<div className='relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden'>
<div className='relative z-10 text-center space-y-3'>
<div className='flex justify-center items-center gap-2 mb-2'>
<Sparkles className='w-5 h-5 text-blue-600' />
<span className='font-semibold text-blue-800 dark:text-blue-200'>
New to Nostr?
</span>
</div>
<p className='text-sm text-blue-700 dark:text-blue-300'>
Create a new account to get started. It's free and open.
</p>
<Button
onClick={handleSignupClick}
className='w-full rounded-full py-3 text-base 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 border-0'
>
<UserPlus className='w-4 h-4 mr-2' />
<span>Sign Up</span>
</Button>
</div>
</div>
{/* Divider */}
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-3 bg-background text-muted-foreground'>
<span>Or log in</span>
</span>
</div>
</div>
{/* Login Methods */}
<Tabs defaultValue={defaultTab} className="w-full">
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="extension" className="flex items-center gap-2">
<Shield className="w-4 h-4" />
<span>Extension</span>
</TabsTrigger>
<TabsTrigger value="key" className="flex items-center gap-2">
<KeyRound className="w-4 h-4" />
<span>Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<Cloud className="w-4 h-4" />
<span>Bunker</span>
</TabsTrigger>
<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-3 bg-muted'>
{errors.extension && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{errors.extension}</AlertDescription>
</Alert>
)}
<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>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
<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'>
Secret Key (nsec)
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Enter your nsec
</label>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
onChange={(e) => setNsec(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<Button
className='w-full rounded-full py-3'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Log In'}
</Button>
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</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'
@@ -319,21 +154,25 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
/>
<Button
variant='outline'
className='w-full'
className='w-full dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
Upload Nsec File
</Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</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-3 bg-muted'>
<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
@@ -341,36 +180,40 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
onChange={(e) => setBunkerUri(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
{bunkerUri && !bunkerUri.startsWith('bunker://') && (
<p className='text-red-500 text-xs'>URI must start with bunker://</p>
)}
</div>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</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>
</DialogContent>
</Dialog>
);
};
);
};
export default LoginDialog;
-50
View File
@@ -1,50 +0,0 @@
import { useState } from 'react';
import { User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
export function LoginIcon() {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
const handleLogin = () => {
setLoginDialogOpen(false);
setSignupDialogOpen(false);
};
if (currentUser) {
return (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
);
}
return (
<>
<Button
onClick={() => setLoginDialogOpen(true)}
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
title="Log in"
>
<User className="!h-6 !w-6" />
</Button>
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
/>
</>
);
}
+109 -653
View File
@@ -1,704 +1,160 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState, useEffect, useRef } from 'react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
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 { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
}
const sanitizeFilename = (filename: string) => {
return filename.replace(/[^a-z0-9_.-]/gi, '_');
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
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 [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({
name: '',
about: '',
picture: ''
});
const login = useLoginActions();
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const avatarFileInputRef = useRef<HTMLInputElement>(null);
const [nsecKey, setNsecKey] = useState('');
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
setIsLoading(true);
setShowSparkles(true);
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
} catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
try {
// Generate a new private key
const privateKey = generateSecretKey();
// Convert to nsec format
const nsec = nip19.nsecEncode(privateKey);
setNsecKey(nsec);
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 = () => {
try {
// Create a blob with the key text
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
// Create a blob with the key text
const blob = new Blob([nsecKey], { type: 'text/plain' });
const url = globalThis.URL.createObjectURL(blob);
// Sanitize filename
const filename = sanitizeFilename('nostr-nsec-key.txt');
// 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();
// Create a temporary link element and trigger download
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Clean up
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Clean up immediately
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Mark as secured
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
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',
});
}
toast({
title: 'Key downloaded',
description: 'Your key has been downloaded. Keep it safe!',
});
};
const finishSignup = () => {
setStep('done');
onClose();
const finishKeySetup = () => {
try {
login.nsec(nsec);
setStep('profile');
} catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
variant: 'destructive',
});
}
toast({
title: 'Account created',
description: 'You are now logged in.',
});
};
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
// Reset file input
e.target.value = '';
// Validate file type
if (!file.type.startsWith('image/')) {
toast({
title: 'Invalid file type',
description: 'Please select an image file for your avatar.',
variant: 'destructive',
});
return;
}
// Validate file size (max 5MB)
if (file.size > 5 * 1024 * 1024) {
toast({
title: 'File too large',
description: 'Avatar image must be smaller than 5MB.',
variant: 'destructive',
});
return;
}
try {
const tags = await uploadFile(file);
// Get the URL from the first tag
const url = tags[0]?.[1];
if (url) {
setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
}
} catch {
toast({
title: 'Upload failed',
description: 'Failed to upload avatar. Please try again.',
variant: 'destructive',
});
}
};
const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try {
// Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
const metadata: Record<string, string> = {};
if (profileData.name) metadata.name = profileData.name;
if (profileData.about) metadata.about = profileData.about;
if (profileData.picture) metadata.picture = profileData.picture;
await publishEvent({
kind: 0,
content: JSON.stringify(metadata),
});
toast({
title: 'Profile Created!',
description: 'Your profile has been set up.',
});
}
// Close signup and show welcome modal
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
} catch {
toast({
title: 'Profile Setup Failed',
description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive',
});
// Still proceed to completion even if profile failed
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
}
};
const getTitle = () => {
if (step === 'welcome') return (
<span className="flex items-center justify-center gap-2">
Create Your Account
</span>
);
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
useEffect(() => {
if (isOpen) {
setStep('welcome');
setIsLoading(false);
setNsec('');
setShowSparkles(false);
setKeySecured('none');
setProfileData({ name: '', about: '', picture: '' });
}
}, [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 (
<Dialog open={isOpen} onOpenChange={onClose}>
<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")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
<DialogTitle className={cn('font-semibold text-center text-lg')}>
{getTitle()}
<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 pt-2 pb-4 space-y-4 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='grid grid-cols-1 gap-2 text-sm'>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Shield className='w-4 h-4' />
Decentralized and censorship-resistant
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<User className='w-4 h-4' />
You are in control of your data
</div>
<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 className='space-y-3'>
<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'
onClick={() => setStep('generate')}
>
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
</div>
)}
{/* Generate Step - Enhanced with animations */}
<div className='px-6 py-8 space-y-6'>
{step === 'generate' && (
<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'>
{/* Animated background elements */}
{showSparkles && (
<div className='absolute inset-0'>
{[...Array(12)].map((_, i) => (
<Sparkles
key={i}
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 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>
{!isLoading && (
<Button
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'
onClick={generateKey}
disabled={isLoading}
>
<Sparkles className='w-5 h-5 mr-2' />
Generate My Secret Key
</Button>
)}
<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>
)}
{/* Download Step - Whimsical and magical */}
{step === 'download' && (
<div className='text-center space-y-4'>
{/* Key reveal */}
<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'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
<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 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'>{nsecKey}</code>
</div>
{/* Key vault */}
{/* Security options */}
<div className='space-y-3'>
<div className='grid grid-cols-1 gap-2'>
{/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
className='w-full h-auto p-0 justify-start hover:bg-transparent'
onClick={downloadKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{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>
</Button>
</CardContent>
</Card>
</div>
{/* Continue button */}
<Button
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
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/60 to-indigo-600/60 text-muted cursor-not-allowed'
}`}
onClick={finishKeySetup}
disabled={keySecured !== 'downloaded'}
>
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
<span className="text-center leading-tight">
{keySecured === 'none' ? (
<>
Please download your key first
</>
) : (
<>
<span className="hidden sm:inline">My Key is Safe - Continue</span>
<span className="sm:hidden">Key Secured - Continue</span>
</>
)}
</span>
</Button>
</div>
</div>
)}
{/* Profile Step - Optional profile setup */}
{step === 'profile' && (
<div className='text-center space-y-4'>
{/* Profile setup 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 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
</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 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>
{/* Publishing status indicator */}
{isPublishing && (
<div className='relative p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-800'>
<div className='flex items-center justify-center gap-3'>
<div className='w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium text-blue-700 dark:text-blue-300'>
Publishing your profile...
</span>
</div>
</div>
)}
{/* Profile form */}
<div className={`space-y-4 text-left ${isPublishing ? 'opacity-50 pointer-events-none' : ''}`}>
<div className='space-y-2'>
<label htmlFor='profile-name' className='text-sm font-medium'>
Display Name
</label>
<Input
id='profile-name'
value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name'
className='rounded-lg'
disabled={isPublishing}
/>
</div>
<div className='space-y-2'>
<label htmlFor='profile-about' className='text-sm font-medium'>
Bio
</label>
<Textarea
id='profile-about'
value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...'
className='rounded-lg resize-none'
rows={3}
disabled={isPublishing}
/>
</div>
<div className='space-y-2'>
<label htmlFor='profile-picture' className='text-sm font-medium'>
Avatar
</label>
<div className='flex gap-2'>
<Input
id='profile-picture'
value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg'
className='rounded-lg flex-1'
disabled={isPublishing}
/>
<input
type='file'
accept='image/*'
className='hidden'
ref={avatarFileInputRef}
onChange={handleAvatarUpload}
/>
<Button
type='button'
variant='outline'
size='icon'
onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing}
className='rounded-lg shrink-0'
title='Upload avatar image'
>
{isUploading ? (
<div className='w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin' />
) : (
<Upload className='w-4 h-4' />
)}
</Button>
</div>
</div>
</div>
{/* Action buttons */}
<div className='space-y-3'>
<Button
className='w-full rounded-full py-4 text-base 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 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none'
onClick={() => finishSignup(false)}
disabled={isPublishing || isUploading}
>
{isPublishing ? (
<>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Creating Profile...
</>
) : (
<>
<User className='w-4 h-4 mr-2' />
Create Profile & Finish
</>
)}
</Button>
<div className='flex flex-col space-y-3'>
<Button
variant='outline'
className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
className='w-full'
onClick={downloadKey}
>
{isPublishing ? (
<>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Setting up account...
</>
) : (
'Skip for now'
)}
<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>
-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>
);
}
-408
View File
@@ -1,408 +0,0 @@
import { useState, useRef, useEffect, useCallback, memo } from 'react';
import { useConversationMessages, useDMContext } from '@/contexts/DMContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { MESSAGE_PROTOCOL, PROTOCOL_MODE, type MessageProtocol } from '@/lib/dmConstants';
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { ArrowLeft, Send, Loader2, AlertTriangle, Key, ShieldCheck } from 'lucide-react';
import { cn } from '@/lib/utils';
import { NoteContent } from '@/components/NoteContent';
import type { NostrEvent } from '@nostrify/nostrify';
interface DMChatAreaProps {
pubkey: string | null;
onBack?: () => void;
className?: string;
}
const MessageBubble = memo(({
message,
isFromCurrentUser
}: {
message: {
id: string;
pubkey: string;
kind: number;
tags: string[][];
decryptedContent?: string;
decryptedEvent?: NostrEvent;
error?: string;
created_at: number;
isSending?: boolean;
};
isFromCurrentUser: boolean;
}) => {
// For NIP-17, use inner message kind (14/15); for NIP-04, use message kind (4)
const actualKind = message.decryptedEvent?.kind || message.kind;
const isNIP4Message = message.kind === 4;
const isFileAttachment = actualKind === 15; // Kind 15 = files/attachments
// Create a NostrEvent object for NoteContent (only used for kind 15)
// For NIP-17 file attachments, use the decryptedEvent which has the actual tags
const messageEvent: NostrEvent = message.decryptedEvent || {
id: message.id,
pubkey: message.pubkey,
created_at: message.created_at,
kind: message.kind,
tags: message.tags,
content: message.decryptedContent || '',
sig: '', // Not needed for display
};
return (
<div className={cn("flex mb-4", isFromCurrentUser ? "justify-end" : "justify-start")}>
<div className={cn(
"max-w-[70%] rounded-lg px-4 py-2",
isFromCurrentUser
? "bg-primary text-primary-foreground"
: "bg-muted"
)}>
{message.error ? (
<Tooltip delayDuration={200}>
<TooltipTrigger asChild>
<p className="text-sm italic opacity-70 cursor-help">🔒 Failed to decrypt</p>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">{message.error}</p>
</TooltipContent>
</Tooltip>
) : isFileAttachment ? (
// Kind 15: Use NoteContent to render files/media with imeta tags
<div className="text-sm">
<NoteContent event={messageEvent} className="whitespace-pre-wrap break-words" />
</div>
) : (
// Kind 4 (NIP-04) and Kind 14 (NIP-17 text): Display plain text
<p className="text-sm whitespace-pre-wrap break-words">
{message.decryptedContent}
</p>
)}
<div className="flex items-center gap-2 mt-1">
<TooltipProvider>
<Tooltip delayDuration={200}>
<TooltipTrigger asChild>
<span className={cn(
"text-xs opacity-70 cursor-default",
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
)}>
{formatConversationTime(message.created_at)}
</span>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">{formatFullDateTime(message.created_at)}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<TooltipProvider>
<Tooltip delayDuration={200}>
<TooltipTrigger asChild>
<span className={cn(
"flex-shrink-0 opacity-50",
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
)}>
{message.kind === 4 ? (
<Key className="h-3 w-3" />
) : (
<ShieldCheck className="h-3 w-3" />
)}
</span>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">
{message.kind === 4 && "NIP-04 Kind 4 (Legacy DM)"}
{message.kind === 14 && "NIP-17 Kind 14 (Private Message)"}
{message.kind === 15 && "NIP-17 Kind 15 (Media)"}
{message.kind !== 4 && message.kind !== 14 && message.kind !== 15 && `Kind ${message.kind}`}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
{isNIP4Message && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex-shrink-0">
<AlertTriangle className="h-3 w-3 text-yellow-600 dark:text-yellow-500" />
</div>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">Uses outdated NIP-04 encryption</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{message.isSending && (
<Loader2 className="h-3 w-3 animate-spin opacity-70" />
)}
</div>
</div>
</div>
);
});
MessageBubble.displayName = 'MessageBubble';
const ChatHeader = ({ pubkey, onBack }: { pubkey: string; onBack?: () => void }) => {
const author = useAuthor(pubkey);
const metadata = author.data?.metadata;
const displayName = metadata?.name || genUserName(pubkey);
const avatarUrl = metadata?.picture;
const initials = displayName.slice(0, 2).toUpperCase();
return (
<div className="p-4 border-b flex items-center gap-3">
{onBack && (
<Button
variant="ghost"
size="icon"
onClick={onBack}
className="md:hidden"
>
<ArrowLeft className="h-5 w-5" />
</Button>
)}
<Avatar className="h-10 w-10">
<AvatarImage src={avatarUrl} alt={displayName} />
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<h2 className="font-semibold truncate">{displayName}</h2>
{metadata?.nip05 && (
<p className="text-xs text-muted-foreground truncate">{metadata.nip05}</p>
)}
</div>
</div>
);
};
const EmptyState = ({ isLoading }: { isLoading: boolean }) => {
return (
<div className="h-full flex items-center justify-center p-8">
<div className="text-center text-muted-foreground max-w-sm">
{isLoading ? (
<>
<Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
<p className="text-sm">Loading conversations...</p>
<p className="text-xs mt-2">
Fetching encrypted messages from relays
</p>
</>
) : (
<>
<p className="text-sm">Select a conversation to start messaging</p>
<p className="text-xs mt-2">
Your messages are encrypted and stored locally
</p>
</>
)}
</div>
</div>
);
};
export const DMChatArea = ({ pubkey, onBack, className }: DMChatAreaProps) => {
const { user } = useCurrentUser();
const { sendMessage, protocolMode, isLoading } = useDMContext();
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(pubkey || '');
const [messageText, setMessageText] = useState('');
const [isSending, setIsSending] = useState(false);
const [isLoadingMore, setIsLoadingMore] = useState(false);
// Determine default protocol based on mode
const getDefaultProtocol = () => {
if (protocolMode === PROTOCOL_MODE.NIP04_ONLY) return MESSAGE_PROTOCOL.NIP04;
if (protocolMode === PROTOCOL_MODE.NIP17_ONLY) return MESSAGE_PROTOCOL.NIP17;
if (protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17) return MESSAGE_PROTOCOL.NIP17;
// Fallback to NIP-17 for any unexpected mode
return MESSAGE_PROTOCOL.NIP17;
};
const [selectedProtocol, setSelectedProtocol] = useState<MessageProtocol>(getDefaultProtocol());
const scrollAreaRef = useRef<HTMLDivElement>(null);
// Determine if selection is allowed
const allowSelection = protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17;
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
if (scrollAreaRef.current) {
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
if (scrollContainer) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
}
}, [messages.length]);
const handleSend = useCallback(async () => {
if (!messageText.trim() || !pubkey || !user) return;
setIsSending(true);
try {
await sendMessage({
recipientPubkey: pubkey,
content: messageText.trim(),
protocol: selectedProtocol,
});
setMessageText('');
} catch (error) {
console.error('Failed to send message:', error);
} finally {
setIsSending(false);
}
}, [messageText, pubkey, user, sendMessage, selectedProtocol]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
const handleLoadMore = useCallback(async () => {
if (!scrollAreaRef.current || isLoadingMore) return;
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
if (!scrollContainer) return;
// Store current scroll position and height
const previousScrollHeight = scrollContainer.scrollHeight;
const previousScrollTop = scrollContainer.scrollTop;
setIsLoadingMore(true);
// Load more messages
loadEarlierMessages();
// Wait for DOM to update, then restore relative scroll position
setTimeout(() => {
if (scrollContainer) {
const newScrollHeight = scrollContainer.scrollHeight;
const heightDifference = newScrollHeight - previousScrollHeight;
scrollContainer.scrollTop = previousScrollTop + heightDifference;
}
setIsLoadingMore(false);
}, 0);
}, [loadEarlierMessages, isLoadingMore]);
if (!pubkey) {
return (
<Card className={cn("h-full", className)}>
<EmptyState isLoading={isLoading} />
</Card>
);
}
if (!user) {
return (
<Card className={cn("h-full flex items-center justify-center", className)}>
<div className="text-center text-muted-foreground">
<p className="text-sm">Please log in to view messages</p>
</div>
</Card>
);
}
return (
<Card className={cn("h-full flex flex-col", className)}>
<ChatHeader pubkey={pubkey} onBack={onBack} />
<ScrollArea ref={scrollAreaRef} className="flex-1 p-4">
{messages.length === 0 ? (
<div className="h-full flex items-center justify-center">
<div className="text-center text-muted-foreground">
<p className="text-sm">No messages yet</p>
<p className="text-xs mt-1">Send a message to start the conversation</p>
</div>
</div>
) : (
<div>
{hasMoreMessages && (
<div className="flex justify-center mb-4">
<Button
variant="outline"
size="sm"
onClick={handleLoadMore}
disabled={isLoadingMore}
className="text-xs"
>
{isLoadingMore ? (
<>
<Loader2 className="h-3 w-3 animate-spin mr-2" />
Loading...
</>
) : (
'Load Earlier Messages'
)}
</Button>
</div>
)}
{messages.map((message) => (
<MessageBubble
key={message.id}
message={message}
isFromCurrentUser={message.pubkey === user.pubkey}
/>
))}
</div>
)}
</ScrollArea>
<div className="p-4 border-t">
<div className="flex gap-2">
<Textarea
value={messageText}
onChange={(e) => setMessageText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type a message... (Enter to send, Shift+Enter for new line)"
className="min-h-[80px] resize-none"
disabled={isSending}
/>
<div className="flex flex-col gap-2">
<Button
onClick={handleSend}
disabled={!messageText.trim() || isSending}
size="icon"
className="h-[44px] w-[90px]"
>
{isSending ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Send className="h-5 w-5" />
)}
</Button>
<Select
value={selectedProtocol}
onValueChange={(value) => setSelectedProtocol(value as MessageProtocol)}
disabled={!allowSelection}
>
<SelectTrigger className="h-[32px] w-[90px] text-xs px-2">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={MESSAGE_PROTOCOL.NIP17} className="text-xs">
NIP-17
</SelectItem>
<SelectItem value={MESSAGE_PROTOCOL.NIP04} className="text-xs">
NIP-04
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
</Card>
);
};
-266
View File
@@ -1,266 +0,0 @@
import { useMemo, useState, memo } from 'react';
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
import { useDMContext } from '@/contexts/DMContext';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import { LOADING_PHASES } from '@/lib/dmConstants';
interface DMConversationListProps {
selectedPubkey: string | null;
onSelectConversation: (pubkey: string) => void;
className?: string;
onStatusClick?: () => void;
}
interface ConversationItemProps {
pubkey: string;
isSelected: boolean;
onClick: () => void;
lastMessage: { decryptedContent?: string; error?: string } | null;
lastActivity: number;
hasNIP4Messages: boolean;
}
const ConversationItemComponent = ({
pubkey,
isSelected,
onClick,
lastMessage,
lastActivity,
hasNIP4Messages
}: ConversationItemProps) => {
const author = useAuthor(pubkey);
const metadata = author.data?.metadata;
const displayName = metadata?.name || genUserName(pubkey);
const avatarUrl = metadata?.picture;
const initials = displayName.slice(0, 2).toUpperCase();
const lastMessagePreview = lastMessage?.error
? '🔒 Encrypted message'
: lastMessage?.decryptedContent || 'No messages yet';
// Show skeleton only for name/avatar while loading (we already have message data)
const isLoadingProfile = author.isLoading && !metadata;
return (
<button
onClick={onClick}
className={cn(
"w-full text-left p-3 rounded-lg transition-colors hover:bg-accent block overflow-hidden",
isSelected && "bg-accent"
)}
>
<div className="flex items-start gap-3 max-w-full">
{isLoadingProfile ? (
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
) : (
<Avatar className="h-10 w-10 flex-shrink-0">
<AvatarImage src={avatarUrl} alt={displayName} />
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
)}
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-2 mb-1">
<div className="flex items-center gap-1.5 min-w-0 flex-1">
{isLoadingProfile ? (
<Skeleton className="h-[1.25rem] w-24" />
) : (
<span className="font-medium text-sm truncate">{displayName}</span>
)}
{hasNIP4Messages && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex-shrink-0">
<AlertTriangle className="h-3.5 w-3.5 text-yellow-600 dark:text-yellow-500" />
</div>
</TooltipTrigger>
<TooltipContent side="left">
<p className="text-xs max-w-[200px]">Some messages use outdated NIP-04 encryption</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="text-xs text-muted-foreground whitespace-nowrap flex-shrink-0 cursor-default">
{formatConversationTime(lastActivity)}
</span>
</TooltipTrigger>
<TooltipContent side="left">
<p className="text-xs">{formatFullDateTime(lastActivity)}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<p className="text-sm text-muted-foreground truncate">
{lastMessagePreview}
</p>
</div>
</div>
</button>
);
};
const ConversationItem = memo(ConversationItemComponent);
ConversationItem.displayName = 'ConversationItem';
const ConversationListSkeleton = () => {
return (
<div className="space-y-2 p-4">
{[1, 2, 3, 4, 5].map((i) => (
<div key={i} className="flex items-start gap-3 p-3">
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
<div className="flex-1 space-y-2">
<div className="flex justify-between">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-12" />
</div>
<Skeleton className="h-3 w-full" />
</div>
</div>
))}
</div>
);
};
export const DMConversationList = ({
selectedPubkey,
onSelectConversation,
className,
onStatusClick
}: DMConversationListProps) => {
const { conversations, isLoading, loadingPhase } = useDMContext();
const [activeTab, setActiveTab] = useState<'known' | 'requests'>('known');
// Filter conversations by type
const { knownConversations, requestConversations } = useMemo(() => {
return {
knownConversations: conversations.filter(c => c.isKnown),
requestConversations: conversations.filter(c => c.isRequest),
};
}, [conversations]);
// Get the current list based on active tab
const currentConversations = activeTab === 'known' ? knownConversations : requestConversations;
// Show skeleton during initial load (cache + relays) if we have no conversations yet
const isInitialLoad = (loadingPhase === LOADING_PHASES.CACHE || loadingPhase === LOADING_PHASES.RELAYS) && conversations.length === 0;
return (
<Card className={cn("h-full flex flex-col overflow-hidden", className)}>
{/* Header - always visible */}
<div className="p-4 border-b flex-shrink-0 flex items-center justify-between">
<div className="flex items-center gap-2">
<h2 className="font-semibold text-lg">Messages</h2>
{(loadingPhase === LOADING_PHASES.CACHE ||
loadingPhase === LOADING_PHASES.RELAYS ||
loadingPhase === LOADING_PHASES.SUBSCRIPTIONS) && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">
{loadingPhase === LOADING_PHASES.CACHE && 'Loading from cache...'}
{loadingPhase === LOADING_PHASES.RELAYS && 'Querying relays for new messages...'}
{loadingPhase === LOADING_PHASES.SUBSCRIPTIONS && 'Setting up subscriptions...'}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
{onStatusClick && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={onStatusClick}
aria-label="View messaging status"
>
<Info className="h-4 w-4" />
</Button>
)}
</div>
{/* Tab buttons - always visible */}
<div className="px-2 pt-2 flex-shrink-0">
<div className="grid grid-cols-2 gap-1 bg-muted p-1 rounded-lg">
<button
onClick={() => setActiveTab('known')}
className={cn(
"text-xs py-2 px-3 rounded-md transition-colors",
activeTab === 'known'
? "bg-background shadow-sm font-medium"
: "text-muted-foreground hover:text-foreground"
)}
>
Active {knownConversations.length > 0 && `(${knownConversations.length})`}
</button>
<button
onClick={() => setActiveTab('requests')}
className={cn(
"text-xs py-2 px-3 rounded-md transition-colors",
activeTab === 'requests'
? "bg-background shadow-sm font-medium"
: "text-muted-foreground hover:text-foreground"
)}
>
Requests {requestConversations.length > 0 && `(${requestConversations.length})`}
</button>
</div>
</div>
{/* Content area - show skeleton during initial load, otherwise show conversations */}
<div className="flex-1 min-h-0 mt-2 overflow-hidden">
{(isLoading || isInitialLoad) ? (
<ConversationListSkeleton />
) : conversations.length === 0 ? (
<div className="flex items-center justify-center h-full text-center text-muted-foreground px-4">
<div>
<p className="text-sm">No conversations yet</p>
<p className="text-xs mt-1">Start a new conversation to get started</p>
</div>
</div>
) : currentConversations.length === 0 ? (
<div className="flex items-center justify-center h-32 text-center text-muted-foreground px-4">
<p className="text-sm">No {activeTab} conversations</p>
</div>
) : (
<ScrollArea className="h-full block">
<div className="block w-full px-2 py-2 space-y-1">
{currentConversations.map((conversation) => (
<ConversationItem
key={conversation.pubkey}
pubkey={conversation.pubkey}
isSelected={selectedPubkey === conversation.pubkey}
onClick={() => onSelectConversation(conversation.pubkey)}
lastMessage={conversation.lastMessage}
lastActivity={conversation.lastActivity}
hasNIP4Messages={conversation.hasNIP4Messages}
/>
))}
</div>
</ScrollArea>
)}
</div>
</Card>
);
};
@@ -1,84 +0,0 @@
import { useState, useCallback } from 'react';
import { DMConversationList } from '@/components/dm/DMConversationList';
import { DMChatArea } from '@/components/dm/DMChatArea';
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
import { useDMContext } from '@/contexts/DMContext';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
interface DMMessagingInterfaceProps {
className?: string;
}
export const DMMessagingInterface = ({ className }: DMMessagingInterfaceProps) => {
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
const [statusModalOpen, setStatusModalOpen] = useState(false);
const isMobile = useIsMobile();
const { clearCacheAndRefetch } = useDMContext();
// On mobile, show only one panel at a time
const showConversationList = !isMobile || !selectedPubkey;
const showChatArea = !isMobile || selectedPubkey;
const handleSelectConversation = useCallback((pubkey: string) => {
setSelectedPubkey(pubkey);
}, []);
const handleBack = useCallback(() => {
setSelectedPubkey(null);
}, []);
return (
<>
{/* Status Modal */}
<Dialog open={statusModalOpen} onOpenChange={setStatusModalOpen}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Messaging Status</DialogTitle>
<DialogDescription>
View loading status, cache info, and connection details
</DialogDescription>
</DialogHeader>
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
</DialogContent>
</Dialog>
<div className={cn("flex gap-4 overflow-hidden", className)}>
{/* Conversation List - Left Sidebar */}
<div className={cn(
"md:w-80 md:flex-shrink-0",
isMobile && !showConversationList && "hidden",
isMobile && showConversationList && "w-full"
)}>
<DMConversationList
selectedPubkey={selectedPubkey}
onSelectConversation={handleSelectConversation}
className="h-full"
onStatusClick={() => setStatusModalOpen(true)}
/>
</div>
{/* Chat Area - Right Panel */}
<div className={cn(
"flex-1 md:min-w-0",
isMobile && !showChatArea && "hidden",
isMobile && showChatArea && "w-full"
)}>
<DMChatArea
pubkey={selectedPubkey}
onBack={isMobile ? handleBack : undefined}
className="h-full"
/>
</div>
</div>
</>
);
};
-214
View File
@@ -1,214 +0,0 @@
import { useState } from 'react';
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
import { useDMContext } from '@/contexts/DMContext';
import { LOADING_PHASES } from '@/lib/dmConstants';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useToast } from '@/hooks/useToast';
interface DMStatusInfoProps {
clearCacheAndRefetch?: () => Promise<void>;
}
export const DMStatusInfo = ({ clearCacheAndRefetch }: DMStatusInfoProps) => {
const [isClearing, setIsClearing] = useState(false);
const { toast } = useToast();
const {
loadingPhase,
subscriptions,
scanProgress,
isDoingInitialLoad,
lastSync,
conversations,
} = useDMContext();
const handleClearCache = async () => {
if (!clearCacheAndRefetch) return;
setIsClearing(true);
try {
await clearCacheAndRefetch();
toast({
title: 'Cache cleared',
description: 'Refetching messages from relays...',
});
setIsClearing(false);
} catch (error) {
console.error('Error clearing cache:', error);
toast({
title: 'Error',
description: 'Failed to clear cache. Please try again.',
variant: 'destructive',
});
setIsClearing(false);
}
};
const getLoadingPhaseInfo = () => {
switch (loadingPhase) {
case LOADING_PHASES.IDLE:
return { label: 'Idle', description: 'Not yet initialized', icon: Loader2, color: 'text-muted-foreground' };
case LOADING_PHASES.CACHE:
return { label: 'Loading from cache', description: 'Reading cached messages...', icon: Database, color: 'text-blue-500' };
case LOADING_PHASES.RELAYS:
return { label: 'Loading from relays', description: 'Fetching messages from Nostr relays...', icon: Wifi, color: 'text-yellow-500' };
case LOADING_PHASES.SUBSCRIPTIONS:
return { label: 'Connecting subscriptions', description: 'Setting up real-time message sync...', icon: RefreshCw, color: 'text-orange-500' };
case LOADING_PHASES.READY:
return { label: 'Ready', description: 'All systems operational', icon: CheckCircle2, color: 'text-green-500' };
default:
return { label: 'Unknown', description: 'Status unknown', icon: Loader2, color: 'text-muted-foreground' };
}
};
const phaseInfo = getLoadingPhaseInfo();
const PhaseIcon = phaseInfo.icon;
const formatTimestamp = (timestamp: number | null) => {
if (!timestamp) return 'Never';
const date = new Date(timestamp * 1000);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffMins < 1440) return `${Math.floor(diffMins / 60)}h ago`;
return date.toLocaleDateString();
};
return (
<div className="space-y-4">
{/* Loading Phase */}
<Card>
<CardContent className="pt-6">
<div className="flex items-start gap-3">
<PhaseIcon className={`h-5 w-5 ${phaseInfo.color} ${loadingPhase !== LOADING_PHASES.READY ? 'animate-pulse' : ''}`} />
<div className="flex-1 space-y-1">
<div className="flex items-center gap-2">
<p className="font-medium">{phaseInfo.label}</p>
{isDoingInitialLoad && (
<Badge variant="secondary" className="text-xs">
Initial Load
</Badge>
)}
</div>
<p className="text-sm text-muted-foreground">{phaseInfo.description}</p>
</div>
</div>
</CardContent>
</Card>
{/* Scan Progress */}
{(scanProgress.nip4 !== null || scanProgress.nip17 !== null) && (
<Card>
<CardContent className="pt-6">
<div className="space-y-3">
<p className="text-sm font-medium">Scanning Messages</p>
{scanProgress.nip4 !== null && (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">NIP-4 (Legacy)</span>
<span className="text-muted-foreground">{scanProgress.nip4.current} events</span>
</div>
<p className="text-xs text-muted-foreground">{scanProgress.nip4.status}</p>
</div>
)}
{scanProgress.nip17 !== null && (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">NIP-17 (Private)</span>
<span className="text-muted-foreground">{scanProgress.nip17.current} events</span>
</div>
<p className="text-xs text-muted-foreground">{scanProgress.nip17.status}</p>
</div>
)}
</div>
</CardContent>
</Card>
)}
{/* Subscriptions */}
<Card>
<CardContent className="pt-6">
<div className="space-y-3">
<p className="text-sm font-medium">Real-time Subscriptions</p>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">NIP-4 (Legacy DMs)</span>
<Badge variant={subscriptions.isNIP4Connected ? 'default' : 'secondary'}>
{subscriptions.isNIP4Connected ? 'Connected' : 'Disconnected'}
</Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">NIP-17 (Private DMs)</span>
<Badge variant={subscriptions.isNIP17Connected ? 'default' : 'secondary'}>
{subscriptions.isNIP17Connected ? 'Connected' : 'Disconnected'}
</Badge>
</div>
</div>
</div>
</CardContent>
</Card>
{/* Cache Info */}
<Card>
<CardContent className="pt-6">
<div className="space-y-3">
<p className="text-sm font-medium">Cache Information</p>
<div className="space-y-2 text-sm">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Conversations</span>
<span className="font-medium">{conversations.length}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Last NIP-4 sync</span>
<span className="font-medium">{formatTimestamp(lastSync.nip4)}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Last NIP-17 sync</span>
<span className="font-medium">{formatTimestamp(lastSync.nip17)}</span>
</div>
</div>
</div>
</CardContent>
</Card>
{/* Actions */}
{clearCacheAndRefetch && (
<>
<Separator />
<div className="space-y-3">
<div className="space-y-1">
<p className="text-sm font-medium">Cache Management</p>
<p className="text-xs text-muted-foreground">
Clear all cached messages and refetch from relays. This will force a fresh sync.
</p>
</div>
<Button
onClick={handleClearCache}
disabled={isClearing}
variant="outline"
className="w-full"
>
{isClearing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Clearing...
</>
) : (
<>
<RefreshCw className="mr-2 h-4 w-4" />
Clear Cache & Refetch
</>
)}
</Button>
</div>
</>
)}
</div>
);
};
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button-variants"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
+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}
/>
))
-21
View File
@@ -1,21 +0,0 @@
import { cva } from "class-variance-authority"
export const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
+22 -3
View File
@@ -1,8 +1,27 @@
import * as React from "react"
import { type VariantProps } from "class-variance-authority"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { badgeVariants } from "./badge-variants"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
@@ -14,4 +33,4 @@ function Badge({ className, variant, ...props }: BadgeProps) {
)
}
export { Badge }
export { Badge, badgeVariants }
-30
View File
@@ -1,30 +0,0 @@
import { cva } from "class-variance-authority"
export const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+31 -3
View File
@@ -1,9 +1,37 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { type VariantProps } from "class-variance-authority"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { buttonVariants } from "./button-variants"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
@@ -25,4 +53,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
)
Button.displayName = "Button"
export { Button }
export { Button, buttonVariants }
+1 -1
View File
@@ -3,7 +3,7 @@ import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button-variants";
import { buttonVariants } from "@/components/ui/button";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
+1 -1
View File
@@ -21,7 +21,7 @@ const Command = React.forwardRef<
))
Command.displayName = CommandPrimitive.displayName
type CommandDialogProps = DialogProps
interface CommandDialogProps extends DialogProps {}
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
-48
View File
@@ -1,48 +0,0 @@
import * as React from "react"
import {
FieldPath,
FieldValues,
useFormContext,
} from "react-hook-form"
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
export const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
type FormItemContextValue = {
id: string
}
export const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
export const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
+44 -1
View File
@@ -7,14 +7,25 @@ import {
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { FormFieldContext, FormItemContext, useFormField } from "./form-utils"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
@@ -28,6 +39,37 @@ const FormField = <
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
@@ -123,6 +165,7 @@ const FormMessage = React.forwardRef<
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
@@ -1,5 +0,0 @@
import { cva } from "class-variance-authority"
export const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
)
+6 -1
View File
@@ -1,9 +1,9 @@
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { navigationMenuTriggerStyle } from "./navigation-menu-variants"
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
@@ -40,6 +40,10 @@ NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
const NavigationMenuItem = NavigationMenuPrimitive.Item
const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
)
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
@@ -112,6 +116,7 @@ NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
+1 -2
View File
@@ -2,8 +2,7 @@ import * as React from "react"
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
import { ButtonProps } from "@/components/ui/button"
import { buttonVariants } from "@/components/ui/button-variants"
import { ButtonProps, buttonVariants } from "@/components/ui/button"
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav
-145
View File
@@ -1,145 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { X, Copy, Check, QrCode, Zap, Clock } from 'lucide-react';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { useEffect, useState } from 'react';
interface QRModalProps {
isOpen: boolean;
onClose: () => void;
title: string;
description: string;
qrCodeUrl: string;
content: string;
icon?: 'qr' | 'zap';
expiryTimestamp?: number;
onExpiry?: () => void;
}
export function QRModal({
isOpen,
onClose,
title,
description,
qrCodeUrl,
content,
icon = 'qr',
expiryTimestamp,
onExpiry,
}: QRModalProps) {
const { copy, copied } = useCopyToClipboard();
const [timeRemaining, setTimeRemaining] = useState<number | null>(null);
const handleCopy = () => {
copy(content);
};
// Countdown timer effect
useEffect(() => {
if (!isOpen || !expiryTimestamp) return;
const updateTimer = () => {
const now = Math.floor(Date.now() / 1000); // Current time in seconds
const remaining = expiryTimestamp - now;
if (remaining <= 0) {
setTimeRemaining(0);
// Call expiry callback
if (onExpiry) {
onExpiry();
}
onClose();
} else {
setTimeRemaining(remaining);
}
};
// Update immediately
updateTimer();
// Then update every second
const interval = setInterval(updateTimer, 1000);
return () => clearInterval(interval);
}, [isOpen, expiryTimestamp, onExpiry, onClose]);
// Format time remaining as MM:SS
const formatTime = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${secs.toString().padStart(2, '0')}`;
};
if (!isOpen) return null;
const IconComponent = icon === 'zap' ? Zap : QrCode;
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={onClose}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<IconComponent className="h-5 w-5 mr-2" />
{title}
</CardTitle>
<CardDescription>
{description}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{expiryTimestamp && timeRemaining !== null && timeRemaining <= 3600 && (
<div className="flex items-center justify-center gap-2 text-sm">
<Clock className="h-4 w-4" />
<span className={timeRemaining < 60 ? "text-destructive font-semibold" : "text-muted-foreground"}>
Expires in {formatTime(timeRemaining)}
</span>
</div>
)}
<div className="flex justify-center">
<div className="bg-white p-4 rounded-lg border shadow-sm">
<img
src={qrCodeUrl}
alt={`${title} QR Code`}
className="w-64 h-64 object-contain"
/>
</div>
</div>
<div className="text-center">
<div
className="bg-muted p-3 rounded-lg border font-mono text-sm cursor-pointer hover:bg-muted/80 transition-colors relative group"
onClick={handleCopy}
title="Click to copy full content"
>
{content.length > 33
? `${content.substring(0, 15)}...${content.substring(content.length - 15)}`
: content}
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4 text-muted-foreground" />
)}
</div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
+1 -1
View File
@@ -12,7 +12,7 @@ const ScrollArea = React.forwardRef<
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!w-full">
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
-52
View File
@@ -1,52 +0,0 @@
import * as React from "react"
import { cva } from "class-variance-authority"
export const SIDEBAR_COOKIE_NAME = "sidebar:state"
export const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
export const SIDEBAR_WIDTH = "16rem"
export const SIDEBAR_WIDTH_MOBILE = "18rem"
export const SIDEBAR_WIDTH_ICON = "3rem"
export const SIDEBAR_KEYBOARD_SHORTCUT = "b"
export type SidebarContext = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
export const SidebarContext = React.createContext<SidebarContext | null>(null)
export function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
export const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+52 -15
View File
@@ -1,6 +1,6 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { VariantProps } from "class-variance-authority"
import { VariantProps, cva } from "class-variance-authority"
import { PanelLeft } from "lucide-react"
import { useIsMobile } from "@/hooks/useIsMobile"
@@ -16,18 +16,34 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
import {
SIDEBAR_COOKIE_NAME,
SIDEBAR_COOKIE_MAX_AGE,
SIDEBAR_WIDTH,
SIDEBAR_WIDTH_MOBILE,
SIDEBAR_WIDTH_ICON,
SIDEBAR_KEYBOARD_SHORTCUT,
SidebarContext,
useSidebar,
sidebarMenuButtonVariants,
type SidebarContext as SidebarContextType,
} from "./sidebar-utils"
const SIDEBAR_COOKIE_NAME = "sidebar:state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContext = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContext | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
const SidebarProvider = React.forwardRef<
HTMLDivElement,
@@ -98,7 +114,7 @@ const SidebarProvider = React.forwardRef<
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextType>(
const contextValue = React.useMemo<SidebarContext>(
() => ({
state,
open,
@@ -493,7 +509,27 @@ const SidebarMenuItem = React.forwardRef<
))
SidebarMenuItem.displayName = "SidebarMenuItem"
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const SidebarMenuButton = React.forwardRef<
HTMLButtonElement,
@@ -721,4 +757,5 @@ export {
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}
+2 -2
View File
@@ -15,10 +15,10 @@ const Slider = React.forwardRef<
)}
{...props}
>
<SliderPrimitive.Track className="relative h-12 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-10 w-10 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
+29
View File
@@ -0,0 +1,29 @@
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }
+2 -1
View File
@@ -2,7 +2,8 @@ import * as React from "react"
import { cn } from "@/lib/utils"
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
-1
View File
@@ -47,7 +47,6 @@ const Toast = React.forwardRef<
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
duration={5000}
{...props}
/>
)
+1 -1
View File
@@ -3,7 +3,7 @@ import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle-variants"
import { toggleVariants } from "@/components/ui/toggle"
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants>
-23
View File
@@ -1,23 +0,0 @@
import { cva } from "class-variance-authority"
export const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+24 -3
View File
@@ -1,9 +1,30 @@
import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle"
import { type VariantProps } from "class-variance-authority"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { toggleVariants } from "./toggle-variants"
const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>,
@@ -19,4 +40,4 @@ const Toggle = React.forwardRef<
Toggle.displayName = TogglePrimitive.Root.displayName
export { Toggle }
export { Toggle, toggleVariants }
-422
View File
@@ -1,422 +0,0 @@
import { useState, useEffect, useRef } from 'react';
import { nip19 } from 'nostr-tools';
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/wallet/useBitcoin';
import { useNsecAccess } from '@/hooks/useNsecAccess';
import { nostrPubkeyToBitcoinAddress, type UTXO } from '@/lib/bitcoin';
import { QRModal } from '@/components/ui/qr-modal';
import { TransactionCard } from './PaymentCard';
import { ConsolidationModal } from './ConsolidationModal';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { QRScanResult } from '@/hooks/wallet/useQRCode';
interface BitcoinWalletHeaderProps {
utxos: UTXO[];
utxoDropdownOpen: boolean;
setUtxoDropdownOpen: (open: boolean) => void;
onShowConsolidationModal: () => void;
isConsolidating: boolean;
onShowBitcoinAddressQR: (qr: string) => void;
}
interface BitcoinWalletProps {
toast: ReturnType<typeof import('@/hooks/useToast').useToast>['toast'];
user?: { pubkey: string };
onRequestQRScanner: () => void;
onQRResult?: (result: QRScanResult) => void;
onWalletHeaderPropsChange?: (props: BitcoinWalletHeaderProps) => void;
}
// Extend Window interface for QR handler
declare global {
interface Window {
__bitcoinWalletQRHandler?: (result: QRScanResult) => void;
}
}
export function BitcoinWallet({
toast,
user,
onRequestQRScanner,
onQRResult,
onWalletHeaderPropsChange,
}: BitcoinWalletProps) {
const { hasNsecAccess } = useNsecAccess();
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
const { isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress);
const {
utxos,
isConsolidating,
bitcoinMaxAmount,
fetchBitcoinUtxos,
handleSendMax,
handleBitcoinSend,
handleBitcoinReceive,
handleConsolidateUtxos,
} = useBitcoinOperations(bitcoinAddress);
const {
data: bitcoinTransactions = [],
isLoading: isBitcoinTransactionsLoading
} = useBitcoinTransactionHistory(bitcoinAddress);
// Bitcoin state
const [bitcoinAmount, setBitcoinAmount] = useState('');
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState<string | null>(null);
const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false);
const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState('');
const [showConsolidationModal, setShowConsolidationModal] = useState(false);
const [showSendModal, setShowSendModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
// UTXO state
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
// Fetch UTXOs when component mounts
useEffect(() => {
if (bitcoinAddress) {
fetchBitcoinUtxos();
}
}, [bitcoinAddress, fetchBitcoinUtxos]);
// Handle drawer close with state reset
const handleSendDrawerClose = (open: boolean) => {
setShowSendModal(open);
if (!open) {
setBitcoinAmount('');
setBitcoinRecipient('');
setPendingBitcoinRecipient(null);
}
};
const handleReceiveDrawerClose = (open: boolean) => {
setShowReceiveModal(open);
};
// Handle focus management when drawers open
useEffect(() => {
if (showSendModal || showReceiveModal || showHistoryModal) {
const activeElement = document.activeElement as HTMLElement;
if (activeElement && activeElement.blur) {
activeElement.blur();
}
}
}, [showSendModal, showReceiveModal, showHistoryModal]);
// Handle QR scan results (called from parent WalletContainer)
useEffect(() => {
if (!onQRResult) return;
const handleQRResult = (result: QRScanResult) => {
if (result.type === 'bitcoin_address') {
setBitcoinRecipient(result.value);
setPendingBitcoinRecipient(result.value);
setShowSendModal(true);
toast({
title: "Bitcoin Address Scanned",
description: "Enter amount to send",
});
} else if (result.type === 'npub') {
try {
const decoded = nip19.decode(result.value);
if (decoded.type === 'npub') {
const address = nostrPubkeyToBitcoinAddress(decoded.data);
setBitcoinRecipient(address);
setPendingBitcoinRecipient(address);
setShowSendModal(true);
toast({
title: "Nostr npub Scanned",
description: "Enter amount to send",
});
}
} catch {
toast({
variant: "destructive",
title: "Invalid npub",
description: "Could not decode npub",
});
}
}
};
// Store handler for parent to call
window.__bitcoinWalletQRHandler = handleQRResult;
return () => {
delete window.__bitcoinWalletQRHandler;
};
}, [onQRResult, toast]);
// Expose WalletHeader props to parent WalletContainer
// Use ref to track previous values and prevent infinite loops
const prevPropsRef = useRef<{
utxosLength?: number;
utxoDropdownOpen?: boolean;
isConsolidating?: boolean;
}>({});
useEffect(() => {
if (!onWalletHeaderPropsChange) return;
// Check if values actually changed
const currentProps = {
utxosLength: utxos?.length,
utxoDropdownOpen,
isConsolidating,
};
const prevProps = prevPropsRef.current;
const hasChanged =
prevProps.utxosLength !== currentProps.utxosLength ||
prevProps.utxoDropdownOpen !== currentProps.utxoDropdownOpen ||
prevProps.isConsolidating !== currentProps.isConsolidating;
if (!hasChanged && Object.keys(prevProps).length > 0) {
// Values haven't changed, skip update
return;
}
// Update ref
prevPropsRef.current = currentProps;
// Send updated props
onWalletHeaderPropsChange({
utxos,
utxoDropdownOpen,
setUtxoDropdownOpen,
onShowConsolidationModal: () => setShowConsolidationModal(true),
isConsolidating,
onShowBitcoinAddressQR: async (qr: string) => {
setBitcoinAddressQRCode(qr);
setShowBitcoinAddressQR(true);
},
});
}, [
onWalletHeaderPropsChange,
utxos,
utxoDropdownOpen,
isConsolidating,
// Note: Functions (setUtxoDropdownOpen, etc.) are not in deps
// because they're stable setters or we accept they may change
// The ref-based change detection ensures we only update when primitives change
]);
return (
<>
{/* Action Buttons and Transaction History Container */}
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
{/* Action Buttons */}
<div className="flex gap-8 justify-center py-8">
<Button
variant="outline"
size="icon"
onClick={() => setShowReceiveModal(true)}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Download className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={onRequestQRScanner}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<ScanLine className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => setShowSendModal(true)}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Send className="h-12 w-12" />
</Button>
</div>
{/* Transaction History Button */}
<div className="max-w-4xl mx-auto">
<button
onClick={() => setShowHistoryModal(true)}
className="w-full py-2 px-4 flex flex-col items-center gap-1 border-t border-muted hover:bg-muted/30 transition-colors"
>
<ChevronUp className="h-5 w-5 text-muted-foreground" />
<span className="text-xs text-muted-foreground font-medium">History</span>
</button>
</div>
</div>
{/* Modals */}
<>
{/* Consolidation Modal */}
<ConsolidationModal
isOpen={showConsolidationModal}
onClose={() => setShowConsolidationModal(false)}
utxos={utxos}
onConfirm={handleConsolidateUtxos}
isConsolidating={isConsolidating}
/>
{/* Bitcoin Address QR Modal */}
<QRModal
isOpen={showBitcoinAddressQR}
onClose={() => setShowBitcoinAddressQR(false)}
title="Bitcoin Address"
description="Scan this QR code to send Bitcoin to your address"
qrCodeUrl={bitcoinAddressQRCode}
content={bitcoinAddress || ''}
icon="qr"
/>
{/* Bottom Drawer Modals */}
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Send Bitcoin on-chain
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode="bitcoin"
operation="send"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={null}
onSend={() => {
handleBitcoinSend(
bitcoinAmount,
pendingBitcoinRecipient,
setBitcoinAmount,
setBitcoinRecipient,
setPendingBitcoinRecipient,
setShowSendModal
);
}}
onReceive={() => {}}
isResolvingAddress={false}
isLoading={isBitcoinBalanceLoading}
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount={bitcoinAmount}
setBitcoinAmount={setBitcoinAmount}
bitcoinRecipient={bitcoinRecipient}
setBitcoinRecipient={setBitcoinRecipient}
pendingBitcoinRecipient={pendingBitcoinRecipient}
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
hasNsecAccess={hasNsecAccess}
bitcoinMaxAmount={bitcoinMaxAmount}
onSendMax={() => handleSendMax(setBitcoinAmount)}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Receive Bitcoin on-chain
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode="bitcoin"
operation="receive"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={null}
onSend={() => {}}
onReceive={() => {
handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR);
setShowReceiveModal(false);
}}
isResolvingAddress={false}
isLoading={isBitcoinBalanceLoading}
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount=""
setBitcoinAmount={() => {}}
bitcoinRecipient=""
setBitcoinRecipient={() => {}}
pendingBitcoinRecipient={null}
setPendingBitcoinRecipient={() => {}}
hasNsecAccess={hasNsecAccess}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
View your Bitcoin transaction history
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
entries={[]}
isLoading={isBitcoinTransactionsLoading}
bitcoinTransactions={bitcoinTransactions}
isBitcoinLoading={isBitcoinTransactionsLoading}
showSats={true}
/>
</ScrollArea>
</DrawerContent>
</Drawer>
</>
</>
);
}
-948
View File
@@ -1,948 +0,0 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { nip19 } from 'nostr-tools';
import { useCashu } from '@/hooks/wallet/useCashu';
import { useLightningAddress } from '@/hooks/wallet/useLightningAddress';
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/wallet/useNpubCash';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import type { QRScanResult } from '@/hooks/wallet/useQRCode';
import { useMintManager } from '@/hooks/wallet/useMintManager';
import { useTokenOperations } from '@/hooks/wallet/useTokenOperations';
import { useLightningOperations } from '@/hooks/wallet/useLightningOperations';
import { useReverseSwapOperations } from '@/hooks/wallet/useReverseSwapOperations';
import { useSeedPhraseRestore } from '@/hooks/wallet/useSeedPhraseRestore';
import { useHistoryManager } from '@/hooks/wallet/useHistoryManager';
import { decodeBolt11Amount } from '@/lib/bolt11Decoder';
import { QRModal } from '@/components/ui/qr-modal';
import { TransactionCard } from './PaymentCard';
import { ProofBreakdownModal } from './ProofBreakdownModal';
import { RemoveMintModal } from './RemoveMintModal';
import { SeedPhraseModal } from './SeedPhraseModal';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
import { Button } from '@/components/ui/button';
interface CashuMint {
url: string;
name?: string;
}
interface CashuWalletHeaderProps {
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
mintDropdownOpen: boolean;
setMintDropdownOpen: (open: boolean) => void;
npubCashUsername?: string;
onShowLightningAddressQR: (qr: string) => void;
onShowSeedPhraseInfo: () => void;
}
interface CashuWalletProps {
mode: 'tokens' | 'lightning';
toast: ReturnType<typeof import('@/hooks/useToast').useToast>['toast'];
generateQRCode: (text: string) => Promise<string>;
user?: { pubkey: string };
onRequestQRScanner: () => void;
onWalletHeaderPropsChange?: (props: CashuWalletHeaderProps) => void;
}
// Extend Window interface for QR handler
declare global {
interface Window {
__cashuWalletQRHandler?: (result: QRScanResult) => void;
}
}
export function CashuWallet({
mode,
toast,
generateQRCode,
user,
onRequestQRScanner,
onWalletHeaderPropsChange,
}: CashuWalletProps) {
// ============================================================================
// CORE HOOKS
// ============================================================================
const {
coco,
repositories,
isInitialized,
isLoading,
error,
mints,
getEncodedToken,
refreshMints,
} = useCashu();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const {
setMint: setNpubCashMint,
getUserInfo: getNpubCashUserInfo,
syncQuotesWithWallet,
isLoggedIn: isNpubCashLoggedIn,
isLoading: isNpubCashLoading,
error: npubCashError,
clearError: clearNpubCashError
} = useNpubCash();
// Wrapper to handle return type mismatch
const handleSetNpubCashMint = (mintUrl: string): Promise<boolean> => {
return setNpubCashMint(mintUrl);
};
// State to track npub.cash user info
const [npubCashUserInfo, setNpubCashUserInfo] = useState<NpubCashUserInfo | null>(null);
// Ref to track if we've fetched user info (only fetch once)
const hasFetchedUserInfoRef = useRef(false);
// Ref to track if we've set a mint from user info (to prevent overwriting with stored mint)
const hasSetMintFromUserInfoRef = useRef(false);
// Persist active mint URL to localStorage
const [storedActiveMintUrl, setStoredActiveMintUrl] = useLocalStorage<string | null>('cashu-active-mint-url', null);
// ============================================================================
// DOMAIN HOOKS
// ============================================================================
const {
activeMintUrl,
setActiveMintUrl,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
} = useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint: handleSetNpubCashMint,
refreshMints,
});
// Wrapper for setActiveMintUrl to handle the async nature
const handleSetActiveMintSync = useCallback((url: string | null) => {
setActiveMintUrl(url);
}, [setActiveMintUrl]);
// Transaction operation hooks
const tokenOps = useTokenOperations({
coco,
activeMintUrl,
generateQRCode,
getEncodedToken,
});
const lightningOps = useLightningOperations({
coco,
activeMintUrl,
generateQRCode,
getLightningInvoice,
});
const reverseSwapOps = useReverseSwapOperations({
coco,
activeMintUrl,
});
const restore = useSeedPhraseRestore({ coco });
// Extract all needed values
const {
tokenInput,
setTokenInput,
sendAmount,
setSendAmount,
sentToken,
setSentToken,
sentTokenQRCode,
} = tokenOps;
const {
quoteAmount,
setQuoteAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
decodedInvoiceAmount,
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
handleConfirmInvoicePayment,
mintQuoteUnsubscribeRef,
} = lightningOps;
const {
pendingBitcoinSwapAddress,
setPendingBitcoinSwapAddress,
bitcoinSwapAmount,
setBitcoinSwapAmount,
swapStatus,
} = reverseSwapOps;
const {
handleRestoreFromSeedPhrase,
isRestoring,
} = restore;
// Combined receive handler that routes to appropriate operation
const handleReceive = async () => {
if (tokenInput) {
return tokenOps.handleTokenReceive();
} else if (quoteAmount) {
return lightningOps.handleLightningReceive();
}
};
// Combined send handler that routes to appropriate operation
const handleSend = async () => {
// Check for token send first
if (sendAmount && activeMintUrl) {
return tokenOps.handleTokenSend();
}
// Check for reverse swap
if (pendingBitcoinSwapAddress && bitcoinSwapAmount) {
return reverseSwapOps.handleReverseSwap();
}
// Check for Lightning address payment
if (pendingLightningAddress) {
return lightningOps.handleLightningAddressPayment();
}
// Handle Lightning invoice/address input detection
const input = lightningInvoice.trim() || lightningAddressInput.trim();
if (!input) return;
// First check if it's a Bitcoin address for reverse swap
if (reverseSwapOps.detectBitcoinAddress(input)) {
setLightningInvoice('');
setLightningAddressInput('');
return;
}
// Then check for Lightning address or invoice
lightningOps.detectAndHandleLightningInput(input);
};
const {
historyEntries,
isLoadingHistory,
} = useHistoryManager({
coco,
isInitialized,
});
// ============================================================================
// UI STATE
// ============================================================================
const showSats = true; // Always show in sats for Cashu wallet
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
const [proofBreakdown, setProofBreakdown] = useState<{
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
} | null>(null);
const [showLightningAddressQR, setShowLightningAddressQR] = useState(false);
const [lightningAddressQRCode, setLightningAddressQRCode] = useState<string>('');
const [showSendModal, setShowSendModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
const [showSeedPhraseInfo, setShowSeedPhraseInfo] = useState(false);
// Handle drawer close with state reset
const handleSendDrawerClose = (open: boolean) => {
setShowSendModal(open);
if (!open) {
// Reset all send-related state when drawer closes
setSendAmount('');
setLightningInvoice('');
setLightningAddressInput('');
setLightningAddressAmount('');
setPendingLightningAddress(null);
setDecodedInvoiceAmount(null);
setPendingInvoice(null);
// Reset reverse swap state
setPendingBitcoinSwapAddress(null);
setBitcoinSwapAmount('');
}
};
const handleReceiveDrawerClose = (open: boolean) => {
setShowReceiveModal(open);
if (!open) {
// Reset all receive-related state when drawer closes
setTokenInput('');
setQuoteAmount('');
}
};
// ============================================================================
// EFFECTS - Error Handling
// ============================================================================
useEffect(() => {
if (error) {
toast({
variant: "destructive",
title: "Wallet Error",
description: error.message,
});
}
}, [error, toast]);
useEffect(() => {
if (npubCashError) {
toast({
variant: "destructive",
title: "Npub.cash Error",
description: npubCashError,
});
clearNpubCashError();
}
}, [npubCashError, clearNpubCashError, toast]);
// ============================================================================
// EFFECTS - NPub.cash Integration
// ============================================================================
// Track previous login state to detect logout
const prevLoggedInRef = useRef(isNpubCashLoggedIn);
// Fetch npub.cash user info once and set mint if available
useEffect(() => {
// Detect logout: was logged in, now not logged in
if (prevLoggedInRef.current && !isNpubCashLoggedIn) {
setNpubCashUserInfo(null);
hasFetchedUserInfoRef.current = false; // Reset so we can fetch again if they log back in
hasSetMintFromUserInfoRef.current = false;
hasAttemptedRestoreRef.current = false; // Reset restore so it can run again
}
prevLoggedInRef.current = isNpubCashLoggedIn;
// Only fetch if logged in, initialized, not loading, and we haven't fetched yet
if (!isNpubCashLoggedIn || !isInitialized || isNpubCashLoading || hasFetchedUserInfoRef.current) {
// If not logged in, mark as "fetched" (skipped) so restore logic can run
if (!isNpubCashLoggedIn && isInitialized && !hasFetchedUserInfoRef.current) {
hasFetchedUserInfoRef.current = true;
}
return;
}
// Mark as fetched to prevent duplicate requests
hasFetchedUserInfoRef.current = true;
const fetchUserInfo = async () => {
console.log('[CashuWallet] Fetching npub.cash user info...');
try {
const userInfo = await getNpubCashUserInfo();
console.log('[CashuWallet] npub.cash user info received:', userInfo);
if (userInfo && userInfo.mintUrl) {
setNpubCashUserInfo(userInfo);
console.log('[CashuWallet] Setting mint from npub.cash:', userInfo.mintUrl);
if (!coco) {
console.warn('[CashuWallet] coco not available, cannot add/set mint');
return;
}
// Check if mint exists (known) by checking all mints
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === userInfo.mintUrl.toLowerCase());
if (isKnown) {
// Mint exists but may not be trusted, ensure it's trusted
const isTrusted = await coco.mint.isTrustedMint(userInfo.mintUrl);
if (!isTrusted) {
console.log('[CashuWallet] Trusting existing mint:', userInfo.mintUrl);
await coco.mint.trustMint(userInfo.mintUrl);
}
} else {
// Add mint from npub.cash and automatically trust it
console.log('[CashuWallet] Adding new mint from npub.cash:', userInfo.mintUrl);
await coco.mint.addMint(userInfo.mintUrl, { trusted: true });
}
// Set as active mint immediately
console.log('[CashuWallet] Setting active mint:', userInfo.mintUrl);
setActiveMintUrl(userInfo.mintUrl, false);
hasSetMintFromUserInfoRef.current = true;
} else {
console.log('[CashuWallet] No mintUrl in user info:', userInfo);
setNpubCashUserInfo(null);
}
} catch (err) {
console.error('[CashuWallet] Failed to get npub.cash user info:', err);
setNpubCashUserInfo(null);
hasFetchedUserInfoRef.current = false; // Allow retry on error
}
};
fetchUserInfo();
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, coco, setActiveMintUrl]);
// Ref to track if we've attempted restore/default mint logic
const hasAttemptedRestoreRef = useRef(false);
// Restore previous mint or add default mint if no user info mint was set
useEffect(() => {
// Only run after wallet is initialized
if (!isInitialized || !coco || hasAttemptedRestoreRef.current) return;
// If logged in, wait for user info check to complete
if (isNpubCashLoggedIn && !hasFetchedUserInfoRef.current) return;
// If we already set a mint from user info, don't override it
if (hasSetMintFromUserInfoRef.current) {
hasAttemptedRestoreRef.current = true;
return;
}
// If there's already an active mint, don't do anything
if (activeMintUrl) {
hasAttemptedRestoreRef.current = true;
return;
}
// Mark as attempted to prevent multiple runs
hasAttemptedRestoreRef.current = true;
const restoreOrAddDefaultMint = async () => {
// First, try to restore from stored mint if it exists and is valid
if (storedActiveMintUrl) {
const allMints = await coco.mint.getAllMints();
const storedMintExists = allMints.some(m => m.mintUrl.toLowerCase() === storedActiveMintUrl.toLowerCase());
if (storedMintExists) {
const isTrusted = await coco.mint.isTrustedMint(storedActiveMintUrl);
if (isTrusted) {
console.log('[CashuWallet] Restoring previous mint:', storedActiveMintUrl);
setActiveMintUrl(storedActiveMintUrl, false);
return;
}
}
}
// If no stored mint to restore, check if we need to add default mint
const trustedMints = await coco.mint.getAllTrustedMints();
// Only add default mint if no mints exist at all
if (trustedMints.length === 0) {
const defaultMintUrl = 'https://mint.minibits.cash/Bitcoin';
console.log('[CashuWallet] No mints found, adding default mint:', defaultMintUrl);
try {
await coco.mint.addMint(defaultMintUrl, { trusted: true });
// Wait a bit for mint to be added, then set as active
setTimeout(() => {
setActiveMintUrl(defaultMintUrl, false);
}, 500);
} catch (err) {
console.error('[CashuWallet] Failed to add default mint:', err);
}
}
};
restoreOrAddDefaultMint();
}, [isInitialized, coco, activeMintUrl, storedActiveMintUrl, setActiveMintUrl, isNpubCashLoggedIn]);
// Save active mint URL to localStorage when it changes
useEffect(() => {
// Save active mint URL to localStorage whenever it changes
// This includes user info mint, restored mint, default mint, and manual selections
if (activeMintUrl && storedActiveMintUrl !== activeMintUrl) {
console.log('[CashuWallet] Saving active mint to localStorage:', activeMintUrl);
setStoredActiveMintUrl(activeMintUrl);
}
}, [activeMintUrl, storedActiveMintUrl, setStoredActiveMintUrl]);
// Set up automatic quote sync subscription when logged into npub.cash
useEffect(() => {
if (!isNpubCashLoggedIn || !coco || !isInitialized) return;
let unsubscribe: (() => void) | null = null;
const setupSync = async () => {
unsubscribe = await syncQuotesWithWallet(coco);
};
setupSync();
return () => {
if (unsubscribe) {
unsubscribe();
}
};
}, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]);
// Handle focus management when drawers open to prevent aria-hidden warnings
useEffect(() => {
if (showSendModal || showReceiveModal || showHistoryModal) {
// Blur any currently focused element to allow drawer's focus trap to work
const activeElement = document.activeElement as HTMLElement;
if (activeElement && activeElement.blur) {
activeElement.blur();
}
}
}, [showSendModal, showReceiveModal, showHistoryModal]);
// ============================================================================
// EFFECTS - Cleanup
// ============================================================================
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, [mintQuoteUnsubscribeRef]);
// Handle QR scan results (called from parent WalletContainer)
const handleQRResult = useCallback((result: QRScanResult) => {
switch (result.type) {
case 'lightning_invoice': {
setLightningInvoice(result.value);
setPendingInvoice(result.value);
// Decode invoice amount
const amount = decodeBolt11Amount(result.value);
setDecodedInvoiceAmount(amount);
setShowSendModal(true);
toast({
title: "Lightning Invoice Scanned",
description: amount ? `${amount} sats` : "Invoice ready to pay",
});
break;
}
case 'lightning_address': {
setLightningAddressInput(result.value);
setPendingLightningAddress(result.value);
setShowSendModal(true);
toast({
title: "Lightning Address Scanned",
description: "Enter amount to send",
});
break;
}
case 'cashu_token': {
setTokenInput(result.value);
setShowReceiveModal(true);
toast({
title: "Cashu Token Scanned",
description: "Token ready to redeem",
});
break;
}
default: {
// Bitcoin addresses and npubs are handled by BitcoinWallet
break;
}
}
}, [setLightningInvoice, setPendingInvoice, setDecodedInvoiceAmount, setShowSendModal, setLightningAddressInput, setPendingLightningAddress, setTokenInput, setShowReceiveModal, toast]);
// Expose handler to parent via window (temporary, will be improved)
useEffect(() => {
window.__cashuWalletQRHandler = handleQRResult;
return () => {
delete window.__cashuWalletQRHandler;
};
}, [handleQRResult]);
// ============================================================================
// RENDER
// ============================================================================
// Expose WalletHeader props to parent WalletContainer
// Use ref to track previous values and prevent infinite loops
const prevPropsRef = useRef<{
activeMintUrl?: string | null;
mintsLength?: number;
firstMintUrl?: string;
mintUrl?: string;
mintDropdownOpen?: boolean;
npubCashUsername?: string;
}>({});
// Extract first mint URL to avoid complex expression in dependency array
const firstMintUrl = mints?.[0]?.url;
useEffect(() => {
if (!onWalletHeaderPropsChange) return;
const npubCashUsername = user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined;
// Check if values actually changed
const currentProps = {
activeMintUrl,
mintsLength: mints?.length,
firstMintUrl,
mintUrl,
mintDropdownOpen,
npubCashUsername,
};
const prevProps = prevPropsRef.current;
const hasChanged =
prevProps.activeMintUrl !== currentProps.activeMintUrl ||
prevProps.mintsLength !== currentProps.mintsLength ||
prevProps.firstMintUrl !== currentProps.firstMintUrl ||
prevProps.mintUrl !== currentProps.mintUrl ||
prevProps.mintDropdownOpen !== currentProps.mintDropdownOpen ||
prevProps.npubCashUsername !== currentProps.npubCashUsername;
if (!hasChanged && Object.keys(prevProps).length > 0) {
// Values haven't changed, skip update
return;
}
// Update ref
prevPropsRef.current = currentProps;
// Send updated props
onWalletHeaderPropsChange({
activeMintUrl,
setActiveMintUrl: handleSetActiveMintSync,
mints: mints || [],
mintUrl,
setMintUrl,
onAddMint: handleAddMint,
onRemoveMint: handleRemoveMintClick,
onShowDenominations: (mintUrl: string) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown),
getCleanMintLabel,
mintDropdownOpen,
setMintDropdownOpen,
npubCashUsername,
onShowLightningAddressQR: async (qr: string) => {
setLightningAddressQRCode(qr);
setShowLightningAddressQR(true);
},
onShowSeedPhraseInfo: () => setShowSeedPhraseInfo(true),
});
}, [
onWalletHeaderPropsChange,
activeMintUrl,
mints,
firstMintUrl,
mintUrl,
mintDropdownOpen,
npubCashUserInfo?.name,
user?.pubkey,
handleSetActiveMintSync,
handleAddMint,
handleRemoveMintClick,
handleShowDenominations,
getCleanMintLabel,
setMintDropdownOpen,
setMintUrl,
setShowProofBreakdown,
setProofBreakdown,
setLightningAddressQRCode,
setShowLightningAddressQR,
setShowSeedPhraseInfo,
// Note: These functions are stable setters or wrapped in useCallback
// because they're stable from hooks or we accept they may change
// The ref-based change detection ensures we only update when primitives change
]);
return (
<>
{/* Action Buttons and Transaction History Container */}
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
{/* Action Buttons */}
<div className="flex gap-8 justify-center py-8">
<Button
variant="outline"
size="icon"
onClick={() => setShowReceiveModal(true)}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Download className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={onRequestQRScanner}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<ScanLine className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => setShowSendModal(true)}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Send className="h-12 w-12" />
</Button>
</div>
{/* Transaction History Button */}
<div className="max-w-4xl mx-auto">
<button
onClick={() => setShowHistoryModal(true)}
className="w-full py-2 px-4 flex flex-col items-center gap-1 border-t border-muted hover:bg-muted/30 transition-colors"
>
<ChevronUp className="h-5 w-5 text-muted-foreground" />
<span className="text-xs text-muted-foreground font-medium">History</span>
</button>
</div>
</div>
{/* Modals */}
<>
{/* Proof Breakdown Modal */}
<ProofBreakdownModal
isOpen={showProofBreakdown}
onClose={() => setShowProofBreakdown(false)}
proofBreakdown={proofBreakdown}
/>
{/* Remove Mint Modal */}
<RemoveMintModal
isOpen={showRemoveMintModal}
onClose={() => setShowRemoveMintModal(false)}
mintToRemove={mintToRemove}
onConfirm={handleConfirmRemoveMint}
isLoading={isLoading || isNpubCashLoading}
/>
{/* QR Modals */}
<QRModal
isOpen={showLightningAddressQR}
onClose={() => setShowLightningAddressQR(false)}
title="Lightning Address"
description="Scan this QR code to send payments to your Lightning address"
qrCodeUrl={lightningAddressQRCode}
content={user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) + '@npubx.cash' : ''}
icon="zap"
/>
{currentInvoice && (
<QRModal
isOpen={showInvoiceModal}
onClose={() => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
setShowInvoiceModal(false);
}}
onExpiry={() => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
toast({
variant: "destructive",
title: "Invoice Expired",
description: "The Lightning invoice has expired. Please create a new one.",
});
}}
title="Lightning Invoice"
description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
qrCodeUrl={currentInvoice.qrCodeUrl}
content={currentInvoice.invoice}
icon="zap"
expiryTimestamp={currentInvoice.expiry}
/>
)}
{/* Sent Token Modal */}
{sentToken && (
<QRModal
isOpen={!!sentToken}
onClose={() => setSentToken(null)}
title="Cashu Token"
description="Share this token with the recipient to send them your sats"
qrCodeUrl={sentTokenQRCode}
content={sentToken}
icon="qr"
/>
)}
{/* Seed Phrase Restore Modal */}
<SeedPhraseModal
isOpen={showSeedPhraseInfo}
onClose={() => setShowSeedPhraseInfo(false)}
onRestoreFromSeedPhrase={handleRestoreFromSeedPhrase}
isRestoring={isRestoring}
mints={mints}
activeMintUrl={activeMintUrl}
/>
{/* Bottom Drawer Modals */}
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Send tokens or Lightning payments
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode={mode}
operation="send"
sendAmount={sendAmount}
setSendAmount={setSendAmount}
lightningInvoice={lightningInvoice}
setLightningInvoice={setLightningInvoice}
lightningAddressInput={lightningAddressInput}
setLightningAddressInput={setLightningAddressInput}
lightningAddressAmount={lightningAddressAmount}
setLightningAddressAmount={setLightningAddressAmount}
pendingLightningAddress={pendingLightningAddress}
setPendingLightningAddress={setPendingLightningAddress}
decodedInvoiceAmount={decodedInvoiceAmount}
setDecodedInvoiceAmount={setDecodedInvoiceAmount}
pendingInvoice={pendingInvoice}
setPendingInvoice={setPendingInvoice}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={activeMintUrl}
onSend={() => {
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
handleSend();
if (mode === 'tokens' || wasPendingBefore) {
setShowSendModal(false);
}
}}
onReceive={() => {}}
onConfirmInvoice={() => {
handleConfirmInvoicePayment();
setShowSendModal(false);
}}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading || isNpubCashLoading}
// Reverse swap props
pendingBitcoinSwapAddress={pendingBitcoinSwapAddress}
setPendingBitcoinSwapAddress={setPendingBitcoinSwapAddress}
bitcoinSwapAmount={bitcoinSwapAmount}
setBitcoinSwapAmount={setBitcoinSwapAmount}
swapStatus={swapStatus}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Receive tokens or Lightning invoices
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode={mode}
operation="receive"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput={tokenInput}
setTokenInput={setTokenInput}
quoteAmount={quoteAmount}
setQuoteAmount={setQuoteAmount}
activeMintUrl={activeMintUrl}
onSend={() => {}}
onReceive={() => {
handleReceive();
setShowReceiveModal(false);
}}
isResolvingAddress={false}
isLoading={isLoading || isNpubCashLoading}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
View your transaction history
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
bitcoinTransactions={[]}
isBitcoinLoading={false}
showSats={showSats}
/>
</ScrollArea>
</DrawerContent>
</Drawer>
</>
</>
);
}
@@ -1,92 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { X, ArrowRightLeft, RefreshCw } from 'lucide-react';
import { UTXO } from '@/lib/bitcoin';
interface ConsolidationModalProps {
isOpen: boolean;
onClose: () => void;
utxos: UTXO[];
onConfirm: () => void;
isConsolidating: boolean;
}
export function ConsolidationModal({
isOpen,
onClose,
utxos,
onConfirm,
isConsolidating,
}: ConsolidationModalProps) {
if (!isOpen) return null;
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4"
onClick={onClose}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<ArrowRightLeft className="h-5 w-5 mr-2 text-primary" />
Consolidate UTXOs
</CardTitle>
<CardDescription>
Combine multiple UTXOs into a single transaction
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="text-center">
<div className="text-2xl font-bold text-primary mb-2">
{utxos.length} UTXO{utxos.length !== 1 ? 's' : ''}
</div>
<div className="text-sm text-muted-foreground">
Total Value: {utxos.reduce((sum, utxo) => sum + utxo.value, 0).toLocaleString()} sats
</div>
</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>🔄 <strong>What this does:</strong> Combines all your UTXOs into a single transaction, sending the total amount (minus fees) back to your own address.</div>
<div>💰 <strong>Benefits:</strong> Reduces transaction fees for future payments and simplifies your UTXO management.</div>
<div>⚠️ <strong>Note:</strong> This will create a new transaction on the Bitcoin network and may take some time to confirm.</div>
</div>
<div className="flex justify-center">
<Button
onClick={() => {
onConfirm();
onClose();
}}
disabled={isConsolidating || utxos.length <= 1}
>
{isConsolidating ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Consolidating...
</>
) : (
<>
<ArrowRightLeft className="h-4 w-4 mr-2" />
Consolidate UTXOs
</>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
-192
View File
@@ -1,192 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, X, Check, ChevronDown, Landmark } from 'lucide-react';
import { useState, useEffect } from 'react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
interface CashuMint {
url: string;
name?: string;
}
interface MintSelectorProps {
balances: { [key: string]: number };
showSats: boolean;
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
}
export function MintSelector({
balances,
showSats,
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
dropdownOpen,
setDropdownOpen,
}: MintSelectorProps) {
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const formatBalance = (sats: number): string => {
if (showSats) {
return `₿${sats.toLocaleString()}`;
} else if (btcUsdRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * btcUsdRate;
return `$${usd.toFixed(2)}`;
} else {
return `₿${sats.toLocaleString()}`;
}
};
const activeMint = mints.find(mint => mint.url === activeMintUrl);
const activeBalance = activeMint ? balances[activeMint.url] || 0 : 0;
return (
<div className="flex gap-2 items-center min-w-0">
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="justify-between rounded-full bg-muted hover:bg-muted/80 border text-base flex-1 h-[40px] px-3 min-w-0">
<div className="flex items-center justify-between w-full min-w-0">
{activeMint ? (
<>
<div className="flex items-center gap-2 min-w-0 flex-1">
<Check className="h-5 w-5 text-primary flex-shrink-0" />
<span className="truncate font-medium min-w-0 flex-1">{getCleanMintLabel(activeMint)}</span>
</div>
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
{formatBalance(activeBalance)}
</span>
</>
) : (
<span className="text-muted-foreground truncate min-w-0 flex-1">Select a mint</span>
)}
</div>
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none max-h-[200px] overflow-hidden">
<div className="max-h-[120px] overflow-y-auto">
{mints
.filter((mint) => mint.url)
.map((mint, index) => {
const isActive = activeMintUrl === mint.url;
const balance = balances[mint.url] || 0;
return (
<DropdownMenuItem
key={`mint-${mint.url || `unknown-${index}`}`}
onClick={() => setActiveMintUrl(mint.url)}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
{isActive && (
<div className="flex-shrink-0">
<Check className="h-5 w-5 text-primary" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate">
{getCleanMintLabel(mint)}
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(balance)}
</span>
<button
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
className="p-1 rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
title="Remove mint"
>
<X className="h-4 w-4" />
</button>
</div>
</DropdownMenuItem>
);
})}
</div>
{mints.length > 0 && <DropdownMenuSeparator />}
<DropdownMenuItem asChild>
<div className="flex gap-2 p-2">
<Input
placeholder="mint.example.com"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
className="flex-1"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Escape') {
setDropdownOpen(false);
} else if (e.key === 'Enter') {
e.preventDefault();
if (mintUrl.trim()) {
onAddMint();
}
}
}}
onKeyUp={(e) => e.stopPropagation()}
/>
<Button
onClick={(e) => {
e.stopPropagation();
onAddMint();
}}
disabled={!mintUrl.trim()}
size="sm"
>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{activeMint && (
<div className="flex flex-col gap-1">
<button
onClick={() => onShowDenominations(activeMint.url)}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="View token breakdown"
>
<Landmark className="h-4 w-4" />
</button>
</div>
)}
</div>
);
}
-568
View File
@@ -1,568 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Send, Download, ArrowRight, Zap, X } from 'lucide-react';
import { useState, useEffect } from 'react';
// Helper function to prevent complex inline ternary operators
const getOperationMessage = (operation: string, mode: string): string => {
if (operation === 'send') {
return mode === 'tokens'
? 'Select a mint to send tokens'
: 'Select a mint to pay Lightning invoices';
} else {
return mode === 'tokens'
? 'Select a mint to receive tokens'
: 'Select a mint to create Lightning invoice';
}
};
// Helper function to truncate long addresses (show first 12, last 12 with ellipsis in middle)
const truncateAddress = (address: string): string => {
if (address.length <= 26) return address; // "first 12" + "..." + "last 12" = 26
return address.slice(0, 12) + '...' + address.slice(-12);
};
interface TransactionCardProps {
mode: 'tokens' | 'lightning' | 'bitcoin';
operation: 'send' | 'receive';
// Send props
sendAmount: string;
setSendAmount: (value: string) => void;
lightningInvoice: string;
setLightningInvoice: (value: string) => void;
lightningAddressInput: string;
setLightningAddressInput: (value: string) => void;
lightningAddressAmount: string;
setLightningAddressAmount: (value: string) => void;
pendingLightningAddress: string | null;
setPendingLightningAddress: (value: string | null) => void;
decodedInvoiceAmount: number | null;
setDecodedInvoiceAmount: (value: number | null) => void;
pendingInvoice: string | null;
setPendingInvoice: (value: string | null) => void;
// Receive props
tokenInput: string;
setTokenInput: (value: string) => void;
quoteAmount: string;
setQuoteAmount: (value: string) => void;
// Common props
activeMintUrl: string | null;
onSend: () => void;
onReceive: () => void;
onConfirmInvoice?: () => void;
isResolvingAddress: boolean;
isLoading: boolean;
// Bitcoin props
bitcoinAddress?: string;
bitcoinAmount?: string;
setBitcoinAmount?: (value: string) => void;
bitcoinRecipient?: string;
setBitcoinRecipient?: (value: string) => void;
pendingBitcoinRecipient?: string | null;
setPendingBitcoinRecipient?: (value: string | null) => void;
hasNsecAccess?: boolean;
bitcoinMaxAmount?: number;
onSendMax?: () => void;
// Reverse swap props (Lightning mode)
pendingBitcoinSwapAddress?: string | null;
setPendingBitcoinSwapAddress?: (value: string | null) => void;
bitcoinSwapAmount?: string;
setBitcoinSwapAmount?: (value: string) => void;
swapStatus?: string | null;
}
export function TransactionCard({
mode,
operation,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
decodedInvoiceAmount,
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
activeMintUrl,
onSend,
onReceive,
onConfirmInvoice,
isResolvingAddress,
isLoading,
bitcoinAddress,
bitcoinAmount,
setBitcoinAmount,
bitcoinRecipient,
setBitcoinRecipient,
pendingBitcoinRecipient,
setPendingBitcoinRecipient,
hasNsecAccess,
bitcoinMaxAmount,
onSendMax,
pendingBitcoinSwapAddress,
setPendingBitcoinSwapAddress,
bitcoinSwapAmount,
setBitcoinSwapAmount,
swapStatus,
}: TransactionCardProps) {
const [sendMaxEnabled, setSendMaxEnabled] = useState(false);
const [swapAmountError, setSwapAmountError] = useState<string | null>(null);
const handleSendMaxToggle = () => {
const newState = !sendMaxEnabled;
setSendMaxEnabled(newState);
if (newState && onSendMax) {
onSendMax();
}
};
// Reset send max toggle when bitcoin recipient changes
useEffect(() => {
if (!pendingBitcoinRecipient) {
setSendMaxEnabled(false);
}
}, [pendingBitcoinRecipient]);
// Reset swap amount error when swap address changes
useEffect(() => {
if (!pendingBitcoinSwapAddress) {
setSwapAmountError(null);
}
}, [pendingBitcoinSwapAddress]);
// Validate swap amount when it changes
useEffect(() => {
if (pendingBitcoinSwapAddress && bitcoinSwapAmount) {
const amount = parseInt(bitcoinSwapAmount);
if (isNaN(amount) || amount <= 0) {
setSwapAmountError('Please enter a valid amount');
} else if (amount < 25_000) {
setSwapAmountError('Minimum amount is 25,000 sats');
} else if (amount > 25_000_000) {
setSwapAmountError('Maximum amount is 25,000,000 sats');
} else {
setSwapAmountError(null);
}
} else {
setSwapAmountError(null);
}
}, [bitcoinSwapAmount, pendingBitcoinSwapAddress]);
return (
<div className="space-y-8">
{/* Title */}
<div className="text-center">
<div className="text-base text-muted-foreground mt-2">
{operation === 'send' ? (
mode === 'tokens'
? 'Generate Cashu token to send'
: mode === 'bitcoin' && !pendingBitcoinRecipient
? 'Send Bitcoin on-chain'
: mode === 'bitcoin' && pendingBitcoinRecipient
? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending to:</span>{' '}
<span className="font-semibold text-foreground">{truncateAddress(pendingBitcoinRecipient)}</span>
</span>
<button
onClick={() => {
setPendingBitcoinRecipient?.(null);
setBitcoinAmount?.('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
)
: pendingInvoice && decodedInvoiceAmount ? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending:</span>{' '}
<span className="font-semibold text-foreground">{decodedInvoiceAmount} sats</span>
</span>
<button
onClick={() => {
setPendingInvoice(null);
setDecodedInvoiceAmount(null);
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : pendingLightningAddress ? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending:</span>{' '}
<span className="font-semibold text-foreground">{truncateAddress(pendingLightningAddress)}</span>
</span>
<button
onClick={() => {
setPendingLightningAddress(null);
setLightningAddressAmount('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : pendingBitcoinSwapAddress ? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-orange-500/10 border border-orange-500/20 rounded-md">
<span className="font-bold text-orange-600 dark:text-orange-400">Reverse Swap to:</span>{' '}
<span className="font-semibold text-foreground">{truncateAddress(pendingBitcoinSwapAddress)}</span>
</span>
<button
onClick={() => {
setPendingBitcoinSwapAddress?.(null);
setBitcoinSwapAmount?.('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : 'Pay invoices, addresses, or Bitcoin addresses'
) : (
mode === 'tokens'
? 'Enter Cashu token to redeem'
: mode === 'bitcoin'
? 'Receive Bitcoin on-chain'
: 'Deposit funds with Lightning'
)}
</div>
</div>
{/* Content */}
<div className="space-y-8">
{!activeMintUrl && mode !== 'bitcoin' && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
{getOperationMessage(operation, mode)}
</div>
)}
{operation === 'send' ? (
// Send Mode
mode === 'bitcoin' ? (
// Bitcoin Send
<div className="space-y-8">
{!hasNsecAccess ? (
<div className="flex justify-center items-center h-32">
<div className="text-sm text-destructive bg-destructive/10 border border-destructive/20 p-3 rounded text-center">
⚠️ Login with nsec required to send Bitcoin
</div>
</div>
) : pendingBitcoinRecipient ? (
// Step 2: Amount Input
<div className="space-y-8">
<div className="flex items-center gap-3">
<Input
placeholder="Amount (sats)"
type="number"
value={bitcoinAmount || ''}
onChange={(e) => setBitcoinAmount?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && (bitcoinAmount || sendMaxEnabled) && pendingBitcoinRecipient && !isLoading) {
onSend();
}
}}
disabled={sendMaxEnabled}
className="flex-1 h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<button
onClick={handleSendMaxToggle}
disabled={!bitcoinMaxAmount}
className={`px-4 py-2 rounded-md border text-sm font-medium transition-colors ${
sendMaxEnabled
? 'bg-orange-500 text-white border-orange-500 hover:bg-orange-600'
: 'bg-gray-100 text-gray-600 border-gray-300 hover:bg-gray-200'
} ${!bitcoinMaxAmount ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
>
Send Max
</button>
</div>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={(!bitcoinAmount && !sendMaxEnabled) || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Send className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Step 1: Recipient Input
<div className="space-y-8">
<Input
placeholder="Bitcoin address or npub..."
value={bitcoinRecipient || ''}
onChange={(e) => setBitcoinRecipient?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && bitcoinRecipient && !isLoading) {
setPendingBitcoinRecipient?.(bitcoinRecipient);
}
}}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={() => {
if (bitcoinRecipient) {
setPendingBitcoinRecipient?.(bitcoinRecipient);
}
}}
disabled={!bitcoinRecipient || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<ArrowRight className="h-5 w-5" />
</Button>
</div>
</div>
)}
</div>
) : mode === 'tokens' ? (
// Cashu Token Send
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={sendAmount}
onChange={(e) => setSendAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && sendAmount && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={!sendAmount || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Send className="h-5 w-5" />
</Button>
</div>
</div>
) : pendingInvoice && decodedInvoiceAmount ? (
// Lightning Invoice Confirmation
<div className="space-y-8">
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onConfirmInvoice}
disabled={!activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
) : pendingBitcoinSwapAddress ? (
// Reverse Swap Amount Input
<div className="space-y-8">
<div className="space-y-2">
<Input
placeholder="Amount (sats)"
type="number"
value={bitcoinSwapAmount || ''}
onChange={(e) => {
setBitcoinSwapAmount?.(e.target.value);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && bitcoinSwapAmount && !swapAmountError && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl || isLoading}
className={`w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield] ${
swapAmountError ? 'border-destructive' : ''
}`}
/>
{swapAmountError && (
<p className="text-sm text-destructive text-center">{swapAmountError}</p>
)}
{!swapAmountError && bitcoinSwapAmount && (
<p className="text-xs text-muted-foreground text-center">
Amount must be between 25,000 and 25,000,000 sats
</p>
)}
{swapStatus && (
<p className="text-sm text-muted-foreground text-center">{swapStatus}</p>
)}
</div>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={!bitcoinSwapAmount || !!swapAmountError || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Send className="h-5 w-5" />
</Button>
</div>
</div>
) : pendingLightningAddress ? (
// Lightning Address Amount Input
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={lightningAddressAmount}
onChange={(e) => setLightningAddressAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && lightningAddressAmount && activeMintUrl && !isResolvingAddress && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Lightning Invoice/Address/Bitcoin Address Input
<div className="space-y-8">
<Input
placeholder="lnbc..., [email protected], or Bitcoin address"
value={lightningInvoice || lightningAddressInput}
onChange={(e) => {
const value = e.target.value;
if (value.includes('@')) {
setLightningAddressInput(value);
setLightningInvoice('');
} else {
setLightningInvoice(value);
setLightningAddressInput('');
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && (lightningInvoice.trim() || lightningAddressInput.trim()) && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<ArrowRight className="h-5 w-5" />
</Button>
</div>
</div>
)
) : (
// Receive Mode
mode === 'bitcoin' ? (
// Bitcoin Receive
<div className="space-y-8">
<div className="text-center">
<div className="font-mono text-sm bg-muted p-3 rounded border break-all">
{bitcoinAddress}
</div>
</div>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onReceive}
disabled={isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Download className="h-5 w-5" />
</Button>
</div>
</div>
) : mode === 'tokens' ? (
// Cashu Token Receive
<div className="space-y-8">
<Input
placeholder="cashuBo2Ft..."
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && tokenInput.trim() && activeMintUrl && !isLoading) {
onReceive();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onReceive}
disabled={!tokenInput.trim() || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Download className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Lightning Invoice Receive
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={quoteAmount}
onChange={(e) => setQuoteAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && quoteAmount && activeMintUrl && !isLoading) {
onReceive();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onReceive}
disabled={!quoteAmount || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
)
)}
</div>
</div>
);
}
@@ -1,83 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { X, Coins } from 'lucide-react';
export interface ProofBreakdown {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}
interface ProofBreakdownModalProps {
isOpen: boolean;
onClose: () => void;
proofBreakdown: ProofBreakdown | null;
}
export function ProofBreakdownModal({
isOpen,
onClose,
proofBreakdown,
}: ProofBreakdownModalProps) {
if (!isOpen || !proofBreakdown) return null;
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={onClose}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<Coins className="h-5 w-5 mr-2" />
Token Breakdown
</CardTitle>
<CardDescription>
{new URL(proofBreakdown.mintUrl).hostname}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center py-2">
<div className="text-2xl font-bold text-primary">
{proofBreakdown.totalBalance.toLocaleString()} sats
</div>
<div className="text-sm text-muted-foreground">Total Balance</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">Denominations:</div>
{Object.entries(proofBreakdown.denominations)
.sort(([a], [b]) => parseInt(a) - parseInt(b))
.map(([amount, count]) => (
<div key={amount} className="flex items-center justify-between p-2 bg-muted/30 rounded">
<div className="flex items-center gap-2">
<Coins className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{parseInt(amount).toLocaleString()} sats</span>
</div>
<Badge variant="secondary" className="bg-primary/10 text-primary">
× {count}
</Badge>
</div>
))}
</div>
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded">
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
</div>
</CardContent>
</Card>
</div>
);
}
-111
View File
@@ -1,111 +0,0 @@
import { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { useToast } from '@/hooks/useToast';
import type { QRScanResult } from '@/hooks/wallet/useQRCode';
interface QRScannerProps {
isOpen: boolean;
onClose: () => Promise<void>;
onResult: (result: QRScanResult) => void;
classifyQRCode: (text: string) => QRScanResult;
startScanning: (onResult: (result: QRScanResult) => void) => Promise<void>;
stopScanning: () => Promise<void>;
setModalOpen?: (isOpen: boolean) => void;
qrError: string | null;
}
export function QRScanner({
isOpen,
onClose,
onResult,
classifyQRCode,
startScanning,
stopScanning,
setModalOpen,
qrError,
}: QRScannerProps) {
const { toast } = useToast();
// Handle paste from clipboard
const handlePasteQRCode = async () => {
try {
const text = await navigator.clipboard.readText();
if (!text || !text.trim()) {
toast({
variant: "destructive",
title: "Clipboard Empty",
description: "No text found in clipboard",
});
return;
}
const result = classifyQRCode(text.trim());
onResult(result);
await stopScanning();
await onClose();
} catch (err) {
toast({
variant: "destructive",
title: "Paste Failed",
description: "Could not read from clipboard",
});
console.error('Error pasting from clipboard:', err);
}
};
// Start/stop scanning based on isOpen
useEffect(() => {
if (isOpen) {
setModalOpen?.(true);
startScanning(onResult);
} else {
setModalOpen?.(false);
stopScanning();
}
}, [isOpen, startScanning, stopScanning, setModalOpen, onResult]);
return (
<Dialog open={isOpen} onOpenChange={async (open) => {
if (!open) {
await onClose();
}
}}>
<DialogContent className="max-w-[min(90vw,500px)] w-full p-4 sm:p-6">
<DialogHeader>
<DialogTitle>Scan QR Code</DialogTitle>
<VisuallyHidden.Root asChild>
<DialogDescription>
Position the QR code within the camera view to scan
</DialogDescription>
</VisuallyHidden.Root>
</DialogHeader>
<div className="relative w-full" style={{ aspectRatio: '1 / 1' }}>
<div
id="qr-reader"
className="w-full h-full rounded-xl overflow-hidden bg-muted"
/>
{qrError && (
<div className="absolute inset-x-4 top-4 p-3 bg-destructive text-destructive-foreground rounded-lg text-center z-50 shadow-lg">
{qrError}
</div>
)}
</div>
<div className="mt-4 flex justify-center">
<Button
onClick={handlePasteQRCode}
className="h-12 px-12 rounded-full"
size="lg"
>
Paste
</Button>
</div>
</DialogContent>
</Dialog>
);
}
-86
View File
@@ -1,86 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { X, AlertTriangle, RefreshCw } from 'lucide-react';
export interface MintToRemove {
url: string;
name?: string;
}
interface RemoveMintModalProps {
isOpen: boolean;
onClose: () => void;
mintToRemove: MintToRemove | null;
onConfirm: () => void;
isLoading: boolean;
}
export function RemoveMintModal({
isOpen,
onClose,
mintToRemove,
onConfirm,
isLoading,
}: RemoveMintModalProps) {
if (!isOpen || !mintToRemove) return null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<AlertTriangle className="h-5 w-5 mr-2 text-destructive" />
Remove Mint
</CardTitle>
<CardDescription>
Are you sure you want to remove this mint from your wallet?
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="font-medium">{mintToRemove.name || new URL(mintToRemove.url).hostname}</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.</div>
<div>💡 You can always add this mint back later if needed.</div>
</div>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={onClose}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirm}
disabled={isLoading}
>
{isLoading ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Removing...
</>
) : (
<>
<X className="h-4 w-4 mr-2" />
Remove Mint
</>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
-136
View File
@@ -1,136 +0,0 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { X, Key, Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
interface SeedPhraseModalProps {
isOpen: boolean;
onClose: () => void;
onRestoreFromSeedPhrase: (seedPhrase: string, mintUrl: string) => Promise<void>;
isRestoring: boolean;
mints: Array<{ url: string; name?: string }>;
activeMintUrl: string | null;
}
export function SeedPhraseModal({
isOpen,
onClose,
onRestoreFromSeedPhrase,
isRestoring,
mints,
activeMintUrl,
}: SeedPhraseModalProps) {
const { toast } = useToast();
const [seedPhraseInput, setSeedPhraseInput] = useState('');
if (!isOpen) return null;
const handleRestore = async () => {
if (!seedPhraseInput.trim()) {
toast({
variant: "destructive",
title: "Missing Information",
description: "Please enter your seed phrase.",
});
return;
}
if (!activeMintUrl) {
toast({
variant: "destructive",
title: "No Active Mint",
description: "Please select a mint first.",
});
return;
}
try {
await onRestoreFromSeedPhrase(seedPhraseInput.trim(), activeMintUrl);
setSeedPhraseInput('');
onClose();
} catch (error) {
toast({
variant: "destructive",
title: "Restore Failed",
description: error instanceof Error ? error.message : "Failed to restore from seed phrase",
});
}
};
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={onClose}
>
<div
className="w-full max-w-md border-0 shadow-lg bg-background rounded-lg"
onClick={(e) => e.stopPropagation()}
>
<div className="relative p-6">
<button
onClick={onClose}
className="absolute top-4 right-4 p-2 hover:bg-muted rounded-md transition-colors"
>
<X className="h-4 w-4" />
</button>
<div className="flex items-center mb-4 pr-8">
<Key className="h-5 w-5 mr-2" />
<h2 className="text-lg font-semibold">Restore from Seed Phrase</h2>
</div>
<p className="text-muted-foreground mb-4">
Enter your seed phrase to restore tokens from the active mint.
</p>
{activeMintUrl && (
<div className="bg-muted p-3 rounded-md mb-4">
<p className="text-sm text-muted-foreground">
<strong>Active Mint:</strong> {mints.find(m => m.url === activeMintUrl)?.name || new URL(activeMintUrl).hostname}
</p>
</div>
)}
<div className="space-y-4">
<div>
<Label htmlFor="seed-phrase">Seed Phrase</Label>
<Input
id="seed-phrase"
type="text"
placeholder="Enter your 12-word seed phrase..."
value={seedPhraseInput}
onChange={(e) => setSeedPhraseInput(e.target.value)}
className="mt-1"
/>
</div>
<div className="bg-muted p-3 rounded-md">
<p className="text-xs text-muted-foreground">
<strong>Note:</strong> This will restore tokens from the provided seed phrase and add them to your current wallet balance.
</p>
</div>
</div>
<div className="mt-6">
<Button
onClick={handleRestore}
disabled={isRestoring || !seedPhraseInput.trim() || !activeMintUrl}
className="w-full"
>
{isRestoring ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Restoring...
</>
) : (
'Restore Tokens'
)}
</Button>
</div>
</div>
</div>
</div>
);
}
@@ -1,226 +0,0 @@
import { Loader2, History, ArrowUpRight, ArrowDownLeft, ArrowLeftRight, Zap, Coins, Link } from 'lucide-react';
import type { HistoryEntry } from 'coco-cashu-core';
export interface BitcoinTransaction {
id: string;
txid: string;
type: 'sent' | 'received' | 'consolidate';
amount: number; // in satoshis
fee?: number; // in satoshis, only for sent transactions
address: string;
confirmations: number;
blockHeight?: number;
timestamp: number;
status: 'confirmed' | 'unconfirmed' | 'pending';
}
interface TransactionHistoryProps {
entries: HistoryEntry[];
isLoading: boolean;
// Bitcoin transaction props
bitcoinTransactions?: BitcoinTransaction[];
isBitcoinLoading?: boolean;
showSats?: boolean;
}
export function TransactionHistory({
entries,
isLoading,
bitcoinTransactions = [],
isBitcoinLoading = false,
showSats = true
}: TransactionHistoryProps) {
// Icon indicating transaction type (Lightning vs Cashu)
const getTransactionTypeIcon = (type: string) => {
switch (type) {
case 'mint':
case 'melt':
return <Zap className="h-4 w-4" />;
case 'send':
case 'receive':
return <Coins className="h-4 w-4" />;
default:
return <History className="h-4 w-4" />;
}
};
// Arrow indicating direction (next to amount)
const getDirectionIcon = (type: string) => {
switch (type) {
case 'mint':
case 'receive':
return <ArrowDownLeft className="h-4 w-4 text-green-500" />;
case 'melt':
case 'send':
return <ArrowUpRight className="h-4 w-4 text-red-500" />;
default:
return null;
}
};
const getHistoryLabel = (type: string) => {
switch (type) {
case 'mint':
case 'receive':
return 'Received';
case 'melt':
case 'send':
return 'Sent';
default:
return type;
}
};
// Bitcoin transaction formatting functions
const formatBitcoinAmount = (sats: number): string => {
if (showSats) {
return `${sats.toLocaleString()} sats`;
} else {
const btc = sats / 100000000;
return `₿${btc.toFixed(8)}`;
}
};
const formatBitcoinAddress = (address: string): string => {
return `${address.slice(0, 8)}...${address.slice(-8)}`;
};
const getBitcoinStatusColor = (status: string): string => {
switch (status) {
case 'confirmed':
return 'text-green-500';
case 'unconfirmed':
return 'text-yellow-500';
case 'pending':
return 'text-blue-500';
default:
return 'text-muted-foreground';
}
};
return (
<div className="space-y-2">
{isLoading || isBitcoinLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<span>Loading transactions...</span>
</div>
) : entries.length === 0 && bitcoinTransactions.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
No transactions yet
</div>
) : (
<>
{/* Cashu/Lightning Transactions */}
{entries.map((entry) => (
<div
key={entry.id}
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-3 flex-1">
<div className="mt-1">
{getTransactionTypeIcon(entry.type)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{getHistoryLabel(entry.type)}
</span>
</div>
<div className="text-sm text-muted-foreground mt-1">
{new URL(entry.mintUrl).hostname}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(entry.createdAt).toLocaleString()}
</div>
</div>
</div>
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'}
{entry.amount.toLocaleString()} {entry.unit}
</div>
{entry.type === 'melt' && (
<div className="text-xs text-muted-foreground mt-1">
+ fees
</div>
)}
</div>
<div className="mt-1">
{getDirectionIcon(entry.type)}
</div>
</div>
</div>
</div>
))}
{/* Bitcoin Transactions */}
{bitcoinTransactions.map((tx) => (
<div
key={tx.id}
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-3 flex-1">
<div className="mt-1">
<Link className="h-4 w-4" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{tx.type === 'received' ? 'Received' : tx.type === 'consolidate' ? 'Consolidate' : 'Sent'}
</span>
<span className={`text-xs px-2 py-1 rounded-full bg-muted ${getBitcoinStatusColor(tx.status)}`}>
{tx.status}
</span>
</div>
<div className="text-sm text-muted-foreground mt-1">
{formatBitcoinAddress(tx.address)}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(tx.timestamp).toLocaleString()}
{tx.confirmations > 0 && (
<span className="ml-2">
• {tx.confirmations} confirmation{tx.confirmations !== 1 ? 's' : ''}
</span>
)}
</div>
{tx.blockHeight && (
<div className="text-xs text-muted-foreground">
Block #{tx.blockHeight}
</div>
)}
</div>
</div>
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{tx.type === 'sent' ? '-' : tx.type === 'consolidate' ? '' : '+'}
{formatBitcoinAmount(tx.amount)}
</div>
{tx.fee !== undefined && tx.fee > 0 && (tx.type === 'sent' || tx.type === 'consolidate') && (
<div className="text-xs text-muted-foreground mt-1">
Fee: {formatBitcoinAmount(tx.fee)}
</div>
)}
</div>
<div className="mt-1">
{tx.type === 'received' ? (
<ArrowDownLeft className="h-4 w-4 text-green-500" />
) : tx.type === 'consolidate' ? (
<ArrowLeftRight className="h-4 w-4 text-blue-500" />
) : (
<ArrowUpRight className="h-4 w-4 text-red-500" />
)}
</div>
</div>
</div>
</div>
))}
</>
)}
</div>
);
}
-127
View File
@@ -1,127 +0,0 @@
import { Button } from '@/components/ui/button';
import { ChevronDown, Merge } from 'lucide-react';
import { useState, useEffect } from 'react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { UTXO } from '@/lib/bitcoin';
interface UTXOSelectorProps {
utxos: UTXO[];
showSats: boolean;
bitcoinAddress: string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
onShowConsolidationModal?: () => void;
isConsolidating?: boolean;
}
export function UTXOSelector({
utxos,
showSats,
dropdownOpen,
setDropdownOpen,
onShowConsolidationModal,
isConsolidating,
}: UTXOSelectorProps) {
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const formatBalance = (sats: number): string => {
if (showSats) {
return `₿${sats.toLocaleString()}`;
} else if (btcUsdRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * btcUsdRate;
return `$${usd.toFixed(2)}`;
} else {
return `₿${sats.toLocaleString()}`;
}
};
const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
const formatUTXOBlock = (utxo: UTXO): string => {
if (utxo.status.block_height) {
return `Block #${utxo.status.block_height}`;
} else {
return 'Unconfirmed';
}
};
return (
<div className="flex gap-2 items-center min-w-0">
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className="justify-between rounded-full bg-muted hover:bg-muted/80 border text-base flex-1 h-[40px] px-3 min-w-0"
disabled={utxos.length === 0}
>
<div className="flex items-center justify-between w-full min-w-0">
<div className="flex items-center gap-2 min-w-0 flex-1">
<span className="truncate font-medium min-w-0 flex-1">
{utxos.length === 0 ? 'No UTXOs' : `${utxos.length} UTXO${utxos.length !== 1 ? 's' : ''}`}
</span>
</div>
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
{formatBalance(totalBalance)}
</span>
</div>
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none max-h-[200px] overflow-hidden">
<div className="max-h-[120px] overflow-y-auto">
{utxos.length === 0 ? (
<DropdownMenuItem disabled className="flex items-center justify-center p-3 text-base text-muted-foreground">
No UTXOs available
</DropdownMenuItem>
) : (
utxos.map((utxo) => (
<DropdownMenuItem
key={`utxo-${utxo.txid}-${utxo.vout}`}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<div className="flex-1 min-w-0">
<div className="font-medium truncate text-sm">
{formatUTXOBlock(utxo)}
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(utxo.value)}
</span>
</div>
</DropdownMenuItem>
))
)}
</div>
</DropdownMenuContent>
</DropdownMenu>
{onShowConsolidationModal && (
<button
onClick={onShowConsolidationModal}
disabled={isConsolidating}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
title="Consolidate UTXOs"
>
<Merge className="h-4 w-4" />
</button>
)}
</div>
);
}
-235
View File
@@ -1,235 +0,0 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { useQRCode, type QRScanResult } from '@/hooks/wallet/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { useCashu } from '@/hooks/wallet/useCashu';
import { useBitcoinBalance } from '@/hooks/wallet/useBitcoin';
import { nostrPubkeyToBitcoinAddress, type UTXO } from '@/lib/bitcoin';
import { WalletHeader } from './WalletHeader';
import { CashuWallet } from './CashuWallet';
import { BitcoinWallet } from './BitcoinWallet';
import { QRScanner } from './QRScanner';
// Extend Window interface for QR handlers
declare global {
interface Window {
__cashuWalletQRHandler?: (result: QRScanResult) => void;
__bitcoinWalletQRHandler?: (result: QRScanResult) => void;
}
}
export function WalletContainer() {
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
const [showSats, setShowSats] = useState(true);
const [showQRScanner, setShowQRScanner] = useState(false);
// Shared hooks
const { user } = useCurrentUser();
const { toast } = useToast();
const { generateQRCode, classifyQRCode, startScanning, stopScanning, setModalOpen, error: qrError } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
// Get balance data for WalletHeader
const { balances, mnemonic } = useCashu();
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
const { data: bitcoinBalanceData } = useBitcoinBalance(bitcoinAddress);
// Calculate total balance based on mode
const totalBalance: number = mode === 'bitcoin'
? (bitcoinBalanceData?.balance || 0)
: (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// Refs to call wallet QR handlers
const cashuWalletQRHandlerRef = useRef<((result: QRScanResult) => void) | null>(null);
const bitcoinWalletQRHandlerRef = useRef<((result: QRScanResult) => void) | null>(null);
// Handle QR scanner results and route to appropriate wallet
const handleQRScanResult = async (result: QRScanResult) => {
try {
await stopScanning();
setShowQRScanner(false);
switch (result.type) {
case 'cashu_token': {
setMode('tokens');
// Call CashuWallet handler if available
if (cashuWalletQRHandlerRef.current) {
cashuWalletQRHandlerRef.current(result);
}
break;
}
case 'lightning_invoice': {
setMode('lightning');
// Call CashuWallet handler if available
if (cashuWalletQRHandlerRef.current) {
cashuWalletQRHandlerRef.current(result);
}
break;
}
case 'lightning_address': {
setMode('lightning');
// Call CashuWallet handler if available
if (cashuWalletQRHandlerRef.current) {
cashuWalletQRHandlerRef.current(result);
}
break;
}
case 'bitcoin_address': {
setMode('bitcoin');
// Call BitcoinWallet handler if available
if (bitcoinWalletQRHandlerRef.current) {
bitcoinWalletQRHandlerRef.current(result);
}
break;
}
case 'npub': {
setMode('bitcoin');
// Call BitcoinWallet handler if available
if (bitcoinWalletQRHandlerRef.current) {
bitcoinWalletQRHandlerRef.current(result);
}
break;
}
default: {
toast({
variant: "destructive",
title: "Unknown QR Code",
description: result.value,
});
}
}
} catch (err) {
console.error('Error handling QR scan:', err);
}
};
// Set up refs to wallet QR handlers
useEffect(() => {
const checkHandlers = () => {
if (window.__cashuWalletQRHandler) {
cashuWalletQRHandlerRef.current = window.__cashuWalletQRHandler;
}
if (window.__bitcoinWalletQRHandler) {
bitcoinWalletQRHandlerRef.current = window.__bitcoinWalletQRHandler;
}
};
// Check periodically for handlers (wallets set them up asynchronously)
const interval = setInterval(checkHandlers, 100);
checkHandlers(); // Initial check
return () => clearInterval(interval);
}, []);
// WalletHeader props - these will be passed from wallets via callbacks
const [walletHeaderProps, setWalletHeaderProps] = useState<{
activeMintUrl?: string | null;
mints?: Array<{ url: string; name?: string }>;
mintUrl?: string;
setMintUrl?: (url: string) => void;
onAddMint?: () => void;
onRemoveMint?: (mint: { url: string; name?: string }) => void;
onShowDenominations?: (mintUrl: string) => void;
getCleanMintLabel?: (mint: { name?: string; url: string }) => string;
mintDropdownOpen?: boolean;
setMintDropdownOpen?: (open: boolean) => void;
npubCashUsername?: string;
utxos?: UTXO[];
utxoDropdownOpen?: boolean;
setUtxoDropdownOpen?: (open: boolean) => void;
onShowConsolidationModal?: () => void;
isConsolidating?: boolean;
onShowLightningAddressQR?: (qr: string) => void;
onShowBitcoinAddressQR?: (qr: string) => void;
onShowSeedPhraseInfo?: () => void;
setActiveMintUrl?: (url: string | null) => void;
}>({});
// Memoize the callback to prevent infinite loops
const handleWalletHeaderPropsChange = useCallback((props: typeof walletHeaderProps) => {
setWalletHeaderProps(props);
}, []);
return (
<>
<div className="max-w-4xl mx-auto pt-16 pb-32 px-3 sm:px-4 relative">
{/* Wallet Header */}
<WalletHeader
totalBalance={totalBalance}
balances={mode === 'bitcoin' ? {} : balances}
showSats={showSats}
setShowSats={setShowSats}
mode={mode}
setMode={setMode}
userPubkey={user?.pubkey}
npubCashUsername={walletHeaderProps.npubCashUsername}
mnemonic={mode !== 'bitcoin' ? mnemonic : undefined}
onCopyToClipboard={copyToClipboard}
onShowLightningAddressQR={walletHeaderProps.onShowLightningAddressQR || (() => {})}
onShowBitcoinAddressQR={walletHeaderProps.onShowBitcoinAddressQR || (() => {})}
onShowSeedPhraseInfo={walletHeaderProps.onShowSeedPhraseInfo || (() => {})}
generateQRCode={generateQRCode}
// MintSelector props (only for tokens/lightning)
activeMintUrl={mode !== 'bitcoin' ? (walletHeaderProps.activeMintUrl ?? null) : null}
setActiveMintUrl={walletHeaderProps.setActiveMintUrl || (() => {})}
mints={mode !== 'bitcoin' ? (walletHeaderProps.mints || []) : []}
mintUrl={walletHeaderProps.mintUrl || ''}
setMintUrl={walletHeaderProps.setMintUrl || (() => {})}
onAddMint={walletHeaderProps.onAddMint || (() => {})}
onRemoveMint={walletHeaderProps.onRemoveMint || (() => {})}
onShowDenominations={walletHeaderProps.onShowDenominations || (() => {})}
getCleanMintLabel={walletHeaderProps.getCleanMintLabel || (() => '')}
dropdownOpen={walletHeaderProps.mintDropdownOpen || false}
setDropdownOpen={walletHeaderProps.setMintDropdownOpen || (() => {})}
// UTXOSelector props (only for bitcoin)
utxos={mode === 'bitcoin' ? (walletHeaderProps.utxos || []) : []}
utxoDropdownOpen={walletHeaderProps.utxoDropdownOpen || false}
setUtxoDropdownOpen={walletHeaderProps.setUtxoDropdownOpen || (() => {})}
onShowConsolidationModal={walletHeaderProps.onShowConsolidationModal}
isConsolidating={walletHeaderProps.isConsolidating}
/>
{/* Render appropriate wallet based on mode */}
{mode === 'tokens' || mode === 'lightning' ? (
<CashuWallet
mode={mode}
toast={toast}
generateQRCode={generateQRCode}
user={user}
onRequestQRScanner={() => setShowQRScanner(true)}
onWalletHeaderPropsChange={handleWalletHeaderPropsChange}
/>
) : (
<BitcoinWallet
toast={toast}
user={user}
onRequestQRScanner={() => setShowQRScanner(true)}
onQRResult={(result) => {
if (bitcoinWalletQRHandlerRef.current) {
bitcoinWalletQRHandlerRef.current(result);
}
}}
onWalletHeaderPropsChange={handleWalletHeaderPropsChange}
/>
)}
</div>
{/* Shared QR Scanner */}
<QRScanner
isOpen={showQRScanner}
onClose={async () => {
await stopScanning();
setShowQRScanner(false);
}}
onResult={handleQRScanResult}
classifyQRCode={classifyQRCode}
startScanning={startScanning}
stopScanning={stopScanning}
setModalOpen={setModalOpen}
qrError={qrError}
/>
</>
);
}
-352
View File
@@ -1,352 +0,0 @@
import { useState, useEffect } from 'react';
import { Zap, Coins, Copy, Check, QrCode, Link, Key } from 'lucide-react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import { LoginIcon } from '@/components/auth/LoginIcon';
import { MintSelector } from './MintSelector';
import { UTXOSelector } from './UTXOSelector';
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
import { UTXO } from '@/lib/bitcoin';
interface CashuMint {
url: string;
name?: string;
}
interface WalletHeaderProps {
totalBalance: number;
balances: { [key: string]: number };
showSats: boolean;
setShowSats: (showSats: boolean) => void;
mode: 'tokens' | 'lightning' | 'bitcoin';
setMode: (mode: 'tokens' | 'lightning' | 'bitcoin') => void;
userPubkey?: string;
npubCashUsername?: string;
mnemonic?: string | null;
onCopyToClipboard: (text: string) => Promise<void>;
onShowLightningAddressQR: (qrCode: string) => void;
onShowBitcoinAddressQR: (qrCode: string) => void;
onShowSeedPhraseInfo: () => void;
generateQRCode: (text: string) => Promise<string>;
// MintSelector props
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
// UTXOSelector props
utxos: UTXO[];
utxoDropdownOpen: boolean;
setUtxoDropdownOpen: (open: boolean) => void;
onShowConsolidationModal?: () => void;
isConsolidating?: boolean;
}
// Helper functions to prevent syntax errors in complex expressions
// These functions break down complex inline logic to make the code more maintainable
// and less prone to syntax errors when AI agents edit this file
const formatBalance = (balance: number, showSats: boolean, btcUsdRate?: number | null): string => {
if (showSats) {
return balance.toLocaleString();
}
if (btcUsdRate) {
const usdAmount = (balance / 100000000 * btcUsdRate).toFixed(2);
return usdAmount;
}
return balance.toLocaleString();
};
const getBalanceSymbol = (showSats: boolean): JSX.Element => {
return showSats ? (
<span className="text-orange-500/70">₿</span>
) : (
<span className="text-green-500/70">$</span>
);
};
const getToggleTitle = (showSats: boolean): string => {
return `Click to show in ${showSats ? 'USD' : 'sats'}`;
};
const getButtonTitle = (mode: string): string => {
switch (mode) {
case 'tokens': return 'Switch to On-Chain';
case 'lightning': return 'Switch to Cashu';
case 'bitcoin': return 'Switch to Lightning';
default: return 'Switch Mode';
}
};
export function WalletHeader({
totalBalance,
balances,
showSats,
setShowSats,
mode,
setMode,
userPubkey,
npubCashUsername,
mnemonic,
onCopyToClipboard,
onShowLightningAddressQR,
onShowBitcoinAddressQR,
onShowSeedPhraseInfo,
generateQRCode,
// MintSelector props
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
dropdownOpen,
setDropdownOpen,
// UTXOSelector props
utxos,
utxoDropdownOpen,
setUtxoDropdownOpen,
onShowConsolidationModal,
isConsolidating,
}: WalletHeaderProps) {
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
const [mnemonicCopied, setMnemonicCopied] = useState(false);
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const toggleMode = () => {
let newMode: 'tokens' | 'lightning' | 'bitcoin';
if (mode === 'lightning') {
newMode = 'tokens';
} else if (mode === 'tokens') {
newMode = 'bitcoin';
} else {
newMode = 'lightning';
}
setMode(newMode);
};
return (
<div className="flex flex-col items-center pt-10 space-y-2">
{/* Mode Toggle */}
<div className="absolute top-3 left-3 sm:left-4 z-10">
<button
onClick={toggleMode}
className="p-3 rounded-full bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
title={getButtonTitle(mode)}
>
{mode === 'tokens' ? (
<Coins className="h-6 w-6" />
) : mode === 'lightning' ? (
<Zap className="h-6 w-6" />
) : (
<Link className="h-6 w-6" />
)}
</button>
</div>
{/* Login Icon */}
<div className="absolute top-3 right-3 sm:right-4 z-10">
<LoginIcon />
</div>
{/* Balance Display */}
<div className="text-center py-2">
<div className="flex items-center justify-center gap-3">
<button
onClick={() => setShowSats(!showSats)}
className="text-6xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
title={getToggleTitle(showSats)}
>
<span className="italic">
{getBalanceSymbol(showSats)}
</span>
{formatBalance(totalBalance, showSats, btcUsdRate)}
</button>
{/* Custody Badge */}
<span className={`px-2 py-1 text-xs font-medium rounded-full ${
mode === 'bitcoin'
? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
}`}>
{mode === 'bitcoin' ? 'Self-Custody' : 'Mint-Custody'}
</span>
</div>
{/* Lightning Address and Mint Selector Grid */}
<div className="mt-3 px-4">
<div className="w-full max-w-[400px] mx-auto">
<div className="grid grid-cols-1 gap-3">
{/* Lightning Address Row */}
{userPubkey && mode === 'lightning' && (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
const lightningAddress = `${npubCashUsername}@npubx.cash`;
await onCopyToClipboard(lightningAddress);
setLightningAddressCopied(true);
setTimeout(() => setLightningAddressCopied(false), 2000);
}}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
title="Click to copy Lightning address"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{npubCashUsername || ''}
</span>
<span className="flex-shrink-0 text-muted-foreground">
@npubx.cash
</span>
</div>
{lightningAddressCopied ? (
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
) : (
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
)}
</button>
<button
onClick={async () => {
const lightningAddress = `${npubCashUsername}@npubx.cash`;
const qr = await generateQRCode(lightningAddress);
onShowLightningAddressQR(qr);
}}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="Show QR Code"
>
<QrCode className="h-4 w-4" />
</button>
</div>
)}
{/* Mnemonic Seed Phrase Row */}
{mode === 'tokens' && mnemonic && (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
await onCopyToClipboard(mnemonic);
setMnemonicCopied(true);
setTimeout(() => setMnemonicCopied(false), 2000);
}}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
title="Click to copy seed phrase"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{mnemonic.split(' ').map(() => '****').join(' ')}
</span>
</div>
{mnemonicCopied ? (
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
) : (
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
)}
</button>
<button
onClick={onShowSeedPhraseInfo}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="What is a seed phrase?"
>
<Key className="h-4 w-4" />
</button>
</div>
)}
{/* Bitcoin Address Row */}
{userPubkey && mode === 'bitcoin' && (() => {
const bitcoinAddress = nostrPubkeyToBitcoinAddress(userPubkey);
return bitcoinAddress ? (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
await onCopyToClipboard(bitcoinAddress);
setBitcoinAddressCopied(true);
setTimeout(() => setBitcoinAddressCopied(false), 2000);
}}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
title="Click to copy Bitcoin address"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{bitcoinAddress}
</span>
</div>
{bitcoinAddressCopied ? (
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
) : (
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
)}
</button>
<button
onClick={async () => {
const qr = await generateQRCode(bitcoinAddress);
onShowBitcoinAddressQR(qr);
}}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="Show QR Code"
>
<QrCode className="h-4 w-4" />
</button>
</div>
) : null;
})()}
{/* UTXO Selector Row */}
{mode === 'bitcoin' && (
<div className="min-w-[300px]">
<UTXOSelector
utxos={utxos}
showSats={showSats}
bitcoinAddress={userPubkey ? nostrPubkeyToBitcoinAddress(userPubkey) : ''}
dropdownOpen={utxoDropdownOpen}
setDropdownOpen={setUtxoDropdownOpen}
onShowConsolidationModal={onShowConsolidationModal}
isConsolidating={isConsolidating}
/>
</div>
)}
{/* Mint Selector Row */}
{mode !== 'bitcoin' && (
<div className="min-w-[300px]">
<MintSelector
balances={balances}
showSats={showSats}
activeMintUrl={activeMintUrl}
setActiveMintUrl={setActiveMintUrl}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={onAddMint}
onRemoveMint={onRemoveMint}
onShowDenominations={onShowDenominations}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={dropdownOpen}
setDropdownOpen={setDropdownOpen}
/>
</div>
)}
</div>
</div>
</div>
</div>
</div>
);
}
-21
View File
@@ -1,21 +0,0 @@
import { createContext } from "react";
export type Theme = "dark" | "light" | "system";
export interface AppConfig {
/** Current theme */
theme: Theme;
/** Selected relay URL */
relayUrl: string;
}
export interface AppContextType {
/** Current application configuration */
config: AppConfig;
/** Update configuration using a callback that receives current config and returns new config */
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
export const AppContext = createContext<AppContextType | undefined>(undefined);
-24
View File
@@ -1,24 +0,0 @@
import { createContext, useContext, ReactNode } from 'react';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/wallet/useCashu';
const CashuContext = createContext<UseCashuReturn | null>(null);
export function CashuProvider({ children }: { children: ReactNode }) {
const cashu = useCashuHook();
return (
<CashuContext.Provider value={cashu}>
{children}
</CashuContext.Provider>
);
}
export function useCashuContext(): UseCashuReturn {
const context = useContext(CashuContext);
if (!context) {
throw new Error('useCashuContext must be used within a CashuProvider');
}
return context;
}
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more