5 Commits
260 changed files with 6084 additions and 17703 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
../.mcp.json
-2
View File
@@ -7,13 +7,11 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
.ai/
yarn.lock
# Editor directories and files
.idea
+1
View File
@@ -0,0 +1 @@
@jsr:registry=https://npm.jsr.io
+180 -234
View File
@@ -15,11 +15,9 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
## Project Structure
- `/docs/`: Specialized documentation for implementation patterns and features
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/components/dm/`: Direct messaging UI components (DMMessagingInterface, DMConversationList, DMChatArea)
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
@@ -34,16 +32,13 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
- **Cashu hooks**: `useCashu` (core wallet management), `useMintManager` (mint operations), `useWalletTransactions` (send/receive), `useHistoryManager` (transaction history) - See **`docs/CASHU_WALLET.md`** for comprehensive implementation guide
- **Bitcoin hooks**: `useBitcoinBalance` (UTXO tracking), `useNsecAccess` (private key access for signing) - See **`docs/BITCOIN_WALLET.md`** for Bitcoin wallet architecture and operations
- **Integration hooks**: `useNpubCash` (npub.cash API), `useLightningAddress` (Lightning address validation), `useWallet` (unified wallet detection), `useNWC` (Nostr Wallet Connect), `useNWCContext` (NWC context provider) - See **`docs/CASHU_WALLET.md`** for integration patterns
- `useShakespeare`: AI chat completions with Shakespeare AI API
- `useZaps`: Lightning zap functionality with payment processing
- `useWallet`: Unified wallet detection (WebLN + NWC)
- `useNWC`: Nostr Wallet Connect connection management
- `useNWCContext`: Access NWC context provider
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
- `useDMContext`: Hook exported from DMContext for direct messaging (NIP-04 & NIP-17)
- `useConversationMessages`: Hook exported from DMContext for paginated messages
- `/src/contexts/`: React context providers (AppContext, NWCContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
@@ -102,22 +97,6 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
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.
## Documentation
The project includes a **`docs/`** directory containing specialized documentation for specific implementation tasks. You are encouraged to add new documentation files to help future development.
- **`docs/AI_CHAT.md`**: Read when building any AI-powered chat interfaces, implementing streaming responses, or integrating with the Shakespeare API.
- **`docs/NOSTR_COMMENTS.md`**: Read when implementing comment systems, adding discussion features to posts/articles, or building community interaction features.
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
- **`docs/NOSTR_DIRECT_MESSAGES.md`**: Read when implementing direct messaging features, building chat interfaces, or working with encrypted peer-to-peer communication (NIP-04 and NIP-17).
- **`docs/CASHU_WALLET.md`**: Read when implementing Cashu/eCash wallet features, Lightning payments, mint management, token operations, or working with the coco-cashu-core library. This guide covers architecture, component structure, hook patterns, and best practices for the Cashu wallet system.
- **`docs/BITCOIN_WALLET.md`**: Read when implementing on-chain Bitcoin wallet features, UTXO management, Bitcoin transactions, consolidation, or working with Bitcoin addresses derived from Nostr pubkeys. This guide covers the Bitcoin wallet architecture, transaction flows, and integration patterns.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
@@ -125,9 +104,9 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly
2. The changes take effect in the next session
## "Vibed with NutStack"
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with NutStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
@@ -135,9 +114,9 @@ This project comes with custom hooks for querying and publishing events on the N
### Nostr Implementation Guidelines
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers if no existing suitable kinds are found after comprehensive research.
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
@@ -145,7 +124,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
@@ -163,7 +142,7 @@ When implementing features that could use existing NIPs, follow this decision fr
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
@@ -302,85 +281,6 @@ function useCustomHook() {
}
```
### Connecting to Multiple Nostr Relays
By default, the `nostr` object from `useNostr` uses a pool configuration that reads data from 1 relay and publishes to all configured relays. However, you can connect to specific relays or groups of relays for more granular control:
#### Single Relay Connection
To read and publish from one specific relay, use `nostr.relay()` with a WebSocket URL:
```typescript
import { useNostr } from '@nostrify/react';
function useSpecificRelay() {
const { nostr } = useNostr();
// Connect to a specific relay
const relay = nostr.relay('wss://relay.damus.io');
// Query from this specific relay only
const events = await relay.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to this specific relay only
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
}
```
#### Multiple Relay Group
To read and publish from a specific set of relays, use `nostr.group()` with an array of relay URLs:
```typescript
import { useNostr } from '@nostrify/react';
function useRelayGroup() {
const { nostr } = useNostr();
// Create a group of specific relays
const relayGroup = nostr.group([
'wss://relay.damus.io',
'wss://relay.nostr.band',
'wss://nos.lol'
]);
// Query from all relays in the group
const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to all relays in the group
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
}
```
#### API Consistency
Both `relay` and `group` objects have the same API as the main `nostr` object, including:
- `.query()` - Query events with filters
- `.req()` - Create subscriptions
- `.event()` - Publish events
- All other Nostr protocol methods
#### Use Cases
**Single Relay (`nostr.relay()`):**
- Testing specific relay behavior
- Querying relay-specific content
- Debugging connectivity issues
- Working with specialized relays
**Relay Group (`nostr.group()`):**
- Querying from trusted relay sets
- Publishing to specific communities
- Load balancing across relay subsets
- Geographic relay optimization
**Default Pool (`nostr`):**
- General application queries
- Maximum reach for publishing
- Default user experience
- Simplified relay management
### 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.
@@ -403,7 +303,71 @@ function usePosts() {
}
```
### Efficient Query Design
### Infinite Scroll for 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';
function GlobalFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, fetchNextPage]);
const posts = data?.pages.flat() || [];
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>
);
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
@@ -443,7 +407,7 @@ const [notes, reposts, genericReposts] = await Promise.all([
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.
### Event Validation
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
@@ -514,7 +478,7 @@ function Post({ event }: { event: NostrEvent }) {
}
```
### `NostrMetadata` type
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
@@ -753,20 +717,6 @@ function EditProfilePage() {
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Direct Messaging (NIP-04 & NIP-17)
The project includes a complete direct messaging system with real-time updates, encrypted storage, and support for both NIP-04 (legacy) and NIP-17 (modern private messaging) protocols. **The system is disabled by default** - enable it by passing `enabled: true` in the `DMProvider` config.
For complete implementation guide including:
- Setup and configuration
- Sending messages and file attachments
- Using the `DMMessagingInterface` component
- Building custom messaging UIs
- Protocol comparison (NIP-04 vs NIP-17)
- Advanced features and architecture
See **`docs/NOSTR_DIRECT_MESSAGES.md`**
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
@@ -833,6 +783,61 @@ export function Post(/* ...props */) {
}
```
### Adding Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
@@ -871,6 +876,34 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
### Import Extensions
This project uses ES modules with Node.js-style module resolution (`"type": "module"` and `"moduleResolution": "nodenext"`). **All imports MUST include explicit file extensions**, and specifically **`.js` extensions must be used** even when importing TypeScript files.
This is because TypeScript compiles to JavaScript, and the runtime expects the actual file extensions that will exist after compilation.
#### Examples
**✅ Correct imports with .js extensions:**
```typescript
// Import TypeScript files with .js extension
import { useAuthor } from '@/hooks/useAuthor.js';
import { Button } from '@/components/ui/button.js';
import { LoginArea } from "@/components/auth/LoginArea.js";
import AppRouter from "./AppRouter.js";
import { cn } from '@/lib/utils.js';
```
**❌ Wrong imports (wrong extensions or no extension):**
```typescript
// These will cause build/runtime errors
import { useAuthor } from '@/hooks/useAuthor';
import { Button } from '@/components/ui/button.tsx';
import { LoginArea } from "@/components/auth/LoginArea.jsx";
import AppRouter from "./AppRouter";
import { cn } from '@/lib/utils.ts';
```
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
@@ -919,66 +952,28 @@ import { Card, CardContent } from '@/components/ui/card';
</div>
```
## CRITICAL Design Standards
## Design Customization
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
**Tailor the site's look and feel based on the user's specific request.** This includes:
### Design Principles
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design’s emotional tone
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
### Avoid Generic Design
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
### Interaction Patterns
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
- Incorporate contextual menus, smart tooltips, and visual cues to enhance navigation and usability
- Implement drag-and-drop, hover effects, and transitions with clear, dynamic visual feedback to elevate the user experience
- Support power users with keyboard shortcuts, ARIA labels, and focus states for accessibility and efficiency
- Add subtle parallax effects or scroll-triggered animations to create depth and engagement without overwhelming the user
### Technical Requirements
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
- Adhere to WCAG 2.1 AA guidelines, including keyboard navigation, screen reader support, and reduced motion options
- Follow an 8px grid system for consistent spacing, padding, and alignment to ensure visual harmony
- Add depth with subtle shadows, gradients, glows, and rounded corners (e.g., 16px radius) to create a polished, modern aesthetic
- Optimize animations and interactions to be lightweight and performant, ensuring smooth experiences across devices
### Components
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using npm:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `@fontsource-variable/inter`
- For Roboto: `@fontsource/roboto`
- For Outfit Variable: `@fontsource-variable/outfit`
- For Poppins: `@fontsource/poppins`
- For Open Sans: `@fontsource/open-sans`
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
@@ -1031,39 +1026,6 @@ When users specify color schemes:
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
### Dialog Component Patterns
When using Dialog components, always ensure accessibility compliance by including required elements:
```tsx
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
// ✅ Correct - Always include DialogHeader with DialogTitle
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent>
<DialogHeader>
<DialogTitle>Dialog Title</DialogTitle>
<DialogDescription>
Optional description for screen readers
</DialogDescription>
</DialogHeader>
{/* Dialog content */}
</DialogContent>
</Dialog>
```
**Important**: Even if you want to hide the title visually, use the `VisuallyHidden` component to maintain accessibility:
```tsx
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
<DialogHeader>
<VisuallyHidden>
<DialogTitle>Hidden Title for Screen Readers</DialogTitle>
</VisuallyHidden>
</DialogHeader>
```
## Writing Tests vs Running Tests
There is an important distinction between **writing new tests** and **running existing tests**:
@@ -1084,7 +1046,7 @@ There is an important distinction between **writing new tests** and **running ex
### Running Tests (Executing the Test Suite)
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
- **You must run the test script** to validate your changes
- **You must run the test script** using `js-dev__run_script` tool with the "test" parameter
- **Your task is not complete** until the test script passes without errors
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
@@ -1118,26 +1080,10 @@ describe('MyComponent', () => {
});
```
## Validating Your Changes
## Testing Your Changes
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
**CRITICAL**: Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
**Your task is not considered finished until this test passes without errors.**
### Validation Priority Order
Run available tools in this priority order:
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
2. **Building/Compilation** (Required): Verify the project builds successfully
3. **Linting** (Recommended): Check code style and catch potential issues
4. **Tests** (If Available): Run existing test suite
5. **Git Commit** (Required): Create a commit with your changes when finished
**Minimum Requirements:**
- Code must type-check without errors
- Code must build/compile successfully
- Fix any critical linting errors that would break functionality
- Create a git commit when your changes are complete
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
**This requirement applies regardless of whether you wrote new tests or not.** The test script validates the entire codebase, including TypeScript compilation, ESLint rules, and existing test suite.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+1 -236
View File
@@ -1,238 +1,3 @@
# MKStack
**The Complete Framework for Building Nostr Clients with AI**
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.
## 🚀 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.*
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
-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>
);
}
```
+1 -6
View File
@@ -2,13 +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 name="viewport" content="width=device-width, initial-scale=1.0" />
<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">
</head>
<body>
+1244 -2850
View File
File diff suppressed because it is too large. Load diff
+9 -21
View File
@@ -4,18 +4,18 @@
"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 && cp dist/index.html dist/404.html",
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
"check": "tsc -p tsconfig.app.json --noEmit",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@bitcoinerlab/secp256k1": "^1.2.0",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@getalby/sdk": "^6.0.0",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -43,28 +43,17 @@
"@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",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
@@ -77,6 +66,7 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71"
},
"devDependencies": {
@@ -84,7 +74,6 @@
"@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",
@@ -92,7 +81,6 @@
"@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",
-2
View File
@@ -1,2 +0,0 @@
User-agent: *
Allow: /
+42
View File
@@ -0,0 +1,42 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// 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.js';
import { Toaster } from "@/components/ui/toaster.js";
import { TooltipProvider } from "@/components/ui/tooltip.js";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider.js';
import { NWCProvider } from '@/contexts/NWCContext.js';
import AppRouter from "./AppRouter.js";
const head = createHead({
plugins: [
InferSeoMetaPlugin(),
],
});
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: 60000, // 1 minute
gcTime: Infinity,
},
},
});
const defaultConfig = {
theme: "light",
relayUrl: "wss://relay.primal.net",
};
const presetRelays = [
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
export function App() {
return (_jsx(UnheadProvider, { head: head, children: _jsx(AppProvider, { storageKey: "nostr:app-config", defaultConfig: defaultConfig, presetRelays: presetRelays, children: _jsx(QueryClientProvider, { client: queryClient, children: _jsx(NostrLoginProvider, { storageKey: 'nostr:login', children: _jsx(NostrProvider, { children: _jsx(NWCProvider, { children: _jsxs(TooltipProvider, { children: [_jsx(Toaster, {}), _jsx(Suspense, { children: _jsx(AppRouter, {}) })] }) }) }) }) }) }) }));
}
export default App;
+7
View File
@@ -0,0 +1,7 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { render } from '@testing-library/react';
import { test } from 'vitest';
import App from "./App.js";
test('App', () => {
render(_jsx(App, {}));
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { render } from '@testing-library/react';
import { test } from 'vitest';
import App from './App';
import App from "./App.js";
test('App', () => {
render(<App />);
+16 -31
View File
@@ -5,16 +5,14 @@ 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 { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import NostrProvider from '@/components/NostrProvider.js';
import { Toaster } from "@/components/ui/toaster.js";
import { TooltipProvider } from "@/components/ui/tooltip.js";
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';
import { AppProvider } from '@/components/AppProvider.js';
import { NWCProvider } from '@/contexts/NWCContext.js';
import { AppConfig } from '@/contexts/AppContext.js';
import AppRouter from "./AppRouter.js";
const head = createHead({
plugins: [
@@ -33,28 +31,17 @@ const queryClient = new QueryClient({
});
const defaultConfig: AppConfig = {
theme: "system",
relayUrl: "wss://relay.ditto.pub",
theme: "light",
relayUrl: "wss://relay.primal.net",
};
const presetRelays = [
{ url: 'wss://relay.ditto.pub', name: 'Ditto' },
{ url: 'wss://ditto.pub/relay', 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,
};
export function App() {
return (
<UnheadProvider head={head}>
@@ -63,14 +50,12 @@ export function App() {
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NWCProvider>
<DMProvider config={dmConfig}>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</DMProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
+10
View File
@@ -0,0 +1,10 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop.js";
import Index from "./pages/Index.js";
import { NIP19Page } from "./pages/NIP19Page.js";
import NotFound from "./pages/NotFound.js";
export function AppRouter() {
return (_jsxs(BrowserRouter, { children: [_jsx(ScrollToTop, {}), _jsxs(Routes, { children: [_jsx(Route, { path: "/", element: _jsx(Index, {}) }), _jsx(Route, { path: "/:nip19", element: _jsx(NIP19Page, {}) }), _jsx(Route, { path: "*", element: _jsx(NotFound, {}) })] })] }));
}
export default AppRouter;
+4 -8
View File
@@ -1,11 +1,9 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { ScrollToTop } from "./components/ScrollToTop.js";
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";
import Index from "./pages/Index.js";
import { NIP19Page } from "./pages/NIP19Page.js";
import NotFound from "./pages/NotFound.js";
export function AppRouter() {
return (
@@ -13,8 +11,6 @@ export function AppRouter() {
<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 */}
+65
View File
@@ -0,0 +1,65 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage.js';
import { AppContext } from '@/contexts/AppContext.js';
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
});
export function AppProvider(props) {
const { children, storageKey, defaultConfig, presetRelays, } = props;
// App configuration state with localStorage persistence
const [config, setConfig] = useLocalStorage(storageKey, defaultConfig, {
serialize: JSON.stringify,
deserialize: (value) => {
const parsed = JSON.parse(value);
return AppConfigSchema.parse(parsed);
}
});
// Generic config updater with callback pattern
const updateConfig = (updater) => {
setConfig(updater);
};
const appContextValue = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
useApplyTheme(config.theme);
return (_jsx(AppContext.Provider, { value: appContextValue, children: children }));
}
/**
* Hook to apply theme changes to the document root
*/
function useApplyTheme(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]);
}
+10 -12
View File
@@ -1,7 +1,7 @@
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';
import { useLocalStorage } from '@/hooks/useLocalStorage.js';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext.js';
interface AppProviderProps {
children: ReactNode;
@@ -14,10 +14,10 @@ interface AppProviderProps {
}
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
}) satisfies z.ZodType<AppConfig>;
});
export function AppProvider(props: AppProviderProps) {
const {
@@ -28,25 +28,23 @@ export function AppProvider(props: AppProviderProps) {
} = props;
// App configuration state with localStorage persistence
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
const [config, setConfig] = useLocalStorage<AppConfig>(
storageKey,
{},
defaultConfig,
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.partial().parse(parsed);
return AppConfigSchema.parse(parsed);
}
}
);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
setConfig(updater);
};
const config = { ...defaultConfig, ...rawConfig };
const appContextValue: AppContextType = {
config,
updateConfig,
@@ -90,11 +88,11 @@ function useApplyTheme(theme: Theme) {
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);
};
+120
View File
@@ -0,0 +1,120 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useNostrPublish } from '@/hooks/useNostrPublish.js';
import { useToast } from '@/hooks/useToast.js';
import { Button } from '@/components/ui/button.js';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from '@/components/ui/form.js';
import { Input } from '@/components/ui/input.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Switch } from '@/components/ui/switch.js';
import { Loader2, Upload } from 'lucide-react';
import { NSchema as n } from '@nostrify/nostrify';
import { useQueryClient } from '@tanstack/react-query';
import { useUploadFile } from '@/hooks/useUploadFile.js';
export const EditProfileForm = () => {
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({
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, field) => {
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) => {
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 (_jsx(Form, { ...form, children: _jsxs("form", { onSubmit: form.handleSubmit(onSubmit), className: "space-y-6", children: [_jsx(FormField, { control: form.control, name: "name", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "Name" }), _jsx(FormControl, { children: _jsx(Input, { placeholder: "Your name", ...field }) }), _jsx(FormDescription, { children: "This is your display name that will be displayed to others." }), _jsx(FormMessage, {})] })) }), _jsx(FormField, { control: form.control, name: "about", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "Bio" }), _jsx(FormControl, { children: _jsx(Textarea, { placeholder: "Tell others about yourself", className: "resize-none", ...field }) }), _jsx(FormDescription, { children: "A short description about yourself." }), _jsx(FormMessage, {})] })) }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsx(FormField, { control: form.control, name: "picture", render: ({ field }) => (_jsx(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') })) }), _jsx(FormField, { control: form.control, name: "banner", render: ({ field }) => (_jsx(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') })) })] }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsx(FormField, { control: form.control, name: "website", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "Website" }), _jsx(FormControl, { children: _jsx(Input, { placeholder: "https://yourwebsite.com", ...field }) }), _jsx(FormDescription, { children: "Your personal website or social media link." }), _jsx(FormMessage, {})] })) }), _jsx(FormField, { control: form.control, name: "nip05", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "NIP-05 Identifier" }), _jsx(FormControl, { children: _jsx(Input, { placeholder: "[email protected]", ...field }) }), _jsx(FormDescription, { children: "Your verified Nostr identifier." }), _jsx(FormMessage, {})] })) })] }), _jsx(FormField, { control: form.control, name: "bot", render: ({ field }) => (_jsxs(FormItem, { className: "flex flex-row items-center justify-between rounded-lg border p-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(FormLabel, { className: "text-base", children: "Bot Account" }), _jsx(FormDescription, { children: "Mark this account as automated or a bot." })] }), _jsx(FormControl, { children: _jsx(Switch, { checked: field.value, onCheckedChange: field.onChange }) })] })) }), _jsxs(Button, { type: "submit", className: "w-full md:w-auto", disabled: isPending || isUploading, children: [(isPending || isUploading) && (_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" })), "Save Profile"] })] }) }));
};
const ImageUploadField = ({ field, label, placeholder, description, previewType, onUpload, }) => {
const fileInputRef = useRef(null);
return (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: label }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(FormControl, { children: _jsx(Input, { placeholder: placeholder, name: field.name, value: field.value ?? '', onChange: e => field.onChange(e.target.value), onBlur: field.onBlur }) }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("input", { type: "file", ref: fileInputRef, accept: "image/*", className: "hidden", onChange: (e) => {
const file = e.target.files?.[0];
if (file) {
onUpload(file);
}
} }), _jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: () => fileInputRef.current?.click(), children: [_jsx(Upload, { className: "h-4 w-4 mr-2" }), "Upload Image"] }), field.value && (_jsx("div", { className: `h-10 ${previewType === 'square' ? 'w-10' : 'w-24'} rounded overflow-hidden`, children: _jsx("img", { src: field.value, alt: `${label} preview`, className: "h-full w-full object-cover" }) }))] })] }), _jsx(FormDescription, { children: description }), _jsx(FormMessage, {})] }));
};
+21 -21
View File
@@ -1,10 +1,10 @@
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 { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useNostrPublish } from '@/hooks/useNostrPublish.js';
import { useToast } from '@/hooks/useToast.js';
import { Button } from '@/components/ui/button.js';
import {
Form,
FormControl,
@@ -13,14 +13,14 @@ import {
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';
} from '@/components/ui/form.js';
import { Input } from '@/components/ui/input.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Switch } from '@/components/ui/switch.js';
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';
import { useUploadFile } from '@/hooks/useUploadFile.js';
export const EditProfileForm: React.FC = () => {
const queryClient = useQueryClient();
@@ -151,10 +151,10 @@ export const EditProfileForm: React.FC = () => {
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea
placeholder="Tell others about yourself"
className="resize-none"
{...field}
<Textarea
placeholder="Tell others about yourself"
className="resize-none"
{...field}
/>
</FormControl>
<FormDescription>
@@ -254,9 +254,9 @@ export const EditProfileForm: React.FC = () => {
)}
/>
<Button
type="submit"
className="w-full md:w-auto"
<Button
type="submit"
className="w-full md:w-auto"
disabled={isPending || isUploading}
>
{(isPending || isUploading) && (
@@ -308,8 +308,8 @@ const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
/>
</FormControl>
<div className="flex items-center gap-2">
<input
type="file"
<input
type="file"
ref={fileInputRef}
accept="image/*"
className="hidden"
@@ -331,9 +331,9 @@ const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
</Button>
{field.value && (
<div className={`h-10 ${previewType === 'square' ? 'w-10' : 'w-24'} rounded overflow-hidden`}>
<img
src={field.value}
alt={`${label} preview`}
<img
src={field.value}
alt={`${label} preview`}
className="h-full w-full object-cover"
/>
</div>
+41
View File
@@ -0,0 +1,41 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Component } from 'react';
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error) {
return {
hasError: true,
error,
};
}
componentDidCatch(error, 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 (_jsx("div", { className: "min-h-screen bg-background flex items-center justify-center p-4", children: _jsxs("div", { className: "max-w-md w-full space-y-4", children: [_jsxs("div", { className: "text-center", children: [_jsx("h2", { className: "text-2xl font-bold text-foreground mb-2", children: "Something went wrong" }), _jsx("p", { className: "text-muted-foreground", children: "An unexpected error occurred. The error has been reported." })] }), _jsx("div", { className: "bg-muted p-4 rounded-lg", children: _jsxs("details", { className: "text-sm", children: [_jsx("summary", { className: "cursor-pointer font-medium text-foreground", children: "Error details" }), _jsxs("div", { className: "mt-2 space-y-2", children: [_jsxs("div", { children: [_jsx("strong", { className: "text-foreground", children: "Message:" }), _jsx("p", { className: "text-muted-foreground mt-1", children: this.state.error?.message })] }), this.state.error?.stack && (_jsxs("div", { children: [_jsx("strong", { className: "text-foreground", children: "Stack trace:" }), _jsx("pre", { className: "text-xs text-muted-foreground mt-1 overflow-auto max-h-32", children: this.state.error.stack })] }))] })] }) }), _jsxs("div", { className: "flex gap-2", children: [_jsx("button", { onClick: this.handleReset, className: "flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors", children: "Try again" }), _jsx("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", children: "Reload page" })] })] }) }));
}
return this.props.children;
}
}
+45
View File
@@ -0,0 +1,45 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useRef } from 'react';
import { NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext.js';
const NostrProvider = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
const queryClient = useQueryClient();
// Create NPool instance only once
const pool = useRef(undefined);
// Use refs so the pool always has the latest data
const relayUrl = useRef(config.relayUrl);
// Update refs when config changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
if (!pool.current) {
pool.current = new NPool({
open(url) {
return new NRelay1(url);
},
reqRouter(filters) {
return new Map([[relayUrl.current, filters]]);
},
eventRouter(_event) {
// Publish to the selected relay
const allRelays = new Set([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 (_jsx(NostrContext.Provider, { value: { nostr: pool.current }, children: children }));
};
export default NostrProvider;
+3 -3
View File
@@ -2,7 +2,7 @@ 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 { useAppContext } from '@/hooks/useAppContext.js';
interface NostrProviderProps {
children: React.ReactNode;
@@ -20,10 +20,10 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
// Use refs so the pool always has the latest data
const relayUrl = useRef<string>(config.relayUrl);
// Invalidate Nostr queries when relayUrl changes
// Update refs when config changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.invalidateQueries({ queryKey: ['nostr'] });
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
+77
View File
@@ -0,0 +1,77 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor.js';
import { genUserName } from '@/lib/genUserName.js';
import { cn } from '@/lib/utils.js';
/** Parses content of text note events so that URLs and hashtags are linkified. */
export function NoteContent({ event, className, }) {
// 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 = [];
let lastIndex = 0;
let match;
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(_jsx("a", { href: url, target: "_blank", rel: "noopener noreferrer", className: "text-blue-500 hover:underline", children: url }, `url-${keyCounter++}`));
}
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(_jsx(NostrMention, { pubkey: pubkey }, `mention-${keyCounter++}`));
}
else {
// For other types, just show as a link
parts.push(_jsx(Link, { to: `/${nostrId}`, className: "text-blue-500 hover:underline", children: fullMatch }, `nostr-${keyCounter++}`));
}
}
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(_jsx(Link, { to: `/t/${tag}`, className: "text-blue-500 hover:underline", children: hashtag }, `hashtag-${keyCounter++}`));
}
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 (_jsx("div", { className: cn("whitespace-pre-wrap break-words", className), children: content.length > 0 ? content : event.content }));
}
// Helper component to display user mentions
function NostrMention({ pubkey }) {
const author = useAuthor(pubkey);
const npub = nip19.npubEncode(pubkey);
const hasRealName = !!author.data?.metadata?.name;
const displayName = author.data?.metadata?.name ?? genUserName(pubkey);
return (_jsxs(Link, { to: `/${npub}`, className: cn("font-medium hover:underline", hasRealName
? "text-blue-500"
: "text-gray-500 hover:text-gray-700"), children: ["@", displayName] }));
}
+98
View File
@@ -0,0 +1,98 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp.js';
import { NoteContent } from "./NoteContent.js";
describe('NoteContent', () => {
it('linkifies URLs in kind 1 events', () => {
const event = {
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(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
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 = {
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(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
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 = {
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(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
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 = {
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(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
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 = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: `Mentioning nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0`,
sig: 'test-sig',
};
render(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
// 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");
});
});
+5 -5
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { NoteContent } from './NoteContent';
import { TestApp } from '@/test/TestApp.js';
import { NoteContent } from "./NoteContent.js";
import type { NostrEvent } from '@nostrify/nostrify';
describe('NoteContent', () => {
@@ -95,7 +95,7 @@ describe('NoteContent', () => {
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');
@@ -123,11 +123,11 @@ describe('NoteContent', () => {
// 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
+3 -3
View File
@@ -2,9 +2,9 @@ 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';
import { useAuthor } from '@/hooks/useAuthor.js';
import { genUserName } from '@/lib/genUserName.js';
import { cn } from '@/lib/utils.js';
interface NoteContentProps {
event: NostrEvent;
+65
View File
@@ -0,0 +1,65 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils.js";
import { Button } from "@/components/ui/button.js";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/components/ui/command.js";
import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover.js";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext.js";
export function RelaySelector(props) {
const { className } = props;
const { config, updateConfig, presetRelays = [] } = useAppContext();
const selectedRelay = config.relayUrl;
const setSelectedRelay = (relay) => {
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) => {
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) => {
setSelectedRelay?.(normalizeRelayUrl(url));
setOpen(false);
setInputValue("");
};
// Check if input value looks like a valid relay URL
const isValidRelayInput = (value) => {
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 (_jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { variant: "outline", role: "combobox", "aria-expanded": open, className: cn("justify-between", className), children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Wifi, { className: "h-4 w-4" }), _jsx("span", { className: "truncate", children: selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..." })] }), _jsx(ChevronsUpDown, { className: "ml-2 h-4 w-4 shrink-0 opacity-50" })] }) }), _jsx(PopoverContent, { className: "w-[300px] p-0", children: _jsxs(Command, { children: [_jsx(CommandInput, { placeholder: "Search relays or type URL...", value: inputValue, onValueChange: setInputValue }), _jsxs(CommandList, { children: [_jsx(CommandEmpty, { children: inputValue && isValidRelayInput(inputValue) ? (_jsxs(CommandItem, { onSelect: () => handleAddCustomRelay(inputValue), className: "cursor-pointer", children: [_jsx(Plus, { className: "mr-2 h-4 w-4" }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "font-medium", children: "Add custom relay" }), _jsx("span", { className: "text-xs text-muted-foreground", children: normalizeRelayUrl(inputValue) })] })] })) : (_jsx("div", { className: "py-6 text-center text-sm text-muted-foreground", children: inputValue ? "Invalid relay URL" : "No relay found." })) }), _jsxs(CommandGroup, { children: [presetRelays
.filter((option) => !inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase()))
.map((option) => (_jsxs(CommandItem, { value: option.url, onSelect: (currentValue) => {
setSelectedRelay(normalizeRelayUrl(currentValue));
setOpen(false);
setInputValue("");
}, children: [_jsx(Check, { className: cn("mr-2 h-4 w-4", selectedRelay === option.url ? "opacity-100" : "opacity-0") }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "font-medium", children: option.name }), _jsx("span", { className: "text-xs text-muted-foreground", children: option.url })] })] }, option.url))), inputValue && isValidRelayInput(inputValue) && (_jsxs(CommandItem, { onSelect: () => handleAddCustomRelay(inputValue), className: "cursor-pointer border-t", children: [_jsx(Plus, { className: "mr-2 h-4 w-4" }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "font-medium", children: "Add custom relay" }), _jsx("span", { className: "text-xs text-muted-foreground", children: normalizeRelayUrl(inputValue) })] })] }))] })] })] }) })] }));
}
+16 -16
View File
@@ -1,6 +1,6 @@
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils.js";
import { Button } from "@/components/ui/button.js";
import {
Command,
CommandEmpty,
@@ -8,14 +8,14 @@ import {
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
} from "@/components/ui/command.js";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
} from "@/components/ui/popover.js";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext";
import { useAppContext } from "@/hooks/useAppContext.js";
interface RelaySelectorProps {
className?: string;
@@ -24,7 +24,7 @@ interface RelaySelectorProps {
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 }));
@@ -39,12 +39,12 @@ export function RelaySelector(props: RelaySelectorProps) {
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}`;
};
@@ -60,7 +60,7 @@ export function RelaySelector(props: RelaySelectorProps) {
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 {
@@ -83,9 +83,9 @@ export function RelaySelector(props: RelaySelectorProps) {
<div className="flex items-center gap-2">
<Wifi className="h-4 w-4" />
<span className="truncate">
{selectedOption
? selectedOption.name
: selectedRelay
{selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..."
}
@@ -96,8 +96,8 @@ export function RelaySelector(props: RelaySelectorProps) {
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0">
<Command>
<CommandInput
placeholder="Search relays or type URL..."
<CommandInput
placeholder="Search relays or type URL..."
value={inputValue}
onValueChange={setInputValue}
/>
@@ -124,8 +124,8 @@ export function RelaySelector(props: RelaySelectorProps) {
</CommandEmpty>
<CommandGroup>
{presetRelays
.filter((option) =>
!inputValue ||
.filter((option) =>
!inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase())
)
+9
View File
@@ -0,0 +1,9 @@
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
+87
View File
@@ -0,0 +1,87 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, forwardRef } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog.js';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, DrawerTrigger, DrawerClose, } from '@/components/ui/drawer.js';
import { Input } from '@/components/ui/input.js';
import { Label } from '@/components/ui/label.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Badge } from '@/components/ui/badge.js';
import { Separator } from '@/components/ui/separator.js';
import { useNWC } from '@/hooks/useNWCContext.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useToast } from '@/hooks/useToast.js';
import { useIsMobile } from '@/hooks/useIsMobile.js';
// Extracted AddWalletContent to prevent re-renders
const AddWalletContent = forwardRef(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (_jsxs("div", { className: "space-y-4 px-4", ref: ref, children: [_jsxs("div", { children: [_jsx(Label, { htmlFor: "alias", children: "Wallet Name (optional)" }), _jsx(Input, { id: "alias", placeholder: "My Lightning Wallet", value: alias, onChange: (e) => setAlias(e.target.value) })] }), _jsxs("div", { children: [_jsx(Label, { htmlFor: "connection-uri", children: "Connection URI" }), _jsx(Textarea, { id: "connection-uri", placeholder: "nostr+walletconnect://...", value: connectionUri, onChange: (e) => setConnectionUri(e.target.value), rows: 3 })] })] })));
AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef(({ hasWebLN, isDetecting, hasNWC, connections, connectionInfo, activeConnection, handleSetActive, handleRemoveConnection, setAddDialogOpen }, ref) => (_jsxs("div", { className: "space-y-6 px-4 pb-4", ref: ref, children: [_jsxs("div", { className: "space-y-3", children: [_jsx("h3", { className: "font-medium", children: "Current Status" }), _jsxs("div", { className: "grid gap-3", children: [_jsxs("div", { className: "flex items-center justify-between p-3 border rounded-lg", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(Globe, { className: "h-4 w-4 text-muted-foreground" }), _jsxs("div", { children: [_jsx("p", { className: "text-sm font-medium", children: "WebLN" }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Browser extension" })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [hasWebLN && _jsx(CheckCircle, { className: "h-4 w-4 text-green-600" }), _jsx(Badge, { variant: hasWebLN ? "default" : "secondary", className: "text-xs", children: isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found" })] })] }), _jsxs("div", { className: "flex items-center justify-between p-3 border rounded-lg", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(WalletMinimal, { className: "h-4 w-4 text-muted-foreground" }), _jsxs("div", { children: [_jsx("p", { className: "text-sm font-medium", children: "Nostr Wallet Connect" }), _jsx("p", { className: "text-xs text-muted-foreground", children: connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection" })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [hasNWC && _jsx(CheckCircle, { className: "h-4 w-4 text-green-600" }), _jsx(Badge, { variant: hasNWC ? "default" : "secondary", className: "text-xs", children: hasNWC ? "Ready" : "None" })] })] })] })] }), _jsx(Separator, {}), _jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("h3", { className: "font-medium", children: "Nostr Wallet Connect" }), _jsxs(Button, { size: "sm", variant: "outline", onClick: () => setAddDialogOpen(true), children: [_jsx(Plus, { className: "h-4 w-4 mr-1" }), "Add"] })] }), connections.length === 0 ? (_jsx("div", { className: "text-center py-6 text-muted-foreground", children: _jsx("p", { className: "text-sm", children: "No wallets connected" }) })) : (_jsx("div", { className: "space-y-2", children: connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (_jsxs("div", { className: `flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`, children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(WalletMinimal, { className: "h-4 w-4 text-muted-foreground" }), _jsxs("div", { children: [_jsx("p", { className: "text-sm font-medium", children: connection.alias || info?.alias || 'Lightning Wallet' }), _jsx("p", { className: "text-xs text-muted-foreground", children: "NWC Connection" })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [isActive && _jsx(CheckCircle, { className: "h-4 w-4 text-green-600" }), !isActive && (_jsx(Button, { size: "sm", variant: "ghost", onClick: () => handleSetActive(connection.connectionString), children: _jsx(Zap, { className: "h-3 w-3" }) })), _jsx(Button, { size: "sm", variant: "ghost", onClick: () => handleRemoveConnection(connection.connectionString), children: _jsx(Trash2, { className: "h-3 w-3" }) })] })] }, connection.connectionString));
}) }))] }), !hasWebLN && connections.length === 0 && (_jsxs(_Fragment, { children: [_jsx(Separator, {}), _jsx("div", { className: "text-center py-4 space-y-2", children: _jsx("p", { className: "text-sm text-muted-foreground", children: "Install a WebLN extension or connect a NWC wallet for zaps." }) })] }))] })));
WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }) {
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 { hasWebLN, isDetecting } = useWallet();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
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) => {
removeConnection(connectionString);
};
const handleSetActive = (connectionString) => {
setActiveConnection(connectionString);
toast({
title: 'Active wallet changed',
description: 'The selected wallet is now active for zaps.',
});
};
const walletContentProps = {
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
};
const addWalletDialog = (_jsx(Dialog, { open: addDialogOpen, onOpenChange: setAddDialogOpen, children: _jsxs(DialogContent, { className: "sm:max-w-[425px]", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Connect NWC Wallet" }), _jsx(DialogDescription, { children: "Enter your connection string from a compatible wallet." })] }), _jsx(AddWalletContent, { alias: alias, setAlias: setAlias, connectionUri: connectionUri, setConnectionUri: setConnectionUri }), _jsx(DialogFooter, { className: "px-4", children: _jsx(Button, { onClick: handleAddConnection, disabled: isConnecting || !connectionUri.trim(), className: "w-full", children: isConnecting ? 'Connecting...' : 'Connect' }) })] }) }));
if (isMobile) {
return (_jsxs(_Fragment, { children: [_jsxs(Drawer, { open: open, onOpenChange: setOpen, children: [_jsx(DrawerTrigger, { asChild: true, children: children || (_jsxs(Button, { variant: "outline", size: "sm", className: className, children: [_jsx(Wallet, { className: "h-4 w-4 mr-2" }), "Wallet Settings"] })) }), _jsxs(DrawerContent, { className: "h-full", children: [_jsxs(DrawerHeader, { className: "text-center relative", children: [_jsx(DrawerClose, { asChild: true, children: _jsxs(Button, { variant: "ghost", size: "sm", className: "absolute right-4 top-4", children: [_jsx(X, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Close" })] }) }), _jsxs(DrawerTitle, { className: "flex items-center justify-center gap-2 pt-2", children: [_jsx(Wallet, { className: "h-5 w-5" }), "Lightning Wallet"] }), _jsx(DrawerDescription, { children: "Connect your lightning wallet to send zaps instantly." })] }), _jsx("div", { className: "overflow-y-auto", children: _jsx(WalletContent, { ...walletContentProps }) })] })] }), _jsx(Drawer, { open: addDialogOpen, onOpenChange: setAddDialogOpen, children: _jsxs(DrawerContent, { children: [_jsxs(DrawerHeader, { children: [_jsx(DrawerTitle, { children: "Connect NWC Wallet" }), _jsx(DrawerDescription, { children: "Enter your connection string from a compatible wallet." })] }), _jsx(AddWalletContent, { alias: alias, setAlias: setAlias, connectionUri: connectionUri, setConnectionUri: setConnectionUri }), _jsx("div", { className: "p-4", children: _jsx(Button, { onClick: handleAddConnection, disabled: isConnecting || !connectionUri.trim(), className: "w-full", children: isConnecting ? 'Connecting...' : 'Connect' }) })] }) })] }));
}
return (_jsxs(_Fragment, { children: [_jsxs(Dialog, { open: open, onOpenChange: setOpen, children: [_jsx(DialogTrigger, { asChild: true, children: children || (_jsxs(Button, { variant: "outline", size: "sm", className: className, children: [_jsx(Wallet, { className: "h-4 w-4 mr-2" }), "Wallet Settings"] })) }), _jsxs(DialogContent, { className: "sm:max-w-[500px] max-h-[80vh] overflow-y-auto", children: [_jsxs(DialogHeader, { children: [_jsxs(DialogTitle, { className: "flex items-center gap-2", children: [_jsx(Wallet, { className: "h-5 w-5" }), "Lightning Wallet"] }), _jsx(DialogDescription, { children: "Connect your lightning wallet to send zaps instantly." })] }), _jsx(WalletContent, { ...walletContentProps })] })] }), addWalletDialog] }));
}
+36 -70
View File
@@ -1,6 +1,6 @@
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 { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import {
Dialog,
DialogContent,
@@ -9,7 +9,7 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
} from '@/components/ui/dialog.js';
import {
Drawer,
DrawerContent,
@@ -18,21 +18,19 @@ import {
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";
} from '@/components/ui/drawer.js';
import { Input } from '@/components/ui/input.js';
import { Label } from '@/components/ui/label.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Badge } from '@/components/ui/badge.js';
import { Separator } from '@/components/ui/separator.js';
import { useNWC } from '@/hooks/useNWCContext.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useToast } from '@/hooks/useToast.js';
import { useIsMobile } from '@/hooks/useIsMobile.js';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC.js';
interface LightningWalletModalProps {
interface WalletModalProps {
children?: React.ReactNode;
className?: string;
}
@@ -70,59 +68,30 @@ AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
webln: WebLNProvider | null;
hasWebLN: boolean;
isDetecting: boolean;
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,
hasWebLN,
isDetecting,
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 */}
{/* Current Status */}
<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>
<h3 className="font-medium">Current Status</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
@@ -134,9 +103,9 @@ const WalletContent = forwardRef<HTMLDivElement, {
</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"}
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
@@ -222,12 +191,12 @@ const WalletContent = forwardRef<HTMLDivElement, {
)}
</div>
{/* Help */}
{!isCashuInitialized && !webln && connections.length === 0 && (
{!hasWebLN && 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
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
@@ -236,7 +205,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
));
WalletContent.displayName = 'WalletContent';
export function LightningWalletModal({ children, className }: LightningWalletModalProps) {
export function WalletModal({ children, className }: WalletModalProps) {
const [open, setOpen] = useState(false);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [connectionUri, setConnectionUri] = useState('');
@@ -253,11 +222,9 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
setActiveConnection
} = useNWC();
const { webln } = useWallet();
const { balances, isInitialized: isCashuInitialized } = useCashu();
const { hasWebLN, isDetecting } = useWallet();
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 () => {
@@ -296,13 +263,12 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
};
const walletContentProps = {
webln,
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
cashuBalance,
isCashuInitialized,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
@@ -344,7 +310,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Payment Settings
Wallet Settings
</Button>
)}
</DrawerTrigger>
@@ -358,10 +324,10 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
</DrawerClose>
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
<Wallet className="h-5 w-5" />
Payment Settings
Lightning Wallet
</DrawerTitle>
<DrawerDescription>
Manage wallet methods for zaps
Connect your lightning wallet to send zaps instantly.
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
@@ -406,7 +372,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Payment Settings
Wallet Settings
</Button>
)}
</DialogTrigger>
@@ -414,10 +380,10 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Payment Settings
Lightning Wallet
</DialogTitle>
<DialogDescription>
Manage wallet methods for zaps
Connect your lightning wallet to send zaps instantly.
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
+23
View File
@@ -0,0 +1,23 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { ZapDialog } from '@/components/ZapDialog.js';
import { useZaps } from '@/hooks/useZaps.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useAuthor } from '@/hooks/useAuthor.js';
import { Zap } from 'lucide-react';
export function ZapButton({ target, className = "text-xs ml-1", showCount = true, zapData: externalZapData }) {
const { user } = useCurrentUser();
const { data: author } = useAuthor(target?.pubkey || '');
const { webln, activeNWC } = useWallet();
// Only fetch data if not provided externally
const { totalSats: fetchedTotalSats, isLoading } = useZaps(externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
webln, activeNWC);
// 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;
}
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
return (_jsx(ZapDialog, { target: target, children: _jsxs("div", { className: `flex items-center gap-1 ${className}`, children: [_jsx(Zap, { className: "h-4 w-4" }), _jsx("span", { className: "text-xs", children: showLoading ? ('...') : showCount && totalSats > 0 ? (`${totalSats.toLocaleString()}`) : ('Zap') })] }) }));
}
+23 -530
View File
@@ -1,40 +1,10 @@
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 { ZapDialog } from '@/components/ZapDialog.js';
import { useZaps } from '@/hooks/useZaps.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useAuthor } from '@/hooks/useAuthor.js';
import { Zap } from 'lucide-react';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
import type { WebLNProvider } from "@webbtc/webln-types";
interface ZapButtonProps {
target: Event;
@@ -43,276 +13,15 @@ interface ZapButtonProps {
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(
@@ -321,245 +30,29 @@ export function ZapButton({
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>
);
}
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
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>
<ZapDialog target={target}>
<div className={`flex items-center gap-1 ${className}`}>
<Zap className="h-4 w-4" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</ZapDialog>
);
}
+164
View File
@@ -0,0 +1,164 @@
import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import { cn } from '@/lib/utils.js';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog.js';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, DrawerTrigger, DrawerClose, } from '@/components/ui/drawer.js';
import { Input } from '@/components/ui/input.js';
import { Label } from '@/components/ui/label.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { Separator } from '@/components/ui/separator.js';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useAuthor } from '@/hooks/useAuthor.js';
import { useToast } from '@/hooks/useToast.js';
import { useZaps } from '@/hooks/useZaps.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useIsMobile } from '@/hooks/useIsMobile.js';
import QRCode from 'qrcode';
const presetAmounts = [
{ amount: 1, icon: Sparkle },
{ amount: 50, icon: Sparkles },
{ amount: 100, icon: Zap },
{ amount: 250, icon: Star },
{ amount: 1000, icon: Rocket },
];
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
const ZapContent = forwardRef(({ invoice, amount, comment, isZapping, qrCodeUrl, copied, hasWebLN, handleZap, handleCopy, openInWallet, setAmount, setComment, inputRef, zap, }, ref) => (_jsx("div", { ref: ref, children: invoice ? (_jsxs("div", { className: "flex flex-col h-full min-h-0", children: [_jsx("div", { className: "text-center pt-4", children: _jsxs("div", { className: "text-2xl font-bold", children: [amount, " sats"] }) }), _jsx(Separator, { className: "my-4" }), _jsxs("div", { className: "flex flex-col justify-center min-h-0 flex-1 px-2", children: [_jsx("div", { className: "flex justify-center", children: _jsx(Card, { className: "p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto", children: _jsx(CardContent, { className: "p-0 flex justify-center", children: qrCodeUrl ? (_jsx("img", { src: qrCodeUrl, alt: "Lightning Invoice QR Code", className: "w-full h-auto aspect-square max-w-full object-contain" })) : (_jsx("div", { className: "w-full aspect-square bg-muted animate-pulse rounded" })) }) }) }), _jsxs("div", { className: "space-y-2 mt-4", children: [_jsx(Label, { htmlFor: "invoice", children: "Lightning Invoice" }), _jsxs("div", { className: "flex gap-2 min-w-0", children: [_jsx(Input, { id: "invoice", value: invoice, readOnly: true, className: "font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis", onClick: (e) => e.currentTarget.select() }), _jsx(Button, { variant: "outline", size: "icon", onClick: handleCopy, className: "shrink-0", children: copied ? (_jsx(Check, { className: "h-4 w-4 text-green-600" })) : (_jsx(Copy, { className: "h-4 w-4" })) })] })] }), _jsxs("div", { className: "space-y-3 mt-4", children: [hasWebLN && (_jsxs(Button, { onClick: () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}, disabled: isZapping, className: "w-full", size: "lg", children: [_jsx(Zap, { className: "h-4 w-4 mr-2" }), isZapping ? "Processing..." : "Pay with WebLN"] })), _jsxs(Button, { variant: "outline", onClick: openInWallet, className: "w-full", size: "lg", children: [_jsx(ExternalLink, { className: "h-4 w-4 mr-2" }), "Open in Lightning Wallet"] }), _jsx("div", { className: "text-xs sm:text-[.65rem] text-muted-foreground text-center", children: "Scan the QR code or copy the invoice to pay with any Lightning wallet." })] })] })] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "grid gap-3 px-4 py-4 w-full overflow-hidden", children: [_jsx(ToggleGroup, { type: "single", value: String(amount), onValueChange: (value) => {
if (value) {
setAmount(parseInt(value, 10));
}
}, className: "grid grid-cols-5 gap-1 w-full", children: presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (_jsxs(ToggleGroupItem, { value: String(presetAmount), className: "flex flex-col h-auto min-w-0 text-xs px-1 py-2", children: [_jsx(Icon, { className: "h-4 w-4 mb-1" }), _jsx("span", { className: "truncate", children: presetAmount })] }, presetAmount))) }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { className: "h-px flex-1 bg-muted" }), _jsx("span", { className: "text-xs text-muted-foreground", children: "OR" }), _jsx("div", { className: "h-px flex-1 bg-muted" })] }), _jsx(Input, { ref: inputRef, id: "custom-amount", type: "number", placeholder: "Custom amount", value: amount, onChange: (e) => setAmount(e.target.value), className: "w-full text-sm" }), _jsx(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 })] }), _jsx("div", { className: "px-4 pb-4", children: _jsx(Button, { onClick: handleZap, className: "w-full", disabled: isZapping, size: "default", children: isZapping ? ('Creating invoice...') : (_jsxs(_Fragment, { children: [_jsx(Zap, { className: "h-4 w-4 mr-2" }), "Zap ", amount, " sats"] })) }) })] })) })));
ZapContent.displayName = 'ZapContent';
export function ZapDialog({ target, children, className }) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const [amount, setAmount] = useState(100);
const [comment, setComment] = useState('');
const [copied, setCopied] = useState(false);
const [qrCodeUrl, setQrCodeUrl] = useState('');
const inputRef = useRef(null);
const isMobile = useIsMobile();
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
}
}, [target]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// 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;
zap(finalAmount, comment);
};
const contentProps = {
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
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 (_jsxs(Drawer, { open: open, onOpenChange: (newOpen) => {
// Reset invoice when closing
if (!newOpen) {
setInvoice(null);
setQrCodeUrl('');
}
setOpen(newOpen);
}, dismissible: true, snapPoints: invoice ? [0.5, 0.75, 0.98] : [0.98], activeSnapPoint: invoice ? 0.98 : 0.98, modal: true, shouldScaleBackground: false, fadeFromIndex: 0, children: [_jsx(DrawerTrigger, { asChild: true, children: _jsx("div", { className: `cursor-pointer ${className || ''}`, children: children }) }), _jsxs(DrawerContent, { className: cn("transition-all duration-300", invoice ? "h-full max-h-screen" : "max-h-[98vh]"), "data-testid": "zap-modal", children: [_jsxs(DrawerHeader, { className: "text-center relative", children: [invoice && (_jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
setInvoice(null);
setQrCodeUrl('');
}, className: "absolute left-4 top-4 flex items-center gap-2", children: _jsx(ArrowLeft, { className: "h-4 w-4" }) })), _jsx(DrawerClose, { asChild: true, children: _jsxs(Button, { variant: "ghost", size: "sm", className: "absolute right-4 top-4", children: [_jsx(X, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Close" })] }) }), _jsx(DrawerTitle, { className: "text-lg break-words pt-2", children: invoice ? 'Lightning Payment' : 'Send a Zap' }), _jsx(DrawerDescription, { className: "text-sm break-words text-center", children: invoice ? ('Pay with Bitcoin Lightning Network') : ('Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!') })] }), _jsx("div", { className: "flex-1 overflow-y-auto px-4 pb-4", children: _jsx(ZapContent, { ...contentProps }) })] }, invoice ? 'payment' : 'form')] }));
}
return (_jsxs(Dialog, { open: open, onOpenChange: setOpen, children: [_jsx(DialogTrigger, { asChild: true, children: _jsx("div", { className: `cursor-pointer ${className || ''}`, children: children }) }), _jsxs(DialogContent, { className: "sm:max-w-[425px] max-h-[95vh] overflow-hidden", "data-testid": "zap-modal", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-lg break-words", children: invoice ? 'Lightning Payment' : 'Send a Zap' }), _jsx(DialogDescription, { className: "text-sm text-center break-words", children: invoice ? ('Pay with Bitcoin Lightning Network') : (_jsx(_Fragment, { children: "Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!" })) })] }), _jsx("div", { className: "overflow-y-auto", children: _jsx(ZapContent, { ...contentProps }) })] })] }));
}
+37 -114
View File
@@ -1,7 +1,7 @@
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 { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import { cn } from '@/lib/utils.js';
import {
Dialog,
DialogContent,
@@ -9,7 +9,7 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
} from '@/components/ui/dialog.js';
import {
Drawer,
DrawerContent,
@@ -18,23 +18,21 @@ import {
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';
} from '@/components/ui/drawer.js';
import { Input } from '@/components/ui/input.js';
import { Label } from '@/components/ui/label.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { Separator } from '@/components/ui/separator.js';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useAuthor } from '@/hooks/useAuthor.js';
import { useToast } from '@/hooks/useToast.js';
import { useZaps } from '@/hooks/useZaps.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useIsMobile } from '@/hooks/useIsMobile.js';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
import type { WebLNProvider } from "@webbtc/webln-types";
interface ZapDialogProps {
target: Event;
@@ -57,10 +55,7 @@ interface ZapContentProps {
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
webln: WebLNProvider | null;
// Cashu-related props
canPayWithCashu: boolean;
cashuBalance: number;
hasWebLN: boolean;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
@@ -78,9 +73,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
isZapping,
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
@@ -145,33 +138,8 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
{/* 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 && (
{hasWebLN && (
<Button
variant="outline"
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
@@ -196,26 +164,13 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
</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."
}
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"
@@ -232,7 +187,6 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
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>
@@ -252,7 +206,6 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="w-full text-sm"
max={canPayWithCashu ? cashuBalance : undefined}
/>
<Textarea
id="custom-comment"
@@ -264,19 +217,9 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
/>
</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"
>
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
{isZapping ? (
'Creating Lightning invoice...'
) : canPayWithCashu ? (
<>
<Coins className="h-4 w-4 mr-2" />
Zap {amount} sats (Cashu → Lightning)
</>
'Creating invoice...'
) : (
<>
<Zap className="h-4 w-4 mr-2" />
@@ -291,14 +234,14 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
));
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 { webln, activeNWC, hasWebLN, detectWebLN } = 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);
@@ -306,16 +249,19 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
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]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
@@ -389,25 +335,6 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
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);
};
@@ -418,9 +345,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
isZapping,
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
@@ -502,9 +427,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
{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!'
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DrawerDescription>
</DrawerHeader>
@@ -532,9 +455,9 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
{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!'
<>
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
</>
)}
</DialogDescription>
</DialogHeader>
+19
View File
@@ -0,0 +1,19 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// 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 { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu.js';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.js';
import { RelaySelector } from '@/components/RelaySelector.js';
import { WalletModal } from '@/components/WalletModal.js';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts.js';
import { genUserName } from '@/lib/genUserName.js';
export function AccountSwitcher({ onAddAccountClick }) {
const { currentUser, otherUsers, setLogin, removeLogin } = useLoggedInAccounts();
if (!currentUser)
return null;
const getDisplayName = (account) => {
return account.metadata.name ?? genUserName(account.pubkey);
};
return (_jsxs(DropdownMenu, { modal: false, children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsxs("button", { className: 'flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground', children: [_jsxs(Avatar, { className: 'w-10 h-10', children: [_jsx(AvatarImage, { src: currentUser.metadata.picture, alt: getDisplayName(currentUser) }), _jsx(AvatarFallback, { children: getDisplayName(currentUser).charAt(0) })] }), _jsx("div", { className: 'flex-1 text-left hidden md:block truncate', children: _jsx("p", { className: 'font-medium text-sm truncate', children: getDisplayName(currentUser) }) }), _jsx(ChevronDown, { className: 'w-4 h-4 text-muted-foreground' })] }) }), _jsxs(DropdownMenuContent, { className: 'w-56 p-2 animate-scale-in', children: [_jsx("div", { className: 'font-medium text-sm px-2 py-1.5', children: "Switch Relay" }), _jsx(RelaySelector, { className: "w-full" }), _jsx(DropdownMenuSeparator, {}), _jsx("div", { className: 'font-medium text-sm px-2 py-1.5', children: "Switch Account" }), otherUsers.map((user) => (_jsxs(DropdownMenuItem, { onClick: () => setLogin(user.id), className: 'flex items-center gap-2 cursor-pointer p-2 rounded-md', children: [_jsxs(Avatar, { className: 'w-8 h-8', children: [_jsx(AvatarImage, { src: user.metadata.picture, alt: getDisplayName(user) }), _jsx(AvatarFallback, { children: getDisplayName(user)?.charAt(0) || _jsx(UserIcon, {}) })] }), _jsx("div", { className: 'flex-1 truncate', children: _jsx("p", { className: 'text-sm font-medium', children: getDisplayName(user) }) }), user.id === currentUser.id && _jsx("div", { className: 'w-2 h-2 rounded-full bg-primary' })] }, user.id))), _jsx(DropdownMenuSeparator, {}), _jsx(WalletModal, { children: _jsxs(DropdownMenuItem, { className: 'flex items-center gap-2 cursor-pointer p-2 rounded-md', onSelect: (e) => e.preventDefault(), children: [_jsx(Wallet, { className: 'w-4 h-4' }), _jsx("span", { children: "Wallet Settings" })] }) }), _jsxs(DropdownMenuItem, { onClick: onAddAccountClick, className: 'flex items-center gap-2 cursor-pointer p-2 rounded-md', children: [_jsx(UserPlus, { className: 'w-4 h-4' }), _jsx("span", { children: "Add another account" })] }), _jsxs(DropdownMenuItem, { onClick: () => removeLogin(currentUser.id), className: 'flex items-center gap-2 cursor-pointer p-2 rounded-md text-red-500', children: [_jsx(LogOut, { className: 'w-4 h-4' }), _jsx("span", { children: "Log out" })] })] })] }));
}
+9 -9
View File
@@ -8,12 +8,12 @@ import {
DropdownMenuItem,
DropdownMenuSeparator,
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';
} from '@/components/ui/dropdown-menu.js';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.js';
import { RelaySelector } from '@/components/RelaySelector.js';
import { WalletModal } from '@/components/WalletModal.js';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts.js';
import { genUserName } from '@/lib/genUserName.js';
interface AccountSwitcherProps {
onAddAccountClick: () => void;
@@ -64,15 +64,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<LightningWalletModal>
<WalletModal>
<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>
<span>Wallet Settings</span>
</DropdownMenuItem>
</LightningWalletModal>
</WalletModal>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+21
View File
@@ -0,0 +1,21 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// 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 { Button } from '@/components/ui/button.js';
import LoginDialog from "./LoginDialog.js";
import SignupDialog from "./SignupDialog.js";
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts.js';
import { AccountSwitcher } from "./AccountSwitcher.js";
import { cn } from '@/lib/utils.js';
export function LoginArea({ className }) {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
const handleLogin = () => {
setLoginDialogOpen(false);
setSignupDialogOpen(false);
};
return (_jsxs("div", { className: cn("inline-flex items-center justify-center", className), children: [currentUser ? (_jsx(AccountSwitcher, { onAddAccountClick: () => setLoginDialogOpen(true) })) : (_jsxs("div", { className: "flex gap-3 justify-center", children: [_jsxs(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', children: [_jsx(User, { className: 'w-4 h-4' }), _jsx("span", { className: 'truncate', children: "Log in" })] }), _jsxs(Button, { onClick: () => setSignupDialogOpen(true), variant: "outline", className: "flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all", children: [_jsx(UserPlus, { className: "w-4 h-4" }), _jsx("span", { children: "Sign Up" })] })] })), _jsx(LoginDialog, { isOpen: loginDialogOpen, onClose: () => setLoginDialogOpen(false), onLogin: handleLogin, onSignup: () => setSignupDialogOpen(true) }), _jsx(SignupDialog, { isOpen: signupDialogOpen, onClose: () => setSignupDialogOpen(false) })] }));
}
+6 -6
View File
@@ -3,12 +3,12 @@
import { useState } from 'react';
import { User, UserPlus } 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';
import { Button } from '@/components/ui/button.js';
import LoginDialog from "./LoginDialog.js";
import SignupDialog from "./SignupDialog.js";
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts.js';
import { AccountSwitcher } from "./AccountSwitcher.js";
import { cn } from '@/lib/utils.js';
export interface LoginAreaProps {
className?: string;
+168
View File
@@ -0,0 +1,168 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// 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 { useRef, useState, useEffect } from 'react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import { Input } from '@/components/ui/input.js';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog.js";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.js';
import { Alert, AlertDescription } from '@/components/ui/alert.js';
import { useLoginActions } from '@/hooks/useLoginActions.js';
import { cn } from '@/lib/utils.js';
const validateNsec = (nsec) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri) => {
return uri.startsWith('bunker://');
};
const LoginDialog = ({ 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({});
const fileInputRef = useRef(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 () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
onLogin();
onClose();
}
catch (e) {
const error = e;
console.error('Bunker login failed:', error);
console.error('Nsec login failed:', 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) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
}
catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
onLogin();
onClose();
// Clear the URI from memory
setBunkerUri('');
}
catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
}
finally {
setIsLoading(false);
}
};
const handleFileUpload = (e) => {
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;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
}
else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
}
else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
};
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
const defaultTab = 'nostr' in window ? 'extension' : 'key';
return (_jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: _jsxs(DialogContent, { className: cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll"), children: [_jsx(DialogHeader, { className: cn('px-6 pt-6 pb-1 relative'), children: _jsx(DialogDescription, { className: "text-center", children: "Sign up or log in to continue" }) }), _jsxs("div", { className: 'px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1', children: [_jsx("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', children: _jsxs("div", { className: 'relative z-10 text-center space-y-3', children: [_jsxs("div", { className: 'flex justify-center items-center gap-2 mb-2', children: [_jsx(Sparkles, { className: 'w-5 h-5 text-blue-600' }), _jsx("span", { className: 'font-semibold text-blue-800 dark:text-blue-200', children: "New to Nostr?" })] }), _jsx("p", { className: 'text-sm text-blue-700 dark:text-blue-300', children: "Create a new account to get started. It's free and open." }), _jsxs(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', children: [_jsx(UserPlus, { className: 'w-4 h-4 mr-2' }), _jsx("span", { children: "Sign Up" })] })] }) }), _jsxs("div", { className: 'relative', children: [_jsx("div", { className: 'absolute inset-0 flex items-center', children: _jsx("div", { className: 'w-full border-t border-gray-300 dark:border-gray-600' }) }), _jsx("div", { className: 'relative flex justify-center text-sm', children: _jsx("span", { className: 'px-3 bg-background text-muted-foreground', children: _jsx("span", { children: "Or log in" }) }) })] }), _jsxs(Tabs, { defaultValue: defaultTab, className: "w-full", children: [_jsxs(TabsList, { className: "grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4", children: [_jsxs(TabsTrigger, { value: "extension", className: "flex items-center gap-2", children: [_jsx(Shield, { className: "w-4 h-4" }), _jsx("span", { children: "Extension" })] }), _jsxs(TabsTrigger, { value: "key", className: "flex items-center gap-2", children: [_jsx(KeyRound, { className: "w-4 h-4" }), _jsx("span", { children: "Key" })] }), _jsxs(TabsTrigger, { value: "bunker", className: "flex items-center gap-2", children: [_jsx(Cloud, { className: "w-4 h-4" }), _jsx("span", { children: "Bunker" })] })] }), _jsxs(TabsContent, { value: 'extension', className: 'space-y-3 bg-muted', children: [errors.extension && (_jsxs(Alert, { variant: "destructive", children: [_jsx(AlertTriangle, { className: "h-4 w-4" }), _jsx(AlertDescription, { children: errors.extension })] })), _jsxs("div", { className: 'text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800', children: [_jsx(Shield, { className: 'w-12 h-12 mx-auto mb-3 text-primary' }), _jsx("p", { className: 'text-sm text-gray-600 dark:text-gray-300 mb-4', children: "Login with one click using the browser extension" }), _jsx("div", { className: "flex justify-center", children: _jsx(Button, { className: 'w-full rounded-full py-4', onClick: handleExtensionLogin, disabled: isLoading, children: isLoading ? 'Logging in...' : 'Login with Extension' }) })] })] }), _jsx(TabsContent, { value: 'key', className: 'space-y-4', children: _jsxs("div", { className: 'space-y-4', children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'nsec', className: 'text-sm font-medium', children: "Secret Key (nsec)" }), _jsx(Input, { id: 'nsec', type: "password", value: nsec, onChange: (e) => {
setNsec(e.target.value);
if (errors.nsec)
setErrors(prev => ({ ...prev, nsec: undefined }));
}, className: `rounded-lg ${errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''}`, placeholder: 'nsec1...', autoComplete: "off" }), errors.nsec && (_jsx("p", { className: "text-sm text-red-500", children: errors.nsec }))] }), _jsx(Button, { className: 'w-full rounded-full py-3', onClick: handleKeyLogin, disabled: isLoading || !nsec.trim(), children: isLoading ? 'Verifying...' : 'Log In' }), _jsxs("div", { className: 'relative', children: [_jsx("div", { className: 'absolute inset-0 flex items-center', children: _jsx("div", { className: 'w-full border-t border-muted' }) }), _jsx("div", { className: 'relative flex justify-center text-xs', children: _jsx("span", { className: 'px-2 bg-background text-muted-foreground', children: "or" }) })] }), _jsxs("div", { className: 'text-center', children: [_jsx("input", { type: 'file', accept: '.txt', className: 'hidden', ref: fileInputRef, onChange: handleFileUpload }), _jsxs(Button, { variant: 'outline', className: 'w-full', onClick: () => fileInputRef.current?.click(), disabled: isLoading || isFileLoading, children: [_jsx(Upload, { className: 'w-4 h-4 mr-2' }), isFileLoading ? 'Reading File...' : 'Upload Your Key File'] }), errors.file && (_jsx("p", { className: "text-sm text-red-500 mt-2", children: errors.file }))] })] }) }), _jsxs(TabsContent, { value: 'bunker', className: 'space-y-3 bg-muted', children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'bunkerUri', className: 'text-sm font-medium text-gray-700 dark:text-gray-400', children: "Bunker URI" }), _jsx(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' : ''}`, placeholder: 'bunker://', autoComplete: "off" }), errors.bunker && (_jsx("p", { className: "text-sm text-red-500", children: errors.bunker }))] }), _jsx("div", { className: "flex justify-center", children: _jsx(Button, { className: 'w-full rounded-full py-4', onClick: handleBunkerLogin, disabled: isLoading || !bunkerUri.trim(), children: isLoading ? 'Connecting...' : 'Login with Bunker' }) })] })] })] })] }) }));
};
export default LoginDialog;
+9 -9
View File
@@ -3,13 +3,13 @@
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 { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button.js';
import { Input } from '@/components/ui/input.js';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog.js";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.js';
import { Alert, AlertDescription } from '@/components/ui/alert.js';
import { useLoginActions } from '@/hooks/useLoginActions.js';
import { cn } from '@/lib/utils.js';
interface LoginDialogProps {
isOpen: boolean;
@@ -182,7 +182,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
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")}
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
@@ -190,7 +190,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
Sign up or log in to continue
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1 min-h-0'>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
{/* 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'>
-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)}
/>
</>
);
}
+266
View File
@@ -0,0 +1,266 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
// 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, 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.js';
import { Input } from '@/components/ui/input.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog.js";
import { Card, CardContent } from '@/components/ui/card.js';
import { toast } from '@/hooks/useToast.js';
import { useLoginActions } from '@/hooks/useLoginActions.js';
import { useNostrPublish } from '@/hooks/useNostrPublish.js';
import { useUploadFile } from '@/hooks/useUploadFile.js';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils.js';
const sanitizeFilename = (filename) => {
return filename.replace(/[^a-z0-9_.-]/gi, '_');
};
const SignupDialog = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState('welcome');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState('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(null);
// 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);
};
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);
// 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 = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// 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',
});
}
};
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',
});
}
};
const handleAvatarUpload = async (e) => {
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 = {};
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 (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Create Your Account" }));
if (step === 'generate')
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Generating Your Key" }));
if (step === 'download')
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Secret Key" }));
if (step === 'profile')
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Create Your Profile" }));
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Welcome!" }));
};
// 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 (_jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: _jsxs(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"), children: [_jsx(DialogHeader, { className: cn('px-6 pt-6 pb-1 relative flex-shrink-0'), children: _jsx(DialogTitle, { className: cn('font-semibold text-center text-lg'), children: getTitle() }) }), _jsxs("div", { className: 'px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1', children: [step === 'welcome' && (_jsxs("div", { className: 'text-center space-y-4', children: [_jsxs("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', children: [_jsxs("div", { className: 'flex justify-center items-center space-x-4 mb-3', children: [_jsxs("div", { className: 'relative', children: [_jsx(UserPlus, { className: 'w-12 h-12 text-blue-600' }), _jsx(Sparkles, { className: 'w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' })] }), _jsx(Globe, { className: 'w-16 h-16 text-blue-700 animate-spin-slow' }), _jsxs("div", { className: 'relative', children: [_jsx(FileText, { className: 'w-12 h-12 text-blue-600' }), _jsx(Sparkles, { className: 'w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse', style: { animationDelay: '0.3s' } })] })] }), _jsxs("div", { className: 'grid grid-cols-1 gap-2 text-sm', children: [_jsxs("div", { className: 'flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300', children: [_jsx(Shield, { className: 'w-4 h-4' }), "Decentralized and censorship-resistant"] }), _jsxs("div", { className: 'flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300', children: [_jsx(User, { className: 'w-4 h-4' }), "You are in control of your data"] }), _jsxs("div", { className: 'flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300', children: [_jsx(Globe, { className: 'w-4 h-4' }), "Join a global network"] })] })] }), _jsx("div", { className: 'space-y-3', children: _jsxs(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'), children: [_jsx(LogIn, { className: 'w-5 h-5 mr-2' }), "Get Started"] }) })] })), step === 'generate' && (_jsxs("div", { className: 'text-center space-y-4', children: [_jsxs("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', children: [showSparkles && (_jsx("div", { className: 'absolute inset-0', children: [...Array(12)].map((_, i) => (_jsx(Sparkles, { 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`
} }, i))) })), _jsx("div", { className: 'relative z-10', children: isLoading ? (_jsxs("div", { className: 'space-y-3', children: [_jsxs("div", { className: 'relative', children: [_jsx(Key, { className: 'w-20 h-20 text-primary mx-auto animate-pulse' }), _jsx("div", { className: 'absolute inset-0 flex items-center justify-center', children: _jsx("div", { className: 'w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin' }) })] }), _jsxs("div", { className: 'space-y-2', children: [_jsxs("p", { className: 'text-lg font-semibold text-primary flex items-center justify-center gap-2', children: [_jsx(Sparkles, { className: 'w-5 h-5' }), "Generating your secret key..."] }), _jsx("p", { className: 'text-sm text-muted-foreground', children: "Creating your secure key" })] })] })) : (_jsxs("div", { className: 'space-y-3', children: [_jsx(Key, { className: 'w-20 h-20 text-primary mx-auto' }), _jsxs("div", { className: 'space-y-2', children: [_jsx("p", { className: 'text-lg font-semibold', children: "Ready to generate your secret key?" }), _jsx("p", { className: 'text-sm text-muted-foreground px-5', children: "This key will be your password to access applications within the Nostr network." })] })] })) })] }), !isLoading && (_jsxs(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, children: [_jsx(Sparkles, { className: 'w-5 h-5 mr-2' }), "Generate My Secret Key"] }))] })), step === 'download' && (_jsxs("div", { className: 'text-center space-y-4', children: [_jsxs("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', children: [_jsxs("div", { className: 'absolute inset-0 pointer-events-none', children: [_jsx(Sparkles, { className: 'absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse', style: { animationDelay: '0s' } }), _jsx(Sparkles, { className: 'absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse', style: { animationDelay: '0.5s' } }), _jsx(Sparkles, { className: 'absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse', style: { animationDelay: '1s' } }), _jsx(Sparkles, { className: 'absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse', style: { animationDelay: '1.5s' } })] }), _jsx("div", { className: 'relative z-10 flex justify-center items-center mb-3', children: _jsxs("div", { className: 'relative', children: [_jsx("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', children: _jsx(Key, { className: 'w-8 h-8 text-indigo-800' }) }), _jsx("div", { className: 'absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce', children: _jsx(Sparkles, { className: 'w-3 h-3 text-white' }) })] }) }), _jsxs("div", { className: 'relative z-10 space-y-2', children: [_jsx("p", { className: 'text-base font-semibold', children: "Your secret key has been generated!" }), _jsx("div", { className: 'relative mx-auto max-w-sm', children: _jsxs("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', children: [_jsxs("div", { className: 'flex items-center gap-2 mb-1', children: [_jsx(FileText, { className: 'w-3 h-3 text-amber-700' }), _jsx("span", { className: 'text-xs font-bold text-amber-800 dark:text-amber-200', children: "Important Warning" })] }), _jsx("p", { className: 'text-xs text-red-700 dark:text-amber-300 italic', children: "This key is your primary and only means of accessing your account. Store it safely and securely." })] }) })] })] }), _jsxs("div", { className: 'space-y-3', children: [_jsx("div", { className: 'grid grid-cols-1 gap-2', children: _jsx(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'}`, children: _jsx(CardContent, { className: 'p-3', children: _jsx(Button, { variant: "ghost", className: 'w-full h-auto p-0 justify-start hover:bg-transparent', onClick: downloadKey, children: _jsxs("div", { className: 'flex items-center gap-3 w-full', children: [_jsx("div", { className: `p-1.5 rounded-lg ${keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'}`, children: keySecured === 'downloaded' ? (_jsx(CheckCircle, { className: 'w-4 h-4 text-green-600' })) : (_jsx(Download, { className: 'w-4 h-4 text-primary' })) }), _jsxs("div", { className: 'flex-1 text-left', children: [_jsx("div", { className: 'font-medium text-sm', children: "Download as File" }), _jsx("div", { className: 'text-xs text-muted-foreground', children: "Save as nostr-nsec-key.txt file" })] }), keySecured === 'downloaded' && (_jsx("div", { className: 'text-xs font-medium text-green-600', children: "\u2713 Downloaded" }))] }) }) }) }) }), _jsxs(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', children: [_jsx(LogIn, { className: 'w-4 h-4 mr-2 flex-shrink-0' }), _jsx("span", { className: "text-center leading-tight", children: keySecured === 'none' ? (_jsx(_Fragment, { children: "Please download your key first" })) : (_jsxs(_Fragment, { children: [_jsx("span", { className: "hidden sm:inline", children: "My Key is Safe - Continue" }), _jsx("span", { className: "sm:hidden", children: "Key Secured - Continue" })] })) })] })] })] })), step === 'profile' && (_jsxs("div", { className: 'text-center space-y-4', children: [_jsxs("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', children: [_jsxs("div", { className: 'absolute inset-0 pointer-events-none', children: [_jsx(Sparkles, { className: 'absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse', style: { animationDelay: '0s' } }), _jsx(Sparkles, { className: 'absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse', style: { animationDelay: '0.5s' } }), _jsx(Sparkles, { className: 'absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse', style: { animationDelay: '1s' } })] }), _jsx("div", { className: 'relative z-10 flex justify-center items-center mb-3', children: _jsxs("div", { className: 'relative', children: [_jsx("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', children: _jsx(User, { className: 'w-8 h-8 text-blue-800' }) }), _jsx("div", { className: 'absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce', children: _jsx(Sparkles, { className: 'w-3 h-3 text-white' }) })] }) }), _jsxs("div", { className: 'relative z-10 space-y-2', children: [_jsx("p", { className: 'text-base font-semibold', children: "Almost there! Let's set up your profile" }), _jsx("p", { className: 'text-sm text-muted-foreground', children: "Your profile is your identity on Nostr." })] })] }), isPublishing && (_jsx("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', children: _jsxs("div", { className: 'flex items-center justify-center gap-3', children: [_jsx("div", { className: 'w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' }), _jsx("span", { className: 'text-sm font-medium text-blue-700 dark:text-blue-300', children: "Publishing your profile..." })] }) })), _jsxs("div", { className: `space-y-4 text-left ${isPublishing ? 'opacity-50 pointer-events-none' : ''}`, children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'profile-name', className: 'text-sm font-medium', children: "Display Name" }), _jsx(Input, { id: 'profile-name', value: profileData.name, onChange: (e) => setProfileData(prev => ({ ...prev, name: e.target.value })), placeholder: 'Your name', className: 'rounded-lg', disabled: isPublishing })] }), _jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'profile-about', className: 'text-sm font-medium', children: "Bio" }), _jsx(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 })] }), _jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'profile-picture', className: 'text-sm font-medium', children: "Avatar" }), _jsxs("div", { className: 'flex gap-2', children: [_jsx(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 }), _jsx("input", { type: 'file', accept: 'image/*', className: 'hidden', ref: avatarFileInputRef, onChange: handleAvatarUpload }), _jsx(Button, { type: 'button', variant: 'outline', size: 'icon', onClick: () => avatarFileInputRef.current?.click(), disabled: isUploading || isPublishing, className: 'rounded-lg shrink-0', title: 'Upload avatar image', children: isUploading ? (_jsx("div", { className: 'w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin' })) : (_jsx(Upload, { className: 'w-4 h-4' })) })] })] })] }), _jsxs("div", { className: 'space-y-3', children: [_jsx(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 Line truncated
};
export default SignupDialog;
+11 -11
View File
@@ -3,17 +3,17 @@
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 { Button } from '@/components/ui/button.js';
import { Input } from '@/components/ui/input.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog.js";
import { Card, CardContent } from '@/components/ui/card.js';
import { toast } from '@/hooks/useToast.js';
import { useLoginActions } from '@/hooks/useLoginActions.js';
import { useNostrPublish } from '@/hooks/useNostrPublish.js';
import { useUploadFile } from '@/hooks/useUploadFile.js';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
import { cn } from '@/lib/utils.js';
interface SignupDialogProps {
isOpen: boolean;
@@ -301,7 +301,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
{getTitle()}
</DialogTitle>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 flex-1'>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
{/* Welcome Step - New engaging introduction */}
{step === 'welcome' && (
<div className='text-center space-y-4'>
+29
View File
@@ -0,0 +1,29 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor.js';
import { useComments } from '@/hooks/useComments.js';
import { CommentForm } from "./CommentForm.js";
import { NoteContent } from '@/components/NoteContent.js';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.js';
import { Button } from '@/components/ui/button.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible.js';
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu.js';
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { genUserName } from '@/lib/genUserName.js';
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }) {
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 (_jsxs("div", { className: `space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`, children: [_jsx(Card, { className: "bg-card/50", children: _jsx(CardContent, { className: "p-4", children: _jsxs("div", { className: "space-y-3", children: [_jsx("div", { className: "flex items-start justify-between", children: _jsxs("div", { className: "flex items-center space-x-3", children: [_jsx(Link, { to: `/${nip19.npubEncode(comment.pubkey)}`, children: _jsxs(Avatar, { className: "h-8 w-8 hover:ring-2 hover:ring-primary/30 transition-all cursor-pointer", children: [_jsx(AvatarImage, { src: metadata?.picture }), _jsx(AvatarFallback, { className: "text-xs", children: displayName.charAt(0) })] }) }), _jsxs("div", { children: [_jsx(Link, { to: `/${nip19.npubEncode(comment.pubkey)}`, className: "font-medium text-sm hover:text-primary transition-colors", children: displayName }), _jsx("p", { className: "text-xs text-muted-foreground", children: timeAgo })] })] }) }), _jsx("div", { className: "text-sm", children: _jsx(NoteContent, { event: comment, className: "text-sm" }) }), _jsxs("div", { className: "flex items-center justify-between pt-2", children: [_jsxs("div", { className: "flex items-center space-x-2", children: [_jsxs(Button, { variant: "ghost", size: "sm", onClick: () => setShowReplyForm(!showReplyForm), className: "h-8 px-2 text-xs", children: [_jsx(MessageSquare, { className: "h-3 w-3 mr-1" }), "Reply"] }), hasReplies && (_jsx(Collapsible, { open: showReplies, onOpenChange: setShowReplies, children: _jsx(CollapsibleTrigger, { asChild: true, children: _jsxs(Button, { variant: "ghost", size: "sm", className: "h-8 px-2 text-xs", children: [showReplies ? (_jsx(ChevronDown, { className: "h-3 w-3 mr-1" })) : (_jsx(ChevronRight, { className: "h-3 w-3 mr-1" })), replies.length, " ", replies.length === 1 ? 'reply' : 'replies'] }) }) }))] }), _jsx(DropdownMenu, { children: _jsx(DropdownMenuTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", className: "h-8 px-2 text-xs", "aria-label": "Comment options", children: _jsx(MoreHorizontal, { className: "h-3 w-3" }) }) }) })] })] }) }) }), showReplyForm && (_jsx("div", { className: "ml-6", children: _jsx(CommentForm, { root: root, reply: comment, onSuccess: () => setShowReplyForm(false), placeholder: "Write a reply...", compact: true }) })), hasReplies && (_jsx(Collapsible, { open: showReplies, onOpenChange: setShowReplies, children: _jsx(CollapsibleContent, { className: "space-y-3", children: replies.map((reply) => (_jsx(Comment, { root: root, comment: reply, depth: depth + 1, maxDepth: maxDepth, limit: limit }, reply.id))) }) }))] }));
}
+14 -14
View File
@@ -2,18 +2,18 @@ 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 { useAuthor } from '@/hooks/useAuthor.js';
import { useComments } from '@/hooks/useComments.js';
import { CommentForm } from "./CommentForm.js";
import { NoteContent } from '@/components/NoteContent.js';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.js';
import { Button } from '@/components/ui/button.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible.js';
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu.js';
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { genUserName } from '@/lib/genUserName';
import { genUserName } from '@/lib/genUserName.js';
interface CommentProps {
root: NostrEvent | URL;
@@ -26,10 +26,10 @@ interface CommentProps {
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 });
@@ -55,7 +55,7 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
</Avatar>
</Link>
<div>
<Link
<Link
to={`/${nip19.npubEncode(comment.pubkey)}`}
className="font-medium text-sm hover:text-primary transition-colors"
>
@@ -83,7 +83,7 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
<MessageSquare className="h-3 w-3 mr-1" />
Reply
</Button>
{hasReplies && (
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
<CollapsibleTrigger asChild>
+29
View File
@@ -0,0 +1,29 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { Button } from '@/components/ui/button.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { usePostComment } from '@/hooks/usePostComment.js';
import { LoginArea } from '@/components/auth/LoginArea.js';
import { MessageSquare, Send } from 'lucide-react';
export function CommentForm({ root, reply, onSuccess, placeholder = "Write a comment...", compact = false }) {
const [content, setContent] = useState('');
const { user } = useCurrentUser();
const { mutate: postComment, isPending } = usePostComment();
const handleSubmit = (e) => {
e.preventDefault();
if (!content.trim() || !user)
return;
postComment({ content: content.trim(), root, reply }, {
onSuccess: () => {
setContent('');
onSuccess?.();
},
});
};
if (!user) {
return (_jsx(Card, { className: compact ? "border-dashed" : "", children: _jsx(CardContent, { className: compact ? "p-4" : "p-6", children: _jsxs("div", { className: "text-center space-y-4", children: [_jsxs("div", { className: "flex items-center justify-center space-x-2 text-muted-foreground", children: [_jsx(MessageSquare, { className: "h-5 w-5" }), _jsxs("span", { children: ["Sign in to ", reply ? 'reply' : 'comment'] })] }), _jsx(LoginArea, {})] }) }) }));
}
return (_jsx(Card, { className: compact ? "border-dashed" : "", children: _jsx(CardContent, { className: compact ? "p-4" : "p-6", children: _jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [_jsx(Textarea, { value: content, onChange: (e) => setContent(e.target.value), placeholder: placeholder, className: compact ? "min-h-[80px]" : "min-h-[100px]", disabled: isPending }), _jsxs("div", { className: "flex justify-between items-center", children: [_jsx("span", { className: "text-sm text-muted-foreground", children: reply ? 'Replying to comment' : 'Adding to the discussion' }), _jsxs(Button, { type: "submit", disabled: !content.trim() || isPending, size: compact ? "sm" : "default", children: [_jsx(Send, { className: "h-4 w-4 mr-2" }), isPending ? 'Posting...' : (reply ? 'Reply' : 'Comment')] })] })] }) }) }));
}
+11 -11
View File
@@ -1,10 +1,10 @@
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 { Button } from '@/components/ui/button.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { usePostComment } from '@/hooks/usePostComment.js';
import { LoginArea } from '@/components/auth/LoginArea.js';
import { NostrEvent } from '@nostrify/nostrify';
import { MessageSquare, Send } from 'lucide-react';
@@ -19,9 +19,9 @@ interface CommentFormProps {
export function CommentForm({
root,
reply,
onSuccess,
onSuccess,
placeholder = "Write a comment...",
compact = false
compact = false
}: CommentFormProps) {
const [content, setContent] = useState('');
const { user } = useCurrentUser();
@@ -29,7 +29,7 @@ export function CommentForm({
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim() || !user) return;
postComment(
@@ -74,8 +74,8 @@ export function CommentForm({
<span className="text-sm text-muted-foreground">
{reply ? 'Replying to comment' : 'Adding to the discussion'}
</span>
<Button
type="submit"
<Button
type="submit"
disabled={!content.trim() || isPending}
size={compact ? "sm" : "default"}
>
@@ -0,0 +1,16 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useComments } from '@/hooks/useComments.js';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card.js';
import { Skeleton } from '@/components/ui/skeleton.js';
import { MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils.js';
import { CommentForm } from "./CommentForm.js";
import { Comment } from "./Comment.js";
export function CommentsSection({ root, title = "Comments", emptyStateMessage = "No comments yet", emptyStateSubtitle = "Be the first to share your thoughts!", className, limit = 500, }) {
const { data: commentsData, isLoading, error } = useComments(root, limit);
const comments = commentsData?.topLevelComments || [];
if (error) {
return (_jsx(Card, { className: "rounded-none sm:rounded-lg mx-0 sm:mx-0", children: _jsx(CardContent, { className: "px-2 py-6 sm:p-6", children: _jsxs("div", { className: "text-center text-muted-foreground", children: [_jsx(MessageSquare, { className: "h-8 w-8 mx-auto mb-2 opacity-50" }), _jsx("p", { children: "Failed to load comments" })] }) }) }));
}
return (_jsxs(Card, { className: cn("rounded-none sm:rounded-lg mx-0 sm:mx-0", className), children: [_jsx(CardHeader, { className: "px-2 pt-6 pb-4 sm:p-6", children: _jsxs(CardTitle, { className: "flex items-center space-x-2", children: [_jsx(MessageSquare, { className: "h-5 w-5" }), _jsx("span", { children: title }), !isLoading && (_jsxs("span", { className: "text-sm font-normal text-muted-foreground", children: ["(", comments.length, ")"] }))] }) }), _jsxs(CardContent, { className: "px-2 pb-6 pt-4 sm:p-6 sm:pt-0 space-y-6", children: [_jsx(CommentForm, { root: root }), isLoading ? (_jsx("div", { className: "space-y-4", children: [...Array(3)].map((_, i) => (_jsx(Card, { className: "bg-card/50", children: _jsx(CardContent, { className: "p-4", children: _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-center space-x-3", children: [_jsx(Skeleton, { className: "h-8 w-8 rounded-full" }), _jsxs("div", { className: "space-y-1", children: [_jsx(Skeleton, { className: "h-4 w-24" }), _jsx(Skeleton, { className: "h-3 w-16" })] })] }), _jsx(Skeleton, { className: "h-16 w-full" })] }) }) }, i))) })) : comments.length === 0 ? (_jsxs("div", { className: "text-center py-8 text-muted-foreground", children: [_jsx(MessageSquare, { className: "h-12 w-12 mx-auto mb-4 opacity-30" }), _jsx("p", { className: "text-lg font-medium mb-2", children: emptyStateMessage }), _jsx("p", { className: "text-sm", children: emptyStateSubtitle })] })) : (_jsx("div", { className: "space-y-4", children: comments.map((comment) => (_jsx(Comment, { root: root, comment: comment }, comment.id))) }))] })] }));
}
+7 -7
View File
@@ -1,11 +1,11 @@
import { useComments } from '@/hooks/useComments';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useComments } from '@/hooks/useComments.js';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card.js';
import { Skeleton } from '@/components/ui/skeleton.js';
import { MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils';
import { cn } from '@/lib/utils.js';
import type { NostrEvent } from '@nostrify/nostrify';
import { CommentForm } from './CommentForm';
import { Comment } from './Comment';
import { CommentForm } from "./CommentForm.js";
import { Comment } from "./Comment.js";
interface CommentsSectionProps {
root: NostrEvent | URL;
@@ -16,7 +16,7 @@ interface CommentsSectionProps {
limit?: number;
}
export function CommentsSection({
export function CommentsSection({
root,
title = "Comments",
emptyStateMessage = "No comments yet",
-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>
);
};
+13
View File
@@ -0,0 +1,13 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils.js";
const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef(({ className, ...props }, ref) => (_jsx(AccordionPrimitive.Item, { ref: ref, className: cn("border-b", className), ...props })));
AccordionItem.displayName = "AccordionItem";
const AccordionTrigger = React.forwardRef(({ className, children, ...props }, ref) => (_jsx(AccordionPrimitive.Header, { className: "flex", children: _jsxs(AccordionPrimitive.Trigger, { ref: ref, className: cn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180", className), ...props, children: [children, _jsx(ChevronDown, { className: "h-4 w-4 shrink-0 transition-transform duration-200" })] }) })));
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef(({ className, children, ...props }, ref) => (_jsx(AccordionPrimitive.Content, { ref: ref, className: "overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down", ...props, children: _jsx("div", { className: cn("pb-4 pt-0", className), children: children }) })));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Accordion = AccordionPrimitive.Root
+26
View File
@@ -0,0 +1,26 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "@/lib/utils.js";
import { buttonVariants } from "@/components/ui/button-variants.js";
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Overlay, { className: cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className), ...props, ref: ref })));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef(({ className, ...props }, ref) => (_jsxs(AlertDialogPortal, { children: [_jsx(AlertDialogOverlay, {}), _jsx(AlertDialogPrimitive.Content, { ref: ref, className: cn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg", className), ...props })] })));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({ className, ...props }) => (_jsx("div", { className: cn("flex flex-col space-y-2 text-center sm:text-left", className), ...props }));
AlertDialogHeader.displayName = "AlertDialogHeader";
const AlertDialogFooter = ({ className, ...props }) => (_jsx("div", { className: cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className), ...props }));
AlertDialogFooter.displayName = "AlertDialogFooter";
const AlertDialogTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Title, { ref: ref, className: cn("text-lg font-semibold", className), ...props })));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Description, { ref: ref, className: cn("text-sm text-muted-foreground", className), ...props })));
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Action, { ref: ref, className: cn(buttonVariants(), className), ...props })));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Cancel, { ref: ref, className: cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className), ...props })));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export { AlertDialog, AlertDialogPortal, AlertDialogOverlay, AlertDialogTrigger, AlertDialogContent, AlertDialogHeader, AlertDialogFooter, AlertDialogTitle, AlertDialogDescription, AlertDialogAction, AlertDialogCancel, };
+2 -2
View File
@@ -1,8 +1,8 @@
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 { cn } from "@/lib/utils.js"
import { buttonVariants } from "@/components/ui/button-variants.js"
const AlertDialog = AlertDialogPrimitive.Root
+22
View File
@@ -0,0 +1,22 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { cva } from "class-variance-authority";
import { cn } from "@/lib/utils.js";
const alertVariants = cva("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground", {
variants: {
variant: {
default: "bg-background text-foreground",
destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
});
const Alert = React.forwardRef(({ className, variant, ...props }, ref) => (_jsx("div", { ref: ref, role: "alert", className: cn(alertVariants({ variant }), className), ...props })));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx("h5", { ref: ref, className: cn("mb-1 font-medium leading-none tracking-tight", className), ...props })));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("text-sm [&_p]:leading-relaxed", className), ...props })));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };
+1 -1
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
+3
View File
@@ -0,0 +1,3 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio };
+11
View File
@@ -0,0 +1,11 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "@/lib/utils.js";
const Avatar = React.forwardRef(({ className, ...props }, ref) => (_jsx(AvatarPrimitive.Root, { ref: ref, className: cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className), ...props })));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef(({ className, ...props }, ref) => (_jsx(AvatarPrimitive.Image, { ref: ref, className: cn("aspect-square h-full w-full object-cover", className), ...props })));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef(({ className, ...props }, ref) => (_jsx(AvatarPrimitive.Fallback, { ref: ref, className: cn("flex h-full w-full items-center justify-center rounded-full bg-muted", className), ...props })));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback };
+1 -1
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
+14
View File
@@ -0,0 +1,14 @@
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",
},
});
+7
View File
@@ -0,0 +1,7 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { cn } from "@/lib/utils.js";
import { badgeVariants } from "./badge-variants.js";
function Badge({ className, variant, ...props }) {
return (_jsx("div", { className: cn(badgeVariants({ variant }), className), ...props }));
}
export { Badge };
+2 -2
View File
@@ -1,8 +1,8 @@
import * as React from "react"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { badgeVariants } from "./badge-variants"
import { cn } from "@/lib/utils.js"
import { badgeVariants } from "./badge-variants.js"
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
+23
View File
@@ -0,0 +1,23 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils.js";
const Breadcrumb = React.forwardRef(({ ...props }, ref) => _jsx("nav", { ref: ref, "aria-label": "breadcrumb", ...props }));
Breadcrumb.displayName = "Breadcrumb";
const BreadcrumbList = React.forwardRef(({ className, ...props }, ref) => (_jsx("ol", { ref: ref, className: cn("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5", className), ...props })));
BreadcrumbList.displayName = "BreadcrumbList";
const BreadcrumbItem = React.forwardRef(({ className, ...props }, ref) => (_jsx("li", { ref: ref, className: cn("inline-flex items-center gap-1.5", className), ...props })));
BreadcrumbItem.displayName = "BreadcrumbItem";
const BreadcrumbLink = React.forwardRef(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a";
return (_jsx(Comp, { ref: ref, className: cn("transition-colors hover:text-foreground", className), ...props }));
});
BreadcrumbLink.displayName = "BreadcrumbLink";
const BreadcrumbPage = React.forwardRef(({ className, ...props }, ref) => (_jsx("span", { ref: ref, role: "link", "aria-disabled": "true", "aria-current": "page", className: cn("font-normal text-foreground", className), ...props })));
BreadcrumbPage.displayName = "BreadcrumbPage";
const BreadcrumbSeparator = ({ children, className, ...props }) => (_jsx("li", { role: "presentation", "aria-hidden": "true", className: cn("[&>svg]:size-3.5", className), ...props, children: children ?? _jsx(ChevronRight, {}) }));
BreadcrumbSeparator.displayName = "BreadcrumbSeparator";
const BreadcrumbEllipsis = ({ className, ...props }) => (_jsxs("span", { role: "presentation", "aria-hidden": "true", className: cn("flex h-9 w-9 items-center justify-center", className), ...props, children: [_jsx(MoreHorizontal, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "More" })] }));
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis";
export { Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator, BreadcrumbEllipsis, };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Breadcrumb = React.forwardRef<
HTMLElement,
+23
View File
@@ -0,0 +1,23 @@
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 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",
},
});
+1 -1
View File
@@ -9,7 +9,7 @@ export const buttonVariants = cva(
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input hover:bg-accent hover:text-accent-foreground",
"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",
+11
View File
@@ -0,0 +1,11 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cn } from "@/lib/utils.js";
import { buttonVariants } from "./button-variants.js";
const Button = React.forwardRef(({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (_jsx(Comp, { className: cn(buttonVariants({ variant, size, className })), ref: ref, ...props }));
});
Button.displayName = "Button";
export { Button };
+2 -2
View File
@@ -2,8 +2,8 @@ import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { buttonVariants } from "./button-variants"
import { cn } from "@/lib/utils.js"
import { buttonVariants } from "./button-variants.js"
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+36
View File
@@ -0,0 +1,36 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils.js";
import { buttonVariants } from "@/components/ui/button-variants.js";
function Calendar({ className, classNames, showOutsideDays = true, ...props }) {
return (_jsx(DayPicker, { showOutsideDays: showOutsideDays, className: cn("p-3", className), classNames: {
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(buttonVariants({ variant: "outline" }), "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell: "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
day: cn(buttonVariants({ variant: "ghost" }), "h-9 w-9 p-0 font-normal aria-selected:opacity-100"),
day_range_end: "day-range-end",
day_selected: "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside: "day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}, components: {
IconLeft: ({ ..._props }) => _jsx(ChevronLeft, { className: "h-4 w-4" }),
IconRight: ({ ..._props }) => _jsx(ChevronRight, { className: "h-4 w-4" }),
}, ...props }));
}
Calendar.displayName = "Calendar";
export { Calendar };
+2 -2
View File
@@ -2,8 +2,8 @@ import * as React from "react";
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 { cn } from "@/lib/utils.js";
import { buttonVariants } from "@/components/ui/button-variants.js";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
+16
View File
@@ -0,0 +1,16 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { cn } from "@/lib/utils.js";
const Card = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("rounded-lg border bg-card text-card-foreground shadow-sm", className), ...props })));
Card.displayName = "Card";
const CardHeader = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("flex flex-col space-y-1.5 p-6", className), ...props })));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx("h3", { ref: ref, className: cn("text-2xl font-semibold leading-none tracking-tight", className), ...props })));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx("p", { ref: ref, className: cn("text-sm text-muted-foreground", className), ...props })));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("p-6 pt-0", className), ...props })));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("flex items-center p-6 pt-0", className), ...props })));
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
+1 -1
View File
@@ -1,6 +1,6 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Card = React.forwardRef<
HTMLDivElement,
+98
View File
@@ -0,0 +1,98 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import useEmblaCarousel from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils.js";
import { Button } from "@/components/ui/button.js";
const CarouselContext = React.createContext(null);
function useCarousel() {
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />");
}
return context;
}
const Carousel = React.forwardRef(({ orientation = "horizontal", opts, setApi, plugins, className, children, ...props }, ref) => {
const [carouselRef, api] = useEmblaCarousel({
...opts,
axis: orientation === "horizontal" ? "x" : "y",
}, plugins);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api) => {
if (!api) {
return;
}
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback((event) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
scrollPrev();
}
else if (event.key === "ArrowRight") {
event.preventDefault();
scrollNext();
}
}, [scrollPrev, scrollNext]);
React.useEffect(() => {
if (!api || !setApi) {
return;
}
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) {
return;
}
onSelect(api);
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
api?.off("select", onSelect);
};
}, [api, onSelect]);
return (_jsx(CarouselContext.Provider, { value: {
carouselRef,
api: api,
opts,
orientation: orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}, children: _jsx("div", { ref: ref, onKeyDownCapture: handleKeyDown, className: cn("relative", className), role: "region", "aria-roledescription": "carousel", ...props, children: children }) }));
});
Carousel.displayName = "Carousel";
const CarouselContent = React.forwardRef(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel();
return (_jsx("div", { ref: carouselRef, className: "overflow-hidden", children: _jsx("div", { ref: ref, className: cn("flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className), ...props }) }));
});
CarouselContent.displayName = "CarouselContent";
const CarouselItem = React.forwardRef(({ className, ...props }, ref) => {
const { orientation } = useCarousel();
return (_jsx("div", { ref: ref, role: "group", "aria-roledescription": "slide", className: cn("min-w-0 shrink-0 grow-0 basis-full", orientation === "horizontal" ? "pl-4" : "pt-4", className), ...props }));
});
CarouselItem.displayName = "CarouselItem";
const CarouselPrevious = React.forwardRef(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (_jsxs(Button, { ref: ref, variant: variant, size: size, className: cn("absolute h-8 w-8 rounded-full", orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90", className), disabled: !canScrollPrev, onClick: scrollPrev, ...props, children: [_jsx(ArrowLeft, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Previous slide" })] }));
});
CarouselPrevious.displayName = "CarouselPrevious";
const CarouselNext = React.forwardRef(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (_jsxs(Button, { ref: ref, variant: variant, size: size, className: cn("absolute h-8 w-8 rounded-full", orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90", className), disabled: !canScrollNext, onClick: scrollNext, ...props, children: [_jsx(ArrowRight, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Next slide" })] }));
});
CarouselNext.displayName = "CarouselNext";
export { Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext, };
+2 -2
View File
@@ -4,8 +4,8 @@ import useEmblaCarousel, {
} from "embla-carousel-react"
import { ArrowLeft, ArrowRight } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils.js"
import { Button } from "@/components/ui/button.js"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
+130
View File
@@ -0,0 +1,130 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import * as React from "react";
import * as RechartsPrimitive from "recharts";
import { cn } from "@/lib/utils.js";
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" };
const ChartContext = React.createContext(null);
function useChart() {
const context = React.useContext(ChartContext);
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />");
}
return context;
}
const ChartContainer = React.forwardRef(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
return (_jsx(ChartContext.Provider, { value: { config }, children: _jsxs("div", { "data-chart": chartId, ref: ref, className: cn("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none", className), ...props, children: [_jsx(ChartStyle, { id: chartId, config: config }), _jsx(RechartsPrimitive.ResponsiveContainer, { children: children })] }) }));
});
ChartContainer.displayName = "Chart";
const ChartStyle = ({ id, config }) => {
const colorConfig = Object.entries(config).filter(([_, config]) => config.theme || config.color);
if (!colorConfig.length) {
return null;
}
return (_jsx("style", { dangerouslySetInnerHTML: {
__html: Object.entries(THEMES)
.map(([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color = itemConfig.theme?.[theme] ||
itemConfig.color;
return color ? ` --color-${key}: ${color};` : null;
})
.join("\n")}
}
`)
.join("\n"),
} }));
};
const ChartTooltip = RechartsPrimitive.Tooltip;
const ChartTooltipContent = React.forwardRef(({ active, payload, className, indicator = "dot", hideLabel = false, hideIndicator = false, label, labelFormatter, labelClassName, formatter, color, nameKey, labelKey, }, ref) => {
const { config } = useChart();
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null;
}
const [item] = payload;
const key = `${labelKey || item.dataKey || item.name || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value = !labelKey && typeof label === "string"
? config[label]?.label || label
: itemConfig?.label;
if (labelFormatter) {
return (_jsx("div", { className: cn("font-medium", labelClassName), children: labelFormatter(value, payload) }));
}
if (!value) {
return null;
}
return _jsx("div", { className: cn("font-medium", labelClassName), children: value });
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
]);
if (!active || !payload?.length) {
return null;
}
const nestLabel = payload.length === 1 && indicator !== "dot";
return (_jsxs("div", { ref: ref, className: cn("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl", className), children: [!nestLabel ? tooltipLabel : null, _jsx("div", { className: "grid gap-1.5", children: payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color || item.payload.fill || item.color;
return (_jsx("div", { className: cn("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground", indicator === "dot" && "items-center"), children: formatter && item?.value !== undefined && item.name ? (formatter(item.value, item.name, item, index, item.payload)) : (_jsxs(_Fragment, { children: [itemConfig?.icon ? (_jsx(itemConfig.icon, {})) : (!hideIndicator && (_jsx("div", { className: cn("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]", {
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent": indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}), style: {
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} }))), _jsxs("div", { className: cn("flex flex-1 justify-between leading-none", nestLabel ? "items-end" : "items-center"), children: [_jsxs("div", { className: "grid gap-1.5", children: [nestLabel ? tooltipLabel : null, _jsx("span", { className: "text-muted-foreground", children: itemConfig?.label || item.name })] }), item.value && (_jsx("span", { className: "font-mono font-medium tabular-nums text-foreground", children: item.value.toLocaleString() }))] })] })) }, item.dataKey));
}) })] }));
});
ChartTooltipContent.displayName = "ChartTooltip";
const ChartLegend = RechartsPrimitive.Legend;
const ChartLegendContent = React.forwardRef(({ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey }, ref) => {
const { config } = useChart();
if (!payload?.length) {
return null;
}
return (_jsx("div", { ref: ref, className: cn("flex items-center justify-center gap-4", verticalAlign === "top" ? "pb-3" : "pt-3", className), children: payload.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
return (_jsxs("div", { className: cn("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"), children: [itemConfig?.icon && !hideIcon ? (_jsx(itemConfig.icon, {})) : (_jsx("div", { className: "h-2 w-2 shrink-0 rounded-[2px]", style: {
backgroundColor: item.color,
} })), itemConfig?.label] }, item.value));
}) }));
});
ChartLegendContent.displayName = "ChartLegend";
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(config, payload, key) {
if (typeof payload !== "object" || payload === null) {
return undefined;
}
const payloadPayload = "payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined;
let configLabelKey = key;
if (key in payload &&
typeof payload[key] === "string") {
configLabelKey = payload[key];
}
else if (payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key] === "string") {
configLabelKey = payloadPayload[key];
}
return configLabelKey in config
? config[configLabelKey]
: config[key];
}
export { ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle, };
+1 -1
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
+8
View File
@@ -0,0 +1,8 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils.js";
const Checkbox = React.forwardRef(({ className, ...props }, ref) => (_jsx(CheckboxPrimitive.Root, { ref: ref, className: cn("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", className), ...props, children: _jsx(CheckboxPrimitive.Indicator, { className: cn("flex items-center justify-center text-current"), children: _jsx(Check, { className: "h-4 w-4" }) }) })));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
+5
View File
@@ -0,0 +1,5 @@
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
+28
View File
@@ -0,0 +1,28 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
import { cn } from "@/lib/utils.js";
import { Dialog, DialogContent } from "@/components/ui/dialog.js";
const Command = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive, { ref: ref, className: cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground", className), ...props })));
Command.displayName = CommandPrimitive.displayName;
const CommandDialog = ({ children, ...props }) => {
return (_jsx(Dialog, { ...props, children: _jsx(DialogContent, { className: "overflow-hidden p-0 shadow-lg", children: _jsx(Command, { className: "[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5", children: children }) }) }));
};
const CommandInput = React.forwardRef(({ className, ...props }, ref) => (_jsxs("div", { className: "flex items-center border-b px-3", "cmdk-input-wrapper": "", children: [_jsx(Search, { className: "mr-2 h-4 w-4 shrink-0 opacity-50" }), _jsx(CommandPrimitive.Input, { ref: ref, className: cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50", className), ...props })] })));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive.List, { ref: ref, className: cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className), ...props })));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef((props, ref) => (_jsx(CommandPrimitive.Empty, { ref: ref, className: "py-6 text-center text-sm", ...props })));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive.Group, { ref: ref, className: cn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground", className), ...props })));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive.Separator, { ref: ref, className: cn("-mx-1 h-px bg-border", className), ...props })));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive.Item, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50", className), ...props })));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({ className, ...props }) => {
return (_jsx("span", { className: cn("ml-auto text-xs tracking-widest text-muted-foreground", className), ...props }));
};
CommandShortcut.displayName = "CommandShortcut";
export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut, CommandSeparator, };
+2 -2
View File
@@ -3,8 +3,8 @@ import { type DialogProps } from "@radix-ui/react-dialog"
import { Command as CommandPrimitive } from "cmdk"
import { Search } from "lucide-react"
import { cn } from "@/lib/utils"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { cn } from "@/lib/utils.js"
import { Dialog, DialogContent } from "@/components/ui/dialog.js"
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
+33
View File
@@ -0,0 +1,33 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils.js";
const ContextMenu = ContextMenuPrimitive.Root;
const ContextMenuTrigger = ContextMenuPrimitive.Trigger;
const ContextMenuGroup = ContextMenuPrimitive.Group;
const ContextMenuPortal = ContextMenuPrimitive.Portal;
const ContextMenuSub = ContextMenuPrimitive.Sub;
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup;
const ContextMenuSubTrigger = React.forwardRef(({ className, inset, children, ...props }, ref) => (_jsxs(ContextMenuPrimitive.SubTrigger, { ref: ref, className: cn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground", inset && "pl-8", className), ...props, children: [children, _jsx(ChevronRight, { className: "ml-auto h-4 w-4" })] })));
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;
const ContextMenuSubContent = React.forwardRef(({ className, ...props }, ref) => (_jsx(ContextMenuPrimitive.SubContent, { ref: ref, className: cn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className), ...props })));
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;
const ContextMenuContent = React.forwardRef(({ className, ...props }, ref) => (_jsx(ContextMenuPrimitive.Portal, { children: _jsx(ContextMenuPrimitive.Content, { ref: ref, className: cn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className), ...props }) })));
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;
const ContextMenuItem = React.forwardRef(({ className, inset, ...props }, ref) => (_jsx(ContextMenuPrimitive.Item, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", inset && "pl-8", className), ...props })));
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
const ContextMenuCheckboxItem = React.forwardRef(({ className, children, checked, ...props }, ref) => (_jsxs(ContextMenuPrimitive.CheckboxItem, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className), checked: checked, ...props, children: [_jsx("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center", children: _jsx(ContextMenuPrimitive.ItemIndicator, { children: _jsx(Check, { className: "h-4 w-4" }) }) }), children] })));
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName;
const ContextMenuRadioItem = React.forwardRef(({ className, children, ...props }, ref) => (_jsxs(ContextMenuPrimitive.RadioItem, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className), ...props, children: [_jsx("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center", children: _jsx(ContextMenuPrimitive.ItemIndicator, { children: _jsx(Circle, { className: "h-2 w-2 fill-current" }) }) }), children] })));
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;
const ContextMenuLabel = React.forwardRef(({ className, inset, ...props }, ref) => (_jsx(ContextMenuPrimitive.Label, { ref: ref, className: cn("px-2 py-1.5 text-sm font-semibold text-foreground", inset && "pl-8", className), ...props })));
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;
const ContextMenuSeparator = React.forwardRef(({ className, ...props }, ref) => (_jsx(ContextMenuPrimitive.Separator, { ref: ref, className: cn("-mx-1 my-1 h-px bg-border", className), ...props })));
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
const ContextMenuShortcut = ({ className, ...props }) => {
return (_jsx("span", { className: cn("ml-auto text-xs tracking-widest text-muted-foreground", className), ...props }));
};
ContextMenuShortcut.displayName = "ContextMenuShortcut";
export { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuCheckboxItem, ContextMenuRadioItem, ContextMenuLabel, ContextMenuSeparator, ContextMenuShortcut, ContextMenuGroup, ContextMenuPortal, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuRadioGroup, };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const ContextMenu = ContextMenuPrimitive.Root
+22
View File
@@ -0,0 +1,22 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils.js";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef(({ className, ...props }, ref) => (_jsx(DialogPrimitive.Overlay, { ref: ref, className: cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className), ...props })));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef(({ className, children, ...props }, ref) => (_jsxs(DialogPortal, { children: [_jsx(DialogOverlay, {}), _jsxs(DialogPrimitive.Content, { ref: ref, className: cn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg", className), ...props, children: [children, _jsxs(DialogPrimitive.Close, { className: "absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground", children: [_jsx(X, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Close" })] })] })] })));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }) => (_jsx("div", { className: cn("flex flex-col space-y-1.5 text-center sm:text-left", className), ...props }));
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({ className, ...props }) => (_jsx("div", { className: cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className), ...props }));
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx(DialogPrimitive.Title, { ref: ref, className: cn("text-lg font-semibold leading-none tracking-tight", className), ...props })));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx(DialogPrimitive.Description, { ref: ref, className: cn("text-sm text-muted-foreground", className), ...props })));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export { Dialog, DialogPortal, DialogOverlay, DialogClose, DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Dialog = DialogPrimitive.Root
+22
View File
@@ -0,0 +1,22 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "@/lib/utils.js";
const Drawer = ({ shouldScaleBackground = true, ...props }) => (_jsx(DrawerPrimitive.Root, { shouldScaleBackground: shouldScaleBackground, ...props }));
Drawer.displayName = "Drawer";
const DrawerTrigger = DrawerPrimitive.Trigger;
const DrawerPortal = DrawerPrimitive.Portal;
const DrawerClose = DrawerPrimitive.Close;
const DrawerOverlay = React.forwardRef(({ className, ...props }, ref) => (_jsx(DrawerPrimitive.Overlay, { ref: ref, className: cn("fixed inset-0 z-50 bg-black/80", className), ...props })));
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
const DrawerContent = React.forwardRef(({ className, children, ...props }, ref) => (_jsxs(DrawerPortal, { children: [_jsx(DrawerOverlay, {}), _jsxs(DrawerPrimitive.Content, { ref: ref, className: cn("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background", className), ...props, children: [_jsx("div", { className: "mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" }), children] })] })));
DrawerContent.displayName = "DrawerContent";
const DrawerHeader = ({ className, ...props }) => (_jsx("div", { className: cn("grid gap-1.5 p-4 text-center sm:text-left", className), ...props }));
DrawerHeader.displayName = "DrawerHeader";
const DrawerFooter = ({ className, ...props }) => (_jsx("div", { className: cn("mt-auto flex flex-col gap-2 p-4", className), ...props }));
DrawerFooter.displayName = "DrawerFooter";
const DrawerTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx(DrawerPrimitive.Title, { ref: ref, className: cn("text-lg font-semibold leading-none tracking-tight", className), ...props })));
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
const DrawerDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx(DrawerPrimitive.Description, { ref: ref, className: cn("text-sm text-muted-foreground", className), ...props })));
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
export { Drawer, DrawerPortal, DrawerOverlay, DrawerTrigger, DrawerClose, DrawerContent, DrawerHeader, DrawerFooter, DrawerTitle, DrawerDescription, };
+1 -1
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Drawer = ({
shouldScaleBackground = true,
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff. Show more